diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d84137c7..9e4b0342 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -60,7 +60,9 @@ jobs: - uses: Swatinem/rust-cache@v2 if: runner.os == 'Windows' with: - workspaces: native/diskhound-native-scanner + workspaces: | + native/diskhound-native-scanner + native/diskhound-mcp - name: Build native scanner for USN integration if: runner.os == 'Windows' @@ -84,7 +86,9 @@ jobs: - uses: Swatinem/rust-cache@v2 with: - workspaces: native/diskhound-native-scanner + workspaces: | + native/diskhound-native-scanner + native/diskhound-mcp - name: Cargo check run: cargo check --manifest-path native/diskhound-native-scanner/Cargo.toml @@ -97,6 +101,12 @@ jobs: DISKHOUND_REQUIRE_USN_TESTS: ${{ runner.os == 'Windows' && '1' || '0' }} run: cargo test --manifest-path native/diskhound-native-scanner/Cargo.toml + - name: Test MCP stdio bridge + run: cargo test --locked --manifest-path native/diskhound-mcp/Cargo.toml + + - name: Build MCP stdio bridge + run: cargo build --locked --release --manifest-path native/diskhound-mcp/Cargo.toml + - name: Cargo build (release) run: cargo build --release --manifest-path native/diskhound-native-scanner/Cargo.toml @@ -129,7 +139,9 @@ jobs: - uses: Swatinem/rust-cache@v2 with: - workspaces: native/diskhound-native-scanner + workspaces: | + native/diskhound-native-scanner + native/diskhound-mcp - name: Install dependencies run: bun install --frozen-lockfile diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1be4dbb1..65142479 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -100,6 +100,25 @@ jobs: cp native/diskhound-native-scanner/target/${{ matrix.rust-target }}/release/diskhound-native-scanner native/diskhound-native-scanner/target/release/diskhound-native-scanner fi + - name: Build and stage MCP stdio bridge + shell: bash + run: | + crate=native/diskhound-mcp + mkdir -p "$crate/target/release" + if [ "${{ runner.os }}" = "macOS" ]; then + cargo build --locked --release --target aarch64-apple-darwin --manifest-path "$crate/Cargo.toml" + cargo build --locked --release --target x86_64-apple-darwin --manifest-path "$crate/Cargo.toml" + lipo -create -output "$crate/target/release/diskhound-mcp" \ + "$crate/target/aarch64-apple-darwin/release/diskhound-mcp" \ + "$crate/target/x86_64-apple-darwin/release/diskhound-mcp" + lipo -info "$crate/target/release/diskhound-mcp" + else + cargo build --locked --release --target ${{ matrix.rust-target }} --manifest-path "$crate/Cargo.toml" + suffix="" + if [ "${{ runner.os }}" = "Windows" ]; then suffix=".exe"; fi + cp "$crate/target/${{ matrix.rust-target }}/release/diskhound-mcp$suffix" "$crate/target/release/" + fi + - name: Verify native binary exists shell: bash run: | diff --git a/.gitignore b/.gitignore index 710adf74..d99d1323 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ dist-electron/ dist-renderer/ /release/ native/diskhound-native-scanner/target/ +native/diskhound-mcp/target/ /test-results/ /playwright-report/ .turbo/ diff --git a/README.md b/README.md index bd64797d..ce3526a6 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ WinDirStat was the gold standard for a decade. DiskHound is what it would be tod - ๐Ÿ”— **Easy Move** โ€” move a large file to another drive, leave a symlink or junction in its place. Fully reversible. Tracks every move so you can put files back with one click. Offers a one-UAC fast-scan mode for system installs. - ๐Ÿ“ **Folder explorer** โ€” drill into directories with breadcrumb navigation and proportional size bars. - ๐Ÿงน **Dev Artifacts** (`Ctrl+4`) โ€” groups worktrees, `node_modules`, Rust `target/` trees, package caches, and venvs. Pick trees and permanently delete them. A finished scan writes a sidecar so the tab opens without reading the drive again. +- ๐Ÿค– **AI agents (MCP)**: let Claude Code, Claude Desktop, Codex, or another MCP client read your scans, run scans, and steer the window while it helps you free up space. Agents get DiskHound's cleanup procedures (including the APFS clone and Time Machine snapshot checks on macOS). You approve each agent in DiskHound and pick what it may do; nothing moves to the Trash or is deleted without your confirmation, and anything a session isn't allowed to do is refused and logged. Claude connects through the bundled stdio helper, Codex over HTTP with OAuth. Off by default; start from the robot button in the header, or see [docs/mcp.md](docs/mcp.md). - ๐Ÿ›Ž๏ธ **Drive monitoring** โ€” periodic free-space polling with delta alerts when space drops meaningfully. Rolling history of drive-level events is persisted. - โš™๏ธ **Processes viewer** โ€” real-time memory + CPU sampling for every process, with icons pulled from each executable. **Four views**: List, Treemap, scrolling CPU Heatmap (time on X, process on Y), and details. - ๐ŸŽฎ **GPU viewer** โ€” per-process GPU utilisation + VRAM pulled from Windows `\GPU Engine(*)` / `\GPU Process Memory(*)` performance counters. Adapter overview (3D / Compute / Decode / Encode stats). @@ -156,6 +157,10 @@ src/ โ”œโ”€โ”€ preload.ts Context bridge (IPC โ†’ renderer) โ”œโ”€โ”€ nativeScanner.ts Spawn and manage the Rust binary โ”œโ”€โ”€ scan/scanWorker.ts JS fallback scanner (worker thread) +โ”œโ”€โ”€ mcp/ Local MCP server for AI agents (loaded on first enable) +โ”‚ โ”œโ”€โ”€ server.ts Tools, prompts, and SEP-2640 skills +โ”‚ โ”œโ”€โ”€ agentOAuth.ts OAuth 2.1 provider (DCR, PKCE, native approval) +โ”‚ โ””โ”€โ”€ electronHost.ts Approval window, Trash confirmation, Settings IPC โ”œโ”€โ”€ shared/ โ”‚ โ”œโ”€โ”€ contracts.ts All TypeScript types and IPC interface โ”‚ โ”œโ”€โ”€ scanDiff.ts Snapshot diff algorithm (top-N) @@ -172,6 +177,8 @@ src/ native/diskhound-native-scanner/ โ””โ”€โ”€ src/main.rs Rust scanner (Win32 APIs + dua-core) + +skills/ Cleanup procedures served to agents over MCP ``` The native scanner uses Win32 APIs on Windows and [dua-core](https://crates.io/crates/dua-core), diff --git a/bun.lock b/bun.lock index 4cbe13da..9c59a17e 100644 --- a/bun.lock +++ b/bun.lock @@ -5,14 +5,18 @@ "": { "name": "diskhound", "dependencies": { + "@modelcontextprotocol/sdk": "1.30.0", "@shutterstock/p-map-iterable": "^1.1.2", "blake2": "^5.0.1", "electron-updater": "^6.6.2", + "express": "5.2.1", "preact": "^10.26.9", + "zod": "4.6.5", }, "devDependencies": { "@playwright/test": "^1.63.0", "@preact/preset-vite": "^2.10.2", + "@types/express": "^5.0.6", "@types/node": "^24.12.0", "electron": "40.6.0", "electron-builder": "^26.0.12", @@ -162,6 +166,8 @@ "@hapi/topo": ["@hapi/topo@6.0.2", "", { "dependencies": { "@hapi/hoek": "^11.0.2" } }, "sha512-KR3rD5inZbGMrHmgPxsJ9dbi6zEK+C3ZwUwTa+eMwWLz7oijWUTWD2pMSNNYJAU6Qq+65NkxXjqHr/7LM2Xkqg=="], + "@hono/node-server": ["@hono/node-server@2.1.1", "", { "peerDependencies": { "hono": "^4" } }, "sha512-ELuehkj5VCBdgEw9zs+ivkKwyzzUCSQuE96YmiPvn1ECBoZCczbFXJLeEGMTYjphP6gydh4pHMqEYPVMYUVgQg=="], + "@isaacs/cliui": ["@isaacs/cliui@8.0.2", "", { "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" } }, "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA=="], "@isaacs/fs-minipass": ["@isaacs/fs-minipass@4.0.1", "", { "dependencies": { "minipass": "^7.0.4" } }, "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w=="], @@ -180,6 +186,8 @@ "@malept/flatpak-bundler": ["@malept/flatpak-bundler@0.4.0", "", { "dependencies": { "debug": "^4.1.1", "fs-extra": "^9.0.0", "lodash": "^4.17.15", "tmp-promise": "^3.0.2" } }, "sha512-9QOtNffcOF/c1seMCDnjckb3R9WHcG34tky+FHpNKKCW0wc/scYLwMtO+ptyGUfMW0/b/n4qRiALlaFHc9Oj7Q=="], + "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.30.0", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA=="], + "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.3", "", { "dependencies": { "@tybys/wasm-util": "^0.10.1" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-xK9sGVbJWYb08+mTJt3/YV24WxvxpXcXtP6B172paPZ+Ts69Re9dAr7lKwJoeIx8OoeuimEiRZ7umkiUVClmmQ=="], "@npmcli/agent": ["@npmcli/agent@3.0.0", "", { "dependencies": { "agent-base": "^7.1.0", "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.1", "lru-cache": "^10.0.1", "socks-proxy-agent": "^8.0.3" } }, "sha512-S79NdEgDQd/NGCay6TCoVzXSj74skRZIKJcpJjC5lOq34SZzyI6MqtiiWoiVWoVrTcGjNeC4ipbh1VIHlpfF5Q=="], @@ -298,20 +306,30 @@ "@tybys/wasm-util": ["@tybys/wasm-util@0.10.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="], + "@types/body-parser": ["@types/body-parser@1.19.6", "", { "dependencies": { "@types/connect": "*", "@types/node": "*" } }, "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g=="], + "@types/cacheable-request": ["@types/cacheable-request@6.0.3", "", { "dependencies": { "@types/http-cache-semantics": "*", "@types/keyv": "^3.1.4", "@types/node": "*", "@types/responselike": "^1.0.0" } }, "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw=="], "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], + "@types/connect": ["@types/connect@3.4.38", "", { "dependencies": { "@types/node": "*" } }, "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug=="], + "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="], "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], + "@types/express": ["@types/express@5.0.6", "", { "dependencies": { "@types/body-parser": "*", "@types/express-serve-static-core": "^5.0.0", "@types/serve-static": "^2" } }, "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA=="], + + "@types/express-serve-static-core": ["@types/express-serve-static-core@5.1.3", "", { "dependencies": { "@types/node": "*", "@types/qs": "*", "@types/range-parser": "*", "@types/send": "*" } }, "sha512-dPfW8NFiOF4wOHc7+N/QSxlY9cfSsenewGbAz8C8U/MULPd/YZ27LvJUIlzaXie7e6Ove9YunJGgC9tbHD2cKw=="], + "@types/fs-extra": ["@types/fs-extra@9.0.13", "", { "dependencies": { "@types/node": "*" } }, "sha512-nEnwB++1u5lVDM2UI4c1+5R+FYaKfaAzS4OococimjVm3nQw3TuzH5UNsocrcTBbhnerblyHj4A49qXbIiZdpA=="], "@types/http-cache-semantics": ["@types/http-cache-semantics@4.2.0", "", {}, "sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q=="], + "@types/http-errors": ["@types/http-errors@2.0.5", "", {}, "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg=="], + "@types/jsesc": ["@types/jsesc@2.5.1", "", {}, "sha512-9VN+6yxLOPLOav+7PwjZbxiID2bVaeq0ED4qSQmdQTdjnXJSaCVKTR58t15oqH1H5t8Ng2ZX1SabJVoN9Q34bw=="], "@types/keyv": ["@types/keyv@3.1.4", "", { "dependencies": { "@types/node": "*" } }, "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg=="], @@ -322,8 +340,16 @@ "@types/plist": ["@types/plist@3.0.5", "", { "dependencies": { "@types/node": "*", "xmlbuilder": ">=11.0.1" } }, "sha512-E6OCaRmAe4WDmWNsL/9RMqdkkzDCY1etutkflWk4c+AcjDU07Pcz1fQwTX0TQz+Pxqn9i4L1TU3UFpjnrcDgxA=="], + "@types/qs": ["@types/qs@6.15.1", "", {}, "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw=="], + + "@types/range-parser": ["@types/range-parser@1.2.7", "", {}, "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ=="], + "@types/responselike": ["@types/responselike@1.0.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw=="], + "@types/send": ["@types/send@1.2.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ=="], + + "@types/serve-static": ["@types/serve-static@2.2.0", "", { "dependencies": { "@types/http-errors": "*", "@types/node": "*" } }, "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ=="], + "@types/verror": ["@types/verror@1.10.11", "", {}, "sha512-RlDm9K7+o5stv0Co8i8ZRGxDbrTxhJtgjqjFyVh/tXQyl/rYtTKlnTvZ88oSTeYREWurwx20Js4kTuKCsFkUtg=="], "@types/whatwg-mimetype": ["@types/whatwg-mimetype@3.0.2", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="], @@ -350,11 +376,15 @@ "abbrev": ["abbrev@3.0.1", "", {}, "sha512-AO2ac6pjRB3SJmGJo+v5/aK6Omggp6fsLrs6wN9bd35ulu4cCwaAU9+7ZhXjeqHVkaHThLuzH0nZr0YpCDhygg=="], + "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], + "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], + "ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], + + "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], "aggregate-error": ["aggregate-error@3.1.0", "", { "dependencies": { "clean-stack": "^2.0.0", "indent-string": "^4.0.0" } }, "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA=="], - "ajv": ["ajv@6.14.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw=="], "ajv-keywords": ["ajv-keywords@3.5.2", "", { "peerDependencies": { "ajv": "^6.9.1" } }, "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ=="], @@ -402,6 +432,8 @@ "blake2": ["blake2@5.0.1", "", { "dependencies": { "nan": "^2.24.0" } }, "sha512-dIg2CknHyB854mKclXtxOx4QSrDLk5+z8IgO9t0NfZcfrUR6d5mNrh89cxn3wTiM2sKm7YkxcWsS+r9zf9sqig=="], + "body-parser": ["body-parser@2.3.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw=="], + "boolbase": ["boolbase@1.0.0", "", {}, "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww=="], "boolean": ["boolean@3.2.0", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="], @@ -422,6 +454,8 @@ "builder-util-runtime": ["builder-util-runtime@9.5.1", "", { "dependencies": { "debug": "^4.3.4", "sax": "^1.2.4" } }, "sha512-qt41tMfgHTllhResqM5DcnHyDIWNgzHvuY2jDcYP9iaGpkWxTUzV6GQjDeLnlR1/DtdlcsWQbA7sByMpmJFTLQ=="], + "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], + "cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="], "cacache": ["cacache@19.0.1", "", { "dependencies": { "@npmcli/fs": "^4.0.0", "fs-minipass": "^3.0.0", "glob": "^10.2.2", "lru-cache": "^10.0.1", "minipass": "^7.0.3", "minipass-collect": "^2.0.1", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "p-map": "^7.0.2", "ssri": "^12.0.0", "tar": "^7.4.3", "unique-filename": "^4.0.0" } }, "sha512-hdsUxulXCi5STId78vRVYEtDAjq99ICAUktLTeTYsLoTE6Z8dS0c8pWNCxwdrk9YfJeobDZc2Y186hD/5ZQgFQ=="], @@ -432,6 +466,8 @@ "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], + "call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="], + "caniuse-lite": ["caniuse-lite@1.0.30001787", "", {}, "sha512-mNcrMN9KeI68u7muanUpEejSLghOKlVhRqS/Za2IeyGllJ9I9otGpR9g3nsw7n4W378TE/LyIteA0+/FOZm4Kg=="], "chai": ["chai@5.3.3", "", { "dependencies": { "assertion-error": "^2.0.1", "check-error": "^2.1.1", "deep-eql": "^5.0.1", "loupe": "^3.1.0", "pathval": "^2.0.0" } }, "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw=="], @@ -472,10 +508,20 @@ "concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="], + "content-disposition": ["content-disposition@1.1.0", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="], + + "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="], + "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], + "cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="], + + "cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="], + "core-util-is": ["core-util-is@1.0.2", "", {}, "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ=="], + "cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="], + "crc": ["crc@3.8.0", "", { "dependencies": { "buffer": "^5.1.0" } }, "sha512-iX3mfgcTMIq3ZKLIsVFAbv7+Mc10kxabAGQb8HvjA1o3T1PIYprbakQ65d3I+2HGHt6nSKkM9PYjgoJO2KcFBQ=="], "cross-dirname": ["cross-dirname@0.1.0", "", {}, "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q=="], @@ -504,6 +550,8 @@ "delayed-stream": ["delayed-stream@1.0.0", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="], + "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], + "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], "detect-node": ["detect-node@2.1.0", "", {}, "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g=="], @@ -532,6 +580,8 @@ "eastasianwidth": ["eastasianwidth@0.2.0", "", {}, "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA=="], + "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], + "ejs": ["ejs@3.1.10", "", { "dependencies": { "jake": "^10.8.5" }, "bin": { "ejs": "bin/cli.js" } }, "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA=="], "electron": ["electron@40.6.0", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="], @@ -552,6 +602,8 @@ "empathic": ["empathic@2.0.0", "", {}, "sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA=="], + "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], + "encoding": ["encoding@0.1.13", "", { "dependencies": { "iconv-lite": "^0.6.2" } }, "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A=="], "end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="], @@ -578,14 +630,26 @@ "escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="], + "escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="], + "escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], "estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="], + "etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="], + + "eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="], + + "eventsource-parser": ["eventsource-parser@3.1.1", "", {}, "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ=="], + "expect-type": ["expect-type@1.3.0", "", {}, "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA=="], "exponential-backoff": ["exponential-backoff@3.1.3", "", {}, "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA=="], + "express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="], + + "express-rate-limit": ["express-rate-limit@8.7.0", "", { "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-hOwV7WOxXfjRpAM1DSJWZDXx3GhplwD8IfwuwvogD8i1Qnkgosw/H45s4ZnFAUHDAhPjlY9hLBvJhKmGMyY26g=="], + "extract-zip": ["extract-zip@2.0.1", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="], "extsprintf": ["extsprintf@1.4.1", "", {}, "sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA=="], @@ -594,18 +658,26 @@ "fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="], + "fast-uri": ["fast-uri@3.1.8", "", {}, "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg=="], + "fd-slicer": ["fd-slicer@1.1.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="], "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], "filelist": ["filelist@1.0.6", "", { "dependencies": { "minimatch": "^5.0.1" } }, "sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA=="], + "finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="], + "follow-redirects": ["follow-redirects@1.15.11", "", {}, "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="], "foreground-child": ["foreground-child@3.3.1", "", { "dependencies": { "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" } }, "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw=="], "form-data": ["form-data@4.0.5", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="], + "forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="], + + "fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="], + "fs-extra": ["fs-extra@10.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="], "fs-minipass": ["fs-minipass@3.0.3", "", { "dependencies": { "minipass": "^7.0.3" } }, "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw=="], @@ -654,12 +726,16 @@ "he": ["he@1.2.0", "", { "bin": { "he": "bin/he" } }, "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw=="], + "hono": ["hono@4.13.8", "", {}, "sha512-/Gng7NfoykZl2pjukW5Z6+8Yxm3BPRf86GTbQnt0SbySkvax4fyL4H3HhY1cCpBGmiW9XDRFzRV+CXK2W8QudQ=="], + "hookable": ["hookable@6.1.0", "", {}, "sha512-ZoKZSJgu8voGK2geJS+6YtYjvIzu9AOM/KZXsBxr83uhLL++e9pEv/dlgwgy3dvHg06kTz6JOh1hk3C8Ceiymw=="], "hosted-git-info": ["hosted-git-info@4.1.0", "", { "dependencies": { "lru-cache": "^6.0.0" } }, "sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA=="], "http-cache-semantics": ["http-cache-semantics@4.2.0", "", {}, "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ=="], + "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], + "http-proxy-agent": ["http-proxy-agent@7.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" } }, "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig=="], "http2-wrapper": ["http2-wrapper@1.0.3", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="], @@ -682,12 +758,16 @@ "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], - "ip-address": ["ip-address@10.1.0", "", {}, "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q=="], + "ip-address": ["ip-address@10.7.2", "", {}, "sha512-7H/2gFSIitxc0hG3nOI1glS8QLo/EHBFFLk8vEUjXY/xu0AdL8jZ9U1IzO2PUm0d2D/ofQcAifb0g6OBkt8U7w=="], + + "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="], "is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], "is-interactive": ["is-interactive@1.0.0", "", {}, "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w=="], + "is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="], + "is-unicode-supported": ["is-unicode-supported@0.1.0", "", {}, "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw=="], "isbinaryfile": ["isbinaryfile@5.0.7", "", {}, "sha512-gnWD14Jh3FzS3CPhF0AxNOJ8CxqeblPTADzI38r0wt8ZyQl5edpy75myt08EG2oKvpyiqSqsx+Wkz9vtkbTqYQ=="], @@ -702,6 +782,8 @@ "joi": ["joi@18.1.2", "", { "dependencies": { "@hapi/address": "^5.1.1", "@hapi/formula": "^3.0.2", "@hapi/hoek": "^11.0.7", "@hapi/pinpoint": "^2.0.1", "@hapi/tlds": "^1.1.1", "@hapi/topo": "^6.0.2", "@standard-schema/spec": "^1.1.0" } }, "sha512-rF5MAmps5esSlhCA+N1b6IYHDw9j/btzGaqfgie522jS02Ju/HXBxamlXVlKEHAxoMKQL77HWI8jlqWsFuekZA=="], + "jose": ["jose@6.2.12", "", {}, "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw=="], + "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], "js-yaml": ["js-yaml@4.1.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="], @@ -710,7 +792,9 @@ "json-buffer": ["json-buffer@3.0.1", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="], - "json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], + "json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], + + "json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="], "json-stringify-safe": ["json-stringify-safe@5.0.1", "", {}, "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA=="], @@ -746,11 +830,15 @@ "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], + "media-typer": ["media-typer@1.1.1", "", {}, "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ=="], + + "merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="], + "mime": ["mime@2.6.0", "", { "bin": { "mime": "cli.js" } }, "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg=="], - "mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], + "mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="], - "mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], + "mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="], "mimic-fn": ["mimic-fn@2.1.0", "", {}, "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="], @@ -802,10 +890,16 @@ "nth-check": ["nth-check@2.1.1", "", { "dependencies": { "boolbase": "^1.0.0" } }, "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w=="], + "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], + + "object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="], + "object-keys": ["object-keys@1.1.1", "", {}, "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA=="], "obug": ["obug@2.1.1", "", {}, "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ=="], + "on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="], + "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], "onetime": ["onetime@5.1.2", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="], @@ -820,12 +914,16 @@ "package-json-from-dist": ["package-json-from-dist@1.0.1", "", {}, "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw=="], + "parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="], + "path-is-absolute": ["path-is-absolute@1.0.1", "", {}, "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg=="], "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], "path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="], + "path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="], + "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], "pathval": ["pathval@2.0.1", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="], @@ -838,6 +936,8 @@ "picomatch": ["picomatch@4.0.4", "", {}, "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A=="], + "pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="], + "playwright": ["playwright@1.63.0", "", { "dependencies": { "playwright-core": "1.63.0" }, "bin": { "playwright": "cli.js" } }, "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg=="], "playwright-core": ["playwright-core@1.63.0", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg=="], @@ -858,22 +958,32 @@ "proper-lockfile": ["proper-lockfile@4.1.2", "", { "dependencies": { "graceful-fs": "^4.2.4", "retry": "^0.12.0", "signal-exit": "^3.0.2" } }, "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA=="], + "proxy-addr": ["proxy-addr@2.0.8", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="], + "proxy-from-env": ["proxy-from-env@2.1.0", "", {}, "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA=="], "pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="], "punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], + "qs": ["qs@6.16.0", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA=="], + "quansync": ["quansync@1.0.0", "", {}, "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA=="], "quick-lru": ["quick-lru@5.1.1", "", {}, "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA=="], + "range-parser": ["range-parser@1.3.0", "", {}, "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw=="], + + "raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="], + "read-binary-file-arch": ["read-binary-file-arch@1.0.6", "", { "dependencies": { "debug": "^4.3.4" }, "bin": { "read-binary-file-arch": "cli.js" } }, "sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg=="], "readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], "require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="], + "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], + "resedit": ["resedit@1.7.2", "", { "dependencies": { "pe-library": "^0.4.1" } }, "sha512-vHjcY2MlAITJhC0eRD/Vv8Vlgmu9Sd3LX9zZvtGzU5ZImdTN3+d6e/4mnTyV8vEbyf1sgNIrWxhWlrys52OkEA=="], "resolve-alpn": ["resolve-alpn@1.2.1", "", {}, "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g=="], @@ -896,6 +1006,8 @@ "rollup": ["rollup@4.60.1", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.60.1", "@rollup/rollup-android-arm64": "4.60.1", "@rollup/rollup-darwin-arm64": "4.60.1", "@rollup/rollup-darwin-x64": "4.60.1", "@rollup/rollup-freebsd-arm64": "4.60.1", "@rollup/rollup-freebsd-x64": "4.60.1", "@rollup/rollup-linux-arm-gnueabihf": "4.60.1", "@rollup/rollup-linux-arm-musleabihf": "4.60.1", "@rollup/rollup-linux-arm64-gnu": "4.60.1", "@rollup/rollup-linux-arm64-musl": "4.60.1", "@rollup/rollup-linux-loong64-gnu": "4.60.1", "@rollup/rollup-linux-loong64-musl": "4.60.1", "@rollup/rollup-linux-ppc64-gnu": "4.60.1", "@rollup/rollup-linux-ppc64-musl": "4.60.1", "@rollup/rollup-linux-riscv64-gnu": "4.60.1", "@rollup/rollup-linux-riscv64-musl": "4.60.1", "@rollup/rollup-linux-s390x-gnu": "4.60.1", "@rollup/rollup-linux-x64-gnu": "4.60.1", "@rollup/rollup-linux-x64-musl": "4.60.1", "@rollup/rollup-openbsd-x64": "4.60.1", "@rollup/rollup-openharmony-arm64": "4.60.1", "@rollup/rollup-win32-arm64-msvc": "4.60.1", "@rollup/rollup-win32-ia32-msvc": "4.60.1", "@rollup/rollup-win32-x64-gnu": "4.60.1", "@rollup/rollup-win32-x64-msvc": "4.60.1", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-VmtB2rFU/GroZ4oL8+ZqXgSA38O6GR8KSIvWmEFv63pQ0G6KaBH9s07PO8XTXP4vI+3UJUEypOfjkGfmSBBR0w=="], + "router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="], + "rxjs": ["rxjs@7.8.2", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="], "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], @@ -910,12 +1022,26 @@ "semver-compare": ["semver-compare@1.0.0", "", {}, "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow=="], + "send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="], + "serialize-error": ["serialize-error@7.0.1", "", { "dependencies": { "type-fest": "^0.13.1" } }, "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw=="], + "serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="], + + "setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="], + "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], + "side-channel": ["side-channel@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4", "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ=="], + + "side-channel-list": ["side-channel-list@1.0.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="], + + "side-channel-map": ["side-channel-map@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="], + + "side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="], + "siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="], "signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="], @@ -948,6 +1074,8 @@ "stat-mode": ["stat-mode@1.0.0", "", {}, "sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg=="], + "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="], + "std-env": ["std-env@3.10.0", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="], "string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], @@ -992,6 +1120,8 @@ "tmp-promise": ["tmp-promise@3.0.3", "", { "dependencies": { "tmp": "^0.2.0" } }, "sha512-RwM7MoPojPxsOBYnyd2hy0bxtIlVrihNs9pj5SUvY8Zz1sQcQG2tG1hSr8PDxfgEB8RNKDhqbIlroIarSNDNsQ=="], + "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="], + "tree-kill": ["tree-kill@1.2.2", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="], "truncate-utf8-bytes": ["truncate-utf8-bytes@1.0.2", "", { "dependencies": { "utf8-byte-length": "^1.0.1" } }, "sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ=="], @@ -1002,6 +1132,8 @@ "type-fest": ["type-fest@0.13.1", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="], + "type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="], + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], "unconfig-core": ["unconfig-core@7.5.0", "", { "dependencies": { "@quansync/fs": "^1.0.0", "quansync": "^1.0.0" } }, "sha512-Su3FauozOGP44ZmKdHy2oE6LPjk51M/TRRjHv2HNCWiDvfvCoxC2lno6jevMA91MYAdCdwP05QnWdWpSbncX/w=="], @@ -1014,6 +1146,8 @@ "universalify": ["universalify@2.0.1", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="], + "unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="], + "unrun": ["unrun@0.2.34", "", { "dependencies": { "rolldown": "1.0.0-rc.12" }, "peerDependencies": { "synckit": "^0.11.11" }, "optionalPeers": ["synckit"], "bin": { "unrun": "dist/cli.mjs" } }, "sha512-LyaghRBR++r7svhDK6tnDz2XaYHWdneBOA0jbS8wnRsHerI9MFljX4fIiTgbbNbEVzZ0C9P1OjWLLe1OqoaaEw=="], "update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="], @@ -1024,6 +1158,8 @@ "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], + "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], + "verror": ["verror@1.10.1", "", { "dependencies": { "assert-plus": "^1.0.0", "core-util-is": "1.0.2", "extsprintf": "^1.2.0" } }, "sha512-veufcmxri4e3XSrT0xwfUR7kguIkaxBeosDg00yDWhk49wdwkSUrvvsm7nc75e1PUyvIeZj6nS8VQRYz2/S4Xg=="], "vite": ["vite@7.3.2", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg=="], @@ -1068,6 +1204,10 @@ "zimmerframe": ["zimmerframe@1.1.4", "", {}, "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ=="], + "zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="], + + "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], + "@babel/code-frame/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.28.5", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="], "@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], @@ -1078,6 +1218,8 @@ "@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.28.5", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="], + "@develar/schema-utils/ajv": ["ajv@6.14.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw=="], + "@electron/asar/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], "@electron/fuses/fs-extra": ["fs-extra@9.1.0", "", { "dependencies": { "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ=="], @@ -1110,6 +1252,8 @@ "@vitest/mocker/estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], + "ajv-keywords/ajv": ["ajv@6.14.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw=="], + "app-builder-lib/@electron/get": ["@electron/get@3.1.0", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ=="], "app-builder-lib/ci-info": ["ci-info@4.3.1", "", {}, "sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA=="], @@ -1118,6 +1262,10 @@ "ast-kit/estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], + "body-parser/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "body-parser/iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], + "cacache/glob": ["glob@10.5.0", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^1.11.1" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg=="], "cacache/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], @@ -1128,6 +1276,7 @@ "dir-compare/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], + "dmg-license/ajv": ["ajv@6.14.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw=="], "dom-serializer/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="], "electron-winstaller/fs-extra": ["fs-extra@7.0.1", "", { "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw=="], @@ -1136,6 +1285,8 @@ "foreground-child/signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="], + "form-data/mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], + "glob/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], "hosted-git-info/lru-cache": ["lru-cache@6.0.0", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA=="], @@ -1152,22 +1303,30 @@ "postject/commander": ["commander@9.5.0", "", {}, "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ=="], + "raw-body/iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], + "rolldown-plugin-dts/@babel/generator": ["@babel/generator@8.0.0-rc.2", "", { "dependencies": { "@babel/parser": "^8.0.0-rc.2", "@babel/types": "^8.0.0-rc.2", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "@types/jsesc": "^2.5.0", "jsesc": "^3.0.2" } }, "sha512-oCQ1IKPwkzCeJzAPb7Fv8rQ9k5+1sG8mf2uoHiMInPYvkRfrDJxbTIbH51U+jstlkghus0vAi3EBvkfvEsYNLQ=="], "rolldown-plugin-dts/@babel/parser": ["@babel/parser@8.0.0-rc.2", "", { "dependencies": { "@babel/types": "^8.0.0-rc.2" }, "bin": "./bin/babel-parser.js" }, "sha512-29AhEtcq4x8Dp3T72qvUMZHx0OMXCj4Jy/TEReQa+KWLln524Cj1fWb3QFi0l/xSpptQBR6y9RNEXuxpFvwiUQ=="], "rolldown-plugin-dts/@babel/types": ["@babel/types@8.0.0-rc.2", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0-rc.2", "@babel/helper-validator-identifier": "^8.0.0-rc.2" } }, "sha512-91gAaWRznDwSX4E2tZ1YjBuIfnQVOFDCQ2r0Toby0gu4XEbyF623kXLMA8d4ZbCu+fINcrudkmEcwSUHgDDkNw=="], + "socks/ip-address": ["ip-address@10.1.0", "", {}, "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q=="], + "source-map-support/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], "strip-literal/js-tokens": ["js-tokens@9.0.1", "", {}, "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ=="], "tiny-async-pool/semver": ["semver@5.7.2", "", { "bin": { "semver": "bin/semver" } }, "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g=="], + "type-is/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + "unrun/rolldown": ["rolldown@1.0.0-rc.12", "", { "dependencies": { "@oxc-project/types": "=0.122.0", "@rolldown/pluginutils": "1.0.0-rc.12" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.0.0-rc.12", "@rolldown/binding-darwin-arm64": "1.0.0-rc.12", "@rolldown/binding-darwin-x64": "1.0.0-rc.12", "@rolldown/binding-freebsd-x64": "1.0.0-rc.12", "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.12", "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.12", "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.12", "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.12", "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.12", "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.12", "@rolldown/binding-linux-x64-musl": "1.0.0-rc.12", "@rolldown/binding-openharmony-arm64": "1.0.0-rc.12", "@rolldown/binding-wasm32-wasi": "1.0.0-rc.12", "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.12", "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.12" }, "bin": { "rolldown": "bin/cli.mjs" } }, "sha512-yP4USLIMYrwpPHEFB5JGH1uxhcslv6/hL0OyvTuY+3qlOSJvZ7ntYnoWpehBxufkgN0cvXxppuTu5hHa/zPh+A=="], "vitest/tinyexec": ["tinyexec@0.3.2", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="], + "@develar/schema-utils/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], + "@electron/asar/minimatch/brace-expansion": ["brace-expansion@1.1.14", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g=="], "@electron/get/fs-extra/jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="], @@ -1184,6 +1343,8 @@ "@prefresh/vite/@rollup/pluginutils/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], + "ajv-keywords/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], + "app-builder-lib/@electron/get/fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="], "app-builder-lib/@electron/get/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], @@ -1196,12 +1357,16 @@ "dir-compare/minimatch/brace-expansion": ["brace-expansion@1.1.14", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g=="], + "dmg-license/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], + "electron-winstaller/fs-extra/jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="], "electron-winstaller/fs-extra/universalify": ["universalify@0.1.2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="], "filelist/minimatch/brace-expansion": ["brace-expansion@2.1.0", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w=="], + "form-data/mime-types/mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], + "glob/minimatch/brace-expansion": ["brace-expansion@1.1.14", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g=="], "hosted-git-info/lru-cache/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 00000000..ac866ea9 --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,359 @@ +# AI agents (MCP) + +DiskHound can act as a local [Model Context Protocol](https://modelcontextprotocol.io) +server, so an AI agent such as Claude Code, Claude Desktop, or Codex can read your scans, run +scans, and steer the DiskHound window while it helps you free up space. The +window follows along: the agent opens folders, switches tabs, and its actions +show up in the header and in Settings. + +It is off by default. Nothing listens until you turn it on, only this +computer can connect, and every agent needs your approval in DiskHound. + +## Find it + +- **The header's agent button** (the small robot head, next to Settings). + It is always there. When nothing is set up, its popover explains the + feature and offers **Set upโ€ฆ**. When agents are on, a green dot shows + DiskHound is listening, an amber badge counts sign-ins waiting for you, and + for ten minutes after an agent acts the button becomes a pill naming it + (blue while it works, red when a call failed or was blocked). +- **The drive picker**: *Using Claude or Codex? Connect an AI agent โ€บ*. +- **The menus**: **Connect an AI Agentโ€ฆ** in the app menu, and **AI Agentsโ€ฆ** + in the tray menu. +- **Settings โ†’ AI Agents**, which the links above open. + +## Turn it on + +Settings โ†’ **AI Agents** โ†’ **Allow local AI agents**. DiskHound listens on +`http://127.0.0.1:51735/mcp`. That port is fixed, so an agent's saved +configuration keeps working after restarts. + +## Connect an agent + +**Connect an agent** in Settings starts with **Copy prompt for your agent**. +Paste it into Claude Code, Codex, or another agent: the agent adds DiskHound to +its own configuration and helps you approve it. DiskHound never writes another +app's configuration. + +Below that is a tab for each client: Claude Code, Claude Desktop (macOS and +Windows), Codex, and other MCP clients. Each tab has that client's prompt with +a Copy button, or for Claude Desktop an **Add to Claude** button, and the +command for doing it by hand behind a **Show** button. A last step shows the +connection live: waiting, waiting for your approval (with **Review**), or +connected, with the agent's last action. It then suggests a first thing to +ask. Once an agent is connected, the guide folds away under **Connect another +agent**. + +### Claude Code (stdio) + +Paste the Claude Code prompt into Claude Code in your terminal or IDE. On a +Mac with DiskHound in Applications it reads: + +```text +Add diskhound to my Claude Code user configuration using the stdio executable "/Applications/DiskHound.app/Contents/Resources/native/diskhound-mcp", with no arguments. Preserve my other MCP servers, then help me connect and approve access in DiskHound. +``` + +To do it yourself, **Show command** gives the command: + +```bash +claude mcp add --scope user --transport stdio diskhound -- '/Applications/DiskHound.app/Contents/Resources/native/diskhound-mcp' +``` + +`--scope user` makes DiskHound available in every directory. Code sessions in +the Claude app read this configuration too, but they also get Claude +Desktop's extension, so in the Claude app use the extension and not both. If +you already registered DiskHound as HTTP, +first run `claude mcp remove --scope user diskhound`, then add it again as +stdio. Start a new session, or run `/mcp` and reconnect diskhound. + +The small Rust helper translates stdio to DiskHound's loopback HTTP server and +handles OAuth itself, so you need no TLS certificate or public endpoint. It +answers the client's handshake at once and asks for your approval in the +background, so a client's connect timeout can't cut your decision short. +Until you approve, the agent sees only `diskhound_status`, which says it is +waiting; after that, the helper tells the client its tool list changed. + +On Windows use the PowerShell command in Settings. The helper is in +`resources/native/diskhound-mcp.exe` beside the installed app. Linux tarball +installs also include `resources/native/diskhound-mcp`. For an **AppImage**, copy +that executable from the running image to a stable location such as +`~/.local/bin/diskhound-mcp`, then use the copied path; temporary AppImage mount +paths change between launches. Replace the copy after an app update. + +### Claude Desktop (extension) + +Claude Desktop's custom connectors connect from Anthropic's servers, so they +can't reach a server on your computer, and its chat can't run commands. So +DiskHound comes to Claude as an extension, an +[MCP Bundle](https://github.com/modelcontextprotocol/mcpb) that holds the +stdio helper. + +Click **Add to Claude**. DiskHound builds the extension from its own helper +and opens it in Claude, which shows what it installs and asks you to confirm. +Click **Install** there; Claude doesn't need a restart. When Claude connects, +DiskHound asks you to approve **Claude Desktop**. The extension works in the +Claude app's chats and its Code sessions. To remove DiskHound, go to Claude's +Settings โ†’ Extensions. + +Claude Desktop loads an extension's tools once, when it connects, and ignores +later changes to the list. So the helper holds Claude's first tool list for up +to 45 seconds while you decide, and Claude gets the tools of the role you +grant. If you take longer, or change the role later, turn DiskHound off and on +in Claude's Settings โ†’ Extensions and start a new chat; `diskhound_status` +tells the agent to ask you. + +Claude passes an extension's tools on to its chats and Code sessions, but not +its resources or prompts, so agents there read DiskHound's skills with the +`diskhound_read_skill` tool. + +Claude runs its own copy of the helper. After you update DiskHound, click +**Add to Claude** again so Claude's copy matches. + +Claude Desktop isn't made for Linux, so DiskHound doesn't offer it there. + +### Codex (HTTP with OAuth) + +Paste the Codex prompt into Codex, or run the command behind **Show command**: + +```bash +codex mcp add diskhound --url http://127.0.0.1:51735/mcp --oauth-client-registration dcr +``` + +This works for the Codex CLI and the Codex app, which share their settings. +Codex opens a browser tab that says **Continue in DiskHound**; approve the +request in DiskHound. + +### Other clients + +Paste the prompt into your agent. To configure a client by hand, **Show +details** gives the URL and the helper command. Clients that support OAuth over +loopback HTTP connect to the URL above. Clients that launch local servers run +the helper, with `--port ` if you moved DiskHound off 51735. No bearer +token belongs in client configuration. Clients that require HTTPS should use +the helper. + +### Saved approvals + +The helper saves each client's approval in macOS Keychain, Windows Credential +Manager, or Linux Secret Service. Later connections from the same client (say, +Claude Code), OS account and port reuse that session; another client asks for +its own. Session roles and revocation remain in DiskHound. +If a credential store is unavailable, unlock it or explicitly add `--ephemeral` +to approve every connection without saving credentials. There is no plaintext +fallback. `diskhound-mcp --forget` removes the saved connections of Claude +Desktop, Claude Code, Codex, Cursor and VS Code locally; revoke their sessions in +Settings as well if you want to invalidate them. Any other client's saved +connection stays until you revoke its session in Settings; the helper then +drops it the next time that client connects. + +## Approving an agent + +DiskHound shows an approval sheet over its main window, naming the client +(Claude Code, Claude Desktop, Codex, or what the client calls itself) and +how it connects. You name the session and pick a role. If the sheet is +behind another app, the header button turns amber and **Review** in its +popover or in Settings brings it back. Several requests wait in line, one +sheet at a time. If the agent stops waiting (it timed out or quit), the sheet +says so and only Deny is left. Closing the sheet counts as Deny. Only +DiskHound's window can approve a request; browser pages and URL parameters +can't. + +![Approval sheet](screenshots/agent-consent.png) + +| Role | Can | +| --- | --- | +| Disk Explorer | Read drives, scan results, history, duplicates, and cleanup suggestions | +| Cleanup Guide (default) | Everything above, plus run scans and steer the DiskHound window | +| Cleanup Operator | Everything above, plus ask to move items to the Trash / Recycle Bin | +| Cleanup Admin | Everything above, plus ask to delete items permanently | + +Picking more than Cleanup Guide shows what the role adds, in red for +permanent delete. **What each permission allows** lists every permission. + +## Managing sessions + +Settings โ†’ **AI Agents** lists each approved session: the client, how it +connects (stdio or HTTP), when you approved it, what it may do, its last +action, and how many of its requests were blocked. From there you can: + +- **Change the role.** The next call uses it. The stdio helper reloads the + agent's tool list on its own, except in Claude Desktop, which needs + DiskHound turned off and on in its Settings โ†’ Extensions; an HTTP client + sees new tools after it reconnects. A role can only use the permissions the agent asked for at + sign-in. Claude Code, Claude Desktop, and Codex ask for all of them; if a + client asked for less, Settings says so and you can revoke and reconnect it. +- **Revoke** it. Its token stops working on the next call. **Forget revoked** + clears the list. +- See **Waiting for approval** (Review or Deny), **Blocked requests**, and + **Recent agent actions**. + +The header popover shows the same sessions, what each did last, and how many +requests were blocked today. + +## What agents can do + +| Tool | Does | +| --- | --- | +| `diskhound_status` | Drives, free space, scanned roots, running scans, what the window shows, and what this session may do. Agents start here. | +| `diskhound_read_skill` | DiskHound's cleanup and growth skills, for clients that can't read MCP resources | +| `diskhound_scan_summary` | Totals, largest files and folders, and file types for a scan | +| `diskhound_list_folder` | One folder's children by size (the Folders tab) | +| `diskhound_search_files` | Search the full scan index by path, extension, and minimum size | +| `diskhound_cleanup_suggestions` | Temp files, caches, old downloads, and other candidates | +| `diskhound_dev_artifacts` | `node_modules`, build output, package caches, venvs, and git worktrees, grouped by project. On APFS, what removing each tree frees, and a range for removing the listed trees together | +| `diskhound_measure_removal` | What removing a set of files and folders together frees, measured on disk now. Counts APFS clones and hardlinks once, including copies outside the set and outside any scan (macOS and Linux) | +| `diskhound_scan_history`, `diskhound_changes` | Past scans, and what grew or shrank between two of them | +| `diskhound_duplicates`, `diskhound_find_duplicates` | Duplicate groups, and starting a duplicate search | +| `diskhound_start_scan`, `diskhound_cancel_scan` | Scan a drive or folder | +| `diskhound_show`, `diskhound_reveal_path` | Point the window at a tab, drive, or folder; reveal an item in Finder or Explorer | +| `diskhound_move_to_trash` | Ask to move up to 20 items to the Trash (Cleanup Operator and Admin) | +| `diskhound_delete_permanently` | Ask to delete up to 20 items permanently (Cleanup Admin only) | + +A session sees only the tools its role grants. Calling one it doesn't have +changes nothing: the agent gets an error that says which permission is +missing and where you can grant it, and DiskHound logs the attempt (see +below). + +Most read tools take `showInApp: true` (for roles that may steer the window), +which moves the window to what the agent is looking at. + +`diskhound_measure_removal` walks the paths it's given and reads metadata +only. It answers when the walk is done: a few seconds for a handful of +projects, a minute or two for millions of files. If the agent's client stops +waiting first (Codex waits 60 seconds by default), DiskHound finishes the +walk anyway, and the same call made again within 5 minutes gets that result +without walking again. + +**You confirm every removal.** Both removal tools show a DiskHound +confirmation listing every item, its size, and the agent's reason; the +default button is Cancel. Nothing moves unless you click **Move to Trash**, +and nothing is deleted unless you click **Delete Permanently**. Protected +folders are always skipped, and so are drive roots, your home folder, its +standard folders (Documents, Downloads, Desktop, Library or AppData, and so +on), DiskHound itself, and any folder that contains one of these. The +confirmation lists what it left out and why. DiskHound checks the real +location on disk, so a different spelling or a symlink doesn't get around +this. + +![Trash confirmation](screenshots/agent-trash-confirm.png) + +## Blocked requests and the security log + +DiskHound records what agents tried and weren't allowed to do: a tool the +session's role doesn't grant, or a Trash or delete request that named a +protected folder. Each one shows as a red entry in the header and in +**Recent agent actions**, and a Trash or delete attempt also shows a +notification. Settings โ†’ AI Agents โ†’ **Blocked requests** lists them, with +repeats within a minute counted rather than listed again. + +They are kept in `agent-security.log` in DiskHound's data folder (NDJSON, +mode 0600), so they survive restarts; **Show file** reveals it. The log only +grows when an agent is refused. It writes at most 60 lines an hour, at least +five minutes apart after the first, and rotates at 256 KB. + +## Deferred tool discovery + +DiskHound publishes its tools through standard `tools/list`; they can be called +without a preceding list request. Its initialization instructions describe when +to discover them: disk usage, large files, duplicates, caches, cleanup, and growth. +Hosts can keep those definitions out of the model's initial context and load +them through their own tool search. [Claude Code does this automatically](https://code.claude.com/docs/en/mcp#scale-with-mcp-tool-search). + +Tool search is a client/host feature, not a required MCP server method. PwrAgent's +native tool catalog likewise adds its own `tool_search` and deferred-loading +flags; those are not advertised by its MCP adapter. DiskHound keeps its full +standard catalog available to clients without tool search, over either transport. + +## Cleanup procedures (skills) + +DiskHound ships two procedures that agents read before recommending anything: + +- **diskhound-free-up-space**: measure the gap, get a fresh scan, walk the + biggest folders, sweep developer caches and duplicates, and check whether + deleting something actually frees space. +- **diskhound-investigate-growth**: compare scans to explain what filled the + disk and when. + +The free-up-space skill has one reference per OS. They cover space that +deleting files does not give back: + +- **macOS**: APFS clones (for example pnpm's `node_modules`), which share + blocks, so the space only comes back when the last copy is gone. Time + Machine local snapshots, which keep deleted data until they expire. Purgeable + space, and the Trash. +- **Windows**: System Restore and Volume Shadow Copies, WSL and Docker + `.vhdx` disks that never shrink, hardlinks, and the Recycle Bin. +- **Linux**: hardlinks (pnpm stores) and reflinks, btrfs and ZFS snapshots, + files deleted but still open, and the systemd journal. + +The skills are served over MCP in two ways: + +- As Skills over MCP (SEP-2640, extension `io.modelcontextprotocol/skills`): + `skills/list`, `skills/get`, and `skill://` resources, with + `resources/directory/read`. This is for clients that support the + extension. +- As the prompts `free-up-space` and `investigate-growth`, for clients that + don't. Claude Code shows these as `/mcp__diskhound__free-up-space` and + `/mcp__diskhound__investigate-growth`. +- As the tool `diskhound_read_skill`, which returns the same text by + `skill://` URI. Claude Desktop passes only tools on to its chats and Code + sessions, so this is how agents there read them. + +The server's instructions and `diskhound_status` also point agents at the +`skill://` URIs. +The source lives in [`skills/`](../skills). + +## Security + +- The server binds `127.0.0.1` only. It rejects any other `Host` header, + non-loopback peers, and browser `Origin`s other than loopback. That blocks + DNS rebinding and cross-site requests from web pages. +- OAuth 2.1 with dynamic client registration, PKCE (S256), and a resource + indicator pinned to the MCP URL. Clients are public; there are no client + secrets. +- Approval happens only in DiskHound's own window. Browser pages and URL + parameters can't approve a request. +- Tokens are stored as SHA-256 hashes in `mcp-policy.json` in DiskHound's + data folder (mode 0600). They don't expire; revoke them in Settings. +- Every tool call checks the session against the policy file, so revoking a + session or changing its role applies immediately. +- Moving items to the Trash needs the Cleanup Operator or Admin role, and + deleting permanently needs Cleanup Admin. Either needs your confirmation in + a native dialog every time. If you revoke the session, change its role, or + turn AI Agents off while a request waits for its dialog, DiskHound drops + the request. +- A tool the session's role doesn't grant is left out of its tool list and + refused before it runs, and the attempt is logged. + +## Troubleshooting + +- **"Port 51735 is already in use"**: another program, or a second copy of + DiskHound, holds the port. Quit it, then toggle AI Agents off and on. +- **The agent says a permission is missing**: open Settings โ†’ AI Agents and + give that session a bigger role. The agent's next call picks it up. +- **Claude Desktop doesn't show DiskHound**: check Claude's Settings โ†’ + Extensions for DiskHound, and click **Add to Claude** again if it's missing. + If **Add to Claude** says it couldn't open Claude, click **Show file** and + open the extension with Claude. If DiskHound wasn't running with AI Agents + on, `diskhound_status` says so. Turn it on and ask again. +- **The approval sheet says the agent stopped waiting**: Deny it and + reconnect from the agent. With the stdio helper this rarely happens, + because the helper keeps waiting after the client's handshake. +- **The agent can't connect after you revoked it**: the stdio helper fails the + current connection and forgets that credential. Reconnect once more to request + approval, or repeat the HTTP client's OAuth login. Tool calls are never retried + automatically because their outcome may be unknown. +- **The stdio command cannot be found**: copy the command from Settings again + after moving the app. In a source checkout, run `bun run build:mcp:debug` first. +- **Secret Service unavailable on Linux**: run in a desktop session with an + unlocked credential store, or add `--ephemeral`. Headless sessions usually do + not have Secret Service. + +## Building the bridge + +`bun run build:mcp:debug` builds the development helper; `bun run build:mcp` +builds the release binary. `bun run dist` includes it automatically. Release CI +builds both macOS architectures and combines them into the universal app. +`cargo test --locked --manifest-path native/diskhound-mcp/Cargo.toml` tests the +transport and credential lifecycle; `e2e/stdio-agent.spec.ts` tests real native +approval and MCP calls using ephemeral credentials in an isolated profile. diff --git a/docs/screenshots/agent-consent.png b/docs/screenshots/agent-consent.png new file mode 100644 index 00000000..14a467fe Binary files /dev/null and b/docs/screenshots/agent-consent.png differ diff --git a/docs/screenshots/agent-trash-confirm.png b/docs/screenshots/agent-trash-confirm.png new file mode 100644 index 00000000..61656c07 Binary files /dev/null and b/docs/screenshots/agent-trash-confirm.png differ diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md index 6bbb7f42..88a87539 100644 --- a/e2e/AGENTS.md +++ b/e2e/AGENTS.md @@ -17,7 +17,7 @@ bun run test:e2e -- --grep restart # extra args go to playwright test too, because `electron` is in `trustedDependencies`. This step still runs `install.js` so a checkout that installed before that trust gets a binary. -2. It builds the debug scanner. +2. It builds the debug scanner and MCP stdio helper. 3. It builds the renderer. 4. It builds main. @@ -54,6 +54,13 @@ wrap the command in `xvfb-run --auto-servernum`. - **Folder dialog.** `dialog.showOpenDialog` is stubbed in main. `handle.setPickDirectory(dir)` sets what "Browse for folder..." returns. +- **Agent port.** Each launch sets `DISKHOUND_AGENT_PORT` to a free + port, so the MCP server never takes 51735 from a DiskHound the + developer runs with AI agents on. `handle.agentPort` is the port; + pass `launch({ agentPort })` to keep it across a restart. +- **Agent Trash.** `stubTrash(handle, dir)` answers the agent's Trash + confirmation with the button the spec picks, and moves items into + `dir` rather than the developer's real Trash or Recycle Bin. - **Scan tree.** The `scanTree` fixture writes five random-content files with known, distinct sizes under the test's output dir, not the OS temp dir. macOS temp resolves under `/private`, which is in @@ -78,6 +85,10 @@ wrap the command in `xvfb-run --auto-servernum`. run, even when the retry passes. - `fixtures/steps.ts` has the shared UI steps: `scanFolderFromPicker`, `waitForScanComplete` and `openTab`. +- `fixtures/agent.ts` plays an MCP agent. `signIn` runs the login + `claude mcp login` does: it registers, opens `/authorize`, answers the + real approval window, and exchanges the code for a token. + `connectAgent` returns an MCP SDK client for that token. - The Playwright page is named `page`, not `window`. Inside `page.evaluate(() => window.diskhound...)`, a variable named `window` would shadow the browser global for TypeScript. diff --git a/e2e/agents.spec.ts b/e2e/agents.spec.ts new file mode 100644 index 00000000..81b2ae18 --- /dev/null +++ b/e2e/agents.spec.ts @@ -0,0 +1,230 @@ +import { existsSync, readFileSync, rmSync, symlinkSync } from "node:fs"; +import { join } from "node:path"; + +import { + callTool, + connectAgent, + mcpStatus, + resultText, + signIn, + signInDenied, + stubTrash, + turnOnAgents, +} from "./fixtures/agent"; +import { expect, test } from "./fixtures/electron-app"; +import { openTab, scanFolderFromPicker, tab } from "./fixtures/steps"; + +// Keep the stub Trash out of the uploaded CI artifacts. +test.afterEach(({}, testInfo) => { + rmSync(testInfo.outputPath("trash"), { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); +}); + +test("an approved agent reads the scan and the window follows it", async ({ launch, scanTree }) => { + const handle = await launch(); + const { page } = handle; + await scanFolderFromPicker(handle, scanTree.root); + + await turnOnAgents(page); + const agent = await connectAgent(handle, await signIn(handle, { sessionName: "Follow-along" })); + + // The cleanup procedures load from the app's skills folder, as skill + // resources and as prompts for clients that don't read skills. + const skill = await agent.readResource({ uri: "skill://diskhound-free-up-space/SKILL.md" }); + expect(JSON.stringify(skill.contents)).toContain("Time Machine"); + const { prompts } = await agent.listPrompts(); + expect(prompts.map((prompt) => prompt.name)).toEqual( + expect.arrayContaining(["free-up-space", "investigate-growth"]), + ); + + const videos = join(scanTree.root, "videos"); + const listed = await callTool(agent, "diskhound_list_folder", { path: videos, showInApp: true, includeFiles: true }); + expect(listed.isError, resultText(listed)).not.toBe(true); + expect(listed.structuredContent).toMatchObject({ fileCount: 2 }); + + // The window opens the same folder, and the header names the session. + await expect(tab(page, "Folders")).toHaveClass(/\bactive\b/); + await expect(page.locator(".folder-crumb.active")).toHaveText("videos"); + await expect(page.locator(".agent-pill")).toHaveClass(/\bactive\b/); + await expect(page.locator(".agent-pill-name")).toHaveText("Follow-along"); + + // Exercise both sides of the responsive breakpoint independently of the + // runner's display size. Its initial native window may already be narrow. + const viewport = await page.evaluate(() => ({ width: innerWidth, height: innerHeight })); + await page.setViewportSize({ width: 1000, height: 720 }); + await expect.poll(() => page.evaluate(() => innerWidth)).toBe(1000); + await expect(page.locator(".agent-pill-name")).toBeHidden(); + await expect(page.locator(".agent-pill")).toHaveAccessibleName(/Follow-along/); + await page.setViewportSize({ width: 1280, height: 720 }); + await expect.poll(() => page.evaluate(() => innerWidth)).toBe(1280); + await expect(page.locator(".agent-pill-name")).toBeVisible(); + await page.setViewportSize(viewport); + + // The pill opens a popover with the session and what it did last. + await page.locator(".agent-pill").click(); + const popover = page.locator(".agent-pop"); + await expect(popover.locator(".agent-pop-row")).toHaveCount(1); + await expect(popover.locator(".agent-pop-name")).toHaveText("Follow-along"); + await expect(popover.locator(".agent-pop-what")).toContainText("videos"); + + // Its link opens Settings โ†’ AI Agents, which lists the session too. + await popover.getByRole("button", { name: "AI Agents settingsโ€ฆ" }).click(); + await expect(popover).toHaveCount(0); + const section = page.locator("#settings-ai-agents"); + await expect(section.locator(".agent-session-row")).toHaveCount(1); + await expect(section.locator(".agent-session-row .agent-session-title")).toHaveText("Follow-along"); + await expect(section.locator(".agent-session-row select")).toHaveValue("builtin.guide"); + await expect(section.locator(".agent-activity-row").first()).toContainText("Listed"); + await expect(section.locator(".agent-activity-row").first()).toContainText("videos"); + + await agent.close(); +}); + +test("only a Cleanup Operator can ask for the Trash, and the user decides", async ({ launch, scanTree }, testInfo) => { + const handle = await launch({ settings: { agents: { enabled: true } } }); + const { page } = handle; + await scanFolderFromPicker(handle, scanTree.root); + const trashDir = testInfo.outputPath("trash"); + const trash = await stubTrash(handle, trashDir); + const agent = await connectAgent(handle, await signIn(handle, { sessionName: "Tidy-up" })); + const docs = join(scanTree.root, "docs"); + const request = { paths: [docs], reason: "Old reports" }; + + // The approval window preselects Cleanup Guide, which doesn't list + // the Trash tool. Calling it anyway is refused and logged. + expect((await agent.listTools()).tools.map((tool) => tool.name)).not.toContain("diskhound_move_to_trash"); + const denied = await callTool(agent, "diskhound_move_to_trash", request); + expect(denied.isError).toBe(true); + expect(resultText(denied)).toContain("Cleanup Guide doesn't grant files.trash"); + expect(resultText(denied)).toContain("DiskHound logged the attempt"); + await expect(page.locator(".agent-pill")).toHaveClass(/\bfailed\b/); + await expect(page.locator(".toast-title", { hasText: "Blocked a request from Tidy-up" })).toBeVisible(); + + // The user raises the role in Settings. The next call uses it. + await openTab(page, "Settings"); + await expect(page.locator("#settings-ai-agents .agent-blocked-row").first()).toContainText("Tried to move items to the Trash"); + const role = page.locator("#settings-ai-agents .agent-session-row select"); + await role.selectOption("builtin.operator"); + await expect(role).toHaveValue("builtin.operator"); + + // The home folder is refused before any dialog. + const home = await handle.app.evaluate(({ app }) => app.getPath("home")); + const refused = await callTool(agent, "diskhound_move_to_trash", { paths: [home] }); + expect(refused.isError).toBe(true); + expect(resultText(refused)).toContain("never lets agents remove this folder"); + expect(await trash.prompts()).toHaveLength(0); + + // Cancel, the default button, moves nothing. + const declined = await callTool(agent, "diskhound_move_to_trash", request); + expect(resultText(declined)).toContain("The user declined"); + expect(existsSync(docs)).toBe(true); + const [prompt] = await trash.prompts(); + expect(prompt.message).toMatch(/^โ€œTidy-upโ€ wants to move 1 item \(\d[\d.]* [KM]B\) to the (Trash|Recycle Bin)\.$/); + expect(prompt.detail).toContain("Reason: Old reports"); + expect(prompt.detail).toContain("docs"); + + // Move to Trash moves it, and Folders keeps the row marked as trashed. + await trash.answer("move"); + const moved = await callTool(agent, "diskhound_move_to_trash", request); + expect(moved.isError, resultText(moved)).not.toBe(true); + expect(moved.structuredContent).toMatchObject({ confirmed: true, movedCount: 1 }); + expect(existsSync(docs)).toBe(false); + expect(existsSync(join(trashDir, "docs"))).toBe(true); + + await openTab(page, "Folders"); + await expect(page.locator(".folder-row.deleted", { hasText: "docs" }).locator(".deleted-path-badge")).toBeVisible(); + + await agent.close(); +}); + +test("only a Cleanup Admin can delete permanently, and every other attempt is logged", async ({ launch, scanTree }, testInfo) => { + const handle = await launch({ settings: { agents: { enabled: true } } }); + const { page } = handle; + await scanFolderFromPicker(handle, scanTree.root); + const trash = await stubTrash(handle, testInfo.outputPath("trash")); + const docs = join(scanTree.root, "docs"); + const request = { paths: [docs], reason: "Too big for the Trash" }; + + // A Cleanup Operator can ask for the Trash, but not for a permanent delete. + const operator = await connectAgent(handle, await signIn(handle, { sessionName: "Operator", roleId: "builtin.operator" })); + const operatorTools = (await operator.listTools()).tools.map((tool) => tool.name); + expect(operatorTools).toContain("diskhound_move_to_trash"); + expect(operatorTools).not.toContain("diskhound_delete_permanently"); + const refused = await callTool(operator, "diskhound_delete_permanently", request); + expect(refused.isError).toBe(true); + expect(resultText(refused)).toContain("Cleanup Operator doesn't grant files.delete"); + expect(await trash.prompts()).toHaveLength(0); + await openTab(page, "Settings"); + const section = page.locator("#settings-ai-agents"); + await expect(section.locator(".agent-blocked-row").first()).toContainText("Tried to delete items permanently"); + await expect(section.locator(".agent-session-row", { hasText: "Operator" }).locator(".agent-blocked-link")).toHaveText("1 blocked"); + // agent-security.log keeps it across restarts. + const log = join(handle.userDataDir, "agent-security.log"); + await expect.poll(() => (existsSync(log) ? readFileSync(log, "utf8") : "")).toContain("diskhound_delete_permanently"); + await operator.close(); + + // Cleanup Admin: the approval sheet warns what it adds, and the user + // still confirms the delete itself. + const admin = await connectAgent(handle, await signIn(handle, { sessionName: "Admin", roleId: "builtin.admin" })); + expect((await admin.listTools()).tools.map((tool) => tool.name)).toContain("diskhound_delete_permanently"); + const declined = await callTool(admin, "diskhound_delete_permanently", request); + expect(resultText(declined)).toBe("The user declined. Nothing was deleted."); + expect(existsSync(docs)).toBe(true); + const [prompt] = await trash.prompts(); + expect(prompt.message).toMatch(/^โ€œAdminโ€ wants to permanently delete 1 item \(\d[\d.]* [KM]B\)\.$/); + expect(prompt.detail).toContain("Deleted items can't be restored."); + + await trash.answer("move"); + const deleted = await callTool(admin, "diskhound_delete_permanently", request); + expect(deleted.isError, resultText(deleted)).not.toBe(true); + expect(deleted.structuredContent).toMatchObject({ confirmed: true, deletedCount: 1 }); + expect(existsSync(docs)).toBe(false); + expect(existsSync(join(testInfo.outputPath("trash"), "docs"))).toBe(false); + await admin.close(); +}); + +test("an approval survives a restart, and Revoke locks the agent out", async ({ launch }) => { + const first = await launch({ settings: { agents: { enabled: true } } }); + + // Deny sends the agent back with access_denied and approves nothing. + const deniedAt = await signInDenied(first, "Stranger"); + expect(deniedAt.searchParams.get("error")).toBe("access_denied"); + + const token = await signIn(first, { sessionName: "Keeper" }); + await first.close(); + + // Same profile and port: the server comes back on and the token works. + const second = await launch({ dataDir: first.dataDir, agentPort: first.agentPort }); + const agent = await connectAgent(second, token); + const status = await callTool(agent, "diskhound_status"); + expect(status.isError, resultText(status)).not.toBe(true); + + await openTab(second.page, "Settings"); + const section = second.page.locator("#settings-ai-agents"); + await expect(section.locator(".agent-session-row")).toHaveCount(1); + await section.locator(".agent-session-row", { hasText: "Keeper" }).getByRole("button", { name: "Revoke" }).click(); + await expect(section.locator(".agent-session-row")).toHaveCount(0); + await expect(section.locator(".agent-revoked")).toContainText("Keeper"); + + expect(await mcpStatus(second, token)).toBe(401); + await agent.close(); +}); + + +test("protected folders remain protected through symlinked ancestors", async ({ launch, scanTree }, testInfo) => { + const alias = join(scanTree.root, "alias"); + symlinkSync(scanTree.root, alias, process.platform === "win32" ? "junction" : "dir"); + const protectedPath = join(alias, "docs"); + const handle = await launch({ settings: { agents: { enabled: true }, scanning: { excludedFolderPaths: [protectedPath] } } }); + const trash = await stubTrash(handle, testInfo.outputPath("trash")); + await trash.answer("move"); + const agent = await connectAgent(handle, await signIn(handle, { roleId: "builtin.operator" })); + try { + for (const path of [protectedPath, join(scanTree.root, "docs"), scanTree.root]) { + const result = await callTool(agent, "diskhound_move_to_trash", { paths: [path] }); + expect(result.isError, resultText(result)).toBe(true); + expect(resultText(result)).toContain("Protected folder"); + } + expect(await trash.prompts()).toHaveLength(0); + expect(existsSync(join(scanTree.root, "docs"))).toBe(true); + } finally { await agent.close(); } +}); diff --git a/e2e/fixtures/agent.ts b/e2e/fixtures/agent.ts new file mode 100644 index 00000000..4637e2f1 --- /dev/null +++ b/e2e/fixtures/agent.ts @@ -0,0 +1,286 @@ +import { createHash, randomBytes } from "node:crypto"; + +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import type { Page } from "@playwright/test"; + +import { BUILT_IN_MCP_ROLES, MCP_AGENT_CAPABILITIES } from "../../src/shared/agentAccess"; +import { expect, type AppHandle } from "./electron-app"; +import { openTab } from "./steps"; + +/** Where a CLI agent's login listens. Nothing needs to: the spec reads + * the code from the 302 instead of following it. */ +const REDIRECT_URI = "http://127.0.0.1:47999/callback"; + +export function agentBaseUrl(handle: AppHandle): string { + return `http://127.0.0.1:${handle.agentPort}`; +} + +/** Wait for the MCP server. With agents seeded on, it starts after the + * main window, so it can lag the fixture's `.app-shell` wait. */ +export async function waitForAgentServer(handle: AppHandle): Promise { + const metadata = `${agentBaseUrl(handle)}/.well-known/oauth-authorization-server`; + await expect + .poll(() => fetch(metadata).then((response) => response.status, () => 0)) + .toBe(200); +} + +/** Settings โ†’ AI Agents, then flip "Allow local AI agents" on. */ +export async function turnOnAgents(page: Page): Promise { + await openTab(page, "Settings"); + const section = page.locator("#settings-ai-agents"); + await section.locator("label.toggle").click(); + await expect(section.locator(".agent-status-chip")).toHaveText("On"); +} + +type Authorization = { + /** The approval window DiskHound opened for this request. */ + approval: Page; + /** Poll the waiting page's status URL until the window has decided. */ + redirect: () => Promise; + clientId: string; + verifier: string; +}; + +/** + * Click Approve or Deny. DiskHound closes the window as soon as it has + * the decision, and on Windows that can land before the click returns, + * so a click cut short by the window closing is the expected outcome. + * The redirect still says what was decided. + */ +async function decide(approval: Page, button: "Approve" | "Deny"): Promise { + const closed = approval.waitForEvent("close"); + try { + await approval.getByRole("button", { name: button }).click(); + } catch (error) { + if (!approval.isClosed()) throw error; + } + await closed; +} + +/** + * The first half of `claude mcp login`: register the client, open + * /authorize, and catch the approval window it opens in DiskHound. + */ +async function authorize(handle: AppHandle, clientName: string): Promise { + await waitForAgentServer(handle); + const base = agentBaseUrl(handle); + const registered = await fetch(`${base}/register`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + client_name: clientName, + redirect_uris: [REDIRECT_URI], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code"], + response_types: ["code"], + }), + }); + expect(registered.status).toBe(201); + const { client_id: clientId } = (await registered.json()) as { client_id: string }; + + const verifier = randomBytes(32).toString("base64url"); + const url = new URL(`${base}/authorize`); + const params = { + response_type: "code", + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_challenge: createHash("sha256").update(verifier).digest("base64url"), + code_challenge_method: "S256", + state: "e2e", + resource: `${base}/mcp`, + scope: MCP_AGENT_CAPABILITIES.join(" "), + }; + for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value); + + const [approval, waiting] = await Promise.all([ + handle.app.waitForEvent("window", { + predicate: async (page) => { + await page.waitForLoadState("domcontentloaded"); + return /[?&]consent=1\b/.test(page.url()); + }, + }), + fetch(url, { redirect: "manual" }), + ]); + // The browser only gets an inert page that polls for the decision. + expect(waiting.status).toBe(200); + const id = /url=\/authorize\/status\?id=([A-Za-z0-9_-]+)/.exec(await waiting.text())?.[1]; + expect(id, "the waiting page names its status URL").toBeTruthy(); + + const redirect = async () => { + let location: string | null = null; + await expect + .poll(async () => { + const response = await fetch(`${base}/authorize/status?id=${id}`, { redirect: "manual" }); + location = response.headers.get("location"); + await response.body?.cancel(); + return response.status; + }) + .toBe(302); + return new URL(location!); + }; + + await expect(approval.locator(".agent-consent")).toContainText(clientName); + return { approval, redirect, clientId, verifier }; +} + +export type SignInOptions = { + clientName?: string; + /** Typed over the suggested name (the client's own) when set. */ + sessionName?: string; + /** Picked from the role cards. The window preselects Cleanup Guide. */ + roleId?: string; +}; + +/** + * The whole login an agent such as Claude Code runs, with the user's + * part played in DiskHound's approval window. Returns the bearer token. + */ +export async function signIn(handle: AppHandle, opts: SignInOptions = {}): Promise { + const clientName = opts.clientName ?? "E2E Agent"; + const { approval, redirect, clientId, verifier } = await authorize(handle, clientName); + + const name = approval.locator(".agent-consent-field input"); + await expect(name).toHaveValue(clientName); + if (opts.sessionName) await name.fill(opts.sessionName); + if (opts.roleId) { + const role = BUILT_IN_MCP_ROLES.find((candidate) => candidate.id === opts.roleId); + if (!role) throw new Error(`unknown role ${opts.roleId}`); + const card = approval.locator(".agent-role-card", { has: approval.locator(".agent-role-name", { hasText: role.name }) }); + await card.click(); + await expect(card).toHaveAttribute("aria-checked", "true"); + await expect(approval.getByRole("button", { name: `Approve as ${role.name}` })).toBeEnabled(); + // Anything past the default says what it adds; a delete says it can't be undone. + if (role.permissions.includes("files.delete")) { + await expect(approval.locator(".agent-consent-delta.destructive")).toContainText("can't be restored"); + } + } + await decide(approval, "Approve"); + + const callback = await redirect(); + expect(callback.searchParams.get("state")).toBe("e2e"); + const code = callback.searchParams.get("code"); + expect(code, `approval redirect ${callback.href}`).toBeTruthy(); + + const base = agentBaseUrl(handle); + const response = await fetch(`${base}/token`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code: code!, + code_verifier: verifier, + client_id: clientId, + redirect_uri: REDIRECT_URI, + resource: `${base}/mcp`, + }), + }); + expect(response.status).toBe(200); + return ((await response.json()) as { access_token: string }).access_token; +} + +/** Start a login and click Deny. Returns where the agent is sent. */ +export async function signInDenied(handle: AppHandle, clientName: string): Promise { + const { approval, redirect } = await authorize(handle, clientName); + await decide(approval, "Deny"); + return redirect(); +} + +export async function connectAgent(handle: AppHandle, token: string): Promise { + await waitForAgentServer(handle); + const transport = new StreamableHTTPClientTransport(new URL(`${agentBaseUrl(handle)}/mcp`), { + requestInit: { headers: { Authorization: `Bearer ${token}` } }, + }); + const client = new Client({ name: "diskhound-e2e", version: "1.0.0" }); + await client.connect(transport); + return client; +} + +export async function callTool( + client: Client, + name: string, + args: Record = {}, +): Promise { + return (await client.callTool({ name, arguments: args })) as CallToolResult; +} + +/** The first text block: the tool's one-paragraph summary or error. */ +export function resultText(result: CallToolResult): string { + const block = result.content[0]; + return block?.type === "text" ? block.text : ""; +} + +/** HTTP status of a bare MCP initialize with this token. */ +export async function mcpStatus(handle: AppHandle, token: string): Promise { + const response = await fetch(`${agentBaseUrl(handle)}/mcp`, { + method: "POST", + headers: { + authorization: `Bearer ${token}`, + "content-type": "application/json", + accept: "application/json, text/event-stream", + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "diskhound-e2e", version: "1" } }, + }), + }); + await response.body?.cancel(); + return response.status; +} + +export type TrashPrompt = { message: string; detail: string }; + +export type TrashStub = { + /** + * The button the next confirmations answer with. Starts as Cancel. + * "move" is the first button: Move to Trash, or Delete Permanently. + */ + answer: (button: "move" | "cancel") => Promise; + /** Every confirmation shown so far, oldest first. */ + prompts: () => Promise; +}; + +type StubbedDialog = { + __e2ePrompts: TrashPrompt[]; + __e2eResponse: number; + showMessageBox: (...args: unknown[]) => Promise<{ response: number; checkboxChecked: boolean }>; +}; + +/** + * Stub the agent's Trash confirmation and the Trash itself in main. + * `dialog.showMessageBox` records what it was asked and answers with + * the button the spec picked. `shell.trashItem` moves the item into + * `trashDir` instead of the developer's real Trash. + */ +export async function stubTrash(handle: AppHandle, trashDir: string): Promise { + await handle.app.evaluate(({ dialog, shell }, dir) => { + const fs = process.getBuiltinModule("node:fs"); + const path = process.getBuiltinModule("node:path"); + const stub = dialog as unknown as StubbedDialog; + stub.__e2ePrompts = []; + stub.__e2eResponse = 1; + stub.showMessageBox = async (...args) => { + // showMessageBox([window,] options) + const options = args.at(-1) as { message?: string; detail?: string }; + stub.__e2ePrompts.push({ message: options.message ?? "", detail: options.detail ?? "" }); + return { response: stub.__e2eResponse, checkboxChecked: false }; + }; + (shell as unknown as { trashItem: (target: string) => Promise }).trashItem = async (target) => { + fs.mkdirSync(dir, { recursive: true }); + fs.renameSync(target, path.join(dir, path.basename(target))); + }; + }, trashDir); + + return { + answer: async (button) => { + // Button 0 is "Move to Trash" (or "Delete Permanently"), 1 is "Cancel". + await handle.app.evaluate(({ dialog }, response) => { + (dialog as unknown as StubbedDialog).__e2eResponse = response; + }, button === "move" ? 0 : 1); + }, + prompts: () => handle.app.evaluate(({ dialog }) => (dialog as unknown as StubbedDialog).__e2ePrompts), + }; +} diff --git a/e2e/fixtures/electron-app.ts b/e2e/fixtures/electron-app.ts index 1f08742b..c14a68bc 100644 --- a/e2e/fixtures/electron-app.ts +++ b/e2e/fixtures/electron-app.ts @@ -1,5 +1,6 @@ import { spawnSync, type ChildProcess } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { createServer, type AddressInfo } from "node:net"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -34,6 +35,7 @@ export type SeedSettings = { monitoring?: Partial; notifications?: Partial; storage?: Partial; + agents?: Partial; }; /** @@ -51,6 +53,8 @@ export type LaunchOptions = { dataDir?: string; /** Merged over the E2E defaults. Only written to a fresh profile. */ settings?: SeedSettings; + /** Port for the AI agent (MCP) server. A free one when omitted. */ + agentPort?: number; }; export type AppHandle = { @@ -59,6 +63,8 @@ export type AppHandle = { /** Temp dir that holds this launch's userData (and HOME on Linux). */ dataDir: string; userDataDir: string; + /** Where the AI agent (MCP) server listens once it is turned on. */ + agentPort: number; /** Path the next "Browse for folder..." dialog returns. */ setPickDirectory: (dir: string | null) => Promise; /** Idempotent. The fixture also calls it after each test. Kills the @@ -111,9 +117,22 @@ function appEnv(extra: Record): Record { // A parent `bun run dev` would make main load its dev server. delete env.VITE_DEV_SERVER_URL; delete env.DISKHOUND_NATIVE_SCANNER_PATH; + delete env.DISKHOUND_AGENT_PORT; return { ...env, ...extra }; } +/** A loopback port nothing is listening on right now. */ +function freePort(): Promise { + return new Promise((resolve, reject) => { + const server = createServer(); + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + const { port } = server.address() as AddressInfo; + server.close(() => resolve(port)); + }); + }); +} + function writeSeedSettings(userDataDir: string, seed: SeedSettings = {}): void { const settings: SeedSettings = {}; for (const group of new Set([...Object.keys(E2E_SETTINGS), ...Object.keys(seed)])) { @@ -154,6 +173,8 @@ export async function launchApp( if (!existsSync(join(userDataDir, "settings.json"))) { writeSeedSettings(userDataDir, opts.settings); } + // Never 51735, which a DiskHound the developer runs may hold. + const agentPort = opts.agentPort ?? (await freePort()); const diagnostics: LaunchDiagnostics = { page: null, userDataDir, mainOutput: [], rendererConsole: [] }; let app: ElectronApplication | null = null; @@ -163,11 +184,12 @@ export async function launchApp( cwd: REPO_ROOT, env: appEnv({ DISKHOUND_NATIVE_SCANNER_PATH: scanner, + DISKHOUND_AGENT_PORT: String(agentPort), DISKHOUND_DISABLE_UPDATES: "1", ...(process.platform === "linux" ? { HOME: homeDir } : {}), }), }); - return await attach(app, dataDir, diagnostics); + return await attach(app, dataDir, diagnostics, agentPort); } catch (error) { // The fixture only learns about a launch that returns, so report and // clean up here. @@ -182,6 +204,7 @@ async function attach( app: ElectronApplication, dataDir: string, diagnostics: LaunchDiagnostics, + agentPort: number, ): Promise { const { userDataDir, mainOutput, rendererConsole } = diagnostics; app.process().stdout?.on("data", (chunk) => mainOutput.push(String(chunk))); @@ -213,6 +236,7 @@ async function attach( page, dataDir, userDataDir, + agentPort, setPickDirectory: async (dir) => { await app.evaluate(({ dialog }, pick) => { (dialog as unknown as { __e2ePick: string | null }).__e2ePick = pick; diff --git a/e2e/shared-storage.spec.ts b/e2e/shared-storage.spec.ts index 988ed2f5..11f12670 100644 --- a/e2e/shared-storage.spec.ts +++ b/e2e/shared-storage.spec.ts @@ -5,6 +5,7 @@ import { dirname, join } from "node:path"; import type { Locator, Page } from "@playwright/test"; +import { callTool, connectAgent, resultText, signIn, turnOnAgents } from "./fixtures/agent"; import { expect, test } from "./fixtures/electron-app"; import { openTab, scanFolderFromPicker } from "./fixtures/steps"; @@ -227,3 +228,56 @@ test.describe("APFS clones", () => { ); }); }); + +test("an agent measures what removing a set frees, counting shared blocks once", async ({ launch }, testInfo) => { + test.skip(process.platform === "win32", "Windows has no measure tool; its scans count each file once"); + // Two worktrees share a file with each other, and the second one also + // shares a file with a store outside the set. On macOS the shared + // files are APFS clones; elsewhere they are hardlinks. + const share = process.platform === "darwin" ? cloneFile : linkSync; + const root = testInfo.outputPath("tree"); + const one = join(root, "wt", "one"); + const two = join(root, "wt", "two"); + const store = join(root, "store"); + for (const dir of [one, two, store]) mkdirSync(dir, { recursive: true }); + writeFileSync(join(one, "shared.bin"), randomBytes(DATA_BYTES)); + share(join(one, "shared.bin"), join(two, "shared.bin")); + writeFileSync(join(one, "own.bin"), randomBytes(OTHER_BYTES)); + writeFileSync(join(store, "held.bin"), randomBytes(OTHER_BYTES)); + share(join(store, "held.bin"), join(two, "held.bin")); + + // No scan: the tool reads the disk as it is now. + const handle = await launch(); + await turnOnAgents(handle.page); + const agent = await connectAgent(handle, await signIn(handle, { sessionName: "Measure" })); + const gone = join(root, "gone"); + const nested = join(two, "held.bin"); + const result = await callTool(agent, "diskhound_measure_removal", { paths: [one, two, nested, gone] }); + expect(result.isError, resultText(result)).not.toBe(true); + // A hardlinked file takes its space once; each clone counts in full. + const sizeBytes = process.platform === "darwin" ? 2 * DATA_BYTES + 2 * OTHER_BYTES : DATA_BYTES + 2 * OTHER_BYTES; + expect(result.structuredContent).toMatchObject({ + total: { + files: 4, + sizeBytes, + freesBytes: DATA_BYTES + OTHER_BYTES, + freesOneAtATimeBytes: OTHER_BYTES, + heldElsewhereBytes: OTHER_BYTES, + uncertainBytes: 0, + }, + paths: [ + { path: one, kind: "folder", files: 2, freesAloneBytes: OTHER_BYTES, sharedBytes: DATA_BYTES }, + { path: two, kind: "folder", files: 2, freesAloneBytes: 0, sharedBytes: DATA_BYTES + OTHER_BYTES }, + ], + missing: [gone], + nested: [{ path: nested, within: two }], + }); + expect(resultText(result)).toContain("Removing these 2 items together frees"); + expect(resultText(result)).toContain(`Not found: ${gone}.`); + + // The same set, asked again in another order, comes from the walk + // that already finished. + const again = await callTool(agent, "diskhound_measure_removal", { paths: [gone, nested, two, one] }); + expect(again.structuredContent?.measuredAt).toBe(result.structuredContent?.measuredAt); + await agent.close(); +}); diff --git a/e2e/stdio-agent.spec.ts b/e2e/stdio-agent.spec.ts new file mode 100644 index 00000000..274d6955 --- /dev/null +++ b/e2e/stdio-agent.spec.ts @@ -0,0 +1,227 @@ +import { dirname, join } from "node:path"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"; +import { unzip } from "../src/test/zipReader"; +import { callTool, resultText, stubTrash, waitForAgentServer } from "./fixtures/agent"; +import { expect, test, type AppHandle } from "./fixtures/electron-app"; +import { openTab, scanFolderFromPicker } from "./fixtures/steps"; + +const executable = join(process.cwd(), "native", "diskhound-mcp", "target", "debug", process.platform === "win32" ? "diskhound-mcp.exe" : "diskhound-mcp"); + +interface ConnectOptions { + /** clientInfo.name: "claude-code", or Claude Desktop's extension name. */ + name?: string; + command?: string; + args?: string[]; + /** List tools right after connecting, before the user decides, as Claude Desktop does. */ + listEarly?: boolean; +} + +/** + * Connect through the helper. It answers initialize at once and asks the + * user in the background, so the decision lands after connect returns. + */ +async function connect(handle: AppHandle, decision: "Approve" | "Deny", options: ConnectOptions = {}) { + const { name = "claude-code", command = executable, args = ["--port", String(handle.agentPort)] } = options; + await waitForAgentServer(handle); + const client = new Client({ name, version: "0.1.0" }); + let toolsChanged = 0; + client.setNotificationHandler(ToolListChangedNotificationSchema, async () => { + toolsChanged += 1; + }); + // Never touch the developer's real OS credential store. + const transport = new StdioClientTransport({ command, args: ["--ephemeral", ...args], stderr: "pipe" }); + let diagnostics = ""; + transport.stderr?.on("data", (chunk) => { diagnostics += chunk.toString(); }); + const opened = handle.app.waitForEvent("window", { + predicate: async (page) => { + await page.waitForLoadState("domcontentloaded"); + return /[?&]consent=1\b/.test(page.url()); + }, + }); + // Catch now so an early failure doesn't become an unhandled rejection. + const connected = client.connect(transport).then(() => null, (error: Error) => error); + const listed = options.listEarly ? connected.then(() => client.listTools()) : null; + const approval = await opened; + const label = name === "claude-code" ? "Claude Code" : "Claude Desktop"; + await expect(approval.locator("h1")).toHaveText(`Approve ${label}?`); + await expect(approval.locator(".agent-consent-eyebrow")).toContainText("via stdio helper"); + const closed = approval.waitForEvent("close"); + try { await approval.getByRole("button", { name: decision }).click(); } + catch (error) { if (!approval.isClosed()) throw error; } + await closed; + return { client, transport, error: await connected, listed, diagnostics: () => diagnostics, toolsChanged: () => toolsChanged }; +} + +test("stdio approves natively, calls deferred tools, reads skills, and respects revocation", async ({ launch }) => { + const handle = await launch({ settings: { agents: { enabled: true } } }); + const agent = await connect(handle, "Approve"); + try { + expect(agent.error, agent.diagnostics()).toBeNull(); + // A host's search can load one tool without ever sending tools/list. + const status = await callTool(agent.client, "diskhound_status"); + expect(status.isError, resultText(status)).not.toBe(true); + expect(agent.client.getInstructions()).toContain("tool catalog"); + expect(agent.client.getInstructions()!.length).toBeLessThanOrEqual(2048); + const skill = await agent.client.readResource({ uri: "skill://diskhound-free-up-space/SKILL.md" }); + expect(JSON.stringify(skill.contents)).toContain("you decide what to keep or remove"); + // Cleanup Guide, the default, lists no tool that removes files. + const names = async () => (await agent.client.listTools()).tools.map((tool) => tool.name); + expect(await names()).not.toContain("diskhound_move_to_trash"); + await openTab(handle.page, "Settings"); + const section = handle.page.locator("#settings-ai-agents"); + const row = section.locator(".agent-session-row", { hasText: "Claude Code" }); + await expect(row.locator(".agent-via")).toHaveText("stdio"); + + // A bigger role reaches the agent without reconnecting: the helper + // sees the new permissions on its next call and reloads the tools. + await row.locator("select").selectOption("builtin.operator"); + await expect(handle.page.locator(".toast-body", { hasText: "reloads its tools on its own" })).toBeVisible(); + const changedBefore = agent.toolsChanged(); + expect((await callTool(agent.client, "diskhound_status")).isError).not.toBe(true); + await expect.poll(() => agent.toolsChanged()).toBeGreaterThan(changedBefore); + expect(await names()).toContain("diskhound_move_to_trash"); + + // The prompt for Claude Code, and the command behind it, name this helper. + await section.getByRole("button", { name: /^Connect another agent/ }).click(); + await section.locator(".agent-client-tabs button", { hasText: "Claude Code" }).click(); + await expect(section.locator(".agent-prompt-text")).toContainText("Add diskhound to my Claude Code user configuration"); + await expect(section.locator(".agent-prompt-text")).toContainText(executable); + await section.getByRole("button", { name: "Show command" }).click(); + await expect(section.locator(".agent-command-text", { hasText: "--transport stdio" })).toContainText(executable); + await section.getByRole("button", { name: "Revoke", exact: true }).click(); + await expect(section.locator(".agent-session-row")).toHaveCount(0); + await expect(callTool(agent.client, "diskhound_status")).rejects.toThrow(/revoked|closed/i); + expect(agent.diagnostics()).not.toContain("dhmcp_"); + } finally { await agent.client.close(); } +}); + +test("Add to Claude hands Claude an extension whose helper connects as Claude Desktop", async ({ launch }, testInfo) => { + test.skip(process.platform === "linux", "Claude Desktop isn't made for Linux"); + const handle = await launch({ settings: { agents: { enabled: true } } }); + // Claude would show its install dialog; keep the file instead. + await handle.app.evaluate(({ shell }) => { + const stub = shell as unknown as { openPath: (target: string) => Promise; __opened?: string }; + stub.openPath = async (target) => { + stub.__opened = target; + return ""; + }; + }); + await openTab(handle.page, "Settings"); + const section = handle.page.locator("#settings-ai-agents"); + await section.locator(".agent-client-tabs button", { hasText: "Claude Desktop" }).click(); + await section.getByRole("button", { name: "Add to Claude" }).click(); + await expect(section.locator(".agent-step-result")).toHaveText("Opened in Claude."); + const bundle = await handle.app.evaluate(({ shell }) => (shell as unknown as { __opened?: string }).__opened); + expect(bundle).toMatch(/DiskHound\.mcpb$/); + + // Install it the way Claude does: unpack, then run the manifest's command. + const installed = testInfo.outputPath("claude-extension"); + for (const entry of unzip(readFileSync(bundle!))) { + mkdirSync(dirname(join(installed, entry.name)), { recursive: true }); + writeFileSync(join(installed, entry.name), entry.data, { mode: entry.mode }); + } + const manifest = JSON.parse(readFileSync(join(installed, "manifest.json"), "utf8")); + expect(readFileSync(join(installed, manifest.server.entry_point)).equals(readFileSync(executable))).toBe(true); + // Claude Desktop lists tools once, right after connecting, and keeps + // that list: the helper holds it until the user decides. + const agent = await connect(handle, "Approve", { + name: "local-agent-mode-DiskHound", + command: manifest.server.mcp_config.command.replace("${__dirname}", installed), + args: manifest.server.mcp_config.args, + listEarly: true, + }); + try { + expect(agent.error, agent.diagnostics()).toBeNull(); + const listed = (await agent.listed!).tools.map((tool) => tool.name); + expect(listed).toContain("diskhound_list_folder"); + expect((await callTool(agent.client, "diskhound_status")).isError).not.toBe(true); + // Claude passes on only tools, so the skills have to come through one. + expect(listed).toContain("diskhound_read_skill"); + const skill = await callTool(agent.client, "diskhound_read_skill", { uri: "skill://diskhound-free-up-space/SKILL.md" }); + expect(skill.isError).not.toBe(true); + expect(resultText(skill)).toContain("# Free up disk space with DiskHound"); + // The guide recognizes Claude Desktop, so its last step stops waiting. + await expect(section.locator(".agent-session-row .agent-session-title")).toHaveText("Claude Desktop"); + await section.getByRole("button", { name: /^Connect another agent/ }).click(); + await section.locator(".agent-client-tabs button", { hasText: "Claude Desktop" }).click(); + await expect(section.locator(".agent-live.connected")).toContainText("Connected as Claude Desktop"); + } finally { await agent.client.close(); } +}); + +test("stdio denial fails the connection without exposing credentials", async ({ launch }) => { + const handle = await launch({ settings: { agents: { enabled: true } } }); + const agent = await connect(handle, "Deny"); + try { + // Connected before the user answered; the next call says no. + expect(agent.error, agent.diagnostics()).toBeNull(); + const status = await callTool(agent.client, "diskhound_status"); + expect(resultText(status)).toContain("The user denied this connection in DiskHound"); + expect(agent.diagnostics()).not.toContain("dhmcp_"); + await openTab(handle.page, "Settings"); + await expect(handle.page.locator("#settings-ai-agents .agent-session-row")).toHaveCount(0); + } finally { await agent.client.close(); } +}); + +test("stdio EOF exits while approval is pending, and withdraws it", async ({ launch }) => { + const handle = await launch({ settings: { agents: { enabled: true } } }); + await waitForAgentServer(handle); + const opened = handle.app.waitForEvent("window"); + const child = spawn(executable, ["--ephemeral", "--port", String(handle.agentPort)], { stdio: "pipe" }); + let stdout = ""; + child.stdout.on("data", (chunk) => { stdout += chunk.toString(); }); + child.stderr.resume(); + const exited = once(child, "exit"); + try { + child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "eof", version: "1" } } }) + "\n"); + const approval = await opened; + await expect(approval.locator(".agent-consent")).toBeVisible(); + // Hanging up withdraws the request, so its sheet closes by itself. + const sheetClosed = approval.waitForEvent("close"); + child.stdin.end(); + await expect.poll(() => child.exitCode).toBe(0); + await exited; + await sheetClosed; + // initialize was answered at once; nothing else was sent. + const lines = stdout.trim().split("\n"); + expect(lines).toHaveLength(1); + expect(JSON.parse(lines[0]!)).toMatchObject({ id: 1, result: { serverInfo: { name: "diskhound" } } }); + } finally { if (child.exitCode === null) child.kill(); } +}); + + +test("closing stdio cancels a pending Trash request", async ({ launch, scanTree }, testInfo) => { + const handle = await launch({ settings: { agents: { enabled: true } } }); + await scanFolderFromPicker(handle, scanTree.root); + const trashDir = testInfo.outputPath("stdio-trash"); + await stubTrash(handle, trashDir); + const agent = await connect(handle, "Approve"); + const target = join(scanTree.root, "docs"); + try { + expect(agent.error, agent.diagnostics()).toBeNull(); + await openTab(handle.page, "Settings"); + await handle.page.locator("#settings-ai-agents .agent-session-row select").selectOption("builtin.operator"); + await handle.app.evaluate(({ dialog }) => { + const stub = dialog as unknown as { showMessageBox: () => Promise; __release?: () => void }; + stub.showMessageBox = () => new Promise((resolve) => { + stub.__release = () => resolve({ response: 0, checkboxChecked: false }); + }); + }); + const pending = callTool(agent.client, "diskhound_move_to_trash", { paths: [target], reason: "Test disconnect" }).catch(() => null); + await expect.poll(() => handle.app.evaluate(({ dialog }) => typeof (dialog as unknown as { __release?: () => void }).__release)).toBe("function"); + await agent.client.close(); + await pending; + await handle.app.evaluate(({ dialog }) => { (dialog as unknown as { __release: () => void }).__release(); }); + // Wait for the tool to finish after its dialog resolves; the file must stay. + await expect.poll(() => handle.page.locator(".agent-activity-row").first().textContent()).toMatch(/cancel|disconnect|closed/i); + expect(existsSync(target)).toBe(true); + expect(existsSync(trashDir)).toBe(false); + } finally { + await agent.client.close(); + rmSync(trashDir, { recursive: true, force: true }); + } +}); diff --git a/electron-builder.yml b/electron-builder.yml index 59ee2504..00eca36f 100644 --- a/electron-builder.yml +++ b/electron-builder.yml @@ -17,6 +17,11 @@ extraResources: filter: - "diskhound-native-scanner" - "diskhound-native-scanner.exe" + - from: native/diskhound-mcp/target/release/ + to: native/ + filter: + - "diskhound-mcp" + - "diskhound-mcp.exe" - from: build/icon.png to: icon.png # Multi-size PNGs used at runtime to (a) build a multi-rep NativeImage @@ -29,6 +34,11 @@ extraResources: to: icons filter: - "*.png" + # MCP skills served to connected AI agents (Settings โ†’ AI Agents). + # Plain files under resources/skills/ so the catalog can hash and + # serve them without reaching into the asar. + - from: skills + to: skills asar: true # Native modules (.node binaries) must live OUTSIDE the asar archive diff --git a/native/diskhound-mcp/Cargo.lock b/native/diskhound-mcp/Cargo.lock new file mode 100644 index 00000000..8a9079e6 --- /dev/null +++ b/native/diskhound-mcp/Cargo.lock @@ -0,0 +1,2339 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-recursion" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + +[[package]] +name = "cc" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "dbus" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e" +dependencies = [ + "libc", + "libdbus-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "dbus-secret-service" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6" +dependencies = [ + "aes", + "block-padding", + "cbc", + "dbus", + "fastrand", + "hkdf", + "num", + "once_cell", + "openssl", + "sha2", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "diskhound-mcp" +version = "0.1.0" +dependencies = [ + "base64 0.22.1", + "dirs", + "fs2", + "getrandom 0.3.4", + "keyring", + "libc", + "reqwest", + "serde_json", + "sha2", + "tokio", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-sink", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "keyring" +version = "3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" +dependencies = [ + "byteorder", + "dbus-secret-service", + "log", + "openssl", + "secret-service", + "security-framework 2.11.1", + "security-framework 3.7.0", + "windows-sys 0.60.2", + "zeroize", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libdbus-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" +dependencies = [ + "cc", + "pkg-config", +] + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-src" +version = "300.6.1+3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846" +dependencies = [ + "cc", +] + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "openssl-src", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "secret-service" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4" +dependencies = [ + "aes", + "cbc", + "futures-util", + "generic-array", + "hkdf", + "num", + "once_cell", + "rand", + "serde", + "sha2", + "zbus", +] + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.15+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "xdg-home" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zbus" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725" +dependencies = [ + "async-broadcast", + "async-process", + "async-recursion", + "async-trait", + "enumflags2", + "event-listener", + "futures-core", + "futures-sink", + "futures-util", + "hex", + "nix", + "ordered-stream", + "rand", + "serde", + "serde_repr", + "sha1", + "static_assertions", + "tracing", + "uds_windows", + "windows-sys 0.52.0", + "xdg-home", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c" +dependencies = [ + "serde", + "static_assertions", + "zvariant", +] + +[[package]] +name = "zerocopy" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zvariant" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe" +dependencies = [ + "endi", + "enumflags2", + "serde", + "static_assertions", + "zvariant_derive", +] + +[[package]] +name = "zvariant_derive" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] diff --git a/native/diskhound-mcp/Cargo.toml b/native/diskhound-mcp/Cargo.toml new file mode 100644 index 00000000..0911dfde --- /dev/null +++ b/native/diskhound-mcp/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "diskhound-mcp" +version = "0.1.0" +edition = "2021" +rust-version = "1.88" +publish = false + +[dependencies] +base64 = "0.22" +fs2 = "0.4" +getrandom = "0.3" +dirs = "6" +libc = "0.2" +reqwest = { version = "0.12", default-features = false, features = ["json"] } +serde_json = "1" +sha2 = "0.10" +tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "net", "signal", "sync", "time"] } + +[target.'cfg(target_os = "macos")'.dependencies] +keyring = { version = "3.6.3", features = ["apple-native"] } +[target.'cfg(target_os = "windows")'.dependencies] +keyring = { version = "3.6.3", features = ["windows-native"] } +[target.'cfg(target_os = "linux")'.dependencies] +keyring = { version = "3.6.3", features = ["sync-secret-service", "crypto-rust", "vendored"] } + +[profile.release] +strip = true +lto = true +codegen-units = 1 diff --git a/native/diskhound-mcp/io-budgets.json b/native/diskhound-mcp/io-budgets.json new file mode 100644 index 00000000..27c5a652 --- /dev/null +++ b/native/diskhound-mcp/io-budgets.json @@ -0,0 +1,9 @@ +{ + "approval-reconnect-and-poll": { + "credentialReads": 102, + "credentialWrites": 1, + "credentialDeletes": 1, + "observedPayloadBytesWritten": 49, + "note": "One real OAuth approval (a read when the connection starts, and one more under the approval lock in case another connection was approved meanwhile), 100 reconnects and 1440 in-memory token checks per connection, then local forget. OS credential API calls are counted exactly; encrypted-store overhead is OS-owned and cannot be measured by Node measureFsIo. One new approval/day is 1 credential write and 0.000049 MB payload/day; 24 new approvals/day is 24 writes and 0.001176 MB/day, at both default and aggressive 1-minute monitoring. Reconnects and requests add zero writes. App-side registration/approval/read I/O is measured in src/mcp/__tests__/agentPersistence.ioBudget.test.ts. The zero-byte process-lock file is created once per port and client and never rewritten." + } +} diff --git a/native/diskhound-mcp/src/credentials.rs b/native/diskhound-mcp/src/credentials.rs new file mode 100644 index 00000000..a56ff9b9 --- /dev/null +++ b/native/diskhound-mcp/src/credentials.rs @@ -0,0 +1,190 @@ +//! Only the OS credential store holds bearer tokens. The file is a process lock. +use crate::Result; +use std::{ + fs::{self, File, OpenOptions}, + path::PathBuf, + time::{Duration, Instant}, +}; + +const UNAVAILABLE: &str = "Unlock your OS credential store (Keychain, Credential Manager, or Secret Service), or use --ephemeral to approve each connection without saving credentials."; +const SERVICE: &str = "com.diskhound.mcp.stdio.v1"; + +/// Clients the helper names (see `client_label`), whose approvals `--forget` removes. +pub const KNOWN_CLIENTS: [&str; 5] = [ + "Claude Desktop", + "Claude Code", + "Codex", + "Cursor", + "VS Code", +]; + +#[derive(Clone)] +pub struct Credentials { + entry: std::sync::Arc, + directory: PathBuf, + /// The OS store's accounts start with this. None for a test store, whose entry is fixed. + origin: Option, + /// Names this client's lock file. None for the port's. + client: Option, +} +impl Credentials { + #[cfg(test)] + pub fn for_test(entry: keyring::Entry, directory: PathBuf) -> Self { + Self { + entry: std::sync::Arc::new(entry), + directory, + origin: None, + client: None, + } + } + + /// The port's store. Its own entry is the one connection saved before + /// approvals were per client; `--forget` removes it. + pub fn new(origin: &str) -> Result { + let directory = dirs::data_local_dir() + .ok_or(UNAVAILABLE)? + .join("DiskHound") + .join("mcp-bridge-locks"); + Ok(Self { + entry: std::sync::Arc::new( + keyring::Entry::new(SERVICE, origin).map_err(|_| UNAVAILABLE)?, + ), + directory, + origin: Some(origin.to_owned()), + client: None, + }) + } + + /// One client's saved approval and lock. Each agent gets its own + /// DiskHound session, so approving Claude Code never lets Claude + /// Desktop in, and one client's pending approval never blocks another's. + pub fn for_client(&self, client: &str) -> Result { + let entry = match &self.origin { + Some(origin) => std::sync::Arc::new( + keyring::Entry::new(SERVICE, &account(origin, client)).map_err(|_| UNAVAILABLE)?, + ), + None => self.entry.clone(), + }; + Ok(Self { + entry, + directory: self.directory.clone(), + origin: self.origin.clone(), + client: Some(lock_key(client)), + }) + } + + pub async fn lock(&self, port: u16) -> Result { + #[cfg(unix)] + { + use std::os::unix::fs::{DirBuilderExt, MetadataExt}; + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(&self.directory) + .map_err(|_| UNAVAILABLE)?; + let info = fs::symlink_metadata(&self.directory).map_err(|_| UNAVAILABLE)?; + if !info.is_dir() + || info.uid() != unsafe { libc::geteuid() } + || info.mode() & 0o777 != 0o700 + { + return Err("Unsafe bridge lock directory"); + } + } + #[cfg(windows)] + { + fs::create_dir_all(&self.directory).map_err(|_| UNAVAILABLE)?; + if fs::symlink_metadata(&self.directory) + .map_err(|_| UNAVAILABLE)? + .file_type() + .is_symlink() + { + return Err("Unsafe bridge lock directory"); + } + } + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC); + } + let file = options + .open(self.directory.join(match &self.client { + Some(key) => format!("{port}-{key}.lock"), + None => format!("{port}.lock"), + })) + .map_err(|_| UNAVAILABLE)?; + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let info = file.metadata().map_err(|_| UNAVAILABLE)?; + if !info.is_file() + || info.uid() != unsafe { libc::geteuid() } + || info.mode() & 0o777 != 0o600 + || info.nlink() != 1 + { + return Err("Unsafe bridge lock file"); + } + } + let deadline = Instant::now() + Duration::from_secs(130); + loop { + match fs2::FileExt::try_lock_exclusive(&file) { + Ok(()) => return Ok(file), + Err(e) if e.raw_os_error() == fs2::lock_contended_error().raw_os_error() && Instant::now() < deadline => + tokio::time::sleep(Duration::from_millis(100)).await, + _ => return Err("Another connection is awaiting approval. Finish it in DiskHound and reconnect."), + } + } + } + // Keychain / Secret Service may prompt or block. Keep stdin closure and + // signals responsive while the OS owns that work. + pub async fn load(&self) -> Result> { + let entry = self.entry.clone(); + tokio::task::spawn_blocking(move || match entry.get_password() { + Ok(token) if valid_token(&token) => Ok(Some(token)), + Ok(_) => Err("Invalid saved credential; run diskhound-mcp --forget and reconnect."), + Err(keyring::Error::NoEntry) => Ok(None), + Err(_) => Err(UNAVAILABLE), + }) + .await + .map_err(|_| UNAVAILABLE)? + } + pub async fn save(&self, token: &str) -> Result<()> { + let entry = self.entry.clone(); + let token = token.to_owned(); + tokio::task::spawn_blocking(move || entry.set_password(&token).map_err(|_| UNAVAILABLE)) + .await + .map_err(|_| UNAVAILABLE)? + } + pub async fn clear(&self) -> Result<()> { + let entry = self.entry.clone(); + tokio::task::spawn_blocking(move || match entry.delete_credential() { + Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), + Err(_) => Err(UNAVAILABLE), + }) + .await + .map_err(|_| UNAVAILABLE)? + } +} +/// The OS store account for one client's approval on one port. +pub fn account(origin: &str, client: &str) -> String { + format!("{origin}#{client}") +} +/// A file-name-safe key for a client name (FNV-1a). +fn lock_key(client: &str) -> String { + let hash = client + .bytes() + .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3) + }); + format!("{hash:016x}") +} +pub fn valid_token(token: &str) -> bool { + token.starts_with("dhmcp_") + && token.len() == 49 + && token[6..] + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') +} diff --git a/native/diskhound-mcp/src/main.rs b/native/diskhound-mcp/src/main.rs new file mode 100644 index 00000000..d23ddac5 --- /dev/null +++ b/native/diskhound-mcp/src/main.rs @@ -0,0 +1,971 @@ +//! Local stdio โ†” loopback Streamable HTTP bridge. DiskHound owns consent and tools. +mod credentials; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use credentials::Credentials; +use reqwest::{redirect::Policy, Client, Response, Url}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::{ + io::Write, + time::{Duration, Instant}, +}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt}; + +type Result = std::result::Result; +const INPUT_LIMIT: usize = 1024 * 1024; +const RESPONSE_LIMIT: usize = 16 * 1024 * 1024; +const DEFAULT_PORT: u16 = 51735; +const UNAVAILABLE: &str = "Keep DiskHound open with Settings > AI Agents enabled. Transport failed; an operation's outcome may be unknown. Check status before retrying."; +const REVOKED: &str = + "This connection was revoked. Reconnect to request fresh approval in DiskHound."; + +#[derive(Debug, PartialEq)] +struct Options { + port: u16, + ephemeral: bool, + forget: bool, +} +fn options(args: impl Iterator) -> Result { + let mut args = args; + let mut options = Options { + port: DEFAULT_PORT, + ephemeral: false, + forget: false, + }; + while let Some(arg) = args.next() { + match arg.as_str() { + "--port" => { + options.port = args + .next() + .and_then(|v| v.parse().ok()) + .filter(|p| *p != 0) + .ok_or("Invalid loopback port")? + } + "--ephemeral" => options.ephemeral = true, + "--forget" => options.forget = true, + _ => return Err("Usage: diskhound-mcp [--port PORT] [--ephemeral | --forget]"), + } + } + if options.forget && options.ephemeral { + return Err("--forget and --ephemeral cannot be combined"); + } + Ok(options) +} +fn random() -> Result { + let mut bytes = [0; 32]; + getrandom::fill(&mut bytes).map_err(|_| "System randomness unavailable")?; + Ok(URL_SAFE_NO_PAD.encode(bytes)) +} +fn field(value: &Value, name: &str) -> Result { + value[name] + .as_str() + .filter(|v| !v.is_empty()) + .map(str::to_owned) + .ok_or("Invalid DiskHound response") +} +async fn bytes(mut response: Response, limit: usize) -> Result> { + let mut data = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|_| UNAVAILABLE)? { + if data.len() + chunk.len() > limit { + return Err("DiskHound response too large"); + } + data.extend_from_slice(&chunk); + } + Ok(data) +} +async fn body(response: Response) -> Result { + serde_json::from_slice(&bytes(response, RESPONSE_LIMIT).await?) + .map_err(|_| "Invalid DiskHound response") +} +fn pending_id(html: &str) -> Result<&str> { + let id = html + .split("/authorize/status?id=") + .nth(1) + .and_then(|s| s.split('"').next()) + .ok_or("Invalid approval response")?; + if id.len() != 43 + || !id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') + { + return Err("Invalid approval response"); + } + Ok(id) +} +fn callback_code(location: &str, redirect: &str, state: &str) -> Result { + let destination = Url::parse(location).map_err(|_| "Invalid OAuth callback")?; + let mut expected = Url::parse(redirect).map_err(|_| "Invalid OAuth callback")?; + expected.set_query(destination.query()); + if destination != expected { + return Err("OAuth callback mismatch"); + } + let pairs: Vec<_> = destination.query_pairs().collect(); + if pairs.iter().filter(|(k, _)| k == "state").count() != 1 + || !pairs.iter().any(|(k, v)| k == "state" && v == state) + { + return Err("OAuth state mismatch"); + } + if pairs.iter().any(|(k, _)| k == "error") { + return Err(DENIED); + } + let codes: Vec<_> = pairs.iter().filter(|(k, _)| k == "code").collect(); + if codes.len() != 1 || codes[0].1.is_empty() { + return Err("Invalid OAuth code"); + } + Ok(codes[0].1.to_string()) +} +/// Known MCP client ids (clientInfo.name) and the names users know them by. +/// Claude Desktop names an extension's connection `local-agent-mode-`. +fn client_label(info: &Value) -> String { + let name = info["name"].as_str().unwrap_or("").trim(); + let title = info["title"].as_str().unwrap_or("").trim(); + let lower = name.to_ascii_lowercase(); + let known = match lower.as_str() { + "claude-ai" => Some("Claude Desktop"), + n if n.starts_with("local-agent-mode-") => Some("Claude Desktop"), + "claude-code" => Some("Claude Code"), + n if n.starts_with("codex") => Some("Codex"), + n if n.contains("cursor") => Some("Cursor"), + "visual studio code" | "vscode" => Some("VS Code"), + _ => None, + }; + let label = known + .map(str::to_owned) + .or_else(|| (!title.is_empty()).then(|| title.to_owned())) + .or_else(|| (!name.is_empty()).then(|| name.to_owned())) + .unwrap_or_else(|| "MCP client".into()); + label.chars().filter(|c| !c.is_control()).take(60).collect() +} + +/// Claude Desktop reads a server's tool list once, when it connects, and +/// keeps it: it ignores `tools/list_changed`. (Its extensions connect as +/// `local-agent-mode-`; `claude-ai` was its name before them.) +fn lists_tools_once(info: &Value) -> bool { + let name = info["name"] + .as_str() + .unwrap_or("") + .trim() + .to_ascii_lowercase(); + name == "claude-ai" || name.starts_with("local-agent-mode-") +} + +/// Versions DiskHound's server speaks; the helper echoes the client's if it's one of these. +const PROTOCOL_VERSIONS: [&str; 4] = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]; +/// A health check (`claude mcp list`) connects and hangs up at once. Wait +/// this long before opening DiskHound's approval sheet, so it doesn't pop +/// up for a client that is already gone. +const APPROVAL_DELAY: Duration = Duration::from_millis(1500); +/// How long a tool call waits for the user before answering "still waiting". +const APPROVAL_WAIT: Duration = Duration::from_secs(30); +/// How long Claude Desktop's first `tools/list` waits for the user. It gives +/// up on a request after 60 s (the MCP SDK's default). +const LIST_WAIT: Duration = Duration::from_secs(45); +const NOT_DISKHOUND: &str = "Something other than DiskHound is listening on DiskHound's port. Ask the user to quit that program and keep DiskHound open with Settings > AI Agents turned on, then call diskhound_status again."; +const OFFLINE: &str = "DiskHound isn't reachable. Ask the user to open DiskHound and turn on Settings > AI Agents > Allow local AI agents, then call diskhound_status again."; +const DENIED: &str = + "The user denied this connection in DiskHound. Reconnect this MCP server to ask again."; +const EXPIRED: &str = + "The approval request expired before the user answered. Call diskhound_status to ask again."; +const PENDING: &str = "DiskHound is waiting for the user to approve this connection in the DiskHound window. Ask them to approve it there, then call diskhound_status again."; +const RECONNECT_FOR_TOOLS: &str = "Claude Desktop loads DiskHound's tools only when it connects, and it connected before this session had its current role, so some of DiskHound's tools may be missing. Ask the user to turn DiskHound off and on in Claude's Settings > Extensions, then start a new chat."; +const INSTRUCTIONS: &str = "DiskHound is a disk-space analyzer on the user's computer: disk usage, large files, duplicates, caches, cleanup, and disk growth. This connection is waiting for the user to approve it in the DiskHound window; call diskhound_status to check. Once it is approved, DiskHound's other tools appear (the tool list changes). If tools are deferred, search your host's tool catalog for DiskHound. Start with diskhound_status, and read skill://diskhound-free-up-space/SKILL.md before recommending deletions."; +/// Response header with the session's permissions; a change means its role changed. +const CAPABILITIES_HEADER: &str = "DiskHound-Capabilities"; + +#[derive(Clone, Debug, PartialEq)] +enum Approval { + Pending, + Approved(String), + Failed(&'static str), +} + +/// The id of the approval DiskHound is showing for this process, while +/// it waits. Shared with the approval task so exit can withdraw it. +type PendingApproval = std::sync::Arc>>; + +/// Clears the pending id once the approval task stops waiting. +struct PendingGuard<'a>(&'a PendingApproval); +impl Drop for PendingGuard<'_> { + fn drop(&mut self) { + if let Ok(mut id) = self.0.lock() { + *id = None; + } + } +} + +struct Bridge { + http: Client, + origin: String, + port: u16, + token: Option, + credentials: Option, + version: String, + /// What the client called itself in `initialize`; names the approval. + client_name: String, + /// DiskHound (not another app) answered on the port. + verified: bool, + /// The background approval, once started. + approval: Option>, + /// When to start the approval if nothing asks for it sooner. + approval_due: Option, + /// The approval's outcome was applied and announced. + approval_applied: bool, + /// Why there's no approval: the user denied it, it expired, or + /// DiskHound isn't reachable. Only a denial is final. + failed: Option<&'static str>, + capabilities: Option, + capabilities_changed: bool, + /// The approval DiskHound is showing, while the user decides. + pending: PendingApproval, + /// The client keeps the tool list it got when it connected (Claude Desktop). + lists_once: bool, + /// ...and that list no longer matches the session's role. + stale_list: bool, +} + +/// Register, open DiskHound's approval, and wait for the user. Holds the +/// per-port lock so parallel connections share one approval. +async fn obtain_token( + http: &Client, + origin: &str, + port: u16, + credentials: Option<&Credentials>, + client_name: &str, + pending: &PendingApproval, +) -> Result { + if let Some(store) = credentials { + let _lock = store.lock(port).await?; + // Another connection may have been approved while this one waited. + if let Some(token) = store.load().await? { + return Ok(token); + } + let token = authenticate(http, origin, client_name, pending).await?; + store.save(&token).await?; + Ok(token) + } else { + authenticate(http, origin, client_name, pending).await + } +} + +async fn authenticate( + http: &Client, + origin: &str, + client_name: &str, + pending: &PendingApproval, +) -> Result { + // Reserve the callback port but consume the validated redirect locally; + // no browser URL or bearer credential crosses stdout to the MCP client. + let callback = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .map_err(|_| "Cannot reserve OAuth callback")?; + let redirect = format!( + "http://127.0.0.1:{}/callback", + callback + .local_addr() + .map_err(|_| "Cannot reserve OAuth callback")? + .port() + ); + let response = http.post(format!("{origin}/register")).json(&json!({ + "client_name": client_name, "redirect_uris": [redirect], "token_endpoint_auth_method": "none", + "grant_types": ["authorization_code"], "response_types": ["code"], + "software_id": "diskhound-mcp", "software_version": env!("CARGO_PKG_VERSION") + })).send().await.map_err(|_| UNAVAILABLE)?; + if !response.status().is_success() { + return Err("DiskHound refused registration"); + } + let client = field(&body(response).await?, "client_id")?; + let verifier = random()?; + let state = random()?; + let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); + let resource = format!("{origin}/mcp"); + let response = http + .get(format!("{origin}/authorize")) + .query(&[ + ("client_id", client.as_str()), + ("redirect_uri", &redirect), + ("response_type", "code"), + ("code_challenge_method", "S256"), + ("code_challenge", &challenge), + ("state", &state), + ("resource", &resource), + ( + "scope", + "disk.read scan.run app.navigate files.trash files.delete", + ), + ]) + .send() + .await + .map_err(|_| UNAVAILABLE)?; + if response.status().as_u16() != 200 { + return Err("DiskHound refused authorization"); + } + let html = String::from_utf8(bytes(response, 65536).await?) + .map_err(|_| "Invalid approval response")?; + let id = pending_id(&html)?; + if let Ok(mut shown) = pending.lock() { + *shown = Some(id.to_owned()); + } + let _shown = PendingGuard(pending); + eprintln!("Approve this connection in the DiskHound window. Choose the role you want this agent to have."); + // DiskHound's own approval expires after 5 minutes. + let deadline = Instant::now() + Duration::from_secs(300); + while Instant::now() < deadline { + let response = http + .get(format!("{origin}/authorize/status")) + .query(&[("id", id)]) + .send() + .await + .map_err(|_| UNAVAILABLE)?; + match response.status().as_u16() { + 200 => { + tokio::time::sleep(Duration::from_millis(500)).await; + } + 302 => { + let location = response + .headers() + .get("Location") + .and_then(|h| h.to_str().ok()) + .ok_or("Invalid OAuth callback")?; + let code = callback_code(location, &redirect, &state)?; + let response = http + .post(format!("{origin}/token")) + .form(&[ + ("grant_type", "authorization_code"), + ("client_id", &client), + ("redirect_uri", &redirect), + ("code_verifier", &verifier), + ("code", &code), + ("resource", &resource), + ]) + .send() + .await + .map_err(|_| UNAVAILABLE)?; + if !response.status().is_success() { + return Err("DiskHound refused the authorization code"); + } + let token = field(&body(response).await?, "access_token")?; + if !credentials::valid_token(&token) { + return Err("Invalid DiskHound token"); + } + return Ok(token); + } + _ => return Err(EXPIRED), + } + } + Err(EXPIRED) +} + +fn result(id: &Value, result: Value) -> Value { + json!({"jsonrpc":"2.0", "id":id, "result":result}) +} +fn notification(method: &str) -> Value { + json!({"jsonrpc":"2.0", "method":method}) +} +fn tool_text(text: &str) -> Value { + json!({"content":[{"type":"text","text":text}], "isError":true}) +} +/// Until the user approves, the only tool: it says approval is pending, +/// and turns into the real diskhound_status once it isn't. +fn placeholder_tools() -> Value { + json!({"tools":[{ + "name":"diskhound_status", + "title":"DiskHound status", + "description":"Start here. Until the user approves this connection in DiskHound, this reports that approval is pending; afterwards it returns drives, scans, and what this session may do. DiskHound's other tools appear once the connection is approved.", + "inputSchema":{"type":"object","properties":{}}, + "annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false} + }]}) +} + +impl Bridge { + fn new(http: Client, origin: String, port: u16, credentials: Option) -> Self { + Bridge { + http, + origin, + port, + token: None, + credentials, + version: "2025-03-26".into(), + client_name: "MCP client".into(), + verified: false, + approval: None, + approval_due: None, + approval_applied: false, + failed: None, + capabilities: None, + capabilities_changed: false, + pending: PendingApproval::default(), + lists_once: false, + stale_list: false, + } + } + + /// Make sure DiskHound owns the port before sending it a token or a login. + async fn verify(&mut self) -> Result<()> { + if self.verified { + return Ok(()); + } + let response = self + .http + .get(format!( + "{}/.well-known/oauth-protected-resource/mcp", + self.origin + )) + .send() + .await + .map_err(|_| UNAVAILABLE)?; + if !response.status().is_success() { + return Err(NOT_DISKHOUND); + } + let metadata = body(response).await.map_err(|_| NOT_DISKHOUND)?; + if metadata["resource_name"] != "DiskHound" + || metadata["resource"] != format!("{}/mcp", self.origin) + { + return Err(NOT_DISKHOUND); + } + self.verified = true; + Ok(()) + } + + async fn load_saved(&mut self) -> Result<()> { + if self.token.is_none() { + if let Some(store) = &self.credentials { + self.token = store.load().await?; + } + } + Ok(()) + } + + /// Load the saved approval, or get one now. Used by `--login`-style + /// callers and tests; connections use the non-blocking path. + #[cfg(test)] + async fn ensure_token(&mut self) -> Result<()> { + self.load_saved().await?; + if self.token.is_none() { + let token = obtain_token( + &self.http, + &self.origin, + self.port, + self.credentials.as_ref(), + &self.client_name, + &self.pending, + ) + .await?; + self.token = Some(token); + } + Ok(()) + } + + fn start_approval(&mut self) { + self.approval_due = None; + if self.approval.is_some() { + return; + } + let (sender, receiver) = tokio::sync::watch::channel(Approval::Pending); + self.approval = Some(receiver); + let http = self.http.clone(); + let origin = self.origin.clone(); + let port = self.port; + let credentials = self.credentials.clone(); + let name = self.client_name.clone(); + let pending = self.pending.clone(); + tokio::spawn(async move { + let outcome = + match obtain_token(&http, &origin, port, credentials.as_ref(), &name, &pending) + .await + { + Ok(token) => Approval::Approved(token), + Err(reason) => Approval::Failed(reason), + }; + let _ = sender.send(outcome); + }); + } + + /// Apply a finished approval once; returns the notifications that tell + /// the client to reload DiskHound's lists. + fn apply_approval(&mut self) -> Vec { + if self.approval_applied { + return Vec::new(); + } + let Some(receiver) = &self.approval else { + return Vec::new(); + }; + let state = receiver.borrow().clone(); + match state { + Approval::Pending => Vec::new(), + Approval::Approved(token) => { + self.approval_applied = true; + self.token = Some(token); + eprintln!("diskhound-mcp: approved in DiskHound"); + vec![ + notification("notifications/tools/list_changed"), + notification("notifications/resources/list_changed"), + notification("notifications/prompts/list_changed"), + ] + } + Approval::Failed(reason) => { + self.approval_applied = true; + self.failed = Some(reason); + eprintln!("diskhound-mcp: {reason}"); + vec![notification("notifications/tools/list_changed")] + } + } + } + + /// Wait (bounded) for the user to decide, for a request made early. + async fn wait_for_approval(&mut self, limit: Duration) { + if self.approval.is_none() { + self.start_approval(); + } + if let Some(receiver) = &mut self.approval { + let _ = tokio::time::timeout( + limit, + receiver.wait_for(|state| *state != Approval::Pending), + ) + .await; + } + } + + /// Before an early tool call: find DiskHound again if it wasn't + /// reachable, and ask again unless the user said no. + async fn retry(&mut self) { + if self.failed == Some(DENIED) { + return; + } + if let Err(reason) = self.verify().await { + self.failed = Some(if reason == NOT_DISKHOUND { + NOT_DISKHOUND + } else { + OFFLINE + }); + return; + } + if self.failed.is_some() { + // Reachable again, or the last request expired: start over. + self.failed = None; + self.approval = None; + self.approval_applied = false; + } + if self.load_saved().await.is_ok() && self.token.is_some() { + return; + } + self.wait_for_approval(APPROVAL_WAIT).await; + } + + /// Handle one client message. Returns the reply (if any) and + /// notifications to send after it. + async fn handle(&mut self, message: &Value) -> Result<(Option, Vec)> { + let method = message["method"].as_str().unwrap_or(""); + let id = message.get("id"); + if method == "initialize" { + self.client_name = client_label(&message["params"]["clientInfo"]); + self.lists_once = lists_tools_once(&message["params"]["clientInfo"]); + if let Some(store) = &self.credentials { + self.credentials = Some(store.for_client(&self.client_name)?); + } + match self.verify().await { + Ok(()) => { + self.load_saved().await?; + if self.token.is_some() { + match self.forward(message).await { + Err(REVOKED) => {} // A stale saved approval: ask again below. + other => return other.map(|reply| (reply, Vec::new())), + } + } + self.approval_due = Some(Instant::now() + APPROVAL_DELAY); + } + // Connect anyway: diskhound_status tells the agent what to ask the user. + Err(reason) => { + self.failed = Some(if reason == NOT_DISKHOUND { + NOT_DISKHOUND + } else { + OFFLINE + }); + } + } + // No approval yet. Answer now and ask the user in the background, + // so a client's connect timeout can't cut the user's decision short. + let requested = message["params"]["protocolVersion"].as_str().unwrap_or(""); + self.version = PROTOCOL_VERSIONS + .iter() + .find(|v| **v == requested) + .unwrap_or(&"2025-06-18") + .to_string(); + let reply = id.map(|id| { + result( + id, + json!({ + "protocolVersion": self.version, + "capabilities": {"tools":{"listChanged":true},"resources":{"listChanged":true},"prompts":{"listChanged":true}}, + "serverInfo": {"name":"diskhound","title":"DiskHound","version":env!("CARGO_PKG_VERSION")}, + "instructions": INSTRUCTIONS + }), + ) + }); + return Ok((reply, Vec::new())); + } + let mut notes = self.apply_approval(); + if self.token.is_none() && method == "tools/call" { + self.retry().await; + notes.extend(self.apply_approval()); + } + // Claude Desktop keeps its first tool list, so hold it until the + // user decides: then it lists the tools of the role they grant. + if self.token.is_none() + && method == "tools/list" + && self.lists_once + && self.failed.is_none() + { + self.wait_for_approval(LIST_WAIT).await; + notes.extend(self.apply_approval()); + } + if self.token.is_some() { + let mut reply = self.forward(message).await?; + let changed = self.take_capability_change(); + self.stale_list |= self.lists_once && !changed.is_empty(); + notes.extend(changed); + if self.stale_list + && method == "tools/call" + && message["params"]["name"] == "diskhound_status" + { + if let Some(content) = reply + .as_mut() + .and_then(|reply| reply["result"]["content"].as_array_mut()) + { + content.push(json!({"type":"text","text":RECONNECT_FOR_TOOLS})); + } + } + return Ok((reply, notes)); + } + let Some(id) = id else { + return Ok((None, notes)); // notifications need no approval + }; + // Listing is what a health check (`claude mcp list`) does before + // it hangs up, so only a tool call or staying connected past + // APPROVAL_DELAY asks the user. + let reply = match method { + "ping" => result(id, json!({})), + "tools/list" => { + self.stale_list |= self.lists_once; + result(id, placeholder_tools()) + } + "tools/call" => result(id, tool_text(self.failed.unwrap_or(PENDING))), + "resources/list" => result(id, json!({"resources":[]})), + "resources/templates/list" => result(id, json!({"resourceTemplates":[]})), + "prompts/list" => result(id, json!({"prompts":[]})), + _ => error(id.clone(), -32000, self.failed.unwrap_or(PENDING)), + }; + Ok((Some(reply), notes)) + } + + /// A changed permissions header means the user changed this session's + /// role: tell the client to reload the tool list. + fn take_capability_change(&mut self) -> Vec { + if !std::mem::take(&mut self.capabilities_changed) { + return Vec::new(); + } + eprintln!("diskhound-mcp: this session's role changed; tool list updated"); + vec![notification("notifications/tools/list_changed")] + } + + /// The client hung up while DiskHound was still asking the user: + /// withdraw the request so its approval sheet closes. + async fn withdraw_pending(&self) { + let id = self.pending.lock().ok().and_then(|id| id.clone()); + let Some(id) = id else { return }; + let request = self + .http + .post(format!("{}/authorize/cancel", self.origin)) + .form(&[("id", id.as_str())]) + .send(); + let _ = tokio::time::timeout(Duration::from_secs(1), request).await; + } + + async fn forward(&mut self, message: &Value) -> Result> { + self.verify().await?; + let response = self + .http + .post(format!("{}/mcp", self.origin)) + .bearer_auth(self.token.as_ref().ok_or("Missing approval")?) + .header("Accept", "application/json, text/event-stream") + .header("MCP-Protocol-Version", &self.version) + .json(message) + .send() + .await + .map_err(|_| { + // Something else may hold the port next time; check again. + self.verified = false; + UNAVAILABLE + })?; + if response.status().as_u16() == 401 { + // Never retry a tool call, or silently regain a revoked permission. + // Keep this process denied; only a new connection may ask again. + if let Some(store) = &self.credentials { + let _lock = store.lock(self.port).await?; + // Another process may already have approved a new session. + if store.load().await? == self.token { + store.clear().await?; + } + } + self.token = None; + return Err(REVOKED); + } + if let Some(granted) = response + .headers() + .get(CAPABILITIES_HEADER) + .and_then(|h| h.to_str().ok()) + { + let granted = granted.to_owned(); + if self + .capabilities + .as_deref() + .is_some_and(|seen| seen != granted) + { + self.capabilities_changed = true; + } + self.capabilities = Some(granted); + } + if response.status().as_u16() == 202 && message.get("id").is_none() { + return Ok(None); + } + let status = response.status(); + let value = body(response).await?; + if value["jsonrpc"] != "2.0" + || value.get("id") != message.get("id") + || (value.get("result").is_some() == value.get("error").is_some()) + { + return Err("Invalid MCP response from DiskHound"); + } + if !status.is_success() && value.get("error").is_none() { + return Err("DiskHound rejected the request"); + } + if message["method"] == "initialize" { + if let Some(version) = value["result"]["protocolVersion"].as_str() { + self.version = version.to_owned(); + } + } + Ok(Some(value)) + } +} +fn error(id: Value, code: i32, message: &str) -> Value { + json!({"jsonrpc":"2.0", "id":id, "error":{"code":code,"message":message}}) +} +async fn run() -> Result<()> { + if std::env::args() + .nth(1) + .is_some_and(|arg| arg == "--help" || arg == "-h") + { + eprintln!("DiskHound MCP stdio bridge\nUsage: diskhound-mcp [--port PORT] [--ephemeral | --forget]\nKeep DiskHound open with Settings > AI Agents enabled.\nCredentials use the OS store. --ephemeral saves none; --forget removes the saved connections of {}. Revoke any other client's session in DiskHound.\nAll diagnostics go to stderr; stdout is reserved for MCP JSON.", credentials::KNOWN_CLIENTS.join(", ")); + return Ok(()); + } + let options = options(std::env::args().skip(1))?; + let origin = format!("http://127.0.0.1:{}", options.port); + let credentials = if options.ephemeral { + None + } else { + Some(Credentials::new(&origin)?) + }; + if options.forget { + let store = credentials.as_ref().ok_or("Missing credential store")?; + for client in credentials::KNOWN_CLIENTS { + let saved = store.for_client(client)?; + let _lock = saved.lock(options.port).await?; + saved.clear().await?; + } + let _lock = store.lock(options.port).await?; + store.clear().await?; + // The OS store can't list entries, so other clients' approvals stay + // until their sessions are revoked (the helper drops a revoked token). + eprintln!( + "Forgot the saved connections of {}. Revoke their sessions in DiskHound to invalidate them, and revoke any other client's session there too.", + credentials::KNOWN_CLIENTS.join(", ") + ); + return Ok(()); + } + let http = Client::builder() + .no_proxy() + .redirect(Policy::none()) + .connect_timeout(Duration::from_secs(2)) + .timeout(Duration::from_secs(180)) + .build() + .map_err(|_| UNAVAILABLE)?; + let mut bridge = Bridge::new(http, origin, options.port, credentials); + let (tx, mut rx) = tokio::sync::mpsc::channel(16); + let (closed, mut eof) = tokio::sync::watch::channel(false); + tokio::spawn(async move { + let mut input = tokio::io::BufReader::new(tokio::io::stdin()); + loop { + let mut line = Vec::new(); + match (&mut input) + .take((INPUT_LIMIT + 1) as u64) + .read_until(b'\n', &mut line) + .await + { + Ok(0) | Err(_) => break, + Ok(_) if line.len() > INPUT_LIMIT => { + eprintln!("diskhound-mcp: MCP input exceeds 1 MiB"); + break; + } + Ok(_) => { + if tx.try_send(line).is_err() { + eprintln!("diskhound-mcp: input queue full or closed; reconnect"); + break; + } + } + } + } + let _ = closed.send(true); + }); + // Whatever ends the session (EOF, a closed stdout, an error), a + // request still waiting in DiskHound is withdrawn on the way out. + let outcome: Result<()> = async { + loop { + let due = bridge.approval_due; + let line = tokio::select! { + _ = tokio::signal::ctrl_c() => break, + line = rx.recv() => match line { Some(line) => line, None => break }, + _ = async { + match due { + Some(at) => tokio::time::sleep_until(at.into()).await, + None => std::future::pending::<()>().await, + } + } => { + bridge.start_approval(); + continue; + } + _ = async { + match bridge.approval.as_mut() { + Some(receiver) if !bridge.approval_applied => { let _ = receiver.changed().await; } + _ => std::future::pending::<()>().await, + } + } => { + for note in bridge.apply_approval() { + output(¬e)?; + } + continue; + } + }; + let message: Value = match serde_json::from_slice(&line) { + Ok(message) => message, + Err(_) => { + output(&error(Value::Null, -32700, "Invalid JSON"))?; + continue; + } + }; + if !message.is_object() + || message["jsonrpc"] != "2.0" + || !message["method"].is_string() + || message + .get("id") + .is_some_and(|id| !id.is_string() && !id.is_number()) + { + output(&error(Value::Null, -32600, "Invalid MCP request"))?; + continue; + } + // Dropping the handler on EOF closes its HTTP request, canceling queued + // Trash work in the app. No write can be retried after an ambiguous disconnect. + let reply = tokio::select! { + biased; + _ = eof.wait_for(|closed| *closed) => break, + _ = tokio::signal::ctrl_c() => break, + reply = bridge.handle(&message) => reply, + }; + match reply { + Ok((reply, notes)) => { + if let (Some(reply), Some(_)) = (reply, message.get("id")) { + output(&reply)?; + } + for note in notes { + output(¬e)?; + } + } + Err(reason) => { + eprintln!("diskhound-mcp: {reason}"); + if let Some(id) = message.get("id") { + output(&error(id.clone(), -32000, reason))?; + } + return Err(reason); + } + } + } + Ok(()) + } + .await; + bridge.withdraw_pending().await; + outcome +} +fn output(value: &Value) -> Result<()> { + let mut output = std::io::stdout().lock(); + writeln!(output, "{value}") + .and_then(|_| output.flush()) + .map_err(|_| "Stdout closed") +} +fn main() { + std::panic::set_hook(Box::new(|_| eprintln!("diskhound-mcp: internal failure"))); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + let code = match runtime.block_on(run()) { + Ok(()) => 0, + Err(e) => { + eprintln!("diskhound-mcp: {e}"); + 1 + } + }; + // Tokio's blocking stdin reader may still be waiting; do not wait for it on exit. + std::process::exit(code); +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn only_loopback_ports_can_be_configured() { + assert_eq!( + options( + ["--port", "1234", "--ephemeral"] + .map(String::from) + .into_iter() + ) + .unwrap() + .port, + 1234 + ); + for args in [ + vec!["--port", "0"], + vec!["--port", "65536"], + vec!["--url", "https://example.com"], + vec!["--forget", "--ephemeral"], + ] { + assert!(options(args.into_iter().map(String::from)).is_err()); + } + } + #[test] + fn approval_destination_and_state_are_bound() { + let redirect = "http://127.0.0.1:1234/callback"; + assert_eq!( + callback_code(&format!("{redirect}?state=s&code=c"), redirect, "s").unwrap(), + "c" + ); + for location in [ + "http://evil.example/callback?state=s&code=c", + "http://127.0.0.1:1234/callback?state=s&state=s&code=c", + "http://127.0.0.1:1234/callback?state=x&code=c", + "http://127.0.0.1:1234/callback?state=s&error=access_denied", + ] { + assert!(callback_code(location, redirect, "s").is_err()); + } + } + #[test] + fn pending_approval_is_an_opaque_id_not_a_url() { + assert_eq!( + pending_id(&format!("/authorize/status?id={}\"", "a".repeat(43))).unwrap(), + "a".repeat(43) + ); + assert!(pending_id("/authorize/status?id=../evil\"").is_err()); + } +} + +#[cfg(test)] +#[path = "tests.rs"] +mod transport_tests; diff --git a/native/diskhound-mcp/src/tests.rs b/native/diskhound-mcp/src/tests.rs new file mode 100644 index 00000000..959e60c6 --- /dev/null +++ b/native/diskhound-mcp/src/tests.rs @@ -0,0 +1,580 @@ +use super::*; +use std::sync::{Arc, Mutex}; +use tokio::io::AsyncWriteExt; + +#[derive(Default, Debug)] +pub struct CredentialCounts { + pub reads: usize, + pub writes: usize, + pub deletes: usize, + pub bytes: usize, + pub token: Option>, +} +#[derive(Debug)] +struct CountedCredential(Arc>); +impl keyring::credential::CredentialApi for CountedCredential { + fn set_secret(&self, secret: &[u8]) -> keyring::Result<()> { + let mut counts = self.0.lock().unwrap(); + counts.writes += 1; + counts.bytes += secret.len(); + counts.token = Some(secret.to_vec()); + Ok(()) + } + fn get_secret(&self) -> keyring::Result> { + let mut counts = self.0.lock().unwrap(); + counts.reads += 1; + counts.token.clone().ok_or(keyring::Error::NoEntry) + } + fn delete_credential(&self) -> keyring::Result<()> { + let mut counts = self.0.lock().unwrap(); + counts.deletes += 1; + counts.token = None; + Ok(()) + } + fn as_any(&self) -> &dyn std::any::Any { + self + } +} +fn store(counts: &Arc>, directory: &std::path::Path) -> Credentials { + Credentials::for_test( + keyring::Entry::new_with_credential(Box::new(CountedCredential(counts.clone()))), + directory.to_owned(), + ) +} +fn bridge(origin: String) -> Bridge { + let port = Url::parse(&origin).unwrap().port().unwrap(); + let mut bridge = Bridge::new( + Client::builder() + .no_proxy() + .redirect(Policy::none()) + .build() + .unwrap(), + origin, + port, + None, + ); + bridge.token = Some(format!("dhmcp_{}", "a".repeat(43))); + // Most tests talk to a one-response peer; identity has its own test. + bridge.verified = true; + bridge +} + +// Tiny loopback peer: record the actual wire request and serve one response. +async fn peer(status: &str, response: Value) -> (String, tokio::task::JoinHandle) { + peer_with_headers(status, "", response).await +} + +async fn peer_with_headers( + status: &str, + headers: &str, + response: Value, +) -> (String, tokio::task::JoinHandle) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let body = response.to_string(); + let reply = format!("HTTP/1.1 {status}\r\n{headers}Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + let task = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let request = read_request(&mut socket).await; + socket.write_all(reply.as_bytes()).await.unwrap(); + request + }); + (origin, task) +} + +async fn read_request(socket: &mut tokio::net::TcpStream) -> String { + let mut request = Vec::new(); + let mut buffer = [0; 4096]; + loop { + let count = socket.read(&mut buffer).await.unwrap(); + assert!(count > 0); + request.extend_from_slice(&buffer[..count]); + if let Some(end) = request.windows(4).position(|v| v == b"\r\n\r\n") { + let headers = String::from_utf8_lossy(&request[..end]).to_lowercase(); + let length: usize = headers + .lines() + .find_map(|line| line.strip_prefix("content-length: ")) + .unwrap_or("0") + .parse() + .unwrap(); + if request.len() >= end + 4 + length { + break; + } + } + } + String::from_utf8(request).unwrap() +} + +async fn approving_peer() -> (String, tokio::task::JoinHandle<()>) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let task = tokio::spawn(async move { + let mut redirect = String::new(); + let mut challenge = String::new(); + for step in 0..4 { + let (mut socket, _) = listener.accept().await.unwrap(); + let request = read_request(&mut socket).await; + let target = request + .lines() + .next() + .unwrap() + .split_whitespace() + .nth(1) + .unwrap(); + let url = Url::parse(&format!("http://127.0.0.1{target}")).unwrap(); + let mut headers = String::new(); + let body = match step { + 0 => { + assert_eq!(url.path(), "/register"); + json!({"client_id":"test-client"}).to_string() + } + 1 => { + assert_eq!(url.path(), "/authorize"); + let pairs: std::collections::HashMap<_, _> = url.query_pairs().collect(); + assert_eq!(pairs["code_challenge_method"], "S256"); + challenge = pairs["code_challenge"].to_string(); + let mut callback = Url::parse(&pairs["redirect_uri"]).unwrap(); + callback + .query_pairs_mut() + .append_pair("state", &pairs["state"]) + .append_pair("code", "test-code"); + redirect = callback.to_string(); + format!( + "", + "a".repeat(43) + ) + } + 2 => { + assert_eq!(url.path(), "/authorize/status"); + headers = format!("Location: {redirect}\r\n"); + String::new() + } + _ => { + assert_eq!(url.path(), "/token"); + let form = Url::parse(&format!( + "http://localhost/?{}", + request.split("\r\n\r\n").nth(1).unwrap() + )) + .unwrap(); + let pairs: std::collections::HashMap<_, _> = form.query_pairs().collect(); + assert_eq!(pairs["code"], "test-code"); + assert_eq!( + URL_SAFE_NO_PAD.encode(Sha256::digest(pairs["code_verifier"].as_bytes())), + challenge + ); + json!({"access_token":format!("dhmcp_{}", "b".repeat(43))}).to_string() + } + }; + let status = if step == 2 { "302 Found" } else { "200 OK" }; + socket.write_all(format!("HTTP/1.1 {status}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()).await.unwrap(); + } + }); + (origin, task) +} + +#[tokio::test] +async fn forwards_rpc_and_negotiates_version_without_reinterpreting_tools() { + let result = json!({"jsonrpc":"2.0", "id":"hello", "result":{"protocolVersion":"2025-06-18", "capabilities":{"tools":{}}}}); + let (origin, seen) = peer("200 OK", result.clone()).await; + let mut client = bridge(origin); + let request = + json!({"jsonrpc":"2.0", "id":"hello", "method":"initialize", "params":{"capabilities":{}}}); + assert_eq!(client.forward(&request).await.unwrap(), Some(result)); + assert_eq!(client.version, "2025-06-18"); + let wire = seen.await.unwrap(); + assert!(wire + .to_lowercase() + .contains("mcp-protocol-version: 2025-03-26")); + assert_eq!( + serde_json::from_str::(wire.split("\r\n\r\n").nth(1).unwrap()).unwrap(), + request + ); +} + +#[tokio::test] +async fn notifications_have_no_reply_and_mismatched_response_ids_fail() { + let (origin, seen) = peer("202 Accepted", Value::Null).await; + assert!(bridge(origin) + .forward(&json!({"jsonrpc":"2.0","method":"notifications/initialized"})) + .await + .unwrap() + .is_none()); + seen.await.unwrap(); + let (origin, seen) = peer("200 OK", json!({"jsonrpc":"2.0","id":2,"result":{}})).await; + assert!(bridge(origin) + .forward(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})) + .await + .is_err()); + seen.await.unwrap(); +} + +#[tokio::test] +async fn transport_failure_and_revocation_do_not_replay_calls() { + let (origin, seen) = peer("401 Unauthorized", json!({"error":"invalid_token"})).await; + let error = bridge(origin) + .forward(&json!({"jsonrpc":"2.0","id":1,"method":"tools/call"})) + .await + .unwrap_err(); + assert_eq!(error, REVOKED); // A second request would fail: the peer has gone away. + seen.await.unwrap(); + let (origin, seen) = peer("503 Unavailable", json!({"error":"offline"})).await; + assert!(bridge(origin) + .forward(&json!({"jsonrpc":"2.0","id":1,"method":"tools/call"})) + .await + .is_err()); + seen.await.unwrap(); +} + +#[tokio::test] +async fn credential_budget_reconnect_and_poll_are_write_free() { + let directory = + std::env::temp_dir().join(format!("diskhound-bridge-test-{}", random().unwrap())); + let counts = Arc::new(Mutex::new(CredentialCounts::default())); + let saved = store(&counts, &directory); + let (origin, approved) = approving_peer().await; + let mut first = bridge(origin.clone()); + first.credentials = Some(store(&counts, &directory)); + first.token = None; + first.ensure_token().await.unwrap(); + approved.await.unwrap(); + // 100 separate connections load once each; 1,440 requests per connection + // (one a minute all day) use only the in-memory token. No per-tick writes. + for _ in 0..100 { + let mut client = bridge(origin.clone()); + client.credentials = Some(store(&counts, &directory)); + client.token = None; + for _ in 0..1440 { + client.ensure_token().await.unwrap(); + } + } + saved.clear().await.unwrap(); + let counts = counts.lock().unwrap(); + let budgets: Value = serde_json::from_str(include_str!("../io-budgets.json")).unwrap(); + let budget = &budgets["approval-reconnect-and-poll"]; + assert_eq!( + counts.reads, + budget["credentialReads"].as_u64().unwrap() as usize + ); + assert_eq!( + counts.writes, + budget["credentialWrites"].as_u64().unwrap() as usize + ); + assert_eq!( + counts.deletes, + budget["credentialDeletes"].as_u64().unwrap() as usize + ); + assert_eq!( + counts.bytes, + budget["observedPayloadBytesWritten"].as_u64().unwrap() as usize + ); + std::fs::remove_dir_all(directory).unwrap(); +} + +#[tokio::test] +async fn concurrent_connections_wait_for_the_first_approval() { + let directory = + std::env::temp_dir().join(format!("diskhound-bridge-lock-{}", random().unwrap())); + let counts = Arc::new(Mutex::new(CredentialCounts::default())); + let saved = store(&counts, &directory); + let first = saved.lock(51735).await.unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(50), saved.lock(51735)) + .await + .is_err() + ); + drop(first); + let second = tokio::time::timeout(Duration::from_secs(1), saved.lock(51735)) + .await + .unwrap() + .unwrap(); + drop(second); + std::fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn approvals_name_the_client_the_user_knows() { + assert_eq!( + client_label(&json!({"name":"claude-ai","version":"0.1.0"})), + "Claude Desktop" + ); + // Claude Desktop 2.16 running DiskHound's extension. + assert_eq!( + client_label(&json!({"name":"local-agent-mode-DiskHound"})), + "Claude Desktop" + ); + assert_eq!(client_label(&json!({"name":"claude-code"})), "Claude Code"); + assert_eq!( + client_label(&json!({"name":"codex-mcp-client","title":"Codex"})), + "Codex" + ); + assert_eq!( + client_label(&json!({"name":"acme","title":"Acme Agent"})), + "Acme Agent" + ); + assert_eq!(client_label(&json!({"name":"acme"})), "acme"); + assert_eq!(client_label(&json!({})), "MCP client"); + assert_eq!(client_label(&json!({"name":"a\u{7}b"})), "ab"); +} + +#[tokio::test] +async fn a_token_is_never_sent_to_another_app_on_the_port() { + let (origin, seen) = peer( + "200 OK", + json!({"resource":"http://127.0.0.1:1/mcp","resource_name":"PwrSuiteLab Control"}), + ) + .await; + let mut client = bridge(origin); + client.verified = false; + assert_eq!(client.verify().await.unwrap_err(), NOT_DISKHOUND); + let wire = seen.await.unwrap(); + assert!(wire.starts_with("GET /.well-known/oauth-protected-resource/mcp")); + assert!(!wire.to_lowercase().contains("authorization:")); +} + +#[tokio::test] +async fn initialize_answers_at_once_while_the_user_decides() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let metadata = + json!({"resource":format!("{origin}/mcp"),"resource_name":"DiskHound"}).to_string(); + let served = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let request = read_request(&mut socket).await; + socket.write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{metadata}", metadata.len()).as_bytes()).await.unwrap(); + request + }); + let mut client = bridge(origin); + client.verified = false; + client.token = None; + let started = Instant::now(); + let (reply, notes) = client + .handle(&json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{ + "protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"claude-code","version":"1"}}})) + .await + .unwrap(); + assert!(started.elapsed() < Duration::from_secs(2)); + assert!(notes.is_empty()); + let reply = reply.unwrap(); + assert_eq!(reply["result"]["protocolVersion"], "2025-06-18"); + assert_eq!( + reply["result"]["capabilities"]["tools"]["listChanged"], + true + ); + assert!(reply["result"]["instructions"] + .as_str() + .unwrap() + .contains("approve")); + assert_eq!(client.client_name, "Claude Code"); + // The approval waits a moment, so a health check never opens it. + assert!(client.approval.is_none() && client.approval_due.is_some()); + assert!(served.await.unwrap().starts_with("GET /.well-known/")); + // Before approval: one placeholder tool, empty lists, no network. + let (prompts, _) = client + .handle(&json!({"jsonrpc":"2.0","id":2,"method":"prompts/list"})) + .await + .unwrap(); + assert_eq!(prompts.unwrap()["result"]["prompts"], json!([])); + let (tools, _) = client + .handle(&json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})) + .await + .unwrap(); + assert_eq!( + tools.unwrap()["result"]["tools"][0]["name"], + "diskhound_status" + ); + // Listing is all a health check does, so it doesn't ask the user. + assert!(client.approval.is_none()); +} + +#[tokio::test] +async fn hanging_up_withdraws_the_approval_diskhound_is_showing() { + let (origin, seen) = peer("204 No Content", json!({})).await; + let client = bridge(origin); + // Nothing waiting: nothing to withdraw, no request. + client.withdraw_pending().await; + *client.pending.lock().unwrap() = Some("a".repeat(43)); + client.withdraw_pending().await; + let wire = seen.await.unwrap(); + assert!(wire.starts_with("POST /authorize/cancel")); + assert!(wire.ends_with(&format!("id={}", "a".repeat(43)))); + assert!(!wire.to_lowercase().contains("authorization:")); +} + +#[tokio::test] +async fn an_unreachable_diskhound_still_connects_and_says_why() { + // Nothing listens on this port. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + drop(listener); + let mut client = bridge(origin); + client.verified = false; + client.token = None; + let (reply, _) = client + .handle(&json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"codex-mcp-client"}}})) + .await + .unwrap(); + assert!(reply.unwrap()["result"]["serverInfo"]["name"] == "diskhound"); + let (tools, _) = client + .handle(&json!({"jsonrpc":"2.0","id":2,"method":"tools/list"})) + .await + .unwrap(); + assert_eq!( + tools.unwrap()["result"]["tools"][0]["name"], + "diskhound_status" + ); + let (status, _) = client + .handle(&json!({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"diskhound_status","arguments":{}}})) + .await + .unwrap(); + let status = status.unwrap(); + assert_eq!(status["result"]["isError"], true); + assert_eq!(status["result"]["content"][0]["text"], OFFLINE); +} + +#[tokio::test] +async fn a_role_change_tells_the_client_to_reload_tools() { + let reply = json!({"jsonrpc":"2.0","id":1,"result":{"tools":[]}}); + let (origin, seen) = peer_with_headers( + "200 OK", + "DiskHound-Capabilities: disk.read,files.trash\r\n", + reply, + ) + .await; + let mut client = bridge(origin); + client.capabilities = Some("disk.read".into()); + let (_, notes) = client + .handle(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})) + .await + .unwrap(); + assert_eq!( + notes, + vec![json!({"jsonrpc":"2.0","method":"notifications/tools/list_changed"})] + ); + assert_eq!( + client.capabilities.as_deref(), + Some("disk.read,files.trash") + ); + seen.await.unwrap(); +} + +#[tokio::test] +async fn claude_desktop_waits_for_the_users_decision_before_listing_tools() { + let reply = + json!({"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"diskhound_list_folder"}]}}); + let (origin, seen) = peer("200 OK", reply).await; + let mut client = bridge(origin); + client.token = None; + assert!(lists_tools_once( + &json!({"name":"local-agent-mode-DiskHound"}) + )); + assert!(lists_tools_once(&json!({"name":"claude-ai"}))); + assert!(!lists_tools_once(&json!({"name":"claude-code"}))); + client.lists_once = true; + // The user approves while Claude's first tools/list is waiting. + let (decide, decision) = tokio::sync::watch::channel(Approval::Pending); + client.approval = Some(decision); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(100)).await; + let _ = decide.send(Approval::Approved(format!("dhmcp_{}", "c".repeat(43)))); + }); + let (tools, _) = client + .handle(&json!({"jsonrpc":"2.0","id":2,"method":"tools/list"})) + .await + .unwrap(); + assert_eq!( + tools.unwrap()["result"]["tools"][0]["name"], + "diskhound_list_folder" + ); + assert!(!client.stale_list); + assert!(seen + .await + .unwrap() + .contains(&format!("Bearer dhmcp_{}", "c".repeat(43)))); +} + +#[tokio::test] +async fn claude_desktop_hears_how_to_reload_tools_it_listed_too_early() { + // It listed before the user approved: its list is the placeholder. + let mut client = bridge("http://127.0.0.1:9".into()); + client.token = None; + client.lists_once = true; + client.failed = Some(OFFLINE); + let (tools, _) = client + .handle(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})) + .await + .unwrap(); + assert_eq!( + tools.unwrap()["result"]["tools"][0]["name"], + "diskhound_status" + ); + assert!(client.stale_list); + // Approved later: diskhound_status says how to get the real list. + let status = json!({"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"ok"}]}}); + let (origin, seen) = peer("200 OK", status).await; + client.origin = origin; + client.failed = None; + client.token = Some(format!("dhmcp_{}", "a".repeat(43))); + let (reply, _) = client + .handle(&json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"diskhound_status","arguments":{}}})) + .await + .unwrap(); + let content = &reply.unwrap()["result"]["content"]; + assert_eq!(content[0]["text"], "ok"); + assert_eq!(content[1]["text"], RECONNECT_FOR_TOOLS); + seen.await.unwrap(); +} + +#[tokio::test] +async fn a_role_change_tells_claude_desktop_to_reconnect() { + let status = json!({"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"ok"}]}}); + let (origin, seen) = peer_with_headers( + "200 OK", + "DiskHound-Capabilities: disk.read,files.trash\r\n", + status, + ) + .await; + let mut client = bridge(origin); + client.lists_once = true; + client.capabilities = Some("disk.read".into()); + let (reply, notes) = client + .handle(&json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"diskhound_status","arguments":{}}})) + .await + .unwrap(); + assert_eq!( + reply.unwrap()["result"]["content"][1]["text"], + RECONNECT_FOR_TOOLS + ); + assert_eq!( + notes, + vec![json!({"jsonrpc":"2.0","method":"notifications/tools/list_changed"})] + ); + seen.await.unwrap(); +} + +#[tokio::test] +async fn each_client_keeps_its_own_approval_and_lock() { + assert_eq!( + credentials::account("http://127.0.0.1:51735", "Claude Desktop"), + "http://127.0.0.1:51735#Claude Desktop" + ); + let directory = + std::env::temp_dir().join(format!("diskhound-bridge-clients-{}", random().unwrap())); + let counts = Arc::new(Mutex::new(CredentialCounts::default())); + let store = store(&counts, &directory); + let code = store.for_client("Claude Code").unwrap(); + let desktop = store.for_client("Claude Desktop").unwrap(); + let waiting = code.lock(51735).await.unwrap(); + // Claude Code waiting for the user doesn't hold up Claude Desktop... + let other = tokio::time::timeout(Duration::from_secs(1), desktop.lock(51735)) + .await + .unwrap() + .unwrap(); + // ...but a second Claude Code connection waits for the first. + assert!( + tokio::time::timeout(Duration::from_millis(50), code.lock(51735)) + .await + .is_err() + ); + drop((waiting, other)); + std::fs::remove_dir_all(directory).unwrap(); +} diff --git a/native/diskhound-native-scanner/src/main.rs b/native/diskhound-native-scanner/src/main.rs index 01256131..d1ee8334 100644 --- a/native/diskhound-native-scanner/src/main.rs +++ b/native/diskhound-native-scanner/src/main.rs @@ -34,6 +34,8 @@ mod index_line; #[cfg(not(windows))] mod hardlinks; #[cfg(not(windows))] +mod measure; +#[cfg(not(windows))] mod walk_prune; #[cfg(test)] mod test_support; @@ -1185,6 +1187,20 @@ fn main() { || matches_flag(&raw_args, "--mode", "query-cursor"); let is_sample = raw_args.iter().any(|a| a == "--mode=sample") || matches_flag(&raw_args, "--mode", "sample"); + let is_measure = raw_args.iter().any(|a| a == "--mode=measure-removal") + || matches_flag(&raw_args, "--mode", "measure-removal"); + + if is_measure { + #[cfg(not(windows))] + let result = measure::run(&raw_args, &CANCELLED); + #[cfg(windows)] + let result: Result<(), String> = Err("measure-removal is not available on Windows".into()); + if let Err(error) = result { + let _ = emit_message(&Message::Error { message: error }); + std::process::exit(1); + } + return; + } if is_sample { if let Err(error) = sample::run_sample_once() { diff --git a/native/diskhound-native-scanner/src/measure.rs b/native/diskhound-native-scanner/src/measure.rs new file mode 100644 index 00000000..d7433df8 --- /dev/null +++ b/native/diskhound-native-scanner/src/measure.rs @@ -0,0 +1,760 @@ +//! `--mode=measure-removal`: what removing a set of files and folders +//! together would free, measured on disk now rather than read from a scan. +//! +//! A scan adds up each file's allocated blocks and counts a hardlinked file +//! once. Removing files gives back less than that when blocks are shared: +//! +//! - **APFS full clones** share every block. The blocks come back only when +//! every clone is gone. APFS reports how many clones a group has +//! (`CLONE_REFCNT`), so clones outside the set, and outside any scan, +//! still count. +//! - **A rewritten clone** owns the blocks it rewrote (`PRIVATESIZE`) and +//! shares the rest with clones nothing identifies. Those shared bytes +//! are reported as uncertain, never as freed. +//! - **A hardlinked file** comes back only when every name is gone. +//! +//! Every byte is counted against the set together and against each path +//! alone. Time Machine local snapshots and the Trash hold freed blocks +//! for a while longer; the app explains those. + +use std::collections::HashMap; +use std::ffi::OsString; +use std::io::Write; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Instant; + +#[cfg(all(unix, not(target_os = "macos")))] +use std::os::unix::fs::MetadataExt; + +use serde::Serialize; + +use crate::clone_attrs::CloneAttrs; +use crate::walk_prune; +use crate::work; + +/// Holders of one shared member: each input path holding a name of it, +/// and whether removing that path alone removes the member. +type Holders = Vec<(u32, bool)>; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PathTotals { + pub files: u64, + /// Allocated bytes, each hardlinked file once. + pub size_bytes: u64, + /// Removing only this path frees this much. + pub frees_alone_bytes: u64, + /// Blocks in this path that files outside it also hold. + pub shared_bytes: u64, + /// Rewritten clones' blocks shared with clones DiskHound can't identify. + pub uncertain_bytes: u64, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SetTotals { + pub files: u64, + pub size_bytes: u64, + /// Removing every path together frees this much. + pub frees_bytes: u64, + /// Blocks that stay because files outside the set hold them too. + pub held_elsewhere_bytes: u64, + pub uncertain_bytes: u64, +} + +struct InodeRec { + nlink: u64, + occupancy: u64, + attrs: CloneAttrs, + names: u64, +} + +struct GroupRec { + refcnt: u32, + /// Blocks the group's clones share, counted once. + bytes: u64, + /// Members the whole set removes. + removed: u32, +} + +/// The accounting, apart from the walk, so tests can feed it files. +#[derive(Default)] +pub struct Tally { + paths: Vec, + total: SetTotals, + inode_ids: HashMap<(u64, u64), u32>, + inodes: Vec, + /// (inode, path) โ†’ names of that inode inside the path. + inode_names: HashMap<(u32, u32), u64>, + group_ids: HashMap<(u64, u64), u32>, + groups: Vec, + /// (group, path) โ†’ members that removing the path alone removes. An + /// entry with 0 still marks the path as holding the group. + group_alone: HashMap<(u32, u32), u32>, +} + +impl Tally { + pub fn new(paths: usize) -> Self { + Self { + paths: vec![PathTotals::default(); paths], + ..Self::default() + } + } + + /// One name of a regular file under input path `path`. + pub fn add_file( + &mut self, + path: u32, + occupancy: u64, + nlink: u64, + inode: (u64, u64), + attrs: CloneAttrs, + ) { + work::step(); + self.total.files += 1; + self.paths[path as usize].files += 1; + if nlink > 1 { + let next = self.inodes.len() as u32; + let id = *self.inode_ids.entry(inode).or_insert(next); + if id == next { + self.inodes.push(InodeRec { + nlink, + occupancy, + attrs, + names: 0, + }); + } + self.inodes[id as usize].names += 1; + *self.inode_names.entry((id, path)).or_insert(0) += 1; + return; + } + self.total.size_bytes += occupancy; + self.paths[path as usize].size_bytes += occupancy; + self.member(true, &[(path, true)], occupancy, attrs); + } + + /// Something whose blocks come back when `together` (the whole set + /// removes it) or when a holder that removes it alone goes. + fn member( + &mut self, + together: bool, + holders: &[(u32, bool)], + occupancy: u64, + attrs: CloneAttrs, + ) { + work::step(); + if !attrs.may_share() { + self.own(together, holders, occupancy, 0); + return; + } + let private = attrs.clone_private_of(occupancy); + let shared = occupancy - private; + let Some((clone_id, refcnt)) = attrs.full_clone_group() else { + // A rewritten clone: what it rewrote is its own, the rest is + // shared with clones nothing here identifies. + self.own(together, holders, private, shared); + return; + }; + self.own(together, holders, private, 0); + let next = self.groups.len() as u32; + let id = *self + .group_ids + .entry((attrs.volume_id, clone_id)) + .or_insert(next); + if id == next { + self.groups.push(GroupRec { + refcnt, + bytes: 0, + removed: 0, + }); + } + let group = &mut self.groups[id as usize]; + group.refcnt = group.refcnt.max(refcnt); + group.bytes = group.bytes.max(shared); + group.removed += u32::from(together); + for &(path, alone) in holders { + work::step(); + *self.group_alone.entry((id, path)).or_insert(0) += u32::from(alone); + } + } + + /// Bytes that only these holders hold, plus `uncertain` bytes that + /// come back only if clones elsewhere go too. + fn own(&mut self, together: bool, holders: &[(u32, bool)], bytes: u64, uncertain: u64) { + if together { + self.total.frees_bytes += bytes; + self.total.uncertain_bytes += uncertain; + } else { + self.total.held_elsewhere_bytes += bytes + uncertain; + } + for &(path, alone) in holders { + work::step(); + let totals = &mut self.paths[path as usize]; + if alone { + totals.frees_alone_bytes += bytes; + totals.uncertain_bytes += uncertain; + } else { + totals.shared_bytes += bytes + uncertain; + } + } + } + + pub fn finish(mut self) -> (Vec, SetTotals) { + // Hardlinked files: each inode once, removed when every name is in. + let mut holders: Vec = (0..self.inodes.len()).map(|_| Vec::new()).collect(); + for (&(inode, path), &names) in &self.inode_names { + work::step(); + let nlink = self.inodes[inode as usize].nlink; + holders[inode as usize].push((path, names >= nlink)); + } + let inodes = std::mem::take(&mut self.inodes); + for (inode, held) in inodes.into_iter().zip(holders) { + work::step(); + self.total.size_bytes += inode.occupancy; + for &(path, _) in &held { + self.paths[path as usize].size_bytes += inode.occupancy; + } + let together = inode.names >= inode.nlink; + self.member(together, &held, inode.occupancy, inode.attrs); + } + // Clone groups: freed once every clone APFS counts is removed. + for group in &self.groups { + work::step(); + if group.removed >= group.refcnt { + self.total.frees_bytes += group.bytes; + } else { + self.total.held_elsewhere_bytes += group.bytes; + } + } + for (&(group, path), &alone) in &self.group_alone { + work::step(); + let group = &self.groups[group as usize]; + let totals = &mut self.paths[path as usize]; + if alone >= group.refcnt { + totals.frees_alone_bytes += group.bytes; + } else { + totals.shared_bytes += group.bytes; + } + } + (self.paths, self.total) + } +} + +// โ”€โ”€ The walk โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PathReport { + pub path: String, + pub kind: &'static str, + #[serde(flatten)] + pub totals: PathTotals, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct NestedPath { + pub path: String, + pub within: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MeasureReport { + #[serde(rename = "type")] + pub kind: &'static str, + pub paths: Vec, + pub total: SetTotals, + /// Paths that don't exist. + pub missing: Vec, + /// Paths inside another listed path, measured as part of it. + pub nested: Vec, + /// Entries that couldn't be read. + pub skipped_entries: u64, + /// Whether APFS clones were read; false off APFS or when turned off. + pub clone_metadata: bool, + pub elapsed_ms: u64, +} + +enum Root { + /// A listed folder: input index. + Folder(u32), + /// The parent folder of listed files: their names and input indices. + Parent(HashMap), +} + +/// Drop exact repeats and paths inside another listed path. +fn outermost(paths: &[PathBuf]) -> (Vec, Vec) { + let mut sorted: Vec<&PathBuf> = paths.iter().collect(); + sorted.sort(); + sorted.dedup(); + let mut kept: Vec = Vec::new(); + let mut nested = Vec::new(); + for path in sorted { + work::step(); + // Sorted, so an ancestor is the last kept path if any is. + match kept.last() { + Some(parent) if path.starts_with(parent) => nested.push(NestedPath { + path: path.to_string_lossy().into_owned(), + within: parent.to_string_lossy().into_owned(), + }), + _ => kept.push(path.clone()), + } + } + (kept, nested) +} + +pub fn measure( + paths: &[PathBuf], + workers: usize, + cancelled: &AtomicBool, +) -> Result { + let started = Instant::now(); + let (kept, nested) = outermost(paths); + let mut missing = Vec::new(); + let mut listed: Vec<(PathBuf, &'static str)> = Vec::new(); + let mut roots: Vec<(PathBuf, Root)> = Vec::new(); + let mut parents: HashMap = HashMap::new(); + for path in kept { + let Ok(metadata) = std::fs::symlink_metadata(&path) else { + missing.push(path.to_string_lossy().into_owned()); + continue; + }; + let index = listed.len() as u32; + if metadata.is_dir() { + listed.push((path.clone(), "folder")); + roots.push((path, Root::Folder(index))); + continue; + } + // A file: read it with the rest of its folder, which is where + // the bulk read returns its clone id. + let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else { + missing.push(path.to_string_lossy().into_owned()); + continue; + }; + listed.push((path.clone(), "file")); + let slot = *parents.entry(parent.to_path_buf()).or_insert_with(|| { + roots.push((parent.to_path_buf(), Root::Parent(HashMap::new()))); + roots.len() - 1 + }); + if let Root::Parent(names) = &mut roots[slot].1 { + names.insert(name.to_owned(), index); + } + } + + let plans: Arc>> = Arc::new( + roots + .iter() + .map(|(path, root)| matches!(root, Root::Folder(_)).then(|| walk_prune::plan_for(path))) + .collect(), + ); + #[cfg(target_os = "macos")] + let clone_metadata = roots + .iter() + .any(|(path, _)| crate::clone_attrs::enable_for_root(path)); + #[cfg(not(target_os = "macos"))] + let clone_metadata = false; + #[cfg(target_os = "macos")] + let options = dua_core::Options { + apfs_clone_metadata: clone_metadata, + ..dua_core::Options::default() + }; + #[cfg(not(target_os = "macos"))] + let options = dua_core::Options::default(); + + let walk_plans = Arc::clone(&plans); + let walker = dua_core::walk_roots( + roots + .iter() + .enumerate() + .map(|(index, (path, _))| (index, path.clone())), + workers.max(1), + dua_core::Order::Completion, + options, + move |root, entry| match &walk_plans[root] { + // A listed file's folder: read it, nothing below it. + None => entry.depth == 0, + Some(plan) => { + entry.depth == 0 + || plan + .skip_reason(&entry.path().to_string_lossy(), true) + .is_none() + } + }, + ); + + let mut tally = Tally::new(listed.len()); + let mut skipped_entries = 0u64; + #[cfg(target_os = "macos")] + let mut clone_cache = crate::clone_attrs::CloneAttrCache::default(); + let mut last_progress = Instant::now(); + for (root, event) in walker { + if cancelled.load(Ordering::Relaxed) { + return Err("Measurement cancelled".into()); + } + let entry = match event { + dua_core::RootEvent::Finished => continue, + dua_core::RootEvent::Entry(Ok(entry)) => entry, + dua_core::RootEvent::Entry(Err(_)) => { + skipped_entries += 1; + continue; + } + }; + if !entry.file_type.is_file() { + continue; + } + let index = match &roots[root].1 { + Root::Folder(index) => *index, + Root::Parent(names) => match (entry.depth, names.get(&entry.file_name)) { + (1, Some(index)) => *index, + _ => continue, + }, + }; + let Some(metadata) = entry.metadata.as_ref().and_then(|meta| meta.as_ref().ok()) else { + skipped_entries += 1; + continue; + }; + let occupancy = metadata.blocks().saturating_mul(512); + let nlink = metadata.nlink(); + let inode = (metadata.dev(), metadata.ino()); + #[cfg(target_os = "macos")] + let attrs = if clone_metadata { + clone_cache.get( + &entry.path(), + metadata.clone_id(), + metadata.real_dev(), + (nlink > 1).then_some(inode), + ) + } else { + CloneAttrs::default() + }; + #[cfg(not(target_os = "macos"))] + let attrs = CloneAttrs::default(); + tally.add_file(index, occupancy, nlink, inode, attrs); + if last_progress.elapsed().as_secs() >= 1 { + last_progress = Instant::now(); + emit(&serde_json::json!({ "type": "progress", "files": tally.total.files })); + } + } + + let (totals, total) = tally.finish(); + Ok(MeasureReport { + kind: "removal-measurement", + paths: listed + .into_iter() + .zip(totals) + .map(|((path, kind), totals)| PathReport { + path: path.to_string_lossy().into_owned(), + kind, + totals, + }) + .collect(), + total, + missing, + nested, + skipped_entries, + clone_metadata, + elapsed_ms: started.elapsed().as_millis() as u64, + }) +} + +fn emit(value: &impl Serialize) { + let mut out = std::io::stdout().lock(); + let _ = serde_json::to_writer(&mut out, value); + let _ = out.write_all(b"\n"); + let _ = out.flush(); +} + +/// `--mode=measure-removal --path [--path โ€ฆ] [--workers N]`. +/// Prints progress lines, then one `removal-measurement` line. +pub fn run(args: &[String], cancelled: &AtomicBool) -> Result<(), String> { + let mut paths = Vec::new(); + let mut workers = None; + let mut iter = args.iter(); + while let Some(arg) = iter.next() { + match arg.as_str() { + "--mode=measure-removal" => {} + "--mode" => { + iter.next(); + } + "--path" => { + let path = PathBuf::from(iter.next().ok_or("Expected a path after --path")?); + if !path.is_absolute() { + return Err(format!("--path must be absolute: {}", path.display())); + } + paths.push(path); + } + "--workers" => { + let value = iter.next().ok_or("Expected a number after --workers")?; + workers = Some( + value + .parse::() + .map_err(|_| format!("Invalid --workers: {value}"))?, + ); + } + other => return Err(format!("Unknown measure-removal arg: {other}")), + } + } + if paths.is_empty() { + return Err("measure-removal needs at least one --path".into()); + } + let workers = crate::walk_workers(workers, num_cpus::get().clamp(1, 8)); + let report = measure(&paths, workers, cancelled)?; + emit(&report); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::clone_attrs::{EF_MAY_SHARE_BLOCKS, EF_SHARES_ALL_BLOCKS}; + + fn clone(id: u64, refcnt: u32) -> CloneAttrs { + CloneAttrs { + private_size: Some(0), + clone_id: id, + volume_id: 7, + clone_refcnt: refcnt, + ext_flags: EF_MAY_SHARE_BLOCKS | EF_SHARES_ALL_BLOCKS, + } + } + + fn rewritten(private: u64) -> CloneAttrs { + CloneAttrs { + private_size: Some(private), + clone_id: 99, + volume_id: 7, + clone_refcnt: 1, + ext_flags: EF_MAY_SHARE_BLOCKS, + } + } + + const PLAIN: CloneAttrs = CloneAttrs { + private_size: None, + clone_id: 0, + volume_id: 0, + clone_refcnt: 0, + ext_flags: 0, + }; + + #[test] + fn ordinary_files_free_their_blocks_alone_and_together() { + let mut tally = Tally::new(2); + tally.add_file(0, 4096, 1, (1, 1), PLAIN); + tally.add_file(1, 8192, 1, (1, 2), PLAIN); + let (paths, total) = tally.finish(); + assert_eq!(paths[0].frees_alone_bytes, 4096); + assert_eq!(paths[1].frees_alone_bytes, 8192); + assert_eq!( + total, + SetTotals { + files: 2, + size_bytes: 12288, + frees_bytes: 12288, + held_elsewhere_bytes: 0, + uncertain_bytes: 0 + } + ); + } + + #[test] + fn a_clone_group_comes_back_only_when_every_clone_is_in_the_set() { + // Group 1: one copy in each path, 2 clones in all โ†’ freed together only. + // Group 2: 3 clones, the third outside the set โ†’ never freed. + let mut tally = Tally::new(2); + tally.add_file(0, 1000, 1, (1, 1), clone(1, 2)); + tally.add_file(1, 1000, 1, (1, 2), clone(1, 2)); + tally.add_file(0, 500, 1, (1, 3), clone(2, 3)); + tally.add_file(1, 500, 1, (1, 4), clone(2, 3)); + let (paths, total) = tally.finish(); + assert_eq!(total.size_bytes, 3000); + assert_eq!(total.frees_bytes, 1000); + assert_eq!(total.held_elsewhere_bytes, 500); + for path in &paths { + assert_eq!(path.frees_alone_bytes, 0); + assert_eq!(path.shared_bytes, 1500); + } + } + + #[test] + fn a_group_inside_one_path_comes_back_with_that_path_alone() { + let mut tally = Tally::new(2); + tally.add_file(0, 1000, 1, (1, 1), clone(1, 2)); + tally.add_file(0, 1000, 1, (1, 2), clone(1, 2)); + let (paths, total) = tally.finish(); + assert_eq!(paths[0].frees_alone_bytes, 1000); + assert_eq!(paths[0].shared_bytes, 0); + assert_eq!(total.frees_bytes, 1000); + } + + #[test] + fn a_rewritten_clone_frees_its_rewrite_and_leaves_the_rest_uncertain() { + let mut tally = Tally::new(1); + tally.add_file(0, 10_000, 1, (1, 1), rewritten(4096)); + let (paths, total) = tally.finish(); + assert_eq!(total.frees_bytes, 4096); + assert_eq!(total.uncertain_bytes, 10_000 - 4096); + assert_eq!(paths[0].frees_alone_bytes, 4096); + assert_eq!(paths[0].uncertain_bytes, 10_000 - 4096); + } + + #[test] + fn a_hardlink_comes_back_when_every_name_is_in_the_set() { + // Inode 5: names in both paths (2 links). Inode 6: one of 2 names. + let mut tally = Tally::new(2); + tally.add_file(0, 4096, 2, (1, 5), PLAIN); + tally.add_file(1, 4096, 2, (1, 5), PLAIN); + tally.add_file(0, 8192, 2, (1, 6), PLAIN); + let (paths, total) = tally.finish(); + assert_eq!(total.files, 3); + assert_eq!(total.size_bytes, 4096 + 8192); + assert_eq!(total.frees_bytes, 4096); + assert_eq!(total.held_elsewhere_bytes, 8192); + assert_eq!(paths[0].size_bytes, 4096 + 8192); + assert_eq!(paths[0].frees_alone_bytes, 0); + assert_eq!(paths[0].shared_bytes, 4096 + 8192); + assert_eq!(paths[1].shared_bytes, 4096); + } + + #[test] + fn a_hardlinked_clone_counts_once_toward_its_group() { + // One inode with two names (one APFS clone), plus its other clone. + let mut tally = Tally::new(1); + tally.add_file(0, 2048, 2, (1, 8), clone(3, 2)); + tally.add_file(0, 2048, 2, (1, 8), clone(3, 2)); + tally.add_file(0, 2048, 1, (1, 9), clone(3, 2)); + let (paths, total) = tally.finish(); + assert_eq!(total.size_bytes, 4096); + assert_eq!(total.frees_bytes, 2048); + assert_eq!(paths[0].frees_alone_bytes, 2048); + } + + #[test] + fn nested_and_repeated_paths_are_measured_once() { + let paths = ["/a/b", "/a", "/c", "/a", "/a/b/c", "/ab"].map(PathBuf::from); + let (kept, nested) = outermost(&paths); + assert_eq!(kept, ["/a", "/ab", "/c"].map(PathBuf::from)); + let pairs: Vec<_> = nested + .iter() + .map(|n| (n.path.as_str(), n.within.as_str())) + .collect(); + assert_eq!(pairs, [("/a/b", "/a"), ("/a/b/c", "/a")]); + } + + /// AGENTS.md scaling rule: N files over K paths, then 8N over 8K. + #[test] + fn tally_work_grows_linearly_with_files_and_paths() { + fn steps(files: u64, paths: u32) -> u64 { + work::take(); + let mut tally = Tally::new(paths as usize); + for i in 0..files { + let path = (i % u64::from(paths)) as u32; + // Every file is a clone held in every path's group, plus + // a hardlink pair per 10 files: the worst sharing. + let attrs = clone(i % 16, paths); + if i % 10 == 0 { + tally.add_file(path, 4096, 2, (1, i), attrs); + tally.add_file((path + 1) % paths, 4096, 2, (1, i), attrs); + } else { + tally.add_file(path, 4096, 1, (1, i), attrs); + } + } + let _ = tally.finish(); + work::take() + } + let small = steps(1_000, 8); + let large = steps(8_000, 64); + let growth = large as f64 / small as f64; + eprintln!("measure tally: {small} -> {large} steps ({growth:.1}x)"); + assert!(growth <= 16.0, "tally grew {growth:.1}x from N to 8N"); + assert!(large <= 8_000 * 12, "tally took {large} steps at 8N"); + } + + #[test] + fn measures_a_real_folder_and_a_listed_file() { + let tree = crate::test_support::TempTree::new("measure"); + tree.write("keep/a.bin", 10_000); + tree.write("gone/b.bin", 20_000); + tree.write("gone/c.bin", 30_000); + let file = tree.write("loose.bin", 5_000); + let gone = tree.path("gone"); + let report = measure( + &[ + gone.clone(), + file.clone(), + gone.join("c.bin"), + tree.path("nope"), + ], + 2, + &AtomicBool::new(false), + ) + .unwrap(); + assert_eq!(report.paths.len(), 2); + let folder = report.paths.iter().find(|p| p.kind == "folder").unwrap(); + assert_eq!(folder.totals.files, 2); + assert!(folder.totals.size_bytes >= 50_000); + assert_eq!(folder.totals.frees_alone_bytes, folder.totals.size_bytes); + let loose = report.paths.iter().find(|p| p.kind == "file").unwrap(); + assert_eq!(loose.totals.files, 1); + assert!(loose.totals.size_bytes >= 5_000); + assert_eq!(report.total.files, 3); + assert_eq!(report.total.frees_bytes, report.total.size_bytes); + assert_eq!( + report.missing, + [tree.path("nope").to_string_lossy().into_owned()] + ); + assert_eq!(report.nested.len(), 1); + } + + #[cfg(unix)] + #[test] + fn measures_hardlinks_on_disk() { + let tree = crate::test_support::TempTree::new("measure-links"); + let target = tree.write("a/data.bin", 64 * 1024); + tree.link(&target, "b/data.bin"); + let a = tree.path("a"); + let b = tree.path("b"); + let alone = measure(std::slice::from_ref(&a), 2, &AtomicBool::new(false)).unwrap(); + assert_eq!(alone.total.frees_bytes, 0); + assert!(alone.total.held_elsewhere_bytes >= 64 * 1024); + let both = measure(&[a, b], 2, &AtomicBool::new(false)).unwrap(); + assert_eq!(both.total.files, 2); + assert_eq!(both.total.size_bytes, alone.total.size_bytes); + assert_eq!(both.total.frees_bytes, both.total.size_bytes); + } + + /// `cp -c` makes real APFS clones; skipped off APFS. + #[cfg(target_os = "macos")] + #[test] + fn measures_apfs_clones_on_disk() { + let tree = crate::test_support::TempTree::new("measure-clones"); + if !crate::clone_attrs::enable_for_root(&tree.path("")) { + eprintln!("not APFS, skipping"); + return; + } + let source = tree.write("a/data.bin", 256 * 1024); + std::fs::create_dir_all(tree.path("b")).unwrap(); + let status = std::process::Command::new("cp") + .arg("-c") + .arg(&source) + .arg(tree.path("b/data.bin")) + .status() + .unwrap(); + assert!(status.success()); + let a = tree.path("a"); + let b = tree.path("b"); + let alone = measure(std::slice::from_ref(&a), 2, &AtomicBool::new(false)).unwrap(); + assert!(alone.clone_metadata); + assert_eq!(alone.total.frees_bytes, 0, "{alone:?}"); + assert!(alone.total.held_elsewhere_bytes >= 256 * 1024); + let both = measure(&[a, b], 2, &AtomicBool::new(false)).unwrap(); + assert_eq!(both.total.size_bytes, 2 * alone.total.size_bytes); + assert_eq!(both.total.frees_bytes, alone.total.size_bytes, "{both:?}"); + for path in &both.paths { + assert_eq!(path.totals.frees_alone_bytes, 0); + assert_eq!(path.totals.shared_bytes, alone.total.size_bytes); + } + } +} diff --git a/package.json b/package.json index 8a9d1b80..f06635b1 100644 --- a/package.json +++ b/package.json @@ -30,19 +30,25 @@ "typecheck": "tsc --noEmit", "test": "vitest run", "test:usn:windows": "bun run build:native:debug && vitest run src/__tests__/usnMonitor.windows.test.ts", - "build:e2e": "node node_modules/electron/install.js && bun run build:native:debug && bun run build:renderer && bun run build:electron", + "build:e2e": "node node_modules/electron/install.js && bun run build:native:debug && bun run build:mcp:debug && bun run build:renderer && bun run build:electron", "test:e2e": "bun run build:e2e && playwright test", - "dist": "bun run build:native && bun run build && electron-builder --config electron-builder.yml" + "dist": "bun run build:native && bun run build:mcp && bun run build && electron-builder --config electron-builder.yml", + "build:mcp": "cargo build --locked --release --manifest-path native/diskhound-mcp/Cargo.toml", + "build:mcp:debug": "cargo build --locked --manifest-path native/diskhound-mcp/Cargo.toml" }, "dependencies": { + "@modelcontextprotocol/sdk": "1.30.0", "@shutterstock/p-map-iterable": "^1.1.2", "blake2": "^5.0.1", "electron-updater": "^6.6.2", - "preact": "^10.26.9" + "express": "5.2.1", + "preact": "^10.26.9", + "zod": "4.6.5" }, "devDependencies": { "@playwright/test": "^1.63.0", "@preact/preset-vite": "^2.10.2", + "@types/express": "^5.0.6", "@types/node": "^24.12.0", "electron": "40.6.0", "electron-builder": "^26.0.12", diff --git a/skills/diskhound-free-up-space/SKILL.md b/skills/diskhound-free-up-space/SKILL.md new file mode 100644 index 00000000..be7648c2 --- /dev/null +++ b/skills/diskhound-free-up-space/SKILL.md @@ -0,0 +1,175 @@ +--- +name: diskhound-free-up-space +description: Find what is using disk space and help the user reclaim it with the DiskHound app's MCP tools. Use when the user asks to free up space, clean up a full drive, or decide what to delete on macOS, Windows, or Linux. Covers space that deleting files does not release, such as APFS clones, Time Machine local snapshots, hardlinks, shadow copies, btrfs/ZFS snapshots, and deleted-but-open files. +license: MIT +compatibility: Requires the DiskHound desktop app with Settings > AI Agents enabled and its MCP server connected. +--- + +# Free up disk space with DiskHound + +DiskHound keeps an index of every file on a scanned drive, so you can explore +sizes instantly without walking the disk yourself. Your job is to turn that +data into a short, trustworthy list of things the user can remove, and to make +sure removing them actually gives the space back. Explain the choices once: +"I can help identify candidates; you decide what to keep or remove." Then +focus on useful findings rather than repeating cautions. A request to understand +disk usage can end with an explanation; it does not imply a cleanup request. + +If the host defers MCP tools, search its tool catalog for DiskHound disk usage +and load the relevant tools as needed. Start with `diskhound_status`. + +## Ground rules + +- **Never delete on your own.** The only delete path is + `diskhound_move_to_trash`. DiskHound shows the user a confirmation dialog + for every call, and items go to the Trash / Recycle Bin, not away forever. +- **Prefer the owning tool.** Package caches, containers, simulators, and + snapshots have their own cleanup commands (`pnpm store prune`, + `docker system prune`, `xcrun simctl delete unavailable`, `tmutil`, โ€ฆ). + Those commands know what is still referenced. Suggest them. Run read-only + diagnostics yourself if your host allows shell commands, but **ask before + running anything that deletes**. +- **Leave system areas alone**: `/System`, `/usr`, `/private/var/db`, + `C:\Windows`, `C:\Program Files`, `/boot`, `/var/lib/dpkg`, app bundles, and + anything under a DiskHound protected folder. The OS has its own tools for + those (see the platform references). +- **Let the user watch.** Pass `showInApp: true` on read tools, or call + `diskhound_show`, so the DiskHound window follows what you are looking at. +- **Sizes are bytes on disk** (allocated blocks), not logical file length. + Sparse files such as `Docker.raw` or VM disks show what they really occupy. + +## Procedure + +### 1. Measure the gap + +Call `diskhound_status`. Note each drive's free space and total size, what the +user wants (a number such as "50 GB", or "whatever is safe"), and which roots +have been scanned and how long ago. + +### 2. Get a fresh scan + +If the drive the user cares about has no scan, or the newest one is more than +about a day old, call `diskhound_start_scan` on the drive root (`/` on macOS +and Linux, `C:\` on Windows; `/home` is fine on Linux if that is its own +filesystem). Repeat scans are incremental and fast. Poll `diskhound_status` +until the root leaves `activeScans`. + +### 3. Account for the whole drive before hunting + +Compare the drive's **used** space (from `diskhound_status`) with the scan's +total (from `diskhound_scan_summary`). A small difference is normal. A large +one (more than about 10 % of the drive, or tens of GB) means space is held +somewhere the file scan cannot see. Deleting files will not fix that part, so +explain it first. Read the platform reference for the causes and the +read-only commands that confirm each one: + +- macOS: [references/macos.md](references/macos.md). Usual causes are Time + Machine local snapshots, other APFS volumes in the same container, + swap/sleepimage, and purgeable space. +- Windows: [references/windows.md](references/windows.md). Usual causes are + System Restore shadow copies, `hiberfil.sys`/`pagefile.sys`, and folders + the scan could not read. +- Linux: [references/linux.md](references/linux.md). Usual causes are + btrfs/ZFS snapshots, reserved blocks, deleted-but-open files, and other + mounts. + +### 4. Walk the tree, biggest first + +Start at the scan root with `diskhound_list_folder` (`showInApp: true`), then +follow the largest folders down a few levels. Stop descending when a folder +clearly belongs to one app or one project. At that point you know who owns +it. `diskhound_scan_summary` gives the heaviest folders and largest files in +one call when you want a shortcut. + +### 5. Run the targeted sweeps + +- `diskhound_dev_artifacts`: `node_modules`, Rust `target/`, build output, + venvs, package caches, git worktrees. Developer machines often have tens + of GB here. See [references/developer-caches.md](references/developer-caches.md) + for the right cleanup command per ecosystem. +- `diskhound_cleanup_suggestions`: temp files, caches, old downloads, + installers, logs, large media, each with a risk level. +- `diskhound_search_files` with `minSizeBytes: 1073741824` (1 GiB) and no + query finds every huge file. Also try `.iso`, `.dmg`, `.vmdk`, `.vhdx`, + `.qcow2`, `.zip`, `.mov`, `.mkv`, `.ipsw`. +- Duplicates are slow on a whole drive. Run `diskhound_find_duplicates` on + specific folders (Downloads, Desktop, media libraries), then + `diskhound_duplicates`. + +### 6. Classify every candidate + +Put each finding in exactly one bucket: + +| Bucket | Examples | What to do | +| --- | --- | --- | +| **Regenerable** | build output, `node_modules`, DerivedData, caches | Usually rebuildable; check for local changes and the time or network access needed to regenerate it. | +| **Owned by a tool** | Docker images, pnpm/npm/cargo stores, simulators, Homebrew, WSL disks, snapshots | Use the tool's own cleanup command. | +| **User data** | videos, photos, archives, downloads, VM images, iOS backups | Ask. Offer to reveal it (`diskhound_reveal_path`) or move it to another drive (DiskHound's Easy Move tab). | +| **System / hands off** | OS folders, app bundles, mail/photos library internals | Point to the OS or app setting instead. | + +### 7. Check that removal will free the space + +Before promising a number, call `diskhound_measure_removal` with the paths +the user might remove, as one call. It measures the disk now and counts +shared blocks once: `total.frees` is what removing them together frees, and +each path's `freesAlone` is what removing only that one frees. Quote those +rather than adding up sizes, and don't measure clones yourself with shell +commands. If the call times out, make the same call again; DiskHound keeps +the result it finished. Then check each candidate against this list. When one +applies, say so plainly. + +- **Trash / Recycle Bin.** Nothing is freed until the Trash is emptied. + DiskHound only moves items to the Trash. +- **APFS clones (macOS).** Files copied with `clonefile` share blocks until + one copy changes. This includes pnpm's `node_modules` on APFS, copies made + in Finder on the same volume, and `cp -c`. **Shared blocks are freed only when + their last reference is removed; a copy's exclusive blocks can be reclaimed + separately.** Deleting one project's + `node_modules` often frees very little while the pnpm store and other + projects still hold clones. `diskhound_dev_artifacts` gives each tree's + `freesAlone` and a `listed.freesTogether` range from the last scan; + `diskhound_measure_removal` gives the exact figure for the set you pick. + Details: + [references/macos.md#apfs-clones](references/macos.md#apfs-clones). +- **Time Machine local snapshots (macOS).** Anything deleted since the last + local snapshot stays allocated until that snapshot expires (usually within + 24 hours) or is thinned. Free space may not move right away, even after + emptying the Trash. See + [references/macos.md#time-machine-local-snapshots](references/macos.md#time-machine-local-snapshots). +- **Hardlinks.** One file can appear at several paths. Scan totals can include multiple paths to shared storage. Use duplicate-group + reclaimable bytes and sharing metadata rather than multiplying file sizes. + Examples are pnpm stores on Linux and old HFS+ Time Machine backups. Space returns only when the last link is gone. Windows scans made + with the native MFT reader count each file once. +- **Snapshots elsewhere.** Windows System Restore / Volume Shadow Copies, + btrfs subvolume snapshots (Snapper, Timeshift), and ZFS snapshots all pin + deleted data. +- **Reflinks (Linux).** `cp --reflink` copies on btrfs or XFS share extents + the same way APFS clones do. +- **Deleted but open (Linux/macOS).** A process holding a deleted file keeps + its space until the process exits. Find these with `lsof +L1`. +- **Growable disk images.** WSL/Docker `.vhdx` files, `Docker.raw`, and VM + disks do not shrink when you delete inside them. Compact them with the + platform tool. + +### 8. Act, then verify + +1. Present a table: path, size, bucket, how confident you are that removal + frees it, and how to remove it. Order by size. Keep it short; the user + can ask for more. +2. For items the user approves: + - Run the owning tool's command, if they asked you to. + - Otherwise call `diskhound_move_to_trash` with a one-line `reason`, + batching related paths into one call. +3. Remind the user to empty the Trash. On macOS, mention that Time Machine + snapshots may hold the space for up to a day. +4. Call `diskhound_status` again and report the change in free space. If it + is much smaller than expected, go back to step 7. Snapshots and clones are + the usual reasons. +5. Offer a follow-up `diskhound_start_scan`. The Changes tab + (`diskhound_changes`) then shows exactly what went away. + +## When the user asks "what filled my disk?" + +That is a different question. Load the `diskhound-investigate-growth` skill +(`skill://diskhound-investigate-growth/SKILL.md`), which compares scans over +time. diff --git a/skills/diskhound-free-up-space/references/developer-caches.md b/skills/diskhound-free-up-space/references/developer-caches.md new file mode 100644 index 00000000..61fcb414 --- /dev/null +++ b/skills/diskhound-free-up-space/references/developer-caches.md @@ -0,0 +1,43 @@ +# Developer caches and build output + +`diskhound_dev_artifacts` finds these trees and names the project that owns +each one. Almost everything here is regenerable, but "regenerable" can still +mean a long rebuild or a big download. Say so when a tree is large. + +Before removing anything inside a project: + +- **Git worktrees.** Check `git -C status` and + `git -C log @{u}..` for uncommitted or unpushed work. Then + remove with `git worktree remove ` from the main checkout, not by + deleting the folder, and run `git worktree prune` afterwards. +- **Shared storage.** pnpm uses APFS clones on macOS and hardlinks on Linux. + Removing one `node_modules` frees little while other projects or the store + still share it. Worktrees of one repository often share their dependency + folders the same way. Pass every tree the user might remove to + `diskhound_measure_removal` in one call for what they free together. See + [macos.md](macos.md#apfs-clones) and [linux.md](linux.md#shared-storage). + +| Ecosystem | Where it lives | Cleanup | +| --- | --- | --- | +| Node: project deps | `/node_modules` | Delete the folder; `npm install` / `pnpm install` / `bun install` restores it. | +| npm | `~/.npm/_cacache` (`%LOCALAPPDATA%\npm-cache` on Windows) | `npm cache clean --force` | +| pnpm | `pnpm store path` | `pnpm store prune` (removes packages no project references) | +| Yarn | `yarn cache dir` | `yarn cache clean` (Berry: `yarn cache clean --all`) | +| Bun | `~/.bun/install/cache` | `bun pm cache rm` | +| JS build output | `dist/`, `build/`, `.next/`, `.turbo/`, `.nuxt/`, `.parcel-cache/` | Delete; the next build recreates it. | +| Rust | `/target` | `cargo clean` in the project. | +| Cargo registry | `~/.cargo/registry` | Deleting `~/.cargo/registry/cache` and `src` is safe; Cargo re-downloads. | +| Go | `go env GOCACHE`, `go env GOMODCACHE` | `go clean -cache`, `go clean -modcache` | +| Python venvs | `/.venv`, `venv/` | Delete; recreate from `requirements.txt` / `pyproject.toml`. | +| pip / uv / conda | `pip cache dir`, `uv cache dir`, `conda info` | `pip cache purge`, `uv cache clean`, `conda clean --all` | +| Hugging Face / model caches | `~/.cache/huggingface`, `~/.ollama/models`, LM Studio model folders | User-downloaded models; ask. `huggingface-cli delete-cache` helps choose. | +| Gradle | `~/.gradle/caches`, `/.gradle`, `/build` | Stop daemons (`./gradlew --stop`), then delete `~/.gradle/caches`. | +| Maven | `~/.m2/repository` | Safe to delete; re-downloads on next build. | +| .NET | `~/.nuget/packages`, `/bin`, `/obj` | `dotnet nuget locals all --clear`; delete `bin`/`obj`. | +| Xcode | DerivedData, Archives, DeviceSupport, simulators | See [macos.md](macos.md#usual-hotspots). Archives hold the dSYMs for shipped builds, so ask first. | +| Android | `~/.android/avd`, `$ANDROID_HOME/system-images`, `$ANDROID_HOME/ndk` | Delete unused emulators in Android Studio's Device Manager; uninstall old SDK parts with the SDK Manager. | +| Docker | Images, build cache, volumes | `docker system df`; `docker builder prune`; `docker image prune -a`; `docker volume prune` deletes data, so ask. | +| Homebrew | `brew --cache`, old kegs | `brew cleanup --prune=all`, `brew autoremove` | +| ccache / sccache | `ccache -s`, `sccache --show-stats` | `ccache -C`; stop sccache and delete its cache directory. | +| CMake builds | `build/`, `cmake-build-*` | Delete; reconfigure to rebuild. | +| IDE caches | JetBrains `caches`/`index`, VS Code `CachedData`, `CachedExtensionVSIXs` | Quit the IDE first. JetBrains: File > Invalidate Caches. | diff --git a/skills/diskhound-free-up-space/references/linux.md b/skills/diskhound-free-up-space/references/linux.md new file mode 100644 index 00000000..33a8f679 --- /dev/null +++ b/skills/diskhound-free-up-space/references/linux.md @@ -0,0 +1,46 @@ +# Linux: where space hides + +DiskHound scans stay on one filesystem. Scan `/`, and separately scan +`/home` or any other mount the user cares about if it is its own +filesystem. `diskhound_status` lists the mounts it sees. + +## When "used" is much bigger than the scan total + +| Cause | Check (read-only) | How it gets freed | +| --- | --- | --- | +| btrfs snapshots (Snapper, Timeshift) | `sudo btrfs subvolume list -s /`, `snapper list`, `sudo timeshift --list` | `snapper delete `, `sudo timeshift --delete --snapshot ''`, or the tool's retention settings. | +| ZFS snapshots | `zfs list -t snapshot -o name,used,refer` | `zfs destroy pool/fs@snap`. This is destructive; confirm with the user first. | +| Deleted files still held open | `sudo lsof -nP +L1` | Restart the process holding them (often a log writer or a database). | +| ext4 reserved blocks (usually 5 %, for root) | `sudo tune2fs -l ` (the "Reserved block count" line) | Normal. Explains a `df` gap; only change it on data-only disks. | +| Other mounts under the scan root | `findmnt`, `df -h` | Scan them as separate roots. | +| Files the scan could not read | `skippedEntries` in `diskhound_scan_summary` | Some root-owned directories need elevated rights; `sudo du -xsh ` confirms their size. | + +## Shared storage + +- **Hardlinks.** DiskHound counts every hardlinked path at full size on + Linux, so trees of hardlinks look bigger than the space they use. pnpm + hardlinks `node_modules` to its store by default. Find multi-link files + with `find -xdev -type f -links +1`. Space returns only when the + last link is removed. `diskhound_measure_removal` counts each file once + and tells you what a set of paths frees. For pnpm: remove the unneeded + `node_modules`, then run `pnpm store prune`. +- **Reflinks.** `cp --reflink` copies on btrfs or XFS, and some package + managers, share extents like APFS clones. Every copy must go before the + extents are freed. On btrfs, `compsize ` (package `btrfs-compsize`) + shows real on-disk usage including shared and compressed extents. + +## Built-in cleanup + +| Area | Check | Cleanup | +| --- | --- | --- | +| systemd journal | `journalctl --disk-usage` | `sudo journalctl --vacuum-size=500M` | +| apt / dnf / pacman caches | `du -sh /var/cache/apt /var/cache/dnf /var/cache/pacman` | `sudo apt clean`, `sudo dnf clean all`, `paccache -r` | +| Old snap revisions | `snap list --all` (look for `disabled`) | `sudo snap remove --revision `; `sudo snap set system refresh.retain=2` | +| Flatpak runtimes | `flatpak list --runtime` | `flatpak uninstall --unused` | +| Docker / Podman | `docker system df`, `podman system df` | `docker system prune` removes stopped containers too, so ask; add `-a` for unused images; `--volumes` deletes data | +| Old kernels | `dpkg -l 'linux-image-*'` | `sudo apt autoremove --purge` removes every package nothing depends on, not only kernels: show the user its list (`apt autoremove --dry-run`) first. | +| Trash | `~/.local/share/Trash` | Empty from the file manager, or `gio trash --empty`. | +| Thumbnails and caches | `~/.cache` | Mostly regenerable; quit apps first. | + +For developer caches (npm, pnpm, cargo, Gradle, pip, Go, โ€ฆ) see +[developer-caches.md](developer-caches.md). diff --git a/skills/diskhound-free-up-space/references/macos.md b/skills/diskhound-free-up-space/references/macos.md new file mode 100644 index 00000000..5d8d7493 --- /dev/null +++ b/skills/diskhound-free-up-space/references/macos.md @@ -0,0 +1,109 @@ +# macOS: where space hides + +Scan `/`. On modern Macs that is the read-only system volume plus the +`/System/Volumes/Data` volume where every user file lives. DiskHound shows +them as one startup disk. + +## When "used" is much bigger than the scan total + +The startup disk is an APFS container that several volumes share: System, +Data, Preboot, Recovery, VM, and sometimes others. Free space is shared across +all of them. Check these, in this order: + +| Cause | Check (read-only) | How it gets freed | +| --- | --- | --- | +| Time Machine local snapshots | `tmutil listlocalsnapshots /` | Expire on their own (about 24 h), or thin or delete them (below). | +| Other APFS snapshots (backup apps) | `diskutil apfs listSnapshots /System/Volumes/Data` | Via the app that made them. `Purgeable: Yes` means macOS may drop it under pressure. | +| Swap and sleep image | `ls -lh /private/var/vm` | Managed by macOS; reboot to shrink swap. | +| Other volumes in the container | `diskutil apfs list` | Their owners (e.g. a second macOS install or a Docker volume). | +| Purgeable space | `diskutil info /` (the "Free Space" lines) | macOS reclaims it on demand (iCloud-evictable files, caches, snapshots). | +| Files the scan could not read | `skippedEntries` in `diskhound_scan_summary` | Grant DiskHound Full Disk Access in System Settings > Privacy & Security, then rescan. | + +System Settings > General > Storage has the same breakdown with Apple's own +cleanup buttons (Documents, iCloud Drive, Messages, Photos, and so on). Point +the user there for app-managed data. + +## APFS clones + +A clone is a copy that shares data blocks with its source (`clonefile(2)`). +Only the blocks one copy changes get their own storage. Clones come from: + +- **pnpm on APFS.** `package-import-method` defaults to `auto`, which clones + from the content-addressable store into each project's `node_modules`. + Check with `pnpm config get package-import-method` and `pnpm store path`. +- **Finder.** Duplicate (Cmd-D), and copy/paste within the same volume. +- **The command line:** `cp -c`, `ditto --clone`, and some backup, sync, and + Xcode workflows. + +What this means for cleanup: + +- **Every clone that shares a block must be deleted before that block is + freed.** Deleting one `node_modules` while five other projects and the + pnpm store still hold clones frees almost nothing. +- Sizes over-count shared data. DiskHound, `du`, and Finder all report each + clone at its full size, so adding up clones overstates what their removal + returns. +- To actually free pnpm space, delete every `node_modules` you no longer need + (Dev Artifacts lists them all) **and** run `pnpm store prune`, which drops + store packages no project references. +- macOS has no standard command that shows how much of a file is shared. + `diskhound_measure_removal` reads each file's clone id and reference count + and tells you what a set of paths frees. A clone that was rewritten after + copying reports its own blocks only; the rest is `uncertainBytes`. To + confirm afterwards, note free space with `diskhound_status`, remove the + items, empty the Trash, and check again. Allow for local snapshots (next + section), which also delay the change. + +## Time Machine local snapshots + +When Time Machine is on, macOS takes hourly local APFS snapshots of the Data +volume and keeps them for about 24 hours, or longer if a backup disk has not +been connected. A snapshot keeps every block that existed when it was taken. +**Files deleted after a snapshot keep using space until that snapshot is gone.** +This is the most common reason a big cleanup "didn't free anything". + +Read-only checks: + +```sh +tmutil listlocalsnapshots / # com.apple.TimeMachine.2026-09-24-101112.local โ€ฆ +tmutil listlocalsnapshotdates / # just the dates +diskutil apfs listSnapshots /System/Volumes/Data # every snapshot of the Data volume, not only Time Machine's +``` + +To free the space sooner (tell the user what each command does, and run it +only if they ask; some need `sudo`): + +```sh +tmutil thinlocalsnapshots / 999999999999 4 # ask macOS to reclaim up to ~1 TB, urgency 4 (highest) +tmutil deletelocalsnapshots 2026-09-24-101112 # delete one snapshot by date +tmutil deletelocalsnapshots / # delete all local snapshots on the volume +``` + +Deleting local snapshots does **not** touch backups on the Time Machine disk. +It only removes the on-Mac restore points from the last day. Leave the +`com.apple.os.update-*` snapshot that `diskutil apfs listSnapshots /` shows +alone. It is the sealed system volume, not user data. macOS also thins +snapshots automatically when free space runs low, so "wait a day" is a valid +answer when the user isn't in a hurry. + +## Usual hotspots + +Look here with `diskhound_list_folder` (replace `~` with the user's home +path): + +| Path | What it is | Cleanup | +| --- | --- | --- | +| `~/Library/Developer/Xcode/DerivedData` | Build intermediates | Safe to delete; Xcode rebuilds. | +| `~/Library/Developer/Xcode/iOS DeviceSupport` | Symbols per iOS version | Old versions are safe to delete. | +| `~/Library/Developer/CoreSimulator` | Simulator devices and runtimes | `xcrun simctl delete unavailable`; `xcrun simctl runtime list` then `xcrun simctl runtime delete `. | +| `~/Library/Containers/com.docker.docker` | Docker Desktop disk image (`Docker.raw`) | `docker system df`, then `docker system prune` (it also removes stopped containers, so ask). Docker Desktop > Settings > Resources sets the image size. | +| `~/Library/Application Support/MobileSync/Backup` | iPhone/iPad backups | Finder > device > Manage Backups. User data: ask. | +| `~/Library/Caches` | App caches | Mostly regenerable. Quit the app first. | +| `~/Library/Mail`, `~/Pictures/Photos Library.photoslibrary` | App-managed libraries | Use the app (e.g. Photos > Settings > iCloud > Optimize Mac Storage). Never delete inside a library. | +| `~/Library/Mobile Documents` | iCloud Drive | Right-click > Remove Download keeps the file in iCloud. | +| `~/Downloads`, `~/Desktop` | Installers, archives, disk images | User data: ask. `.dmg`/`.pkg`/`.zip` installers are usually safe once installed. | +| `/Library/Updates`, `/private/var/folders` | OS update staging, per-user temp | Leave to macOS; a reboot clears much of it. | +| `$(brew --cache)`, `/opt/homebrew/Cellar` | Homebrew downloads and old versions | `brew cleanup --prune=all`, `brew autoremove`. | + +For developer caches (npm, pnpm, cargo, Gradle, pip, Go, โ€ฆ) see +[developer-caches.md](developer-caches.md). diff --git a/skills/diskhound-free-up-space/references/windows.md b/skills/diskhound-free-up-space/references/windows.md new file mode 100644 index 00000000..16152374 --- /dev/null +++ b/skills/diskhound-free-up-space/references/windows.md @@ -0,0 +1,66 @@ +# Windows: where space hides + +Scan `C:\` (and any other drive the user cares about). When DiskHound runs +elevated it reads the NTFS Master File Table directly. That is much faster, +it sees folders a normal user cannot open, and it counts each hardlinked file +**once**. Settings > Performance in DiskHound sets this up. + +## When "used" is much bigger than the scan total + +| Cause | Check (read-only; some need an admin terminal) | How it gets freed | +| --- | --- | --- | +| System Restore / Volume Shadow Copies | `vssadmin list shadowstorage` | System Properties > System Protection > Configure (lower Max Usage, or Delete restore points). | +| Hibernation file | `Get-Item -Force C:\hiberfil.sys` (PowerShell) | `powercfg /hibernate off` (admin) if the user never hibernates. | +| Page file | `Get-Item -Force C:\pagefile.sys` (PowerShell) | Leave it to Windows unless the user knows why they're changing it. | +| Folders the scan could not read | `skippedEntries` in `diskhound_scan_summary` | Run DiskHound elevated (Settings > Performance) and rescan. | +| Recycle Bin on each drive | `C:\$Recycle.Bin` | Empty it in Explorer, or `Clear-RecycleBin -DriveLetter C` (PowerShell). | + +## Things that look big but aren't (or won't shrink) + +- **`C:\Windows\WinSxS`** is mostly hardlinks into `C:\Windows\System32`, so + Explorer overstates it. Never delete inside it. Measure and clean it with + `Dism.exe /Online /Cleanup-Image /AnalyzeComponentStore`, then + `Dism.exe /Online /Cleanup-Image /StartComponentCleanup` (admin). +- **`C:\Windows\Installer`, `C:\ProgramData\Package Cache`**: deleting these + breaks uninstall and repair. Leave them alone. +- **WSL 2 and Docker Desktop disks** (`ext4.vhdx`, `docker_data.vhdx`, under + `%LOCALAPPDATA%`) grow but never shrink on their own. Deleting files + inside the Linux distro does not return space to Windows until the disk is + compacted: + - Run `wsl --manage --set-sparse true` once (recent WSL), or + - Run `wsl --shutdown`, then `Optimize-VHD -Path -Mode Full` + (Hyper-V PowerShell module), or use diskpart's `compact vdisk`. + - For Docker: `docker system prune` first (it also removes stopped + containers, so ask), then compact. +- **OneDrive placeholders.** Files On-Demand that are cloud-only use almost + no space. Right-click > "Free up space" turns downloaded files back into + placeholders. +- **Hardlinks elsewhere.** With the MFT scanner, DiskHound counts them once. + Explorer and many tools count each link. + +## Built-in cleanup + +- **Settings > System > Storage > Temporary files** covers Windows Update + cleanup, Delivery Optimization, previous Windows installations + (`C:\Windows.old`), thumbnails, and the Recycle Bin. Storage Sense can + automate it. +- **Disk Cleanup** (`cleanmgr`) > "Clean up system files" does the same on + older builds. +- Delete `C:\Windows.old` only through those tools; the folder is protected. + +## Usual hotspots + +| Path | What it is | Cleanup | +| --- | --- | --- | +| `%LOCALAPPDATA%\Temp` | Per-user temp | Mostly safe; skip files in use. | +| `C:\Windows\SoftwareDistribution\Download` | Update downloads | Temporary files > Windows Update Cleanup. | +| `%LOCALAPPDATA%\Packages\\LocalState\ext4.vhdx` | WSL 2 disk | Clean inside the distro, then compact (above). | +| `%LOCALAPPDATA%\Docker\wsl` | Docker Desktop data | `docker system prune` (ask: it removes stopped containers), then compact. | +| `%USERPROFILE%\Downloads` | Installers, archives, ISOs | User data: ask. Installers (`.exe`, `.msi`) are usually safe once installed. | +| `%APPDATA%\Apple Computer\MobileSync\Backup` or `%USERPROFILE%\Apple\MobileSync\Backup` | iPhone backups | Manage in iTunes / Apple Devices. User data: ask. | +| `%LOCALAPPDATA%\NVIDIA\DXCache`, `%LOCALAPPDATA%\D3DSCache` | Shader caches | Regenerable. | +| `C:\Users\\AppData\Local\Microsoft\Windows\INetCache`, browser profiles | Web caches | Clear from the browser's settings. | +| Game libraries (`Steam\steamapps`, `Epic Games`, `XboxGames`) | Installed games | Uninstall from the launcher, never by deleting folders. | + +For developer caches (npm, pnpm, NuGet, cargo, Gradle, pip, Go, โ€ฆ) see +[developer-caches.md](developer-caches.md). diff --git a/skills/diskhound-investigate-growth/SKILL.md b/skills/diskhound-investigate-growth/SKILL.md new file mode 100644 index 00000000..d6cb2ae4 --- /dev/null +++ b/skills/diskhound-investigate-growth/SKILL.md @@ -0,0 +1,74 @@ +--- +name: diskhound-investigate-growth +description: Explain why a drive lost free space by comparing DiskHound's scan history with its MCP tools. Use when the user asks what filled their disk, what grew this week, or why free space keeps dropping. Also covers growth no file scan can see, such as local snapshots, shadow copies, and deleted-but-open files. +license: MIT +compatibility: Requires the DiskHound desktop app with Settings > AI Agents enabled and its MCP server connected. +--- + +# Why did my disk fill up? + +DiskHound keeps several past scans per drive (Settings > Storage sets how +many) and can diff any two of them. Use that history to name what grew, +when, and which app or project owns it. + +## Procedure + +1. **Establish the timeline.** Call `diskhound_status` for current free + space, then `diskhound_scan_history` for the root. Ask the user roughly + when space started disappearing, if they know. + +2. **Make sure there is something to compare.** + - With only one scan, start a new one (`diskhound_start_scan`, + `showInApp: true`). The first diff will cover only the time since the + old scan. + - Suggest scheduled rescans (Settings > Drive Monitoring > full rescan + interval) so future questions have history. + - If the newest scan is stale, rescan first so the diff reaches today. + +3. **Get the overview.** Call `diskhound_changes` with `detail: "summary"` + and `showInApp: true`. Pick `since` to match the user's timeline (`1d`, + `1w`, `1M`), or pass `baselineId` from the history. Read: + - `net`: total growth between the scans. + - `folders`: the directories that moved most. This is usually the answer. + - `fileTypes`: e.g. `.log`, `.mov`, `.vhdx` growing points at the + culprit. + +4. **Drill in.** For each large growing folder: + - Call `diskhound_list_folder` on it (`showInApp: true`) to see which + child grew. + - For exact files, call `diskhound_changes` with `detail: "files"`. It + walks the full per-file index and can take a while on big drives. + - Name the owner: an app's cache, a project's build output, a VM or + container disk, a sync client, a log that never rotates. + +5. **Compare with what the OS says.** If free space fell by much more than + the diff's `net`, the growth is outside the files DiskHound indexed: + - **macOS**: Time Machine local snapshots grow with every change since + the last snapshot (`tmutil listlocalsnapshots /`), swap grows under + memory pressure (`ls -lh /private/var/vm`), and other APFS volumes + share the container (`diskutil apfs list`). + - **Windows**: System Restore shadow copies (`vssadmin list shadowstorage`), + and WSL/Docker `.vhdx` disks that grew and never shrink. + - **Linux**: btrfs/ZFS snapshots, deleted-but-open files + (`sudo lsof -nP +L1`), and a growing systemd journal + (`journalctl --disk-usage`). + + Details for each are in the `diskhound-free-up-space` skill's platform + references (`skill://diskhound-free-up-space/references/macos.md`, + `โ€ฆ/windows.md`, `โ€ฆ/linux.md`). + +6. **Report.** Give a short explanation first: "About 38 GB went into Docker's + disk image and 12 GB into Xcode DerivedData since last Tuesday." Follow + with a table of the top movers: path, change, owner, and whether it will + keep growing. If the user wants to reclaim space, switch to the + `diskhound-free-up-space` skill (`skill://diskhound-free-up-space/SKILL.md`). + +## Reading the numbers + +- Sizes are bytes on disk. Sparse files (VM disks, `Docker.raw`) count + only their allocated blocks. +- If `sizeSemanticsChanged` is true, the two scans measured sizes + differently (an older DiskHound build on Windows). Compare folders, not + the total. +- Summary lists are the biggest movers DiskHound tracked for each scan. + `detail: "files"` is exhaustive. diff --git a/src/__tests__/renderer.agents.ioBudget.test.ts b/src/__tests__/renderer.agents.ioBudget.test.ts new file mode 100644 index 00000000..39e644b5 --- /dev/null +++ b/src/__tests__/renderer.agents.ioBudget.test.ts @@ -0,0 +1,344 @@ +// @vitest-environment happy-dom +import "node:fs/promises"; +import * as FS from "node:fs"; +import * as HTTP from "node:http"; +import * as NET from "node:net"; +import * as Path from "node:path"; + +import { Fragment, h } from "preact"; +import { beforeAll, describe, expect, it, vi } from "vitest"; + +import { McpPolicyStore } from "../mcp/accessPolicy"; +import { AgentButton } from "../renderer/components/AgentButton"; +import { AgentsSection } from "../renderer/components/AgentsSection"; +import { focusAgentSettings } from "../renderer/lib/agentAccessStore"; +import { nativeApi } from "../renderer/nativeApi"; +import { MCP_AGENT_CAPABILITIES } from "../shared/agentAccess"; +import { expectIoBudget, measureFsIo } from "../test/ioBudget"; +import { bootMainProcess, type MainProcess } from "../test/mainProcessHarness"; +import { hostRoot, seedProfile } from "../test/mainProfileFixture"; +import { bootRenderer, button, click, one, type Renderer, withText } from "../test/rendererHarness"; +import { unzip } from "../test/zipReader"; + +vi.mock("node:fs", async (importOriginal) => + (await import("../test/ioBudget")).instrumentFs(await importOriginal())); +vi.mock("node:fs/promises", async (importOriginal) => + (await import("../test/ioBudget")).instrumentFsPromises(await importOriginal())); +vi.mock("node:child_process", async (importOriginal) => + (await import("../test/ioBudget")).instrumentChildProcess(await importOriginal())); +vi.mock("node:worker_threads", async (importOriginal) => + (await import("../test/ioBudget")).instrumentWorkerThreads(await importOriginal())); +vi.mock("electron", async () => + (await import("../test/mainProcessHarness")).fakeElectron()); +vi.mock("../shared/crashLog", async (importOriginal) => + (await import("../test/mainProcessHarness")).settledCrashLog(await importOriginal())); +// main requires the agent runtime as its own bundle (mcp/agentRuntime.cjs), +// which vitest doesn't build. Hand it the source module instead, loaded +// in beforeAll, so turning agents on starts the real listener. +const runtime = vi.hoisted(() => ({ module: null as unknown })); +vi.mock("node:module", async (importOriginal) => { + const original = await importOriginal(); + const createRequire = (from: string | URL) => { + const real = original.createRequire(from); + return Object.assign( + (id: string) => (id.replaceAll("\\", "/").endsWith("/mcp/agentRuntime.cjs") ? runtime.module : real(id)), + real, + ) as NodeJS.Require; + }; + return { ...original, createRequire, default: { ...original, createRequire } }; +}); + +// The header agent button and Settings โ†’ AI Agents share one snapshot +// that main pushes changes into. Opening the popover, switching client +// tabs and following links between them should never ask main for +// anything, and an agent's blocked request should reach the UI as a +// push, costing one append to the security log. + +vi.setConfig({ testTimeout: 30_000 }); + +const ROOT = hostRoot("/Volumes/Data"); +const ALL = [...MCP_AGENT_CAPABILITIES]; + +let main: MainProcess; +let ui: Renderer; +let port: number; +let guideToken: string; +// Claude Desktop isn't made for Linux, so DiskHound doesn't offer it there. +const hasClaudeDesktop = process.platform !== "linux"; + +function freePort(): Promise { + return new Promise((resolve, reject) => { + const server = NET.createServer(); + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + const { port: free } = server.address() as NET.AddressInfo; + server.close(() => resolve(free)); + }); + }); +} + +/** One JSON-RPC POST to /mcp, as Codex sends it. node:http so Host is exact. */ +function mcpPost(token: string, body: unknown): Promise<{ status: number; json: any }> { + return new Promise((resolve, reject) => { + const payload = JSON.stringify(body); + const request = HTTP.request({ + host: "127.0.0.1", + port, + method: "POST", + path: "/mcp", + agent: false, + headers: { + host: `127.0.0.1:${port}`, + authorization: `Bearer ${token}`, + "content-type": "application/json", + accept: "application/json, text/event-stream", + "content-length": Buffer.byteLength(payload), + }, + }, (response) => { + let text = ""; + response.setEncoding("utf8"); + response.on("data", (chunk: string) => (text += chunk)); + response.on("end", () => resolve({ status: response.statusCode ?? 0, json: JSON.parse(text) })); + }); + request.on("error", reject); + request.end(payload); + }); +} + +beforeAll(async () => { + runtime.module = await import("../mcp/agentRuntime"); + port = await freePort(); + process.env.DISKHOUND_AGENT_PORT = String(port); + main = await bootMainProcess({ + seed: async (userData) => { + await seedProfile(userData, { roots: [{ rootPath: ROOT, scans: 1 }] }); + // A stand-in for the stdio helper, which a checkout under test may not + // have built: a release build's 1.4 MB (one architecture), half noise + // so it deflates to about the real one's 0.7 MB. + const helper = Path.join(Path.dirname(userData), "helper", "diskhound-mcp"); + const noise = Buffer.alloc(700_000); + for (let i = 0, x = 2_463_534_242; i < noise.length; i++) { + x ^= x << 13; x ^= x >>> 17; x ^= x << 5; // xorshift32 + noise[i] = x & 0xff; + } + FS.mkdirSync(Path.dirname(helper), { recursive: true }); + FS.writeFileSync(helper, Buffer.concat([noise, Buffer.alloc(700_000)])); + process.env.DISKHOUND_MCP_PATH = helper; + const settingsFile = Path.join(userData, "settings.json"); + const settings = JSON.parse(FS.readFileSync(settingsFile, "utf8")); + FS.writeFileSync(settingsFile, JSON.stringify({ ...settings, agents: { enabled: true } }, null, 2)); + + // A profile that has used agents for a while: three live sessions, + // a revoked one, and refusals from earlier runs. + const policy = new McpPolicyStore(Path.join(userData, "mcp-policy.json")); + guideToken = policy.createSession("Claude Code โ€” diskhound", "builtin.guide", { clientId: "client_cc", scopes: ALL }, + { name: "Claude Code", via: "stdio" }).token; + policy.createSession("Codex", "builtin.operator", { clientId: "client_codex", scopes: ALL }, { name: "Codex", via: "http" }); + policy.createSession("Claude Desktop", "builtin.reader", { clientId: "client_cd", scopes: ["disk.read", "scan.run", "app.navigate"] }, + { name: "Claude Desktop", via: "stdio" }); + const old = policy.createSession("Old agent", "builtin.guide", { clientId: "client_old", scopes: ALL }); + policy.revokeSession(old.session.id); + const at = Date.now() - 3 * 24 * 60 * 60_000; + const lines = Array.from({ length: 40 }, (_, i) => JSON.stringify({ + id: `security-old-${i}`, + at: at + i * 60_000, + sessionId: old.session.id, + sessionName: "Old agent", + roleName: "Cleanup Guide", + kind: "tool_not_allowed", + tool: "diskhound_move_to_trash", + detail: `Tried to move items to the Trash; Cleanup Guide doesn't allow it. (${i})`, + count: 1, + })); + FS.writeFileSync(Path.join(userData, "agent-security.log"), `${lines.join("\n")}\n`, { mode: 0o600 }); + }, + }); + ui = await bootRenderer(); +}, 60_000); + +function mountAgentUi(): HTMLElement { + return ui.mount(h(Fragment, null, + h(AgentButton, { onOpenSettings: (target) => focusAgentSettings(target) }), + h(AgentsSection, null), + )); +} + +describe("AI Agents UI", () => { + it("loads the snapshot once, then opens the popover, switches client tabs and follows links from memory", async () => { + const view = mountAgentUi(); + await ui.settle(); + // One load shared by the header button and Settings. + expect(ui.takeIpc()).toEqual(["diskhound:agent-access-get"]); + expect(view.querySelectorAll(".agent-session-row")).toHaveLength(3); + // Connected agents fold the connect guide. + expect(view.querySelector(".agent-connect")).toBeNull(); + // The popover's clock is the renderer's first visible poll here, and + // the first poll asks main once whether the window is shown. In the + // app, the header's disk polls did that at launch. + await click(one(view, ".agent-btn")); + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + await ui.settle(); + expect(ui.takeIpc()).toEqual(["diskhound:is-window-shown"]); + + const seen: Record = {}; + const { io } = await measureFsIo(async () => { + for (let i = 0; i < 3; i++) { + await click(one(view, ".agent-btn")); + seen.popoverRows = view.querySelectorAll(".agent-pop-row").length; + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + await ui.settle(); + } + seen.popoverClosed = view.querySelector(".agent-pop") === null; + await click(one(view, ".agent-btn")); + await click(button(view, "Connect an agentโ€ฆ")); + seen.connectOpen = view.querySelector(".agent-connect") !== null; + const tabs = hasClaudeDesktop + ? ["Claude Desktop", "Codex", "Other MCP clients", "Claude Desktop", "Claude Code"] + : ["Codex", "Other MCP clients", "Claude Code"]; + for (const tab of tabs) { + await click(withText(view, ".agent-client-tabs button", tab)); + seen[`tab:${tab}`] = view.querySelector(".agent-prompt-text")?.textContent ?? null; + seen[`add:${tab}`] = view.querySelector(".agent-step-action button")?.textContent ?? null; + } + seen.tabs = [...view.querySelectorAll(".agent-client-tabs button")].map((tab) => tab.textContent); + await click(button(view, "Show command")); + seen.command = view.querySelectorAll(".agent-command-text").length; + await click(button(view, "Hide command")); + await ui.settle(); + }, { countProcesses: true }); + + expect(seen.popoverRows).toBe(3); + expect(seen.popoverClosed).toBe(true); + expect(seen.connectOpen).toBe(true); + // Each tab hands the user a prompt for the agent to set itself up; + // DiskHound never writes another app's configuration. + expect(seen["tab:Codex"]).toContain("Add diskhound to my Codex user configuration"); + expect(seen["tab:Claude Code"]).toContain("Add diskhound to my Claude Code user configuration"); + expect(seen.command).toBe(2); + if (hasClaudeDesktop) { + // Claude's chat can't run commands: Claude installs DiskHound's extension itself. + expect(seen["tab:Claude Desktop"]).toBeNull(); + expect(seen["add:Claude Desktop"]).toBe("Add to Claude"); + } else { + expect(seen.tabs).toEqual(["Claude Code", "Codex", "Other MCP clients"]); + } + expect(ui.takeIpc()).toEqual([]); + expectIoBudget({ + scenario: "renderer-agents-browse", + note: "Header popover opened 4 times, 3-5 client tabs, a command disclosure and a link into Settings with 3 sessions and 40 logged refusals: " + + "local state, 0 IPC, 0 reads and 0 writes/day at any monitoring interval.", + io, + }); + ui.unmount(); + }); + + it("refuses an agent's delete its role doesn't grant, and shows it without a read", async () => { + const view = mountAgentUi(); + await ui.settle(); + ui.takeIpc(); + + let reply!: { status: number; json: any }; + const { io } = await measureFsIo(async () => { + reply = await mcpPost(guideToken, { + jsonrpc: "2.0", + id: 7, + method: "tools/call", + params: { name: "diskhound_delete_permanently", arguments: { paths: [`${ROOT}/Downloads`] } }, + }); + // The log appends 2 s after the first refusal. + await new Promise((resolve) => setTimeout(resolve, 2_200)); + await ui.settle(); + }, { countProcesses: true }); + + expect(reply.status).toBe(200); + expect(reply.json.result.isError).toBe(true); + expect(reply.json.result.content[0].text).toContain("isn't available to this DiskHound session (Cleanup Guide doesn't grant files.delete)"); + // Pushed into Settings (blocked list, the session's link) and the header. + expect(view.querySelector(".agent-blocked-row")?.textContent).toContain("Tried to delete items permanently; Cleanup Guide doesn't allow it."); + expect(withText(view, ".agent-session-row", "Claude Code โ€” diskhound").querySelector(".agent-blocked-link")?.textContent) + .toContain("1 blocked"); + // The header turns into the agent's pill, red because the call was refused. + const pill = one(view, ".agent-pill.failed"); + expect(pill.textContent).toContain("Claude Code โ€” diskhound"); + await click(pill); + expect(one(view, ".agent-pop-blocked").textContent).toBe("1 blocked request today"); + expect(ui.takeIpc()).toEqual([]); + const log = FS.readFileSync(Path.join(main.userData, "agent-security.log"), "utf8").trim().split("\n"); + expect(JSON.parse(log.at(-1)!)).toMatchObject({ tool: "diskhound_delete_permanently", sessionName: "Claude Code โ€” diskhound", count: 1 }); + expectIoBudget({ + scenario: "renderer-agents-blocked-delete", + note: "A Cleanup Guide agent calls diskhound_delete_permanently over HTTP: refused before any tool runs, one append to " + + "agent-security.log and the crash.log line, pushed to the UI with 0 IPC. Writes happen only when an agent is refused " + + "(not per monitoring tick), and the log caps them at 288 appends and ~0.5 MB/day even for an agent refused nonstop.", + io, + }); + ui.unmount(); + }); + + it("builds DiskHound's Claude extension from its helper and opens it in Claude", async () => { + const view = mountAgentUi(); + await ui.settle(); + await click(withText(view, ".agent-disclose", "Connect another agent")); + ui.takeIpc(); + // Imported once main has booted: the fake electron belongs to the harness. + const { shell } = await import("electron"); + const opened: string[] = []; + shell.openPath = async (target: string) => { + opened.push(target); + return ""; + }; + + const { io } = await measureFsIo(async () => { + if (hasClaudeDesktop) { + await click(withText(view, ".agent-client-tabs button", "Claude Desktop")); + await click(button(view, "Add to Claude")); + } else { + // No tab on Linux; the handler is the same everywhere. + await nativeApi.addAgentToClaude(); + } + await ui.settle(); + }, { countProcesses: true }); + + expect(ui.takeIpc()).toEqual(["diskhound:agent-access-add-to-claude"]); + if (hasClaudeDesktop) expect(one(view, ".agent-step-result").textContent).toBe("Opened in Claude."); + expect(opened).toHaveLength(1); + const entries = unzip(FS.readFileSync(opened[0]!)); + expect(entries.map((entry) => entry.name)).toContain(`server/${process.platform === "win32" ? "diskhound-mcp.exe" : "diskhound-mcp"}`); + expect(JSON.parse(entries[0]!.data.toString("utf8")).server.mcp_config.args).toEqual(["--port", String(port)]); + expectIoBudget({ + scenario: "renderer-agents-add-to-claude", + note: "Add to Claude: reads the helper (1.4 MB), the icon and, unpackaged, package.json, then writes the ~0.7 MB " + + "bundle to temp once and hands it to Claude. A user click, about once per setup, so 0 writes/day and 0 MB/day " + + "from monitoring at the default or the 1-minute interval.", + io, + }); + ui.unmount(); + }); + + it("changes a session's role and revokes one with one policy write each", async () => { + const view = mountAgentUi(); + await ui.settle(); + ui.takeIpc(); + const row = withText(view, ".agent-session-row", "Codex"); + const select = one(row, "select"); + + const { io } = await measureFsIo(async () => { + select.value = "builtin.admin"; + select.dispatchEvent(new Event("change", { bubbles: true })); + await ui.settle(); + await click(button(withText(view, ".agent-session-row", "Claude Desktop"), "Revoke")); + await ui.settle(); + }, { countProcesses: true }); + + expect(ui.takeIpc()).toEqual(["diskhound:agent-access-assign-role", "diskhound:agent-access-revoke"]); + expect(view.querySelectorAll(".agent-session-row")).toHaveLength(2); + expect(one(withText(view, ".agent-session-row", "Codex"), "select").value).toBe("builtin.admin"); + expectIoBudget({ + scenario: "renderer-agents-role-change-revoke", + note: "One role change and one revoke from Settings: each replaces mcp-policy.json once (atomic write + rename). " + + "User clicks only, so a few writes/day and well under 0.1 MB/day at any monitoring interval.", + io, + }); + ui.unmount(); + }); +}); diff --git a/src/main.ts b/src/main.ts index f1b68a18..af4d44b3 100644 --- a/src/main.ts +++ b/src/main.ts @@ -30,7 +30,10 @@ import { type DevBranch, type DevGitRepoInfo, type DiskIoSnapshot, + type DuplicateAnalysis, + type DuplicateScanProgress, type FullDiffStatus, + type IndexSearchQuery, type MonitoringSnapshot, type NavigateViewPayload, type PathActionResult, @@ -180,6 +183,7 @@ import { searchIndexFile } from "./shared/scanIndex"; import { analyzeCleanupFromIndex } from "./shared/suggestions"; import { createNativeScannerSession, type NativeScannerSession } from "./nativeScanner"; import * as elevationModule from "./elevation"; +import { createAgentHost, type AgentHost } from "./mcp/electronHost"; const SCAN_SNAPSHOT_CHANNEL = "diskhound:scan-snapshot"; const DISK_DELTA_CHANNEL = "diskhound:disk-delta"; @@ -1018,7 +1022,16 @@ void (async () => { // โ”€โ”€ Scan helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + // Latest running snapshot per root. scanStore only holds the most + // recent broadcast, which is ambiguous with parallel scans; MCP agents + // polling progress need each root's own numbers. + const liveSnapshotByKey = new Map(); + const broadcastSnapshot = async (nextSnapshot: ScanSnapshot, options?: SnapshotWriteOptions) => { + if (nextSnapshot.rootPath) { + if (nextSnapshot.status === "running") liveSnapshotByKey.set(scanKey(nextSnapshot.rootPath), nextSnapshot); + else liveSnapshotByKey.delete(scanKey(nextSnapshot.rootPath)); + } await scanStore.set(nextSnapshot, options); mainWindow?.webContents.send(SCAN_SNAPSHOT_CHANNEL, nextSnapshot); }; @@ -2082,7 +2095,7 @@ void (async () => { if (result) throw new Error(result); }), ); - ipcMain.handle("diskhound:trash-path", async (_event, targetPath: string) => { + const trashPathImpl = async (targetPath: string): Promise => { const blocked = protectedPathBlock(targetPath, "Trash"); if (blocked) { writeCrashLog("trash", `blocked path=${targetPath} ${blocked.message}`); @@ -2113,8 +2126,16 @@ void (async () => { writeCrashLog("trash", `ok path=${resolved}`); return { ok: true, message: "Moved to trash." }; } - }); - ipcMain.handle("diskhound:permanent-delete-path", async (_event, targetPath: string, expectedFiles?: number) => { + }; + // Removals from the UI change what an agent's removal measurement + // would find. The agent host sets this once it exists. + let pathsRemoved = () => {}; + const noteRemoved = (result: PathActionResult) => { + if (result.ok) pathsRemoved(); + return result; + }; + ipcMain.handle("diskhound:trash-path", async (_event, targetPath: string) => noteRemoved(await trashPathImpl(targetPath))); + const permanentDeletePathImpl = async (targetPath: string, expectedFiles?: number): Promise => { const blocked = protectedPathBlock(targetPath, "Delete"); if (blocked) { writeCrashLog("delete", `blocked path=${targetPath} ${blocked.message}`); @@ -2151,7 +2172,10 @@ void (async () => { `${result.ok ? "ok" : result.requiresElevation ? "needs-admin" : "fail"} elapsedMs=${Date.now() - deleteStartedAt} path=${resolved} ${result.message}`, ); return result; - }); + }; + ipcMain.handle("diskhound:permanent-delete-path", async (_event, targetPath: string, expectedFiles?: number) => + noteRemoved(await permanentDeletePathImpl(targetPath, expectedFiles)), + ); ipcMain.handle("diskhound:permanent-delete-path-elevated", async (_event, targetPath: string) => { const blocked = protectedPathBlock(targetPath, "Delete"); if (blocked) { @@ -2178,7 +2202,7 @@ void (async () => { }; } catch { writeCrashLog("delete", `elevated-ok path=${Path.resolve(targetPath)}`); - return { ok: true, message: "Permanently deleted." }; + return noteRemoved({ ok: true, message: "Permanently deleted." }); } }); @@ -2237,7 +2261,10 @@ void (async () => { ipcMain.handle("diskhound:get-settings", () => settingsStore!.get()); ipcMain.handle("diskhound:update-settings", async (_event, settings: AppSettings) => { const previousSettings = settingsStore!.get(); - const normalizedSettings = normalizeAppSettings(settings); + // `agents` is owned by the AI Agents toggle (its own IPC, which also + // starts/stops the listener). A Settings save carrying a stale copy + // must not flip it back. + const normalizedSettings = normalizeAppSettings({ ...settings, agents: previousSettings.agents }); await settingsStore!.set(normalizedSettings); @@ -3200,12 +3227,11 @@ void (async () => { return tree; } - ipcMain.handle( - "diskhound:get-folder-children", - async (_event, rootPath: string, parentPath: string) => { + const getFolderChildrenImpl = async (rootPath: string, parentPath: string) => { const history = getScanHistory(rootPath); const currentId = history[0]?.id; const empty = { + visibleDirCount: 0, dirs: [], files: [], totalSize: 0, @@ -3270,7 +3296,10 @@ void (async () => { const failed = recentFolderTreeFailure(currentId); return failed ? { ...empty, unavailableMessage: folderTreeFailureMessage(failed) } : empty; } - }, + }; + ipcMain.handle( + "diskhound:get-folder-children", + (_event, rootPath: string, parentPath: string) => getFolderChildrenImpl(rootPath, parentPath), ); ipcMain.handle("diskhound:get-latest-diff", async (_event, rootPath: string) => { @@ -3333,7 +3362,7 @@ void (async () => { // โ”€โ”€ IPC: Cleanup Analysis โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - ipcMain.handle("diskhound:analyze-cleanup", async (_event, rootPath: string) => { + const analyzeCleanupImpl = async (rootPath: string) => { const history = getScanHistory(rootPath); const current = history[0]; const settings = settingsStore!.get(); @@ -3351,13 +3380,17 @@ void (async () => { settings.cleanup, settings.scanning.excludedFolderPaths, ); - }); - ipcMain.handle("diskhound:search-index", async (_event, rootPath: string, query: { query: string; minSizeBytes?: number; extension?: string; limit?: number }) => { + }; + ipcMain.handle("diskhound:analyze-cleanup", (_event, rootPath: string) => analyzeCleanupImpl(rootPath)); + const searchIndexImpl = async (rootPath: string, query: IndexSearchQuery) => { const history = getScanHistory(rootPath); const current = history[0]; if (!current) return { hits: [], truncated: false, filesScanned: 0 }; return searchIndexFile(indexFilePath(current.id), query); - }); + }; + ipcMain.handle("diskhound:search-index", (_event, rootPath: string, query: IndexSearchQuery) => + searchIndexImpl(rootPath, query), + ); // Reports per scan, empty ones included: Overview and the Dev tab // ask on every mount. const devArtifactCache = new Map(); @@ -3399,7 +3432,10 @@ void (async () => { previousId ? devArtifactsSidecarPath(previousId) : null, ); - ipcMain.handle("diskhound:get-dev-artifacts", async (_event, rootPath: string, options?: { sidecarOnly?: boolean }) => { + const getDevArtifactsImpl = async ( + rootPath: string, + options?: { sidecarOnly?: boolean }, + ): Promise => { const history = getScanHistory(rootPath); const current = history[0]; if (!current) return null; @@ -3485,7 +3521,10 @@ void (async () => { }); devArtifactInflight.set(current.id, pending); return pending; - }); + }; + ipcMain.handle("diskhound:get-dev-artifacts", (_event, rootPath: string, options?: { sidecarOnly?: boolean }) => + getDevArtifactsImpl(rootPath, options), + ); ipcMain.handle("diskhound:cancel-dev-artifacts-rescan", (_event, rootPath: string) => { const key = scanKey(rootPath); @@ -3619,7 +3658,11 @@ void (async () => { // โ”€โ”€ IPC: Duplicate Detection โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - ipcMain.handle("diskhound:start-duplicate-scan", (_event, rootPath: string, options?: { minSizeBytes?: number }) => { + // Latest duplicate progress / result per root, kept so MCP agents can + // read them โ€” the renderer keeps its own copies from the broadcasts. + const duplicateProgressByKey = new Map(); + const duplicateResultByKey = new Map(); + const startDuplicateScanImpl = (rootPath: string, options?: { minSizeBytes?: number }) => { // Whole-handler try/catch โ€” main-process IPC handlers that throw // synchronously surface as the "DiskHound โ€” Unexpected error" // dialog via the uncaughtException hook. Belt-and-suspenders. @@ -3656,6 +3699,8 @@ void (async () => { // memory than re-walking the filesystem. Fall back to walk if no // suitable index exists or if the path isn't under any known scan. const indexPath = findIndexCoveringPath(resolvedRoot); + duplicateResultByKey.delete(key); + duplicateProgressByKey.delete(key); const handle = runDuplicateScan( resolvedRoot, @@ -3663,12 +3708,12 @@ void (async () => { onProgress: (progress) => { // Tag every progress emission with the rootPath so the // renderer can route it to the right per-drive state slot. - mainWindow?.webContents.send(DUPLICATE_PROGRESS_CHANNEL, { - ...progress, - rootPath: resolvedRoot, - }); + const tagged = { ...progress, rootPath: resolvedRoot }; + duplicateProgressByKey.set(key, { ...tagged, newGroups: undefined }); + mainWindow?.webContents.send(DUPLICATE_PROGRESS_CHANNEL, tagged); }, onResult: (result) => { + duplicateResultByKey.set(key, result); mainWindow?.webContents.send(DUPLICATE_RESULT_CHANNEL, result); activeDuplicateScans.delete(key); sendToast("success", "Duplicate scan complete", @@ -3686,7 +3731,7 @@ void (async () => { "dup-scan-error", `root=${resolvedRoot} error=${error.stack ?? error.message ?? String(error)}`, ); - mainWindow?.webContents.send(DUPLICATE_PROGRESS_CHANNEL, { + const errorProgress: DuplicateScanProgress = { rootPath: resolvedRoot, status: "error", filesWalked: 0, @@ -3695,7 +3740,9 @@ void (async () => { groupsConfirmed: 0, elapsedMs: 0, errorMessage: error.message, - }); + }; + duplicateProgressByKey.set(key, errorProgress); + mainWindow?.webContents.send(DUPLICATE_PROGRESS_CHANNEL, errorProgress); activeDuplicateScans.delete(key); }, }, @@ -3737,7 +3784,10 @@ void (async () => { }); } catch { /* ignore */ } } - }); + }; + ipcMain.handle("diskhound:start-duplicate-scan", (_event, rootPath: string, options?: { minSizeBytes?: number }) => + startDuplicateScanImpl(rootPath, options), + ); /** * Search the scan-history index for the most recent scan whose root @@ -4229,6 +4279,13 @@ void (async () => { quitDiskHound(); }, }; + // Settings โ†’ AI Agents, for users who never scroll that far. + const connectAgentItem: MenuItemConstructorOptions = { + label: "Connect an AI Agentโ€ฆ", + click: () => { + void agentHost?.showSettings(); + }, + }; const template: MenuItemConstructorOptions[] = process.platform === "darwin" ? [ { @@ -4236,6 +4293,8 @@ void (async () => { submenu: [ { role: "about" }, { type: "separator" }, + connectAgentItem, + { type: "separator" }, { role: "hide" }, { role: "hideOthers" }, { role: "unhide" }, @@ -4247,7 +4306,7 @@ void (async () => { { role: "editMenu" }, ] : [ - { label: "File", submenu: [quitItem] }, + { label: "File", submenu: [connectAgentItem, { type: "separator" }, quitItem] }, { role: "editMenu" }, ]; Menu.setApplicationMenu(Menu.buildFromTemplate(template)); @@ -4284,6 +4343,12 @@ void (async () => { void createSystemWidgetWindow(); }, }, + { + label: "AI Agentsโ€ฆ", + click: () => { + void agentHost?.showSettings(); + }, + }, { type: "separator" }, { label: "Quit", @@ -4302,14 +4367,14 @@ void (async () => { // โ”€โ”€ Window โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - const loadRenderer = async (window: BrowserWindow, mode: "app" | "widget") => { + const loadRenderer = async (window: BrowserWindow, mode: "app" | "widget" | "consent") => { if (rendererEntryUrl) { - const url = mode === "widget" - ? `${rendererEntryUrl}${rendererEntryUrl.includes("?") ? "&" : "?"}widget=1` - : rendererEntryUrl; + const url = mode === "app" + ? rendererEntryUrl + : `${rendererEntryUrl}${rendererEntryUrl.includes("?") ? "&" : "?"}${mode}=1`; await window.loadURL(url); - } else if (mode === "widget") { - await window.loadFile(rendererEntryFile, { query: { widget: "1" } }); + } else if (mode !== "app") { + await window.loadFile(rendererEntryFile, { query: { [mode]: "1" } }); } else { await window.loadFile(rendererEntryFile); } @@ -4602,9 +4667,71 @@ void (async () => { // Wire launchOnStartup from persisted settings applyLoginItemSettings(settings.general.launchOnStartup); + // โ”€โ”€ Local AI agents (MCP) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + // Loopback MCP server + OAuth + native approval window. Idle unless + // Settings โ†’ AI Agents is on. See src/mcp/ and docs/mcp.md. The IPC + // handlers register before the window loads; the server starts after. + let agentHost: AgentHost | null = null; + try { + agentHost = createAgentHost({ + projectRoot, + preloadPath: Path.join(__dirname, "preload.cjs"), + getMainWindow: () => mainWindow, + ensureMainWindow, + loadRenderer, + getSettings: () => settingsStore!.get(), + setAgentsEnabled: async (enabled) => { + await settingsStore!.update((current) => ({ ...current, agents: { ...current.agents, enabled } })); + }, + toast: sendToast, + log: writeCrashLog, + listDrives: () => getRecentDiskSpace(), + activeScans: () => + Array.from(activeScans.values()).map((session) => + liveSnapshotByKey.get(scanKey(session.rootPath)) ?? { + ...createIdleScanSnapshot(), + status: "running", + rootPath: session.rootPath, + }, + ), + currentSnapshotRoot: async () => (await scanStore.get()).rootPath, + allHistory: () => [...getAllEntries()], + scanHistory: (rootPath) => getScanHistory(rootPath), + loadSnapshot: (id) => loadHistoricalSnapshotCached(id), + startScan: (rootPath) => startScan(rootPath, defaultScanOptions()), + cancelScan: async (rootPath) => { + await cancelActiveScan(rootPath); + }, + folderChildren: (rootPath, parentPath) => getFolderChildrenImpl(rootPath, parentPath), + searchIndex: (rootPath, query) => searchIndexImpl(rootPath, query), + cleanupSuggestions: (rootPath) => analyzeCleanupImpl(rootPath), + devArtifacts: (rootPath) => getDevArtifactsImpl(rootPath), + diff: (baselineId, currentId) => computeScanDiffCached(baselineId, currentId), + fullDiff: (baselineId, currentId, limit) => fullDiffLoader.load(baselineId, currentId, limit), + duplicates: (rootPath) => { + const key = scanKey(Path.resolve(rootPath)); + return { + running: activeDuplicateScans.has(key), + progress: duplicateProgressByKey.get(key) ?? null, + analysis: duplicateResultByKey.get(key) ?? null, + }; + }, + startDuplicateScan: (rootPath, minSizeBytes) => startDuplicateScanImpl(rootPath, { minSizeBytes }), + trashPath: (targetPath) => trashPathImpl(targetPath), + permanentDeletePath: (targetPath) => permanentDeletePathImpl(targetPath), + }); + pathsRemoved = () => agentHost?.pathsRemoved(); + } catch (err) { + writeCrashLog("agent-access", `startup failed: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`); + } + restartMonitoring(settings); await ensureMainWindow(); writeStartupLog("window created and loaded"); + await agentHost?.start().catch((err: unknown) => { + writeCrashLog("agent-access", `start failed: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`); + }); + // "Start minimized" is an AUTOSTART-ONLY preference โ€” we want a // fresh-install launch, a post-update restart, and a user-initiated @@ -4879,6 +5006,7 @@ void (async () => { // snapshot and its cursor wait for quit. scanStore.flush(); flushUsnCursorStore(); + void agentHost?.dispose(); }); })().catch((err: unknown) => { const error = err as { stack?: string; message?: string }; diff --git a/src/mcp/__tests__/accessPolicy.test.ts b/src/mcp/__tests__/accessPolicy.test.ts new file mode 100644 index 00000000..c6e486e1 --- /dev/null +++ b/src/mcp/__tests__/accessPolicy.test.ts @@ -0,0 +1,331 @@ +import { createHash } from "node:crypto"; +import * as FS from "node:fs"; +import * as OS from "node:os"; +import * as Path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { MCP_AGENT_CAPABILITIES, type McpAgentCapability } from "../../shared/agentAccess"; +import { + FixedMcpAuthorizer, + McpAccessError, + McpPolicyStore, + MCP_POLICY_PROTOCOL, + MCP_POLICY_VERSION, + PolicyFileAuthorizer, + type McpAccessErrorCode, +} from "../accessPolicy"; +import { roleAuthorization } from "./fakeBackend"; + +const ALL_SCOPES: McpAgentCapability[] = [...MCP_AGENT_CAPABILITIES]; +const oauth = (scopes: McpAgentCapability[] = ALL_SCOPES) => ({ clientId: "client_abc", scopes }); + +let tempDir: string; +let policyFile: string; + +beforeEach(() => { + tempDir = FS.mkdtempSync(Path.join(OS.tmpdir(), "diskhound-mcp-policy-test-")); + policyFile = Path.join(tempDir, "nested", "mcp-policy.json"); +}); + +afterEach(() => { + FS.rmSync(tempDir, { recursive: true, force: true }); +}); + +function accessError(run: () => unknown): McpAccessError { + try { + run(); + } catch (error) { + expect(error).toBeInstanceOf(McpAccessError); + return error as McpAccessError; + } + throw new Error("expected an McpAccessError"); +} + +function expectCode(run: () => unknown, code: McpAccessErrorCode): McpAccessError { + const error = accessError(run); + expect(error.code).toBe(code); + return error; +} + +const sha256Hex = (value: string) => createHash("sha256").update(value, "utf8").digest("hex"); + +describe("McpPolicyStore", () => { + it("reads a missing policy file as empty and does not create it", () => { + const store = new McpPolicyStore(policyFile); + expect(store.sessions()).toEqual([]); + expect(store.exists()).toBe(false); + expect(FS.existsSync(policyFile)).toBe(false); + }); + + it("creates a session with a dhmcp_ token and stores only its SHA-256", () => { + const fixed = new Date("2026-09-24T12:00:00.000Z"); + const store = new McpPolicyStore(policyFile, () => fixed); + const { session, token } = store.createSession(" Claude Code ", "builtin.guide", oauth()); + + expect(token).toMatch(/^dhmcp_[A-Za-z0-9_-]{43}$/); + expect(session).toEqual({ + id: expect.stringMatching(/^session_[0-9a-f-]{36}$/), + name: "Claude Code", + roleId: "builtin.guide", + createdAt: fixed.toISOString(), + updatedAt: fixed.toISOString(), + revokedAt: null, + oauth: { clientId: "client_abc", scopes: ALL_SCOPES }, + }); + + const contents = FS.readFileSync(policyFile, "utf8"); + expect(contents).not.toContain(token); + expect(contents).not.toContain(token.slice("dhmcp_".length)); + const parsed = JSON.parse(contents) as { protocol: string; version: number; sessions: Record[] }; + expect(parsed.protocol).toBe(MCP_POLICY_PROTOCOL); + expect(parsed.version).toBe(MCP_POLICY_VERSION); + expect(parsed.sessions).toHaveLength(1); + expect(parsed.sessions[0]!.tokenHash).toBe(sha256Hex(token)); + + // The public view never leaks the hash either. + expect(store.sessions()).toEqual([session]); + expect(JSON.stringify(store.sessions())).not.toContain(sha256Hex(token)); + }); + + it("issues a distinct token and id per session", () => { + const store = new McpPolicyStore(policyFile); + const a = store.createSession("Agent", "builtin.reader", oauth()); + const b = store.createSession("Agent", "builtin.reader", oauth()); + expect(a.token).not.toBe(b.token); + expect(a.session.id).not.toBe(b.session.id); + expect(store.sessions()).toHaveLength(2); + }); + + it("rejects invalid names and unknown roles", () => { + const store = new McpPolicyStore(policyFile); + expectCode(() => store.createSession(" ", "builtin.reader", oauth()), "invalid_input"); + expectCode(() => store.createSession("x".repeat(201), "builtin.reader", oauth()), "invalid_input"); + expectCode(() => store.createSession("Agent", "builtin.root", oauth()), "invalid_input"); + expect(store.sessions()).toEqual([]); + }); + + it("authorizes a token for the capabilities its role grants", () => { + const store = new McpPolicyStore(policyFile); + const { session, token } = store.createSession("Codex", "builtin.guide", oauth()); + const auth = store.authorize(token, ["disk.read", "scan.run"]); + expect(auth).toEqual({ + sessionId: session.id, + sessionName: "Codex", + roleId: "builtin.guide", + roleName: "Cleanup Guide", + capabilities: ["disk.read", "scan.run", "app.navigate"], + oauthClientId: session.oauth!.clientId, + }); + // No required capabilities: still identifies the session. + expect(store.authorize(token).sessionId).toBe(session.id); + }); + + it("throws missing_capability, naming the capability and pointing at Settings", () => { + const store = new McpPolicyStore(policyFile); + const { token } = store.createSession("Codex", "builtin.reader", oauth()); + const error = expectCode(() => store.authorize(token, ["disk.read", "files.trash", "scan.run"]), "missing_capability"); + expect(error.message).toContain("does not grant: files.trash, scan.run."); + expect(error.message).toContain("Settings"); + expect(error.message).toContain("Disk Explorer"); + }); + + it("intersects the role with the OAuth scopes the user approved", () => { + const store = new McpPolicyStore(policyFile); + const scopes: McpAgentCapability[] = ["disk.read", "scan.run", "app.navigate"]; + const { token } = store.createSession("Agent", "builtin.operator", oauth(scopes)); + const auth = store.authorize(token, ["disk.read"]); + expect(auth.roleId).toBe("builtin.operator"); + expect(auth.capabilities).toEqual(scopes); + expectCode(() => store.authorize(token, ["files.trash"]), "missing_capability"); + }); + + it("revokes a session so its token stops working", () => { + let clock = new Date("2026-09-24T12:00:00.000Z"); + const store = new McpPolicyStore(policyFile, () => clock); + const { session, token } = store.createSession("Agent", "builtin.guide", oauth()); + clock = new Date("2026-09-24T13:00:00.000Z"); + const revoked = store.revokeSession(session.id); + expect(revoked.revokedAt).toBe(clock.toISOString()); + expect(revoked.updatedAt).toBe(clock.toISOString()); + expectCode(() => store.authorize(token), "revoked_session"); + + // Revoking again keeps the original revokedAt. + const firstRevokedAt = revoked.revokedAt; + clock = new Date("2026-09-24T14:00:00.000Z"); + expect(store.revokeSession(session.id).revokedAt).toBe(firstRevokedAt); + + expectCode(() => store.revokeSession("session_missing"), "invalid_input"); + }); + + it("applies a role change on the next authorize, capped by the approved scopes", () => { + const store = new McpPolicyStore(policyFile); + const { session, token } = store.createSession("Agent", "builtin.reader", oauth()); + expectCode(() => store.authorize(token, ["scan.run"]), "missing_capability"); + + expect(store.assignRole(session.id, "builtin.operator").roleId).toBe("builtin.operator"); + expect(store.authorize(token, ["files.trash"]).roleName).toBe("Cleanup Operator"); + + store.assignRole(session.id, "builtin.reader"); + expectCode(() => store.authorize(token, ["files.trash"]), "missing_capability"); + + // A second store on the same file sees the change (no in-memory cache). + const other = new McpPolicyStore(policyFile); + expect(other.authorize(token).roleId).toBe("builtin.reader"); + + // Moving to a bigger role never exceeds what the agent was approved for. + const capped = store.createSession("Capped", "builtin.guide", oauth(["disk.read", "scan.run", "app.navigate"])); + store.assignRole(capped.session.id, "builtin.operator"); + expectCode(() => store.authorize(capped.token, ["files.trash"]), "missing_capability"); + + expectCode(() => store.assignRole(session.id, "builtin.root"), "invalid_input"); + expectCode(() => store.assignRole("session_missing", "builtin.reader"), "invalid_input"); + }); + + it("forgetRevoked removes only revoked sessions", () => { + const store = new McpPolicyStore(policyFile); + const keep = store.createSession("Keep", "builtin.reader", oauth()); + const drop1 = store.createSession("Drop 1", "builtin.reader", oauth()); + const drop2 = store.createSession("Drop 2", "builtin.reader", oauth()); + store.revokeSession(drop1.session.id); + store.revokeSession(drop2.session.id); + + expect(store.forgetRevoked()).toBe(2); + expect(store.sessions().map((session) => session.name)).toEqual(["Keep"]); + expect(store.forgetRevoked()).toBe(0); + expect(store.authorize(keep.token).sessionName).toBe("Keep"); + expectCode(() => store.authorize(drop1.token), "invalid_session"); + }); + + it("rejects unknown tokens as invalid_session", () => { + const store = new McpPolicyStore(policyFile); + expectCode(() => store.authorize("dhmcp_nope"), "invalid_session"); + store.createSession("Agent", "builtin.reader", oauth()); + expectCode(() => store.authorize("dhmcp_nope"), "invalid_session"); + expectCode(() => store.authorize(""), "invalid_session"); + }); + + it("uses the role's permissions directly for sessions without an OAuth binding", () => { + const token = "dhmcp_legacy-token"; + FS.mkdirSync(Path.dirname(policyFile), { recursive: true }); + FS.writeFileSync(policyFile, JSON.stringify({ + protocol: MCP_POLICY_PROTOCOL, + version: MCP_POLICY_VERSION, + sessions: [{ + id: "session_legacy", + name: "Legacy", + roleId: "builtin.operator", + tokenHash: sha256Hex(token), + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + revokedAt: null, + }], + })); + const store = new McpPolicyStore(policyFile); + expect(store.authorize(token, ["files.trash"]).capabilities).toEqual(["disk.read", "scan.run", "app.navigate", "files.trash"]); + }); + + it("refuses to authorize from a corrupt or foreign policy file", () => { + FS.mkdirSync(Path.dirname(policyFile), { recursive: true }); + const store = new McpPolicyStore(policyFile); + + FS.writeFileSync(policyFile, "{not json"); + expectCode(() => store.sessions(), "invalid_policy"); + + FS.writeFileSync(policyFile, JSON.stringify({ protocol: "other/v1", version: 1, sessions: [] })); + expectCode(() => store.authorize("dhmcp_x"), "invalid_policy"); + + FS.writeFileSync(policyFile, JSON.stringify({ protocol: MCP_POLICY_PROTOCOL, version: 1, sessions: [{ id: "bad id!" }] })); + expectCode(() => store.sessions(), "invalid_policy"); + + const session = { + id: "session_dup", + name: "Dup", + roleId: "builtin.reader", + tokenHash: sha256Hex("a"), + createdAt: "x", + updatedAt: "x", + revokedAt: null, + }; + FS.writeFileSync(policyFile, JSON.stringify({ protocol: MCP_POLICY_PROTOCOL, version: 1, sessions: [session, session] })); + expectCode(() => store.sessions(), "invalid_policy"); + + FS.writeFileSync(policyFile, JSON.stringify({ + protocol: MCP_POLICY_PROTOCOL, + version: 1, + sessions: [{ ...session, oauth: { clientId: "client", scopes: ["disk.read", "root"] } }], + })); + expectCode(() => store.sessions(), "invalid_policy"); + }); + + it("reports invalid_role when a stored session points at a role that no longer exists", () => { + const token = "dhmcp_retired"; + FS.mkdirSync(Path.dirname(policyFile), { recursive: true }); + FS.writeFileSync(policyFile, JSON.stringify({ + protocol: MCP_POLICY_PROTOCOL, + version: MCP_POLICY_VERSION, + sessions: [{ + id: "session_retired", + name: "Retired", + roleId: "builtin.retired", + tokenHash: sha256Hex(token), + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + revokedAt: null, + }], + })); + expectCode(() => new McpPolicyStore(policyFile).authorize(token), "invalid_role"); + }); + + it("caps the file at 256 sessions, evicting the oldest revoked one first", () => { + const store = new McpPolicyStore(policyFile); + const created = Array.from({ length: 256 }, (_, index) => store.createSession(`Agent ${index}`, "builtin.reader", oauth())); + expectCode(() => store.createSession("One too many", "builtin.reader", oauth()), "invalid_input"); + + store.revokeSession(created[10]!.session.id); + store.revokeSession(created[20]!.session.id); + const next = store.createSession("Replacement", "builtin.reader", oauth()); + const names = store.sessions().map((session) => session.name); + expect(names).toHaveLength(256); + expect(names).not.toContain("Agent 10"); + expect(names).toContain("Agent 20"); + expect(store.authorize(next.token).sessionName).toBe("Replacement"); + }); + + it.skipIf(process.platform === "win32")("writes the policy file 0600 in a 0700 directory, atomically", () => { + const store = new McpPolicyStore(policyFile); + const { session } = store.createSession("Agent", "builtin.reader", oauth()); + expect(FS.statSync(policyFile).mode & 0o777).toBe(0o600); + expect(FS.statSync(Path.dirname(policyFile)).mode & 0o777).toBe(0o700); + + // A permissive file is tightened on the next write. + FS.chmodSync(policyFile, 0o644); + store.revokeSession(session.id); + expect(FS.statSync(policyFile).mode & 0o777).toBe(0o600); + + // No temp files are left behind. + expect(FS.readdirSync(Path.dirname(policyFile))).toEqual(["mcp-policy.json"]); + }); +}); + +describe("PolicyFileAuthorizer", () => { + it("re-reads the policy file on every call", async () => { + const store = new McpPolicyStore(policyFile); + const { session, token } = store.createSession("Agent", "builtin.guide", oauth()); + const authorizer = new PolicyFileAuthorizer(store, token); + await expect(authorizer.authorize(["scan.run"])).resolves.toMatchObject({ sessionId: session.id }); + store.revokeSession(session.id); + await expect(authorizer.authorize(["scan.run"])).rejects.toMatchObject({ code: "revoked_session" }); + }); +}); + +describe("FixedMcpAuthorizer", () => { + it("grants what its authorization lists and rejects the rest", async () => { + const authorizer = new FixedMcpAuthorizer(roleAuthorization("builtin.reader")); + await expect(authorizer.authorize(["disk.read"])).resolves.toMatchObject({ roleId: "builtin.reader" }); + await expect(authorizer.authorize()).resolves.toMatchObject({ roleId: "builtin.reader" }); + const error = await authorizer.authorize(["disk.read", "files.trash"]).catch((cause: unknown) => cause); + expect(error).toBeInstanceOf(McpAccessError); + expect(error).toMatchObject({ code: "missing_capability" }); + expect((error as Error).message).toContain("files.trash"); + }); +}); diff --git a/src/mcp/__tests__/agentAccessServer.test.ts b/src/mcp/__tests__/agentAccessServer.test.ts new file mode 100644 index 00000000..856709ef --- /dev/null +++ b/src/mcp/__tests__/agentAccessServer.test.ts @@ -0,0 +1,972 @@ +import { createHash, randomBytes } from "node:crypto"; +import * as FS from "node:fs"; +import * as HTTP from "node:http"; +import * as NET from "node:net"; +import * as OS from "node:os"; +import * as Path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { auth, type OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import type { + OAuthClientInformationMixed, + OAuthClientMetadata, + OAuthTokens, +} from "@modelcontextprotocol/sdk/shared/auth.js"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; + +import { MCP_AGENT_CAPABILITIES, type McpAgentCapability } from "../../shared/agentAccess"; +import { McpPolicyStore } from "../accessPolicy"; +import { AgentAccessServer, allowedOrigin, isLoopbackAddress, withDefaultArguments } from "../agentAccessServer"; +import { AgentAccessService } from "../agentAccessService"; +import type { TrashRequest } from "../backend"; +import { ConsentBroker, type ConsentSender, type ConsentWindow } from "../consentBroker"; +import { loadSkillCatalog } from "../skills"; +import { createFakeBackend, RecordingActivity, RecordingSecurity, SKILLS_DIR, type FakeBackend } from "./fakeBackend"; + +const SKILLS = loadSkillCatalog(SKILLS_DIR); +const ALL_SCOPES = MCP_AGENT_CAPABILITIES.join(" "); +// Loopback redirect (RFC 8252). Nothing listens here: the test reads the +// 302 Location instead of following it. +const REDIRECT_URI = "http://127.0.0.1:47999/callback"; + +// โ”€โ”€ Consent window stand-in โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +class FakeConsentWindow implements ConsentWindow { + private static nextId = 1; + readonly webContentsId = FakeConsentWindow.nextId++; + private readonly listeners: (() => void)[] = []; + private destroyed = false; + onClosed(listener: () => void) { + this.listeners.push(listener); + } + close() { + if (this.destroyed) return; + this.destroyed = true; + for (const listener of this.listeners.splice(0)) listener(); + } + isDestroyed() { + return this.destroyed; + } + get main(): ConsentSender { + return { webContentsId: this.webContentsId, isMainFrame: true }; + } +} + +// โ”€โ”€ Harness โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +let tempDir: string; +let policy: McpPolicyStore; +let backend: FakeBackend; +let activity: RecordingActivity; +let security: RecordingSecurity; +let windows: FakeConsentWindow[]; +let broker: ConsentBroker; +let onChanged: ReturnType void>>; +let server: AgentAccessServer; +let base: string; +let clients: Client[]; + +beforeEach(async () => { + tempDir = FS.mkdtempSync(Path.join(OS.tmpdir(), "diskhound-agent-server-test-")); + policy = new McpPolicyStore(Path.join(tempDir, "mcp-policy.json")); + backend = createFakeBackend(); + activity = new RecordingActivity(); + security = new RecordingSecurity(); + windows = []; + broker = new ConsentBroker( + () => { + const window = new FakeConsentWindow(); + windows.push(window); + return window; + }, + () => policy.sessions().filter((session) => session.revokedAt === null).map((session) => session.name), + ); + onChanged = vi.fn<() => void>(); + clients = []; + server = new AgentAccessServer({ + backend, + activity, + security, + skills: SKILLS, + policy, + clientsFile: Path.join(tempDir, "mcp-oauth-clients.json"), + requestConsent: broker.request, + onChanged, + port: 0, + }); + await server.start(); + base = `http://127.0.0.1:${server.port}`; +}); + +afterEach(async () => { + for (const client of clients.splice(0)) await client.close().catch(() => undefined); + broker.close(); + await server.stop(); + FS.rmSync(tempDir, { recursive: true, force: true }); +}); + +// โ”€โ”€ HTTP helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +interface RawResponse { + status: number; + headers: HTTP.IncomingHttpHeaders; + body: string; +} + +/** node:http so the test controls Host and Origin exactly (fetch owns Host). */ +function rawRequest(options: { method?: string; path: string; headers?: Record; body?: string }): Promise { + return new Promise((resolve, reject) => { + const request = HTTP.request( + { + host: "127.0.0.1", + port: server.port, + method: options.method ?? "GET", + path: options.path, + headers: { host: `127.0.0.1:${server.port}`, ...options.headers }, + agent: false, + }, + (response) => { + let body = ""; + response.setEncoding("utf8"); + response.on("data", (chunk: string) => (body += chunk)); + response.on("end", () => resolve({ status: response.statusCode ?? 0, headers: response.headers, body })); + }, + ); + request.on("error", reject); + if (options.body !== undefined) request.write(options.body); + request.end(); + }); +} + +const INITIALIZE = JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "raw", version: "1" } }, +}); +const MCP_HEADERS = { "content-type": "application/json", accept: "application/json, text/event-stream" }; + +function pkce() { + const verifier = randomBytes(32).toString("base64url"); + const challenge = createHash("sha256").update(verifier).digest("base64url"); + return { verifier, challenge }; +} + +async function register(name = "Test Agent CLI", redirectUris = [REDIRECT_URI]): Promise<{ client_id: string } & Record> { + const response = await fetch(`${base}/register`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + client_name: name, + redirect_uris: redirectUris, + token_endpoint_auth_method: "none", + grant_types: ["authorization_code"], + response_types: ["code"], + }), + }); + expect(response.status).toBe(201); + return (await response.json()) as { client_id: string }; +} + +function authorizeUrl(clientId: string, challenge: string, extra: Record = {}): URL { + const url = new URL(`${base}/authorize`); + const params: Record = { + response_type: "code", + client_id: clientId, + redirect_uri: REDIRECT_URI, + code_challenge: challenge, + code_challenge_method: "S256", + state: "state-123", + resource: server.mcpUrl, + scope: ALL_SCOPES, + ...extra, + }; + for (const [key, value] of Object.entries(params)) if (value !== undefined) url.searchParams.set(key, value); + return url; +} + +/** GET /authorize and return the approval id from the waiting page. */ +async function openApproval(url: URL): Promise { + const response = await fetch(url, { redirect: "manual" }); + expect(response.status).toBe(200); + expect(response.headers.get("content-security-policy")).toContain("default-src 'none'"); + const html = await response.text(); + expect(html).toContain("Continue in DiskHound"); + expect(html).not.toMatch(/ { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const response = await fetch(`${base}/authorize/status?id=${id}`, { redirect: "manual" }); + if (response.status === 302) return new URL(response.headers.get("location")!); + expect(response.status).toBe(200); + await response.text(); + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error("timed out waiting for the approval redirect"); +} + +function latestWindow(): FakeConsentWindow { + const window = windows.at(-1); + if (!window) throw new Error("no consent window was opened"); + return window; +} + +/** What the user does in the native approval window. */ +function approve(roleId: string, sessionName = "My Agent"): void { + const window = latestWindow(); + const prompt = broker.read(window.main); + if (!prompt) throw new Error("consent window has no prompt"); + expect(broker.decide(window.main, { requestId: prompt.requestId, decision: "allow", sessionName, roleId })).toEqual({ ok: true }); +} + +function exchange(params: Record): Promise { + return fetch(`${base}/token`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams(params), + }); +} + +/** Full manual OAuth dance. Returns the bearer token. */ +async function login(roleId = "builtin.guide", scope = ALL_SCOPES, sessionName = "My Agent"): Promise<{ token: string; clientId: string }> { + const { client_id: clientId } = await register(); + const { verifier, challenge } = pkce(); + const id = await openApproval(authorizeUrl(clientId, challenge, { scope })); + approve(roleId, sessionName); + const callback = await waitForRedirect(id); + const code = callback.searchParams.get("code"); + expect(code).toBeTruthy(); + const response = await exchange({ + grant_type: "authorization_code", + code: code!, + code_verifier: verifier, + client_id: clientId, + redirect_uri: REDIRECT_URI, + resource: server.mcpUrl, + }); + expect(response.status).toBe(200); + const tokens = (await response.json()) as OAuthTokens; + return { token: tokens.access_token, clientId }; +} + +async function mcpClient(token: string): Promise { + const transport = new StreamableHTTPClientTransport(new URL(server.mcpUrl), { + requestInit: { headers: { Authorization: `Bearer ${token}` } }, + }); + const client = new Client({ name: "diskhound-http-test", version: "1.0.0" }); + await client.connect(transport); + clients.push(client); + return client; +} + +function text(result: CallToolResult): string { + const block = result.content[0]; + return block?.type === "text" ? block.text : ""; +} + +// โ”€โ”€ Tests โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +describe("AgentAccessServer basics", () => { + it("binds an ephemeral loopback port when given port 0", () => { + expect(server.listening).toBe(true); + expect(server.port).toBeGreaterThan(0); + expect(server.mcpUrl).toBe(`http://127.0.0.1:${server.port}/mcp`); + }); + + it("stops cleanly and can be stopped twice", async () => { + await server.stop(); + expect(server.listening).toBe(false); + await server.stop(); + }); + + it("restarts on the same port and keeps registered clients across instances", async () => { + const { client_id: clientId } = await register(); + const port = server.port; + await server.stop(); + await server.start(); + expect(server.port).toBe(port); + + // A fresh instance (an app relaunch) reads the persisted client store. + await server.stop(); + server = new AgentAccessServer({ + backend, + activity, + skills: SKILLS, + policy, + clientsFile: Path.join(tempDir, "mcp-oauth-clients.json"), + requestConsent: broker.request, + onChanged, + port: 0, + }); + await server.start(); + base = `http://127.0.0.1:${server.port}`; + await openApproval(authorizeUrl(clientId, pkce().challenge)); + expect(broker.read(latestWindow().main)?.clientName).toBe("Test Agent CLI"); + }); +}); + +describe("AgentAccessService", () => { + function service(port: number, saveEnabled = vi.fn<(enabled: boolean) => void>()) { + return { + saveEnabled, + service: new AgentAccessService({ + backend, + activity, + skills: SKILLS, + policy, + clientsFile: Path.join(tempDir, "mcp-oauth-clients.json"), + requestConsent: broker.request, + onChanged, + port, + saveEnabled, + }), + }; + } + + it("turns the listener on and off, persisting the setting", async () => { + const { service: access, saveEnabled } = service(0); + const on = await access.setEnabled(true); + expect(on).toMatchObject({ enabled: true, listening: true }); + expect(on.port).toBeGreaterThan(0); + expect(on.mcpUrl).toBe(`http://127.0.0.1:${on.port}/mcp`); + expect(on.error).toBeUndefined(); + + const off = await access.setEnabled(false); + expect(off).toMatchObject({ enabled: false, listening: false }); + expect(saveEnabled.mock.calls).toEqual([[true], [false]]); + + // Serialized: a fast on โ†’ off โ†’ on ends listening. + const results = await Promise.all([access.setEnabled(true, false), access.setEnabled(false, false), access.setEnabled(true, false)]); + expect(results.map((status) => status.listening)).toEqual([true, false, true]); + expect(access.status().listening).toBe(true); + expect(saveEnabled).toHaveBeenCalledTimes(2); + await access.dispose(); + expect(access.status().listening).toBe(false); + }); + + it("reports a busy port instead of throwing", async () => { + const blocker = NET.createServer(); + await new Promise((resolve) => blocker.listen(0, "127.0.0.1", resolve)); + const port = (blocker.address() as NET.AddressInfo).port; + try { + const { service: access } = service(port); + const status = await access.setEnabled(true); + expect(status).toMatchObject({ enabled: true, listening: false, port }); + expect(status.error).toContain(`Port ${port} is already in use`); + await access.dispose(); + } finally { + await new Promise((resolve) => blocker.close(() => resolve())); + } + }); +}); + +describe("request guards", () => { + it("answers an unauthenticated POST /mcp with 401 and a discovery challenge", async () => { + const response = await rawRequest({ method: "POST", path: "/mcp", headers: MCP_HEADERS, body: INITIALIZE }); + expect(response.status).toBe(401); + const challenge = response.headers["www-authenticate"] ?? ""; + expect(challenge).toMatch(/^Bearer /); + expect(challenge).toContain(`resource_metadata="${base}/.well-known/oauth-protected-resource/mcp"`); + expect(challenge).toContain(`scope="${ALL_SCOPES}"`); + expect(JSON.parse(response.body)).toEqual({ error: "unauthorized" }); + }); + + it("rejects an unknown bearer token with 401", async () => { + const response = await rawRequest({ + method: "POST", + path: "/mcp", + headers: { ...MCP_HEADERS, authorization: "Bearer dhmcp_not-a-real-token" }, + body: INITIALIZE, + }); + expect(response.status).toBe(401); + }); + + it("answers GET and DELETE /mcp with 405 before checking auth", async () => { + for (const method of ["GET", "DELETE"]) { + const response = await rawRequest({ method, path: "/mcp", headers: { accept: "text/event-stream" } }); + expect(response.status, method).toBe(405); + expect(response.headers.allow).toBe("POST"); + expect(response.headers["www-authenticate"]).toBeUndefined(); + } + }); + + it("rejects a Host header that is not the bound 127.0.0.1:", async () => { + for (const host of ["localhost:" + server.port, "evil.example", `127.0.0.1:${server.port + 1}`, "127.0.0.1"]) { + const response = await rawRequest({ path: "/.well-known/oauth-authorization-server", headers: { host } }); + expect(response.status, host).toBe(403); + expect(JSON.parse(response.body)).toEqual({ error: "forbidden_origin" }); + } + }); + + it("rejects non-loopback and opaque Origins but allows loopback ones", async () => { + for (const origin of ["https://evil.example", "http://127.0.0.1.evil.example", "null", "file://", "chrome-extension://abc"]) { + const response = await rawRequest({ path: "/.well-known/oauth-authorization-server", headers: { origin } }); + expect(response.status, origin).toBe(403); + } + for (const origin of ["http://localhost:5173", "http://127.0.0.1:3000", "https://[::1]:8443"]) { + const response = await rawRequest({ path: "/.well-known/oauth-authorization-server", headers: { origin } }); + expect(response.status, origin).toBe(200); + } + // Also enforced on /mcp, before auth. + const mcp = await rawRequest({ method: "POST", path: "/mcp", headers: { ...MCP_HEADERS, origin: "https://evil.example" }, body: INITIALIZE }); + expect(mcp.status).toBe(403); + }); + + it("answers unknown routes and malformed bodies with JSON, never an HTML stack page", async () => { + const missing = await rawRequest({ path: "/nope" }); + expect(missing.status).toBe(404); + expect(JSON.parse(missing.body)).toEqual({ error: "not_found" }); + + const malformed = await rawRequest({ method: "POST", path: "/mcp", headers: MCP_HEADERS, body: "{not json" }); + expect(malformed.status).toBe(400); + expect(JSON.parse(malformed.body)).toEqual({ error: "request_failed" }); + expect(malformed.body).not.toContain("at "); + }); + + it("defaults a missing `arguments` only on tools/call and prompts/get", () => { + expect(withDefaultArguments({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "x" } })) + .toEqual({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "x", arguments: {} } }); + const given = { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "x", arguments: { a: 1 } } }; + expect(withDefaultArguments(given)).toBe(given); + const other = { jsonrpc: "2.0", id: 3, method: "tools/list", params: {} }; + expect(withDefaultArguments(other)).toBe(other); + expect(withDefaultArguments([{ method: "prompts/get", params: { name: "p" } }, "junk"])) + .toEqual([{ method: "prompts/get", params: { name: "p", arguments: {} } }, "junk"]); + expect(withDefaultArguments(undefined)).toBeUndefined(); + }); + + it("helper predicates accept only loopback peers and origins", () => { + expect(isLoopbackAddress("127.0.0.1")).toBe(true); + expect(isLoopbackAddress("::1")).toBe(true); + expect(isLoopbackAddress("::ffff:127.0.0.1")).toBe(true); + expect(isLoopbackAddress("10.0.0.2")).toBe(false); + expect(isLoopbackAddress(undefined)).toBe(false); + expect(allowedOrigin(undefined)).toBe(true); + expect(allowedOrigin("http://localhost")).toBe(true); + expect(allowedOrigin("ftp://localhost")).toBe(false); + expect(allowedOrigin("not a url")).toBe(false); + }); +}); + +describe("OAuth metadata", () => { + it("serves protected resource metadata at the path-aware well-known URL", async () => { + const response = await fetch(`${base}/.well-known/oauth-protected-resource/mcp`); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ + resource: server.mcpUrl, + authorization_servers: [`${base}/`], + scopes_supported: [...MCP_AGENT_CAPABILITIES], + resource_name: "DiskHound", + }); + }); + + it("serves authorization server metadata for a public-client, PKCE-only server", async () => { + const response = await fetch(`${base}/.well-known/oauth-authorization-server`); + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ + issuer: `${base}/`, + authorization_endpoint: `${base}/authorize`, + token_endpoint: `${base}/token`, + registration_endpoint: `${base}/register`, + revocation_endpoint: `${base}/revoke`, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code"], + token_endpoint_auth_methods_supported: ["none"], + code_challenge_methods_supported: ["S256"], + scopes_supported: [...MCP_AGENT_CAPABILITIES], + }); + }); +}); + +describe("OAuth flow", () => { + it("registers public clients only and persists them 0600", async () => { + const response = await fetch(`${base}/register`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ client_name: "Secretive", redirect_uris: [REDIRECT_URI], token_endpoint_auth_method: "client_secret_post" }), + }); + expect(response.status).toBe(201); + const client = (await response.json()) as Record; + expect(client.client_id).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(client.client_secret).toBeUndefined(); + expect(client.token_endpoint_auth_method).toBe("none"); + expect(client.grant_types).toEqual(["authorization_code"]); + + const file = Path.join(tempDir, "mcp-oauth-clients.json"); + const saved = JSON.parse(FS.readFileSync(file, "utf8")) as { client_id: string }[]; + expect(saved.map((entry) => entry.client_id)).toEqual([client.client_id]); + expect(FS.readFileSync(file, "utf8")).not.toContain("client_secret\""); + if (process.platform !== "win32") expect(FS.statSync(file).mode & 0o777).toBe(0o600); + }); + + it("walks DCR โ†’ authorize โ†’ native approval โ†’ token โ†’ MCP tools", async () => { + const { client_id: clientId } = await register(); + const { verifier, challenge } = pkce(); + const id = await openApproval(authorizeUrl(clientId, challenge)); + + // The native window shows the agent's name and requested scopes. + const window = latestWindow(); + const prompt = broker.read(window.main)!; + expect(prompt).toMatchObject({ + clientName: "Test Agent CLI", + sessionName: "Test Agent CLI", + requestedScopes: [...MCP_AGENT_CAPABILITIES], + defaultRoleId: "builtin.guide", + }); + + // Before the user decides, the status URL keeps serving the waiting page. + const waiting = await fetch(`${base}/authorize/status?id=${id}`, { redirect: "manual" }); + expect(waiting.status).toBe(200); + await waiting.text(); + + approve("builtin.guide", " My Claude "); + const callback = await waitForRedirect(id); + expect(callback.origin + callback.pathname).toBe(REDIRECT_URI); + expect(callback.searchParams.get("state")).toBe("state-123"); + expect(callback.searchParams.get("error")).toBeNull(); + const code = callback.searchParams.get("code")!; + expect(code).toMatch(/^[A-Za-z0-9_-]{43}$/); + + // The status URL is single-use. + expect((await fetch(`${base}/authorize/status?id=${id}`, { redirect: "manual" })).status).toBe(404); + + const tokenParams = { + grant_type: "authorization_code", + code, + code_verifier: verifier, + client_id: clientId, + redirect_uri: REDIRECT_URI, + resource: server.mcpUrl, + }; + const wrongVerifier = await exchange({ ...tokenParams, code_verifier: pkce().verifier }); + expect(wrongVerifier.status).toBe(400); + expect(await wrongVerifier.json()).toMatchObject({ error: "invalid_grant" }); + + const response = await exchange(tokenParams); + expect(response.status).toBe(200); + const tokens = (await response.json()) as OAuthTokens; + expect(tokens.access_token).toMatch(/^dhmcp_/); + expect(tokens.token_type.toLowerCase()).toBe("bearer"); + expect(tokens.refresh_token).toBeUndefined(); + expect(onChanged).toHaveBeenCalled(); + + // Codes are single-use. + const replay = await exchange(tokenParams); + expect(replay.status).toBe(400); + expect(await replay.json()).toMatchObject({ error: "invalid_grant" }); + + // The Session landed in the policy file with the trimmed name and the scope ceiling. + expect(policy.sessions()).toEqual([ + expect.objectContaining({ + name: "My Claude", + roleId: "builtin.guide", + revokedAt: null, + oauth: { clientId, scopes: [...MCP_AGENT_CAPABILITIES] }, + }), + ]); + + const client = await mcpClient(tokens.access_token); + const { tools } = await client.listTools(); + expect(tools.map((tool) => tool.name)).toContain("diskhound_status"); + + const status = (await client.callTool({ name: "diskhound_status", arguments: {} })) as CallToolResult; + expect(status.isError).not.toBe(true); + expect(status.structuredContent).toMatchObject({ + session: { name: "My Claude", role: "Cleanup Guide", capabilities: ["disk.read", "scan.run", "app.navigate"] }, + }); + + const trash = (await client.callTool({ name: "diskhound_move_to_trash", arguments: { paths: ["/Users/test/Downloads/ubuntu.iso"] } })) as CallToolResult; + expect(trash.isError).toBe(true); + expect(text(trash)).toContain("files.trash"); + expect(text(trash)).toContain("Settings"); + expect(backend.confirmAndTrash).not.toHaveBeenCalled(); + + expect(activity.entries).toEqual([ + expect.objectContaining({ sessionName: "My Claude", tool: "diskhound_status", ok: true }), + expect.objectContaining({ sessionName: "My Claude", tool: "diskhound_move_to_trash", ok: false }), + ]); + + // Skills are reachable over HTTP too. + const skills = await client.readResource({ uri: "skill://diskhound-free-up-space/SKILL.md" }); + expect((skills.contents[0] as { text: string }).text).toContain("name: diskhound-free-up-space"); + }); + + it("lets the operator role trash (after the user confirms) and applies role changes on the next call", async () => { + const { token } = await login("builtin.operator"); + const client = await mcpClient(token); + const trash = (await client.callTool({ name: "diskhound_move_to_trash", arguments: { paths: ["/tmp/a"] } })) as CallToolResult; + expect(trash.isError).not.toBe(true); + expect(backend.confirmAndTrash).toHaveBeenCalledWith(expect.objectContaining({ sessionName: "My Agent", paths: ["/tmp/a"] })); + + const [session] = policy.sessions(); + policy.assignRole(session!.id, "builtin.reader"); + const again = (await client.callTool({ name: "diskhound_move_to_trash", arguments: { paths: ["/tmp/a"] } })) as CallToolResult; + expect(again.isError).toBe(true); + expect(backend.confirmAndTrash).toHaveBeenCalledTimes(1); + }); + + it("lets a queued trash request see a revoke, and aborts it when the server stops", async () => { + const { token } = await login("builtin.operator"); + const client = await mcpClient(token); + let request: TrashRequest | undefined; + let dialogUp!: () => void; + const up = new Promise((resolve) => (dialogUp = resolve)); + backend.confirmAndTrash.mockImplementationOnce((req) => { + request = req; + dialogUp(); + // A dialog that stays up until the request is aborted. + return new Promise((_, reject) => req.signal?.addEventListener("abort", () => reject(new Error("aborted")))); + }); + const pending = client + .callTool({ name: "diskhound_move_to_trash", arguments: { paths: ["/tmp/a"] } }) + .catch((error: unknown) => error); + await up; + + await expect(request!.recheck!()).resolves.toBeUndefined(); + policy.revokeSession(policy.sessions()[0]!.id); + await expect(request!.recheck!()).rejects.toMatchObject({ code: "revoked_session" }); + + expect(request!.signal!.aborted).toBe(false); + await server.stop(); + expect(request!.signal!.aborted).toBe(true); + await pending; + }); + + it("lets the guide role upgrade to operator in Settings when the agent asked for every scope", async () => { + const { token } = await login("builtin.guide"); + const client = await mcpClient(token); + const denied = (await client.callTool({ name: "diskhound_move_to_trash", arguments: { paths: ["/tmp/a"] } })) as CallToolResult; + expect(denied.isError).toBe(true); + expect(activity.entries.at(-1)).toMatchObject({ tool: "diskhound_move_to_trash", ok: false, sessionName: "My Agent" }); + + const [session] = policy.sessions(); + policy.assignRole(session!.id, "builtin.operator"); + const allowed = (await client.callTool({ name: "diskhound_move_to_trash", arguments: { paths: ["/tmp/a"] } })) as CallToolResult; + expect(allowed.isError).not.toBe(true); + }); + + it("hides removal tools the role doesn't grant, and refuses and logs a call to one", async () => { + const { token } = await login("builtin.guide"); + const client = await mcpClient(token); + const { tools } = await client.listTools(); + expect(tools.map((tool) => tool.name)).not.toContain("diskhound_move_to_trash"); + expect(tools.map((tool) => tool.name)).not.toContain("diskhound_delete_permanently"); + + const refused = (await client.callTool({ name: "diskhound_delete_permanently", arguments: { paths: ["/tmp/a"] } })) as CallToolResult; + expect(refused.isError).toBe(true); + expect(text(refused)).toContain("diskhound_delete_permanently isn't available to this DiskHound session (Cleanup Guide doesn't grant files.delete)"); + expect(text(refused)).toContain("DiskHound logged the attempt"); + expect(backend.confirmAndDelete).not.toHaveBeenCalled(); + expect(security.events).toEqual([ + { + sessionId: policy.sessions()[0]!.id, + sessionName: "My Agent", + roleName: "Cleanup Guide", + kind: "tool_not_allowed", + tool: "diskhound_delete_permanently", + detail: "Tried to delete items permanently; Cleanup Guide doesn't allow it.", + }, + ]); + expect(activity.entries.at(-1)).toMatchObject({ + tool: "diskhound_delete_permanently", + ok: false, + summary: "Blocked: tried to delete items permanently (Cleanup Guide)", + }); + }); + + it("logs a hidden tool called inside a JSON-RPC batch", async () => { + const { token } = await login("builtin.guide"); + await rawRequest({ + method: "POST", + path: "/mcp", + headers: { ...MCP_HEADERS, authorization: `Bearer ${token}` }, + body: JSON.stringify([ + { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "diskhound_move_to_trash", arguments: { paths: ["/tmp/a"] } } }, + { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "diskhound_status", arguments: {} } }, + ]), + }); + expect(backend.confirmAndTrash).not.toHaveBeenCalled(); + expect(security.events).toMatchObject([{ kind: "tool_not_allowed", tool: "diskhound_move_to_trash" }]); + }); + + it("gives Cleanup Admin both removal tools, each behind the user's confirmation", async () => { + const { token } = await login("builtin.admin"); + const client = await mcpClient(token); + const { tools } = await client.listTools(); + expect(tools.map((tool) => tool.name)).toEqual(expect.arrayContaining(["diskhound_move_to_trash", "diskhound_delete_permanently"])); + const deleted = (await client.callTool({ name: "diskhound_delete_permanently", arguments: { paths: ["/tmp/a"] } })) as CallToolResult; + expect(deleted.isError).not.toBe(true); + expect(backend.confirmAndDelete).toHaveBeenCalledWith(expect.objectContaining({ sessionName: "My Agent", roleName: "Cleanup Admin", paths: ["/tmp/a"] })); + expect(security.events).toEqual([]); + }); + + it("reports the session's permissions in a response header", async () => { + const { token } = await login("builtin.operator"); + const response = await rawRequest({ + method: "POST", + path: "/mcp", + headers: { ...MCP_HEADERS, authorization: `Bearer ${token}` }, + body: INITIALIZE, + }); + expect(response.status).toBe(200); + expect(response.headers["diskhound-capabilities"]).toBe("app.navigate,disk.read,files.trash,scan.run"); + }); + + it("accepts tools/call and prompts/get without `arguments` (rmcp clients omit it)", async () => { + const { token } = await login("builtin.reader"); + const client = await mcpClient(token); + const status = (await client.callTool({ name: "diskhound_status" })) as CallToolResult; + expect(status.isError).not.toBe(true); + const prompt = await client.getPrompt({ name: "free-up-space" }); + expect(prompt.messages).toHaveLength(2); + }); + + it("caps the Session at the scopes the agent asked for", async () => { + const { token } = await login("builtin.guide", "disk.read scan.run app.navigate"); + const [session] = policy.sessions(); + expect(session!.oauth?.scopes).toEqual(["disk.read", "scan.run", "app.navigate"]); + // Settings moves the Session to Operator, but the approved scopes still exclude files.trash. + policy.assignRole(session!.id, "builtin.operator"); + const client = await mcpClient(token); + const trash = (await client.callTool({ name: "diskhound_move_to_trash", arguments: { paths: ["/tmp/a"] } })) as CallToolResult; + expect(trash.isError).toBe(true); + }); + + it("rejects the token on the next request once the Session is revoked", async () => { + const { token } = await login(); + const ok = await rawRequest({ + method: "POST", + path: "/mcp", + headers: { ...MCP_HEADERS, authorization: `Bearer ${token}` }, + body: INITIALIZE, + }); + expect(ok.status).toBe(200); + expect(JSON.parse(ok.body)).toMatchObject({ result: { serverInfo: { name: "diskhound" } } }); + + policy.revokeSession(policy.sessions()[0]!.id); + const revoked = await rawRequest({ + method: "POST", + path: "/mcp", + headers: { ...MCP_HEADERS, authorization: `Bearer ${token}` }, + body: INITIALIZE, + }); + expect(revoked.status).toBe(401); + }); + + it("revokes a token through /revoke for the client that owns it", async () => { + const { token, clientId } = await login(); + const other = await register("Someone Else"); + const wrongClient = await fetch(`${base}/revoke`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ token, client_id: other.client_id }), + }); + expect(wrongClient.status).toBe(200); + expect(policy.sessions()[0]!.revokedAt).toBeNull(); + + const response = await fetch(`${base}/revoke`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ token, client_id: clientId }), + }); + expect(response.status).toBe(200); + expect(policy.sessions()[0]!.revokedAt).not.toBeNull(); + }); + + it("redirects with error=access_denied when the user denies", async () => { + const { client_id: clientId } = await register(); + const id = await openApproval(authorizeUrl(clientId, pkce().challenge)); + const window = latestWindow(); + const prompt = broker.read(window.main)!; + broker.decide(window.main, { requestId: prompt.requestId, decision: "deny", sessionName: "", roleId: "" }); + const callback = await waitForRedirect(id); + expect(callback.searchParams.get("error")).toBe("access_denied"); + expect(callback.searchParams.get("state")).toBe("state-123"); + expect(callback.searchParams.get("code")).toBeNull(); + expect(policy.sessions()).toEqual([]); + }); + + it("closes the approval when the stdio helper withdraws it, and answers every cancel the same", async () => { + const { client_id: clientId } = await register(); + const id = await openApproval(authorizeUrl(clientId, pkce().challenge)); + expect(broker.pending()).toHaveLength(1); + const cancel = (body: string) => rawRequest({ + method: "POST", + path: "/authorize/cancel", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body, + }); + expect((await cancel("id=not-a-real-id")).status).toBe(204); + expect(broker.pending()).toHaveLength(1); + expect((await cancel(`id=${id}`)).status).toBe(204); + await expect.poll(() => broker.pending().length).toBe(0); + expect(latestWindow().isDestroyed()).toBe(true); + const status = await fetch(`${base}/authorize/status?id=${id}`, { redirect: "manual" }); + expect(status.status).toBe(404); + }); + + it("treats closing the approval window as a deny", async () => { + const { client_id: clientId } = await register(); + const id = await openApproval(authorizeUrl(clientId, pkce().challenge)); + latestWindow().close(); + const callback = await waitForRedirect(id); + expect(callback.searchParams.get("error")).toBe("access_denied"); + }); + + it("gives a read-only request only the reader role", async () => { + const { client_id: clientId } = await register(); + await openApproval(authorizeUrl(clientId, pkce().challenge, { scope: "disk.read" })); + const prompt = broker.read(latestWindow().main)!; + expect(prompt.roles.map((role) => role.id)).toEqual(["builtin.reader"]); + expect(prompt.requestedScopes).toEqual(["disk.read"] satisfies McpAgentCapability[]); + }); + + it("offers every role to a client that asks for no scope", async () => { + const { client_id: clientId } = await register(); + await openApproval(authorizeUrl(clientId, pkce().challenge, { scope: undefined })); + expect(broker.read(latestWindow().main)!.requestedScopes).toEqual([...MCP_AGENT_CAPABILITIES]); + }); + + it("refuses authorization requests that can't be satisfied, via the redirect", async () => { + const { client_id: clientId } = await register(); + // The last flag: whether `state` survives. The SDK's authorize handler + // only learns `state` after its own schema check, so "plain" PKCE + // (rejected by that schema) comes back without it. + const cases: [Record, string, boolean][] = [ + [{ resource: undefined }, "invalid_target", true], + [{ resource: `${base}/other` }, "invalid_target", true], + [{ scope: "disk.read root.shell" }, "invalid_scope", true], + [{ code_challenge: "too-short" }, "invalid_request", true], + [{ code_challenge_method: "plain" }, "invalid_request", false], + ]; + for (const [extra, error, keepsState] of cases) { + const label = JSON.stringify(extra); + const response = await fetch(authorizeUrl(clientId, pkce().challenge, extra), { redirect: "manual" }); + expect(response.status, label).toBe(302); + const location = new URL(response.headers.get("location")!); + expect(location.origin + location.pathname, label).toBe(REDIRECT_URI); + expect(location.searchParams.get("error"), label).toBe(error); + if (keepsState) expect(location.searchParams.get("state"), label).toBe("state-123"); + } + expect(windows).toHaveLength(0); + }); + + it("never lets URL parameters or POSTs decide an approval", async () => { + const { client_id: clientId } = await register(); + for (const key of ["decision", "approve", "diskhound_decision", "consent_transaction"]) { + const response = await fetch(authorizeUrl(clientId, pkce().challenge, { [key]: "allow" }), { redirect: "manual" }); + expect(response.status, key).toBe(400); + } + const post = await fetch(`${base}/authorize`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: authorizeUrl(clientId, pkce().challenge).searchParams, + redirect: "manual", + }); + expect(post.status).toBe(405); + expect(windows).toHaveLength(0); + + expect((await fetch(`${base}/authorize/status?id=forged`, { redirect: "manual" })).status).toBe(404); + }); + + it("rejects token requests without the resource or with a different redirect_uri", async () => { + const { client_id: clientId } = await register(); + const { verifier, challenge } = pkce(); + const id = await openApproval(authorizeUrl(clientId, challenge)); + approve("builtin.reader"); + const code = (await waitForRedirect(id)).searchParams.get("code")!; + const params = { grant_type: "authorization_code", code, code_verifier: verifier, client_id: clientId, redirect_uri: REDIRECT_URI, resource: server.mcpUrl }; + + const noResource: Record = { ...params }; + delete noResource.resource; + const missingResource = await exchange(noResource); + expect(missingResource.status).toBe(400); + expect(await missingResource.json()).toMatchObject({ error: "invalid_target" }); + + const otherRedirect = await exchange({ ...params, redirect_uri: "http://127.0.0.1:47999/elsewhere" }); + expect(otherRedirect.status).toBe(400); + expect(await otherRedirect.json()).toMatchObject({ error: "invalid_grant" }); + + // Another client cannot redeem this client's code. + const thief = await register("Thief"); + const stolen = await exchange({ ...params, client_id: thief.client_id }); + expect(stolen.status).toBe(400); + + expect((await exchange(params)).status).toBe(200); + }); + + it("refuses refresh tokens", async () => { + const { client_id: clientId } = await register(); + const response = await exchange({ grant_type: "refresh_token", refresh_token: "x", client_id: clientId }); + expect(response.status).toBe(400); + expect(await response.json()).toMatchObject({ error: "invalid_grant" }); + }); +}); + +describe("SDK client OAuth discovery", () => { + class TestOAuthProvider implements OAuthClientProvider { + readonly redirectUrl = REDIRECT_URI; + readonly clientMetadata: OAuthClientMetadata = { + client_name: "SDK Discovery Client", + redirect_uris: [REDIRECT_URI], + grant_types: ["authorization_code"], + response_types: ["code"], + token_endpoint_auth_method: "none", + }; + info: OAuthClientInformationMixed | undefined; + saved: OAuthTokens | undefined; + verifier = ""; + authorizationUrl: URL | undefined; + clientInformation() { + return this.info; + } + saveClientInformation(info: OAuthClientInformationMixed) { + this.info = info; + } + tokens() { + return this.saved; + } + saveTokens(tokens: OAuthTokens) { + this.saved = tokens; + } + redirectToAuthorization(url: URL) { + this.authorizationUrl = url; + } + saveCodeVerifier(verifier: string) { + this.verifier = verifier; + } + codeVerifier() { + return this.verifier; + } + } + + it("discovers metadata, registers, and authorizes with the SDK's own auth() flow", async () => { + const provider = new TestOAuthProvider(); + expect(await auth(provider, { serverUrl: server.mcpUrl })).toBe("REDIRECT"); + expect(provider.info?.client_id).toBeTruthy(); + const url = provider.authorizationUrl!; + expect(url.origin + url.pathname).toBe(`${base}/authorize`); + expect(url.searchParams.get("resource")).toBe(server.mcpUrl); + expect(url.searchParams.get("code_challenge_method")).toBe("S256"); + + const id = await openApproval(url); + approve("builtin.guide", "SDK Agent"); + const code = (await waitForRedirect(id)).searchParams.get("code")!; + expect(await auth(provider, { serverUrl: server.mcpUrl, authorizationCode: code })).toBe("AUTHORIZED"); + expect(provider.saved?.access_token).toMatch(/^dhmcp_/); + + const transport = new StreamableHTTPClientTransport(new URL(server.mcpUrl), { authProvider: provider }); + const client = new Client({ name: "sdk-auth-test", version: "1.0.0" }); + await client.connect(transport); + clients.push(client); + const status = (await client.callTool({ name: "diskhound_status", arguments: {} })) as CallToolResult; + expect(status.structuredContent).toMatchObject({ session: { name: "SDK Agent", role: "Cleanup Guide" } }); + }); +}); diff --git a/src/mcp/__tests__/agentOAuth.test.ts b/src/mcp/__tests__/agentOAuth.test.ts new file mode 100644 index 00000000..f9009bb3 --- /dev/null +++ b/src/mcp/__tests__/agentOAuth.test.ts @@ -0,0 +1,299 @@ +import { createHash, randomBytes } from "node:crypto"; +import * as FS from "node:fs"; +import * as OS from "node:os"; +import * as Path from "node:path"; +import type { Response } from "express"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + InvalidGrantError, + InvalidRequestError, + InvalidTokenError, +} from "@modelcontextprotocol/sdk/server/auth/errors.js"; +import type { AuthorizationParams } from "@modelcontextprotocol/sdk/server/auth/provider.js"; +import type { OAuthClientInformationFull } from "@modelcontextprotocol/sdk/shared/auth.js"; + +import { McpPolicyStore } from "../accessPolicy"; +import { AgentOAuth, type ConsentDecision, type ConsentRequest } from "../agentOAuth"; + +const RESOURCE = new URL("http://127.0.0.1:51733/mcp"); +const REDIRECT_URI = "http://127.0.0.1:47999/callback"; +const TTL_MS = 5 * 60_000; + +/** Just enough of an Express Response to capture what AgentOAuth sends. */ +class FakeResponse { + statusCode = 200; + headers: Record = {}; + body = ""; + location: string | undefined; + setHeader(name: string, value: string) { + this.headers[name.toLowerCase()] = value; + return this; + } + status(code: number) { + this.statusCode = code; + return this; + } + type(_type: string) { + return this; + } + send(body: string) { + this.body = body; + return this; + } + redirect(code: number, url: string) { + this.statusCode = code; + this.location = url; + } + get asExpress(): Response { + return this as unknown as Response; + } +} + +let tempDir: string; +let policy: McpPolicyStore; +let requests: ConsentRequest[]; +let consent: (request: ConsentRequest) => Promise; +let oauth: AgentOAuth; +let onChanged: ReturnType void>>; + +beforeEach(() => { + tempDir = FS.mkdtempSync(Path.join(OS.tmpdir(), "diskhound-oauth-test-")); + policy = new McpPolicyStore(Path.join(tempDir, "mcp-policy.json")); + requests = []; + consent = async () => ({ decision: "allow", sessionName: "Agent", roleId: "builtin.guide" }); + onChanged = vi.fn<() => void>(); + oauth = new AgentOAuth({ + policy, + clientsFile: Path.join(tempDir, "clients.json"), + resource: RESOURCE, + requestConsent: (request) => { + requests.push(request); + return consent(request); + }, + onChanged, + }); +}); + +afterEach(() => { + vi.useRealTimers(); + oauth.close(); + FS.rmSync(tempDir, { recursive: true, force: true }); +}); + +async function registerClient(name = "Test Agent"): Promise { + return (await oauth.clientsStore.registerClient!({ + client_name: name, + redirect_uris: [REDIRECT_URI], + } as OAuthClientInformationFull)) as OAuthClientInformationFull; +} + +function pkce() { + const verifier = randomBytes(32).toString("base64url"); + return { verifier, challenge: createHash("sha256").update(verifier).digest("base64url") }; +} + +function params(challenge: string, extra: Partial = {}): AuthorizationParams { + return { + state: "s1", + scopes: ["disk.read", "scan.run", "app.navigate", "files.trash"], + codeChallenge: challenge, + redirectUri: REDIRECT_URI, + resource: RESOURCE, + ...extra, + }; +} + +/** Start an authorization and return the approval id from the waiting page. */ +async function begin(client: OAuthClientInformationFull, challenge = pkce().challenge, extra: Partial = {}) { + const response = new FakeResponse(); + await oauth.authorize(client, params(challenge, extra), response.asExpress); + const id = /status\?id=([A-Za-z0-9_-]+)/.exec(response.body)?.[1]; + if (!id) throw new Error("no approval id in the waiting page"); + return id; +} + +/** Let the consent promise chain settle. */ +async function flush() { + for (let i = 0; i < 5; i++) await Promise.resolve(); +} + +function poll(id: string): FakeResponse { + const response = new FakeResponse(); + oauth.status(id, response.asExpress); + return response; +} + +describe("AgentOAuth", () => { + it("issues a single-use code bound to the client and creates the Session at exchange", async () => { + const client = await registerClient(); + const { verifier, challenge } = pkce(); + const id = await begin(client, challenge); + await flush(); + const redirect = poll(id); + expect(redirect.statusCode).toBe(302); + const code = new URL(redirect.location!).searchParams.get("code")!; + + expect(await oauth.challengeForAuthorizationCode(client, code)).toBe(challenge); + const other = await registerClient("Other"); + await expect(oauth.challengeForAuthorizationCode(other, code)).rejects.toBeInstanceOf(InvalidGrantError); + + const tokens = await oauth.exchangeAuthorizationCode(client, code, verifier, REDIRECT_URI, RESOURCE); + expect(tokens).toMatchObject({ token_type: "bearer", scope: "disk.read scan.run app.navigate files.trash" }); + expect(onChanged).toHaveBeenCalledTimes(1); + await expect(oauth.exchangeAuthorizationCode(client, code, verifier, REDIRECT_URI, RESOURCE)).rejects.toBeInstanceOf(InvalidGrantError); + + const info = await oauth.verifyAccessToken(tokens.access_token); + expect(info).toEqual({ + token: tokens.access_token, + clientId: client.client_id, + scopes: ["disk.read", "scan.run", "app.navigate"], + resource: RESOURCE, + }); + }); + + it("aborts the consent request and forgets the approval when it expires", async () => { + vi.useFakeTimers(); + let signal: AbortSignal | undefined; + consent = (request) => { + signal = request.signal; + return new Promise(() => undefined); + }; + const id = await begin(await registerClient()); + expect(signal?.aborted).toBe(false); + expect(poll(id).statusCode).toBe(200); + + vi.advanceTimersByTime(TTL_MS); + expect(signal?.aborted).toBe(true); + expect(poll(id).statusCode).toBe(404); + }); + + it("ignores an approval that arrives after the request expired", async () => { + vi.useFakeTimers(); + let decide: ((decision: ConsentDecision) => void) | undefined; + consent = () => new Promise((resolve) => (decide = resolve)); + const id = await begin(await registerClient()); + vi.advanceTimersByTime(TTL_MS + 1); + decide!({ decision: "allow", sessionName: "Late", roleId: "builtin.guide" }); + await flush(); + expect(poll(id).statusCode).toBe(404); + expect(policy.sessions()).toEqual([]); + }); + + it("expires unused authorization codes after five minutes", async () => { + vi.useFakeTimers(); + const client = await registerClient(); + const { verifier, challenge } = pkce(); + const id = await begin(client, challenge); + await flush(); + const code = new URL(poll(id).location!).searchParams.get("code")!; + vi.advanceTimersByTime(TTL_MS); + await expect(oauth.exchangeAuthorizationCode(client, code, verifier, REDIRECT_URI, RESOURCE)).rejects.toBeInstanceOf(InvalidGrantError); + }); + + it("denies, as defense in depth, decisions the approval window should never produce", async () => { + const client = await registerClient(); + const cases: [string, () => Promise, Partial][] = [ + ["role beyond the requested scopes", async () => ({ decision: "allow", sessionName: "A", roleId: "builtin.operator" }), { scopes: ["disk.read"] }], + ["blank session name", async () => ({ decision: "allow", sessionName: " ", roleId: "builtin.reader" }), {}], + ["unknown role", async () => ({ decision: "allow", sessionName: "A", roleId: "builtin.root" }), {}], + ["consent callback throws", async () => { + throw new Error("window crashed"); + }, {}], + ]; + for (const [label, decide, extra] of cases) { + consent = decide; + const id = await begin(client, pkce().challenge, extra); + await flush(); + const redirect = poll(id); + expect(redirect.statusCode, label).toBe(302); + const location = new URL(redirect.location!); + expect(location.searchParams.get("error"), label).toBe("access_denied"); + expect(location.searchParams.get("state"), label).toBe("s1"); + } + expect(policy.sessions()).toEqual([]); + }); + + it("passes the client name and requested scopes to the consent callback", async () => { + await begin(await registerClient(" Claude Code "), pkce().challenge, { scopes: ["disk.read"] }); + await begin(await registerClient(" "), pkce().challenge, { scopes: [] }); + expect(requests.map((request) => [request.clientName, request.scopes])).toEqual([ + ["Claude Code", ["disk.read"]], + ["Local MCP client", ["disk.read", "scan.run", "app.navigate", "files.trash", "files.delete"]], + ]); + }); + + it("limits pending approvals to 64", async () => { + consent = () => new Promise(() => undefined); + const client = await registerClient(); + for (let i = 0; i < 64; i++) await begin(client); + await expect(oauth.authorize(client, params(pkce().challenge), new FakeResponse().asExpress)).rejects.toBeInstanceOf(InvalidRequestError); + }); + + it("shows the same waiting page for a repeated authorize URL instead of asking twice", async () => { + const decide: ((decision: ConsentDecision) => void)[] = []; + consent = () => new Promise((resolve) => decide.push(resolve)); + const client = await registerClient("Codex"); + const { challenge } = pkce(); + const first = await begin(client, challenge); + // Codex opens the URL in the browser and the user opens it again. + const again = await begin(client, challenge); + expect(again).toBe(first); + expect(decide).toHaveLength(1); + // A new login (new PKCE challenge) is a new request. + await begin(client); + expect(decide).toHaveLength(2); + + decide[0]!({ decision: "allow", sessionName: "Codex", roleId: "builtin.guide" }); + await flush(); + expect(poll(first).statusCode).toBe(302); + }); + + it("withdraws a request its client gave up on, but not one already decided", async () => { + const signals: AbortSignal[] = []; + const decide: ((decision: ConsentDecision) => void)[] = []; + consent = (request) => { + signals.push(request.signal); + return new Promise((resolve) => decide.push(resolve)); + }; + const client = await registerClient("Claude Code"); + const gone = await begin(client); + oauth.cancel(gone); + expect(signals[0]!.aborted).toBe(true); + expect(poll(gone).statusCode).toBe(404); + + const decided = await begin(client); + decide[1]!({ decision: "allow", sessionName: "Claude Code", roleId: "builtin.guide" }); + await flush(); + oauth.cancel(decided); + oauth.cancel("no-such-id"); + expect(signals[1]!.aborted).toBe(false); + expect(poll(decided).statusCode).toBe(302); + }); + + it("close() aborts every pending approval", async () => { + const signals: AbortSignal[] = []; + consent = (request) => { + signals.push(request.signal); + return new Promise(() => undefined); + }; + const client = await registerClient(); + await begin(client); + await begin(client); + oauth.close(); + expect(signals.map((signal) => signal.aborted)).toEqual([true, true]); + }); + + it("rejects revoked or unknown tokens and treats revoking them as a no-op", async () => { + await expect(oauth.verifyAccessToken("dhmcp_unknown")).rejects.toBeInstanceOf(InvalidTokenError); + const client = await registerClient(); + await expect(oauth.revokeToken(client, { token: "dhmcp_unknown" })).resolves.toBeUndefined(); + await expect(oauth.exchangeRefreshToken()).rejects.toBeInstanceOf(InvalidGrantError); + }); + + it("recovers from a corrupt client store by starting empty", () => { + const file = Path.join(tempDir, "corrupt-clients.json"); + FS.writeFileSync(file, "{oops"); + const fresh = new AgentOAuth({ policy, clientsFile: file, resource: RESOURCE, requestConsent: consent, onChanged }); + expect(fresh.clientsStore.getClient("anything")).toBeUndefined(); + }); +}); diff --git a/src/mcp/__tests__/agentPersistence.ioBudget.test.ts b/src/mcp/__tests__/agentPersistence.ioBudget.test.ts new file mode 100644 index 00000000..4fa9505e --- /dev/null +++ b/src/mcp/__tests__/agentPersistence.ioBudget.test.ts @@ -0,0 +1,147 @@ +import * as FS from "node:fs"; +import * as FSP from "node:fs/promises"; +import * as OS from "node:os"; +import * as Path from "node:path"; +import type { Response } from "express"; +import type { OAuthClientInformationFull } from "@modelcontextprotocol/sdk/shared/auth.js"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { expectIoBudget, measureFsIo } from "../../test/ioBudget"; +import { MCP_AGENT_CAPABILITIES } from "../../shared/agentAccess"; +import { McpPolicyStore } from "../accessPolicy"; +import { AgentOAuth } from "../agentOAuth"; +import { AgentActivityLog } from "../activityLog"; + +vi.mock("node:fs", async (original) => (await import("../../test/ioBudget")).instrumentFs(await original())); +vi.mock("node:fs/promises", async (original) => (await import("../../test/ioBudget")).instrumentFsPromises(await original())); + +const resource = new URL("http://127.0.0.1:51733/mcp"); +const redirect = "http://127.0.0.1:47999/callback"; +let dir: string; +let policy: McpPolicyStore; +let oauth: AgentOAuth; +let client: OAuthClientInformationFull; +let active: ReturnType; +const scopes = [...MCP_AGENT_CAPABILITIES]; + +class Reply { + body = ""; + location = ""; + setHeader() { return this; } + type() { return this; } + status() { return this; } + send(body: string) { this.body = body; return this; } + redirect(_status: number, url: string) { this.location = url; } + get response() { return this as unknown as Response; } +} + +async function register(name: string) { + return await oauth.clientsStore.registerClient!({ client_name: name, redirect_uris: [redirect] }) as OAuthClientInformationFull; +} + +beforeEach(async () => { + dir = await FSP.mkdtemp(Path.join(OS.tmpdir(), "diskhound-agent-io-")); + policy = new McpPolicyStore(Path.join(dir, "policy.json")); + oauth = new AgentOAuth({ policy, clientsFile: Path.join(dir, "clients.json"), resource, + requestConsent: async () => ({ decision: "allow", sessionName: "Claude Code โ€” cleanup", roleId: "builtin.guide" }), + onChanged: () => undefined }); + // A used profile: several agents/projects and retained session history. + for (let i = 0; i < 32; i++) { + client = await register(`Local development agent ${i.toString().padStart(3, "0")}`); + active = policy.createSession(`Project ${i.toString().padStart(3, "0")} agent`, "builtin.guide", { clientId: client.client_id, scopes }); + } +}); +afterEach(() => { oauth.close(); FS.rmSync(dir, { recursive: true, force: true }); }); + +function budget(scenario: string, io: Awaited>["io"], detail: string) { + expectIoBudget({ scenario, io, note: `${detail} Not tied to monitoring: at default or aggressive 1-minute monitoring, ` + + `assuming 1 event/day: ${io.writeFile} file writes/day, ${(io.bytesWritten / 1e6).toFixed(3)} MB/day; ` + + `24 events/day: ${24 * io.writeFile} file writes/day, ${(24 * io.bytesWritten / 1e6).toFixed(3)} MB/day. ` + + "Each changed file is atomically replaced with a rename; polling adds no writes." }); +} + +it("budgets one client registration in a used profile", async () => { + const { io } = await measureFsIo(() => register("Claude Code โ€” new project")); + budget("mcp-client-registration", io, "Registration with 32 saved clients; one complete client-store replacement."); +}); + +it("budgets registration at the 256-client cap", async () => { + for (let i = 32; i < 256; i++) await register(`Local development agent ${i.toString().padStart(3, "0")}`); + const { io } = await measureFsIo(() => register("Claude Code โ€” new project")); + budget("mcp-client-registration-at-cap", io, "256 saved clients; evicts one unapproved client and replaces the bounded store once."); +}); + +it("budgets OAuth approval, role change, and revocation", async () => { + const { io } = await measureFsIo(async () => { + const response = new Reply(); + await oauth.authorize(client, { codeChallenge: "x".repeat(43), redirectUri: redirect, resource, scopes }, response.response); + const id = /status\?id=([A-Za-z0-9_-]+)/.exec(response.body)![1]!; + await Promise.resolve(); + const approved = new Reply(); + oauth.status(id, approved.response); + const code = new URL(approved.location).searchParams.get("code")!; + const tokens = await oauth.exchangeAuthorizationCode(client, code, undefined, redirect, resource); + const auth = policy.authorize(tokens.access_token); + policy.assignRole(auth.sessionId, "builtin.operator"); + await oauth.revokeToken(client, { token: tokens.access_token }); + await expect(oauth.verifyAccessToken(tokens.access_token)).rejects.toThrow(); + }); + budget("mcp-session-lifecycle", io, "32 existing sessions; approval, role change and revocation replace the policy three times per lifecycle."); +}); + +it("does not persist repeated role assignments or revocations", async () => { + policy.revokeSession(active.session.id); + const { io } = await measureFsIo(() => { + policy.assignRole(active.session.id, "builtin.guide"); + policy.revokeSession(active.session.id); + policy.forgetRevoked(); + policy.forgetRevoked(); + }); + // Only actually removing the revoked record changes disk state. + budget("mcp-policy-idempotent-updates", io, "Repeated role/revoke/forget requests; only the first forget changes the policy (one replacement)."); +}); + +it("keeps token verification, pending-approval polling and activity reads write-free", async () => { + const pending = new AgentOAuth({ policy, clientsFile: Path.join(dir, "clients.json"), resource, + requestConsent: () => new Promise(() => undefined), onChanged: () => undefined }); + try { + const response = new Reply(); + await pending.authorize(client, { codeChallenge: "x".repeat(43), redirectUri: redirect, resource, scopes }, response.response); + const id = /status\?id=([A-Za-z0-9_-]+)/.exec(response.body)![1]!; + const activity = new AgentActivityLog(() => undefined); + const { io } = await measureFsIo(async () => { + for (let i = 0; i < 60; i++) { + await oauth.verifyAccessToken(active.token); + policy.authorize(active.token, ["disk.read"]); + await oauth.clientsStore.getClient(client.client_id); + pending.status(id, new Reply().response); + activity.record({ sessionId: active.session.id, sessionName: "Agent", tool: "diskhound_status", summary: "Read status", ok: true }); + activity.list(); + } + }); + budget("mcp-read-poll-activity", io, "60 token/read/poll/activity cycles with 32 sessions; 0 writes/day and 0 MB/day even at one cycle/second (86,400/day)."); + } finally { pending.close(); } +}); + +it("budgets a stdio approval followed by reused connections", async () => { + const { io } = await measureFsIo(async () => { + const bridge = await register("DiskHound stdio"); + const response = new Reply(); + await oauth.authorize(bridge, { codeChallenge: "x".repeat(43), redirectUri: redirect, resource, scopes }, response.response); + const id = /status\?id=([A-Za-z0-9_-]+)/.exec(response.body)![1]!; + await Promise.resolve(); + const approved = new Reply(); + oauth.status(id, approved.response); + const code = new URL(approved.location).searchParams.get("code")!; + const tokens = await oauth.exchangeAuthorizationCode(bridge, code, undefined, redirect, resource); + // The native helper loads its saved token on reconnect and keeps it in + // memory for ordinary calls; it does not register/sign in every time. + for (let connection = 0; connection < 24; connection++) { + for (let request = 0; request < 60; request++) { + await oauth.verifyAccessToken(tokens.access_token); + } + } + }); + budget("mcp-stdio-approval-and-reuse", io, + "One stdio registration and approval with 32 saved clients/sessions, then 24 reconnects and 1,440 requests. " + + "The helper's separate OS-store budget is in native/diskhound-mcp/io-budgets.json; no token is written to a file."); +}); diff --git a/src/mcp/__tests__/claudeExtension.test.ts b/src/mcp/__tests__/claudeExtension.test.ts new file mode 100644 index 00000000..4a323428 --- /dev/null +++ b/src/mcp/__tests__/claudeExtension.test.ts @@ -0,0 +1,82 @@ +import * as FS from "node:fs"; +import * as OS from "node:os"; +import * as Path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { unzip } from "../../test/zipReader"; +import { writeClaudeExtension, zip } from "../claudeExtension"; + +const dirs: string[] = []; +const scratch = () => { + const dir = FS.mkdtempSync(Path.join(OS.tmpdir(), "dh-claude-ext-")); + dirs.push(dir); + return dir; +}; +afterEach(() => { + for (const dir of dirs.splice(0)) FS.rmSync(dir, { recursive: true, force: true }); +}); + +describe("Claude extension", () => { + it("bundles the helper as an executable, with a manifest Claude can install", async () => { + const dir = scratch(); + const helper = Path.join(dir, "diskhound-mcp"); + const icon = Path.join(dir, "icon.png"); + // Compressible like a real binary, and big enough to span deflate blocks. + FS.writeFileSync(helper, Buffer.from(Array.from({ length: 300_000 }, (_, i) => (i * 7) % 251))); + FS.writeFileSync(icon, Buffer.from("png")); + const file = Path.join(dir, "out", "DiskHound.mcpb"); + + await writeClaudeExtension(file, { helperPath: helper, iconPath: icon, version: "0.6.4", port: 51735, platform: "darwin" }); + + const entries = unzip(FS.readFileSync(file)); + expect(entries.map((entry) => [entry.name, entry.mode.toString(8)])).toEqual([ + ["manifest.json", "644"], + ["icon.png", "644"], + ["server/diskhound-mcp", "755"], + ]); + expect(entries[2]!.data.equals(FS.readFileSync(helper))).toBe(true); + expect(JSON.parse(entries[0]!.data.toString("utf8"))).toMatchObject({ + manifest_version: "0.2", + name: "diskhound", + display_name: "DiskHound", + version: "0.6.4", + icon: "icon.png", + server: { + type: "binary", + entry_point: "server/diskhound-mcp", + mcp_config: { command: "${__dirname}/server/diskhound-mcp", args: [] }, + }, + tools_generated: true, + compatibility: { platforms: ["darwin"] }, + }); + }); + + it("names the Windows helper .exe, passes a non-default port, and skips a missing icon", async () => { + const dir = scratch(); + const helper = Path.join(dir, "diskhound-mcp.exe"); + FS.writeFileSync(helper, "MZ"); + const file = Path.join(dir, "DiskHound.mcpb"); + + await writeClaudeExtension(file, { helperPath: helper, iconPath: Path.join(dir, "missing.png"), version: "1.2.3-beta.4", port: 51999, platform: "win32" }); + + const entries = unzip(FS.readFileSync(file)); + expect(entries.map((entry) => entry.name)).toEqual(["manifest.json", "server/diskhound-mcp.exe"]); + const manifest = JSON.parse(entries[0]!.data.toString("utf8")); + expect(manifest.icon).toBeUndefined(); + expect(manifest.server.mcp_config).toEqual({ command: "${__dirname}/server/diskhound-mcp.exe", args: ["--port", "51999"], env: {} }); + }); + + it("fails without writing anything when the helper is missing", async () => { + const dir = scratch(); + const file = Path.join(dir, "out", "DiskHound.mcpb"); + await expect(writeClaudeExtension(file, { helperPath: Path.join(dir, "nope"), iconPath: null, version: "0.6.4", port: 51735, platform: "darwin" })) + .rejects.toMatchObject({ code: "ENOENT" }); + expect(FS.existsSync(Path.join(dir, "out"))).toBe(false); + }); + + it("writes an empty entry and UTF-8 names", async () => { + const entries = unzip(await zip([{ name: "รฉ/empty", data: Buffer.alloc(0), mode: 0o600 }])); + expect(entries).toEqual([{ name: "รฉ/empty", data: Buffer.alloc(0), mode: 0o600 }]); + }); +}); diff --git a/src/mcp/__tests__/consentBroker.test.ts b/src/mcp/__tests__/consentBroker.test.ts new file mode 100644 index 00000000..76894fb9 --- /dev/null +++ b/src/mcp/__tests__/consentBroker.test.ts @@ -0,0 +1,425 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { BUILT_IN_MCP_ROLES, MCP_AGENT_CAPABILITIES, type McpAgentCapability } from "../../shared/agentAccess"; +import type { ConsentDecision } from "../agentOAuth"; +import { AGENT_CONSENT_STATE_CHANNEL, ConsentBroker, type ConsentSender, type ConsentWindow } from "../consentBroker"; + +const ALL: McpAgentCapability[] = [...MCP_AGENT_CAPABILITIES]; + +/** Stand-in for the Electron BrowserWindow slice the broker uses. */ +class FakeWindow implements ConsentWindow { + private static nextId = 100; + readonly webContentsId = FakeWindow.nextId++; + private readonly closedListeners: (() => void)[] = []; + private destroyed = false; + closeCalls = 0; + focusCalls = 0; + readonly sent: { channel: string; payload: unknown }[] = []; + + onClosed(listener: () => void): void { + this.closedListeners.push(listener); + } + + /** Programmatic close (the broker) or the user clicking the close button. */ + close(): void { + this.closeCalls++; + if (this.destroyed) return; + this.destroyed = true; + for (const listener of this.closedListeners.splice(0)) listener(); + } + + isDestroyed(): boolean { + return this.destroyed; + } + + focus(): void { + this.focusCalls++; + } + + send(channel: string, payload: unknown): void { + this.sent.push({ channel, payload }); + } + + get main(): ConsentSender { + return { webContentsId: this.webContentsId, isMainFrame: true }; + } +} + +let windows: FakeWindow[]; +let activeNames: string[]; +let changes: number; +let broker: ConsentBroker; +let createWindow: ReturnType ConsentWindow>>; + +beforeEach(() => { + windows = []; + activeNames = []; + changes = 0; + createWindow = vi.fn(() => { + const window = new FakeWindow(); + windows.push(window); + return window; + }); + broker = new ConsentBroker(createWindow, () => activeNames, () => changes++); +}); + +/** Let the broker open the next sheet (createWindow may be async). */ +async function flush(): Promise { + for (let i = 0; i < 4; i++) await Promise.resolve(); +} + +interface AskOptions { + scopes?: McpAgentCapability[]; + signal?: AbortSignal; + via?: "stdio" | "http"; + waiting?: () => boolean; +} + +/** Ask for consent; `window` is the sheet opened for it, if it's the one shown. */ +async function ask(clientName = "Claude Code", options: AskOptions = {}) { + const before = windows.length; + const decision = broker.request({ + clientName, + via: options.via ?? "stdio", + scopes: options.scopes ?? ALL, + signal: options.signal ?? new AbortController().signal, + clientWaiting: options.waiting ?? (() => true), + }); + await flush(); + const window = windows.length > before ? windows.at(-1)! : undefined; + return { decision, window }; +} + +/** Ask, and deny whatever is on screen first so this request is the one shown. */ +async function show(clientName = "Claude Code", options: AskOptions = {}) { + for (const window of windows) if (!window.isDestroyed()) window.close(); + await flush(); + const asked = await ask(clientName, options); + if (!asked.window) throw new Error(`${clientName} was queued, not shown`); + return { decision: asked.decision, window: asked.window }; +} + +/** Whether a promise has settled after the current microtasks drain. */ +async function settled(promise: Promise): Promise { + let done = false; + void promise.then(() => (done = true), () => (done = true)); + await flush(); + return done; +} + +const DENY: ConsentDecision = { decision: "deny", sessionName: "", roleId: "" }; + +describe("ConsentBroker.request / read", () => { + it("opens a sheet for the request and shows the prompt only to its main frame", async () => { + const { window } = await show(); + expect(createWindow).toHaveBeenCalledTimes(1); + const prompt = broker.read(window.main); + expect(prompt).toEqual({ + requestId: expect.stringMatching(/^[0-9a-f-]{36}$/), + clientName: "Claude Code", + via: "stdio", + sessionName: "Claude Code", + requestedScopes: ALL, + roles: [ + expect.objectContaining({ id: "builtin.reader" }), + expect.objectContaining({ id: "builtin.guide" }), + expect.objectContaining({ id: "builtin.operator" }), + expect.objectContaining({ id: "builtin.admin" }), + ], + defaultRoleId: "builtin.guide", + stale: false, + next: null, + }); + + expect(broker.read({ webContentsId: window.webContentsId, isMainFrame: false })).toBeNull(); + expect(broker.read({ webContentsId: 1, isMainFrame: true })).toBeNull(); + }); + + it("offers only roles that fit inside the requested scopes", async () => { + const readOnly = await show("Reader", { scopes: ["disk.read"] }); + expect(broker.read(readOnly.window.main)).toMatchObject({ + roles: [expect.objectContaining({ id: "builtin.reader" })], + defaultRoleId: "builtin.reader", + }); + + const noNavigate = await show("Scanner", { scopes: ["disk.read", "scan.run"] }); + expect(broker.read(noNavigate.window.main)?.roles.map((role) => role.id)).toEqual(["builtin.reader"]); + + const guide = await show("Guide", { scopes: ["disk.read", "scan.run", "app.navigate"] }); + expect(broker.read(guide.window.main)).toMatchObject({ + roles: [expect.objectContaining({ id: "builtin.reader" }), expect.objectContaining({ id: "builtin.guide" })], + defaultRoleId: "builtin.guide", + }); + + // Signed in before permanent delete existed: no Cleanup Admin. + const trash = await show("Older Codex", { scopes: ["disk.read", "scan.run", "app.navigate", "files.trash"] }); + expect(broker.read(trash.window.main)?.roles.map((role) => role.id)).toEqual([ + "builtin.reader", + "builtin.guide", + "builtin.operator", + ]); + + const nothing = await show("Trash only", { scopes: ["files.trash"] }); + expect(broker.read(nothing.window.main)).toMatchObject({ roles: [], defaultRoleId: "" }); + }); + + it("copies roles into the prompt so the built-in role table cannot be mutated through it", async () => { + const { window } = await show(); + const prompt = broker.read(window.main)!; + prompt.roles[0]!.permissions.push("files.trash"); + expect(BUILT_IN_MCP_ROLES[0]!.permissions).toEqual(["disk.read"]); + }); + + it("de-duplicates the suggested Session name against active and waiting Sessions", async () => { + activeNames = ["Claude Code", "Claude Code 2", "Codex"]; + const { window } = await ask("Claude Code"); + expect(broker.read(window!.main)?.sessionName).toBe("Claude Code 3"); + // Queued behind the first, and named around it. + await ask("Claude Code"); + expect(broker.pending().map((pending) => pending.clientName)).toEqual(["Claude Code", "Claude Code"]); + window!.close(); + await flush(); + expect(broker.read(windows.at(-1)!.main)?.sessionName).toBe("Claude Code 4"); + + const other = await show("Cursor"); + expect(broker.read(other.window.main)?.sessionName).toBe("Cursor"); + }); + + it("trims the suggested Session name to 180 characters", async () => { + const { window } = await show("x".repeat(500)); + const prompt = broker.read(window.main)!; + expect(prompt.clientName).toHaveLength(500); + expect(prompt.sessionName).toHaveLength(180); + }); +}); + +describe("ConsentBroker.decide", () => { + it("resolves the request with the chosen name and role and closes the sheet", async () => { + const { decision, window } = await show(); + const prompt = broker.read(window.main)!; + expect( + broker.decide(window.main, { requestId: prompt.requestId, decision: "allow", sessionName: "My Claude", roleId: "builtin.admin" }), + ).toEqual({ ok: true }); + await expect(decision).resolves.toEqual({ decision: "allow", sessionName: "My Claude", roleId: "builtin.admin" }); + expect(window.isDestroyed()).toBe(true); + expect(broker.read(window.main)).toBeNull(); + // Deciding twice is refused. + expect(broker.decide(window.main, { requestId: prompt.requestId, decision: "deny", sessionName: "", roleId: "" }).ok).toBe(false); + }); + + it("rejects decisions from other windows, subframes, or for another request", async () => { + const { decision, window } = await show(); + // Queued: no sheet yet, so nothing can decide it. + const queued = await ask("Codex"); + expect(queued.window).toBeUndefined(); + const prompt = broker.read(window.main)!; + const allow = { requestId: prompt.requestId, decision: "allow" as const, sessionName: "X", roleId: "builtin.reader" }; + + expect(broker.decide({ webContentsId: window.webContentsId, isMainFrame: false }, allow)).toMatchObject({ ok: false }); + expect(broker.decide({ webContentsId: 424242, isMainFrame: true }, allow)).toMatchObject({ ok: false }); + expect(broker.decide(window.main, { ...allow, requestId: "not-the-request" })).toMatchObject({ ok: false }); + const queuedId = broker.pending()[1]!.requestId; + expect(broker.decide(window.main, { ...allow, requestId: queuedId })).toMatchObject({ ok: false }); + + expect(await settled(decision)).toBe(false); + expect(await settled(queued.decision)).toBe(false); + expect(window.isDestroyed()).toBe(false); + }); + + it("requires a name and one of the offered roles to allow", async () => { + const { decision, window } = await show("Reader", { scopes: ["disk.read"] }); + const { requestId } = broker.read(window.main)!; + const base = { requestId, decision: "allow" as const }; + expect(broker.decide(window.main, { ...base, sessionName: " ", roleId: "builtin.reader" }).ok).toBe(false); + expect(broker.decide(window.main, { ...base, sessionName: "x".repeat(201), roleId: "builtin.reader" }).ok).toBe(false); + // builtin.operator exists but was not offered for a read-only request. + expect(broker.decide(window.main, { ...base, sessionName: "Reader", roleId: "builtin.operator" }).ok).toBe(false); + expect(broker.decide(window.main, { ...base, sessionName: "Reader", roleId: "builtin.nope" }).ok).toBe(false); + expect( + broker.decide(window.main, { requestId, decision: "maybe" as never, sessionName: "Reader", roleId: "builtin.reader" }).ok, + ).toBe(false); + expect(await settled(decision)).toBe(false); + + expect(broker.decide(window.main, { ...base, sessionName: "Reader", roleId: "builtin.reader" })).toEqual({ ok: true }); + await expect(decision).resolves.toMatchObject({ decision: "allow", roleId: "builtin.reader" }); + }); + + it("accepts a deny without a name or role", async () => { + const { decision, window } = await show(); + const { requestId } = broker.read(window.main)!; + expect(broker.decide(window.main, { requestId, decision: "deny", sessionName: "", roleId: "" })).toEqual({ ok: true }); + await expect(decision).resolves.toMatchObject({ decision: "deny" }); + expect(window.isDestroyed()).toBe(true); + }); + + it("tolerates a malformed IPC payload", async () => { + const { window } = await show(); + expect(broker.decide(window.main, undefined as never)).toMatchObject({ ok: false }); + expect(broker.decide(window.main, null as never)).toMatchObject({ ok: false }); + }); +}); + +describe("ConsentBroker queue", () => { + it("shows requests one at a time, oldest first", async () => { + const first = await ask("Claude Code"); + const second = await ask("Codex", { via: "http" }); + expect(createWindow).toHaveBeenCalledTimes(1); + expect(first.window).toBeDefined(); + expect(second.window).toBeUndefined(); + expect(broker.pending()).toEqual([ + expect.objectContaining({ clientName: "Claude Code", via: "stdio", stale: false }), + expect.objectContaining({ clientName: "Codex", via: "http", stale: false }), + ]); + expect(broker.read(first.window!.main)?.next).toBe("Codex"); + + const { requestId } = broker.read(first.window!.main)!; + broker.decide(first.window!.main, { requestId, decision: "deny", sessionName: "", roleId: "" }); + await first.decision; + await flush(); + expect(createWindow).toHaveBeenCalledTimes(2); + const shown = windows.at(-1)!; + expect(broker.read(shown.main)).toMatchObject({ clientName: "Codex", next: null }); + }); + + it("tells the sheet on screen when the queue behind it changes", async () => { + const { window } = await ask("Claude Code"); + await ask("Codex"); + expect(window!.sent.at(-1)).toEqual({ + channel: AGENT_CONSENT_STATE_CHANNEL, + payload: expect.objectContaining({ stale: false, next: "Codex" }), + }); + broker.dismiss(broker.pending()[1]!.requestId); + expect(window!.sent.at(-1)?.payload).toEqual(expect.objectContaining({ next: null })); + }); + + it("dismiss() denies one waiting request and leaves the rest", async () => { + const first = await ask("Claude Code"); + const second = await ask("Codex"); + const before = changes; + broker.dismiss(broker.pending()[1]!.requestId); + await expect(second.decision).resolves.toEqual(DENY); + expect(await settled(first.decision)).toBe(false); + expect(first.window!.isDestroyed()).toBe(false); + expect(broker.pending()).toHaveLength(1); + expect(changes).toBeGreaterThan(before); + + // Dismissing the one on screen closes its sheet. + broker.dismiss(broker.pending()[0]!.requestId); + await expect(first.decision).resolves.toEqual(DENY); + expect(first.window!.isDestroyed()).toBe(true); + }); + + it("focus() brings the sheet on screen forward", async () => { + expect(broker.focus()).toBe(false); + const { window } = await ask(); + expect(broker.focus()).toBe(true); + expect(window!.focusCalls).toBe(1); + }); + + it("marks a request stale when its agent stops checking back, and fresh when it returns", async () => { + let waiting = true; + const { window } = await ask("Claude Code", { waiting: () => waiting }); + const before = changes; + broker.checkStale(); + expect(broker.pending()[0]!.stale).toBe(false); + expect(changes).toBe(before); + + waiting = false; + broker.checkStale(); + expect(broker.pending()[0]!.stale).toBe(true); + expect(broker.read(window!.main)?.stale).toBe(true); + expect(window!.sent.at(-1)).toEqual({ + channel: AGENT_CONSENT_STATE_CHANNEL, + payload: expect.objectContaining({ stale: true }), + }); + expect(changes).toBe(before + 1); + + waiting = true; + broker.checkStale(); + expect(broker.pending()[0]!.stale).toBe(false); + expect(window!.sent.at(-1)?.payload).toEqual(expect.objectContaining({ stale: false })); + }); + + it("denies a request whose sheet can't be opened and shows the next one", async () => { + createWindow.mockImplementationOnce(() => { + throw new Error("main window is gone"); + }); + const first = await ask("Claude Code"); + const second = await ask("Codex"); + await expect(first.decision).resolves.toEqual(DENY); + await flush(); + expect(broker.read(windows.at(-1)!.main)?.clientName).toBe("Codex"); + expect(await settled(second.decision)).toBe(false); + }); +}); + +describe("ConsentBroker deny paths", () => { + it("treats closing the sheet as a deny", async () => { + const { decision, window } = await show(); + window.close(); + await expect(decision).resolves.toEqual(DENY); + expect(broker.read(window.main)).toBeNull(); + }); + + it("treats an aborted request (expired OAuth approval) as a deny and closes the sheet", async () => { + const controller = new AbortController(); + const { decision, window } = await show("Claude Code", { signal: controller.signal }); + controller.abort(); + await expect(decision).resolves.toEqual(DENY); + expect(window.isDestroyed()).toBe(true); + expect(window.closeCalls).toBe(1); + }); + + it("drops an aborted request from the queue without opening a sheet", async () => { + await ask("Claude Code"); + const controller = new AbortController(); + const queued = await ask("Codex", { signal: controller.signal }); + controller.abort(); + await expect(queued.decision).resolves.toEqual(DENY); + expect(broker.pending().map((pending) => pending.clientName)).toEqual(["Claude Code"]); + expect(createWindow).toHaveBeenCalledTimes(1); + }); + + it("denies an already-aborted request without opening a sheet", async () => { + const controller = new AbortController(); + controller.abort(); + await expect(broker.request({ + clientName: "Late", + via: "http", + scopes: ALL, + signal: controller.signal, + clientWaiting: () => true, + })).resolves.toEqual(DENY); + expect(createWindow).not.toHaveBeenCalled(); + }); + + it("caps waiting approvals at 8", async () => { + const pending = []; + for (let index = 0; index < 8; index++) pending.push(await ask(`Agent ${index}`)); + expect(createWindow).toHaveBeenCalledTimes(1); + expect(broker.pending()).toHaveLength(8); + await expect(broker.request({ + clientName: "Ninth", + via: "stdio", + scopes: ALL, + signal: new AbortController().signal, + clientWaiting: () => true, + })).resolves.toEqual(DENY); + + // Finishing one frees a slot. + pending[0]!.window!.close(); + await pending[0]!.decision; + await ask("Ninth again"); + expect(broker.pending()).toHaveLength(8); + }); + + it("close() denies everything waiting and closes the sheet", async () => { + const first = await ask("One"); + const second = await ask("Two"); + broker.close(); + await expect(first.decision).resolves.toEqual(DENY); + await expect(second.decision).resolves.toEqual(DENY); + expect(first.window!.isDestroyed()).toBe(true); + expect(broker.pending()).toEqual([]); + }); +}); diff --git a/src/mcp/__tests__/fakeBackend.ts b/src/mcp/__tests__/fakeBackend.ts new file mode 100644 index 00000000..dc0ad6fe --- /dev/null +++ b/src/mcp/__tests__/fakeBackend.ts @@ -0,0 +1,343 @@ +// Shared fixtures for the MCP tests: a fake DiskhoundAgentBackend with +// plausible data for one scanned root, plus helpers for authorizations +// and the bundled skill catalog. Not a test file itself (no `.test.ts`). + +import { fileURLToPath } from "node:url"; +import { vi } from "vitest"; + +import type { + CleanupAnalysis, + DevArtifactReport, + DiskSpaceInfo, + FullDiffResult, + IndexSearchResult, + ScanDiffResult, + ScanFileRecord, + ScanHistoryEntry, + ScanSnapshot, +} from "../../shared/contracts"; +import { BUILT_IN_MCP_ROLES, type AgentActivityEntry } from "../../shared/agentAccess"; +import type { McpAuthorization } from "../accessPolicy"; +import type { AgentActivitySink, DiskhoundAgentBackend, DuplicateState, FolderChildren } from "../backend"; +import type { RemovalMeasurement } from "../removalMeasure"; +import type { AgentSecuritySink, SecurityEventInput } from "../securityLog"; + +export const SKILLS_DIR = fileURLToPath(new URL("../../../skills", import.meta.url)); +export const SERVER_SOURCE = fileURLToPath(new URL("../server.ts", import.meta.url)); + +export const NOW = Date.UTC(2026, 8, 24, 12, 0, 0); +export const ROOT = "/Users/test"; + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +const MB = 1024 ** 2; +const GB = 1024 ** 3; + +function file(path: string, size: number, modifiedAt = NOW - 3 * DAY): ScanFileRecord { + const slash = path.lastIndexOf("/"); + const name = path.slice(slash + 1); + const dot = name.lastIndexOf("."); + return { + path, + name, + parentPath: path.slice(0, slash) || "/", + extension: dot > 0 ? name.slice(dot).toLowerCase() : "", + size, + modifiedAt, + }; +} + +export const HISTORY: ScanHistoryEntry[] = [ + { id: "scan-3", rootPath: ROOT, scannedAt: NOW - HOUR, filesVisited: 120_000, directoriesVisited: 9_000, bytesSeen: 70 * GB, elapsedMs: 40_000, engine: "native-sidecar", sizeSemantics: "allocated" }, + { id: "scan-2", rootPath: ROOT, scannedAt: NOW - 2 * DAY, filesVisited: 118_000, directoriesVisited: 8_900, bytesSeen: 66 * GB, elapsedMs: 42_000, engine: "native-sidecar", sizeSemantics: "allocated" }, + { id: "scan-1", rootPath: ROOT, scannedAt: NOW - 10 * DAY, filesVisited: 110_000, directoriesVisited: 8_500, bytesSeen: 60 * GB, elapsedMs: 45_000, engine: "native-sidecar", sizeSemantics: "allocated" }, +]; + +export const DRIVE: DiskSpaceInfo = { + drive: "/", + totalBytes: 500 * GB, + freeBytes: 120 * GB, + usedBytes: 380 * GB, + usedPercent: 76.04, + timestamp: NOW, +}; + +const ISO = file(`${ROOT}/Downloads/ubuntu.iso`, 5 * GB); +const MOV = file(`${ROOT}/Movies/trip.mov`, 3 * GB); + +export const SNAPSHOT: ScanSnapshot = { + status: "done", + engine: "native-sidecar", + rootPath: ROOT, + scanOptions: {}, + startedAt: NOW - HOUR - 40_000, + finishedAt: NOW - HOUR, + elapsedMs: 40_000, + filesVisited: 120_000, + directoriesVisited: 9_000, + skippedEntries: 3, + bytesSeen: 70 * GB, + largestFiles: [ISO, MOV], + hottestDirectories: [ + { path: `${ROOT}/Developer`, size: 20 * GB, fileCount: 80_000, depth: 1 }, + { path: `${ROOT}/Library`, size: 40 * GB, fileCount: 30_000, depth: 1 }, + ], + topExtensions: [ + { extension: ".iso", size: 5 * GB, count: 1 }, + { extension: ".mov", size: 3 * GB, count: 1 }, + ], + errorMessage: null, + lastUpdatedAt: NOW - HOUR, + sizeSemantics: "allocated", +}; + +const EMPTY_CHILDREN: FolderChildren = { + visibleDirCount: 0, + dirs: [], + files: [], + totalSize: 0, + totalItemCount: 0, + hiddenExcludedCount: 0, + hiddenExcludedBytes: 0, +}; + +/** A small folder tree under ROOT, keyed by parent path. */ +export const TREE: Record = { + [ROOT]: { + visibleDirCount: 4, + dirs: [ + { path: `${ROOT}/Developer`, size: 20 * GB, fileCount: 80_000 }, + { path: `${ROOT}/Library`, size: 40 * GB, fileCount: 30_000 }, + { path: `${ROOT}/Downloads`, size: 5 * GB, fileCount: 12 }, + { path: `${ROOT}/Movies`, size: 3 * GB, fileCount: 4 }, + ], + files: [file(`${ROOT}/notes.txt`, 4096)], + totalSize: 68 * GB + 4096, + totalItemCount: 5, + hiddenExcludedCount: 0, + hiddenExcludedBytes: 0, + }, + [`${ROOT}/Developer`]: { + visibleDirCount: 2, + dirs: [ + { path: `${ROOT}/Developer/app`, size: 18 * GB, fileCount: 79_000 }, + { path: `${ROOT}/Developer/scratch`, size: 2 * GB, fileCount: 1_000 }, + ], + files: [], + totalSize: 20 * GB, + totalItemCount: 2, + hiddenExcludedCount: 1, + hiddenExcludedBytes: 64 * MB, + }, + [`${ROOT}/Downloads`]: { + visibleDirCount: 0, + dirs: [], + files: [ISO, file(`${ROOT}/Downloads/installer.dmg`, 400 * MB), file(`${ROOT}/Downloads/readme.pdf`, 2 * MB)], + totalSize: 5 * GB, + totalItemCount: 3, + hiddenExcludedCount: 0, + hiddenExcludedBytes: 0, + }, +}; + +const CLEANUP: CleanupAnalysis = { + suggestions: [ + { + id: "old-downloads", + category: "old-downloads", + risk: "low", + title: "Old downloads", + description: "Installers and disk images in Downloads.", + paths: [ISO.path, `${ROOT}/Downloads/installer.dmg`], + totalSize: 5 * GB + 400 * MB, + fileCount: 2, + reasoning: "Not opened in months.", + }, + ], + totalReclaimableBytes: 5 * GB + 400 * MB, + analyzedAt: NOW - HOUR, + scanRootPath: ROOT, +}; + +const DEV: DevArtifactReport = { + artifacts: [ + { + path: `${ROOT}/Developer/app/node_modules`, + kind: "node-modules", + projectPath: `${ROOT}/Developer/app`, + projectName: "app", + size: 2 * GB, + fileCount: 50_000, + previousSize: GB, + deltaBytes: GB, + }, + { + path: `${ROOT}/Developer/app/target`, + kind: "rust-target", + projectPath: `${ROOT}/Developer/app`, + projectName: "app", + size: 6 * GB, + fileCount: 9_000, + previousSize: null, + deltaBytes: null, + }, + ], + totalBytes: 8 * GB, + totalFiles: 59_000, + projectCount: 1, + kindTotals: [ + { kind: "node-modules", size: 2 * GB, count: 1 }, + { kind: "rust-target", size: 6 * GB, count: 1 }, + ], + generatedAt: NOW - HOUR, + rootPath: ROOT, +}; + +/** Two worktrees sharing clones with each other and with a store outside. */ +export const MEASUREMENT: RemovalMeasurement = { + paths: [ + { path: `${ROOT}/wt/one`, kind: "folder", files: 1_000, sizeBytes: 4 * GB, freesAloneBytes: 1 * GB, sharedBytes: 3 * GB, uncertainBytes: 0 }, + { path: `${ROOT}/wt/two`, kind: "folder", files: 2_000, sizeBytes: 5 * GB, freesAloneBytes: 2 * GB, sharedBytes: 3 * GB, uncertainBytes: 0 }, + ], + total: { files: 3_000, sizeBytes: 9 * GB, freesBytes: 4 * GB, heldElsewhereBytes: 2 * GB, uncertainBytes: 0 }, + missing: [], + nested: [], + skippedEntries: 0, + cloneMetadata: true, + elapsedMs: 1_200, + measuredAt: NOW, +}; + +function diffFor(baselineId: string, currentId: string): ScanDiffResult | null { + const baseline = HISTORY.find((entry) => entry.id === baselineId); + const current = HISTORY.find((entry) => entry.id === currentId); + if (!baseline || !current) return null; + return { + baselineId, + baselineScannedAt: baseline.scannedAt, + currentId, + currentScannedAt: current.scannedAt, + rootPath: ROOT, + totalBytesDelta: current.bytesSeen - baseline.bytesSeen, + totalFilesDelta: current.filesVisited - baseline.filesVisited, + totalDirsDelta: current.directoriesVisited - baseline.directoriesVisited, + previousBytesSeen: baseline.bytesSeen, + currentBytesSeen: current.bytesSeen, + fileDeltas: [ + { path: ISO.path, name: ISO.name, extension: ".iso", kind: "added", size: ISO.size, previousSize: 0, deltaBytes: ISO.size }, + ], + directoryDeltas: [ + { path: `${ROOT}/Downloads`, kind: "grew", size: 5 * GB, previousSize: 0, deltaBytes: 5 * GB, fileCount: 12, previousFileCount: 2 }, + { path: `${ROOT}/Library`, kind: "shrank", size: 40 * GB, previousSize: 41 * GB, deltaBytes: -GB, fileCount: 30_000, previousFileCount: 30_100 }, + ], + extensionDeltas: [ + { extension: ".iso", size: 5 * GB, previousSize: 0, deltaBytes: 5 * GB, count: 1, previousCount: 0 }, + ], + timeBetweenMs: current.scannedAt - baseline.scannedAt, + sizeSemanticsChanged: false, + hardlinkAccountingChanged: false, + volumeAccountingChanged: false, + }; +} + +function fullDiffFor(baselineId: string, currentId: string, limit: number): FullDiffResult | null { + if (!HISTORY.some((entry) => entry.id === baselineId) || !HISTORY.some((entry) => entry.id === currentId)) return null; + return { + baselineId, + currentId, + totalChanges: 2, + totalAdded: 1, + totalRemoved: 1, + totalGrew: 0, + totalShrank: 0, + totalBytesAdded: ISO.size, + totalBytesRemoved: GB, + changes: [ + { path: ISO.path, kind: "added" as const, size: ISO.size, previousSize: 0, deltaBytes: ISO.size }, + { path: `${ROOT}/Library/old.cache`, kind: "removed" as const, size: 0, previousSize: GB, deltaBytes: -GB }, + ].slice(0, limit), + truncated: false, + }; +} + +const NO_DUPLICATES: DuplicateState = { running: false, progress: null, analysis: null }; + +/** + * Build a fake backend. Every method is a `vi.fn` so tests can assert on + * calls or override one result with `mockResolvedValueOnce`. + */ +export function createFakeBackend() { + const backend = { + platform: "darwin" as NodeJS.Platform, + appVersion: "9.9.9-test", + listDrives: vi.fn(async () => [{ ...DRIVE }]), + activeScans: vi.fn(async () => []), + scannedRoots: vi.fn(() => [HISTORY[0]!]), + scanHistory: vi.fn((rootPath) => (rootPath === ROOT ? [...HISTORY] : [])), + latestSnapshot: vi.fn(async (rootPath) => (rootPath === ROOT ? SNAPSHOT : null)), + currentRoot: vi.fn(async () => ROOT), + folderChildren: vi.fn(async (_rootPath, parentPath) => TREE[parentPath] ?? EMPTY_CHILDREN), + searchIndex: vi.fn(async (): Promise => ({ + hits: [MOV, ISO], + truncated: false, + filesScanned: 120_000, + })), + cleanupSuggestions: vi.fn(async () => CLEANUP), + devArtifacts: vi.fn(async () => DEV), + diff: vi.fn(async (baselineId, currentId) => diffFor(baselineId, currentId)), + fullDiff: vi.fn(async (baselineId, currentId, limit) => fullDiffFor(baselineId, currentId, limit)), + duplicates: vi.fn(() => NO_DUPLICATES), + startScan: vi.fn(async (rootPath) => ({ + ...SNAPSHOT, + rootPath, + status: "running", + finishedAt: null, + startedAt: NOW, + })), + cancelScan: vi.fn(async () => undefined), + startDuplicateScan: vi.fn(() => undefined), + navigate: vi.fn(async () => undefined), + revealPath: vi.fn(async () => ({ ok: true, message: "Revealed." })), + measureRemoval: vi.fn>(async () => MEASUREMENT), + confirmAndTrash: vi.fn(async (request) => ({ + confirmed: true, + results: request.paths.map((path) => ({ path, ok: true, message: "Moved to Trash.", sizeBytes: 100 * MB })), + })), + confirmAndDelete: vi.fn(async (request) => ({ + confirmed: true, + results: request.paths.map((path) => ({ path, ok: true, message: "Deleted.", sizeBytes: 100 * MB })), + })), + } satisfies DiskhoundAgentBackend; + return backend; +} + +export type FakeBackend = ReturnType; + +/** Authorization for one of the built-in roles, as FixedMcpAuthorizer expects. */ +export function roleAuthorization(roleId: string, sessionName = "Test Agent"): McpAuthorization { + const role = BUILT_IN_MCP_ROLES.find((candidate) => candidate.id === roleId); + if (!role) throw new Error(`unknown role ${roleId}`); + return { + sessionId: `session_${roleId}`, + sessionName, + roleId: role.id, + roleName: role.name, + capabilities: [...role.permissions], + }; +} + +/** Activity sink that keeps every entry in call order. */ +export class RecordingActivity implements AgentActivitySink { + readonly entries: Omit[] = []; + record(entry: Omit): void { + this.entries.push(entry); + } +} + +export class RecordingSecurity implements AgentSecuritySink { + readonly events: SecurityEventInput[] = []; + record(event: SecurityEventInput): void { + this.events.push(event); + } +} diff --git a/src/mcp/__tests__/paths.test.ts b/src/mcp/__tests__/paths.test.ts new file mode 100644 index 00000000..0b3773db --- /dev/null +++ b/src/mcp/__tests__/paths.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from "vitest"; + +import { agentPath, isInside } from "../paths"; + +describe("isInside", () => { + it("accepts the root itself and anything below it", () => { + expect(isInside("/Users/test", "/Users/test")).toBe(true); + expect(isInside("/Users/test", "/Users/test/")).toBe(true); + expect(isInside("/Users/test/", "/Users/test/Downloads/a.iso")).toBe(true); + }); + + it("is separator-aware, so a sibling with the same prefix is outside", () => { + expect(isInside("/Users/a", "/Users/ab")).toBe(false); + expect(isInside("/Users/a", "/Users/ab/c")).toBe(false); + expect(isInside("/Users/test", "/Users")).toBe(false); + }); + + it("treats a POSIX filesystem root as containing every absolute path", () => { + expect(isInside("/", "/")).toBe(true); + expect(isInside("/", "/Users/test")).toBe(true); + expect(isInside("/", "C:\\Users")).toBe(false); + }); + + it("handles Windows drive roots and backslash separators", () => { + expect(isInside("C:\\", "C:\\Users\\test")).toBe(true); + expect(isInside("C:\\Users", "C:\\Users\\test\\AppData")).toBe(true); + expect(isInside("C:\\Users", "C:\\Users2")).toBe(false); + expect(isInside("C:\\", "D:\\data")).toBe(false); + }); + + it.runIf(process.platform === "win32")("ignores case on Windows", () => { + expect(isInside("C:\\Users\\Test", "c:\\users\\test\\file.txt")).toBe(true); + }); +}); + +describe("agentPath", () => { + it("normalizes absolute POSIX paths", () => { + expect(agentPath("/Users/test/Downloads/../Desktop/", "darwin")).toBe("/Users/test/Desktop"); + }); + + it("expands ~ to the home folder", () => { + expect(agentPath("~", "linux", "/home/test")).toBe("/home/test"); + expect(agentPath("~/Downloads", "darwin", "/Users/test")).toBe("/Users/test/Downloads"); + expect(agentPath("~\\Downloads", "win32", "C:\\Users\\test")).toBe("C:\\Users\\test\\Downloads"); + }); + + it("refuses relative paths", () => { + expect(() => agentPath("Downloads", "darwin")).toThrow(/absolute path/); + expect(() => agentPath("./a", "linux")).toThrow(/absolute path/); + expect(() => agentPath("Downloads", "win32")).toThrow(/absolute path/); + }); + + it("turns a bare drive letter into the drive root on Windows", () => { + expect(agentPath("C:", "win32")).toBe("C:\\"); + expect(agentPath("d:\\", "win32")).toBe("d:\\"); + expect(agentPath("C:/Users/test", "win32")).toBe("C:\\Users\\test"); + }); + + it("refuses drive-relative Windows paths but keeps UNC paths", () => { + expect(() => agentPath("\\Users\\test", "win32")).toThrow(/absolute path/); + expect(() => agentPath("C:Users", "win32")).toThrow(/absolute path/); + expect(agentPath("\\\\server\\share\\dir", "win32")).toBe("\\\\server\\share\\dir"); + }); +}); diff --git a/src/mcp/__tests__/removalMeasure.test.ts b/src/mcp/__tests__/removalMeasure.test.ts new file mode 100644 index 00000000..52d243dc --- /dev/null +++ b/src/mcp/__tests__/removalMeasure.test.ts @@ -0,0 +1,183 @@ +import * as FS from "node:fs"; +import * as OS from "node:os"; +import * as Path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { nativeRemovalMeasurer, RemovalMeasurements, type RemovalMeasurement } from "../removalMeasure"; + +const RESULT: RemovalMeasurement = { + paths: [], + total: { files: 1, sizeBytes: 4096, freesBytes: 4096, heldElsewhereBytes: 0, uncertainBytes: 0 }, + missing: [], + nested: [], + skippedEntries: 0, + cloneMetadata: true, + elapsedMs: 5, + measuredAt: 0, +}; + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +describe("RemovalMeasurements", () => { + it("measures a set once, whatever the order or repeats, and answers again from memory", async () => { + const run = vi.fn(async (_paths: readonly string[]) => RESULT); + const measurements = new RemovalMeasurements(run); + await measurements.measure(["/b", "/a", "/a"]); + expect(await measurements.measure(["/a", "/b"])).toBe(RESULT); + expect(run).toHaveBeenCalledTimes(1); + expect(run.mock.calls[0]![0]).toEqual(["/a", "/b"]); + }); + + it("measures again once the result is older than the TTL", async () => { + let now = 0; + const run = vi.fn(async () => RESULT); + const measurements = new RemovalMeasurements(run, { ttlMs: 1_000, now: () => now }); + await measurements.measure(["/a"]); + now = 1_001; + await measurements.measure(["/a"]); + expect(run).toHaveBeenCalledTimes(2); + }); + + it("keeps measuring when the agent stops waiting, so the same call made again gets the result", async () => { + const walk = deferred(); + const run = vi.fn((_paths: readonly string[], _signal: AbortSignal) => walk.promise); + const measurements = new RemovalMeasurements(run); + const caller = new AbortController(); + const first = measurements.measure(["/a"], caller.signal); + await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)); + caller.abort(); + await expect(first).rejects.toThrow("stopped waiting"); + expect(run.mock.calls[0]![1].aborted).toBe(false); + walk.resolve(RESULT); + expect(await measurements.measure(["/a"], new AbortController().signal)).toBe(RESULT); + expect(run).toHaveBeenCalledTimes(1); + }); + + it("doesn't keep a failure", async () => { + const run = vi.fn().mockRejectedValueOnce(new Error("no scanner")).mockResolvedValue(RESULT); + const measurements = new RemovalMeasurements(run); + await expect(measurements.measure(["/a"])).rejects.toThrow("no scanner"); + expect(await measurements.measure(["/a"])).toBe(RESULT); + expect(run).toHaveBeenCalledTimes(2); + }); + + it("runs one walk at a time", async () => { + const first = deferred(); + const run = vi.fn().mockReturnValueOnce(first.promise).mockResolvedValue(RESULT); + const measurements = new RemovalMeasurements(run); + const a = measurements.measure(["/a"]); + const b = measurements.measure(["/b"]); + await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(run).toHaveBeenCalledTimes(1); + first.resolve(RESULT); + await Promise.all([a, b]); + expect(run).toHaveBeenCalledTimes(2); + }); + + it("forgets finished results after a removal and keeps only the newest few", async () => { + let now = 0; + const run = vi.fn(async () => RESULT); + const measurements = new RemovalMeasurements(run, { maxKept: 2, now: () => ++now }); + await measurements.measure(["/a"]); + measurements.invalidate(); + await measurements.measure(["/a"]); + expect(run).toHaveBeenCalledTimes(2); + await measurements.measure(["/b"]); + await measurements.measure(["/c"]); + await measurements.measure(["/d"]); + await measurements.measure(["/a"]); + expect(run).toHaveBeenCalledTimes(6); + }); + + it("aborts a running walk on dispose", async () => { + const run = vi.fn((_paths: readonly string[], signal: AbortSignal) => + new Promise((_resolve, reject) => signal.addEventListener("abort", () => reject(new Error("killed"))))); + const measurements = new RemovalMeasurements(run); + const pending = measurements.measure(["/a"]); + await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)); + measurements.dispose(); + await expect(pending).rejects.toThrow("killed"); + }); + + it("never keeps a walk that was running when a removal went through", async () => { + const walk = deferred(); + const run = vi.fn().mockReturnValueOnce(walk.promise).mockResolvedValue(RESULT); + const measurements = new RemovalMeasurements(run); + const first = measurements.measure(["/a"]); + await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)); + measurements.invalidate(); + walk.resolve(RESULT); + await first; + await measurements.measure(["/a"]); + expect(run).toHaveBeenCalledTimes(2); + }); + + it("never starts a walk that dispose cancelled while it waited its turn", async () => { + const walk = deferred(); + const run = vi.fn().mockReturnValueOnce(walk.promise).mockResolvedValue(RESULT); + const measurements = new RemovalMeasurements(run); + const first = measurements.measure(["/a"]); + const queued = measurements.measure(["/b"]); + await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1)); + measurements.dispose(); + walk.resolve(RESULT); + await first; + await expect(queued).rejects.toThrow("cancelled"); + expect(run).toHaveBeenCalledTimes(1); + }); +}); + +// The real scanner is covered by its Rust tests and the agent E2E; this +// checks the process plumbing with a stand-in. +describe.skipIf(process.platform === "win32")("nativeRemovalMeasurer", () => { + const dirs: string[] = []; + afterEach(() => { + for (const dir of dirs.splice(0)) FS.rmSync(dir, { recursive: true, force: true }); + }); + + function fakeScanner(body: string): { binary: string; argsFile: string } { + const dir = FS.mkdtempSync(Path.join(OS.tmpdir(), "diskhound-measure-")); + dirs.push(dir); + const binary = Path.join(dir, "diskhound-native-scanner"); + const argsFile = Path.join(dir, "args"); + FS.writeFileSync(binary, `#!/bin/sh\nprintf '%s\\n' "$@" > '${argsFile}'\n${body}\n`, { mode: 0o755 }); + return { binary, argsFile }; + } + + it("passes each path and the worker count, and returns the measurement line", async () => { + const line = JSON.stringify({ ...RESULT, type: "removal-measurement", measuredAt: undefined }); + const { binary, argsFile } = fakeScanner(`echo '{"type":"progress","files":1}'\necho '${line}'`); + const result = await nativeRemovalMeasurer(binary, () => 3, () => 42)(["/a b", "/c"], new AbortController().signal); + expect(result).toMatchObject({ total: RESULT.total, measuredAt: 42 }); + expect(FS.readFileSync(argsFile, "utf8").trim().split("\n")).toEqual([ + "--mode=measure-removal", "--path", "/a b", "--path", "/c", "--workers", "3", + ]); + }); + + it("reports the scanner's error", async () => { + const { binary } = fakeScanner(`echo '{"type":"error","message":"--path must be absolute: x"}'\nexit 1`); + await expect(nativeRemovalMeasurer(binary)(["x"], new AbortController().signal)).rejects.toThrow("--path must be absolute: x"); + }); + + it("stops the scanner when aborted", async () => { + // Replace the shell, like the real scanner's single process. A separate + // sleep child survives SIGTERM to the shell and holds its pipes open, + // delaying Node's close event until sleep finishes. + const { binary } = fakeScanner("exec sleep 10"); + const controller = new AbortController(); + const pending = nativeRemovalMeasurer(binary)(["/a"], controller.signal); + setTimeout(() => controller.abort(), 50); + const started = Date.now(); + await expect(pending).rejects.toThrow("cancelled"); + expect(Date.now() - started).toBeLessThan(5_000); + }); +}); diff --git a/src/mcp/__tests__/securityLog.ioBudget.test.ts b/src/mcp/__tests__/securityLog.ioBudget.test.ts new file mode 100644 index 00000000..e1efda2a --- /dev/null +++ b/src/mcp/__tests__/securityLog.ioBudget.test.ts @@ -0,0 +1,102 @@ +import * as FS from "node:fs"; +import * as FSP from "node:fs/promises"; +import * as OS from "node:os"; +import * as Path from "node:path"; +import { afterEach, beforeEach, it, vi } from "vitest"; + +import { expectIoBudget, measureFsIo } from "../../test/ioBudget"; +import { AgentSecurityLog, type SecurityEventInput } from "../securityLog"; + +vi.mock("node:fs", async (original) => (await import("../../test/ioBudget")).instrumentFs(await original())); +vi.mock("node:fs/promises", async (original) => (await import("../../test/ioBudget")).instrumentFsPromises(await original())); + +let dir: string; +let file: string; +let clock: number; + +const refusal = (detail: string, tool = "diskhound_move_to_trash"): SecurityEventInput => ({ + sessionId: "session_0123456789abcdef", + sessionName: "Claude Code โ€” ~/github/diskhound", + roleName: "Cleanup Guide", + kind: detail.startsWith("Asked") ? "protected_path" : "tool_not_allowed", + tool, + detail, +}); + +beforeEach(async () => { + dir = await FSP.mkdtemp(Path.join(OS.tmpdir(), "diskhound-security-io-")); + file = Path.join(dir, "agent-security.log"); + clock = Date.UTC(2026, 8, 30, 12); + // A used log: a few hundred lines from earlier runs. + const old = Array.from({ length: 300 }, (_, i) => + JSON.stringify({ ...refusal(`Asked to move /Users/me/Library/Old ${i} to the Trash; agents may never remove it.`), id: `old-${i}`, at: clock - i * 60_000, count: 1 }), + ); + await FSP.writeFile(file, `${old.join("\n")}\n`); +}); + +afterEach(() => { + vi.useRealTimers(); + FS.rmSync(dir, { recursive: true, force: true }); +}); + +const log = () => new AgentSecurityLog({ file, now: () => clock }); + +function budget(scenario: string, io: Awaited>["io"], detail: string) { + expectIoBudget({ + scenario, + io, + note: `${detail} Only an agent's refused request writes, so the monitoring interval doesn't change it: ` + + "the same at the default and at the 1-minute interval. Appends are at least 5 minutes apart after the first " + + "and capped at 60 lines an hour, so an agent refused nonstop for a day costs at most 288 appends and " + + "1,440 lines (about 0.5 MB/day); the file rotates at 256 KB.", + }); +} + +it("budgets one refused request", async () => { + const security = log(); + const { io } = await measureFsIo(async () => { + security.record(refusal("Tried to delete items permanently; Cleanup Guide doesn't allow it.", "diskhound_delete_permanently")); + await security.flush(); + }); + budget("agent-security-log-one-refusal", io, + "One refusal: one stat for the file's size, then one append of one line. A few refusals a day is a few appends and under 1 KB/day."); +}); + +it("budgets one Trash request naming 20 protected folders", async () => { + const security = log(); + const { io } = await measureFsIo(async () => { + for (let i = 0; i < 20; i++) { + security.record(refusal(`Asked to move /System/Library/Folder ${i} to the Trash; agents may never remove it.`)); + } + await security.flush(); + }); + budget("agent-security-log-burst", io, "20 refusals in one request become one append of 20 lines."); +}); + +it("budgets an agent refused nonstop for an hour", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const security = log(); + const { io } = await measureFsIo(async () => { + // Every 10 s, a new blocked call, and the same one repeated twice. + for (let second = 0; second < 3_600; second += 10) { + clock += 10_000; + security.record(refusal(`Asked to move /Users/me/Protected ${second} to the Trash; agents may never remove it.`)); + security.record(refusal("Tried to delete items permanently; Cleanup Guide doesn't allow it.", "diskhound_delete_permanently")); + security.record(refusal("Tried to delete items permanently; Cleanup Guide doesn't allow it.", "diskhound_delete_permanently")); + await vi.advanceTimersByTimeAsync(10_000); + } + await security.flush(); + }); + budget("agent-security-log-looping-agent", io, + "360 distinct refusals and 720 repeats in an hour: the 60-line cap fills within minutes, so 60 lines reach disk in 3 appends " + + "(2 s after the first refusal, 5 minutes later, and at quit). Later refusals stay in memory for Settings."); +}); + +it("budgets loading the log for Settings once, and later reads from memory", async () => { + const security = log(); + const { io } = await measureFsIo(async () => { + for (let i = 0; i < 20; i++) await security.list(); + security.recent(); + }); + budget("agent-security-log-load", io, "Opening Settings โ†’ AI Agents reads the log once per run; 20 more opens read nothing. No writes."); +}); diff --git a/src/mcp/__tests__/securityLog.test.ts b/src/mcp/__tests__/securityLog.test.ts new file mode 100644 index 00000000..f382065b --- /dev/null +++ b/src/mcp/__tests__/securityLog.test.ts @@ -0,0 +1,163 @@ +import * as FS from "node:fs"; +import * as OS from "node:os"; +import * as Path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import type { AgentSecurityEvent } from "../../shared/agentAccess"; +import { AgentSecurityLog, type SecurityEventInput } from "../securityLog"; + +let dir: string; +let file: string; +let clock: number; +let seen: { event: AgentSecurityEvent; repeated: boolean; logged: boolean }[]; + +function event(overrides: Partial = {}): SecurityEventInput { + return { + sessionId: "session_1", + sessionName: "Codex", + roleName: "Cleanup Guide", + kind: "tool_not_allowed", + tool: "diskhound_delete_permanently", + detail: "Tried to delete items permanently; Cleanup Guide doesn't allow it.", + ...overrides, + }; +} + +function open(): AgentSecurityLog { + return new AgentSecurityLog({ + file, + now: () => clock, + onEvent: (e, info) => seen.push({ event: e, ...info }), + }); +} + +function lines(): AgentSecurityEvent[] { + return FS.readFileSync(file, "utf8").trim().split("\n").map((line) => JSON.parse(line) as AgentSecurityEvent); +} + +beforeEach(() => { + dir = FS.mkdtempSync(Path.join(OS.tmpdir(), "diskhound-security-log-")); + file = Path.join(dir, "agent-security.log"); + clock = 1_000_000; + seen = []; +}); + +afterEach(() => { + vi.useRealTimers(); + FS.rmSync(dir, { recursive: true, force: true }); +}); + +describe("AgentSecurityLog", () => { + it("counts an identical refusal within a minute instead of adding an event", () => { + const log = open(); + log.record(event()); + clock += 30_000; + log.record(event()); + log.record(event({ detail: "Something else" })); + const [other, repeat] = log.recent(); + expect(repeat).toMatchObject({ count: 2, at: clock }); + expect(other).toMatchObject({ count: 1, detail: "Something else" }); + expect(seen.map((s) => [s.repeated, s.event.count])).toEqual([[false, 1], [true, 2], [false, 1]]); + }); + + it("starts a new event once a minute has passed", () => { + const log = open(); + log.record(event()); + clock += 61_000; + log.record(event()); + expect(log.recent().map((e) => e.count)).toEqual([1, 1]); + }); + + it("keeps a different session's refusal separate", () => { + const log = open(); + log.record(event()); + log.record(event({ sessionId: "session_2", sessionName: "Claude Code" })); + expect(log.recent()).toHaveLength(2); + }); + + it("appends NDJSON readable only by the user, and a later run loads it newest first", async () => { + const log = open(); + log.record(event()); + clock += 1; + log.record(event({ kind: "protected_path", tool: "diskhound_move_to_trash", detail: "Asked to trash /System" })); + await log.flush(); + expect(lines().map((e) => e.tool)).toEqual(["diskhound_delete_permanently", "diskhound_move_to_trash"]); + if (process.platform !== "win32") expect(FS.statSync(file).mode & 0o777).toBe(0o600); + + const next = open(); + expect((await next.list()).map((e) => e.tool)).toEqual(["diskhound_move_to_trash", "diskhound_delete_permanently"]); + }); + + it("writes a repeat's new count after the first line was flushed, and loads the higher count", async () => { + const log = open(); + log.record(event()); + await log.flush(); + clock += 10_000; + log.record(event()); + log.record(event()); + await log.flush(); + expect(lines().map((e) => e.count)).toEqual([1, 3]); + const loaded = await open().list(); + expect(loaded).toHaveLength(1); + expect(loaded[0]).toMatchObject({ count: 3 }); + }); + + it("merges what is on disk with what this run recorded before the first read", async () => { + FS.writeFileSync(file, `${JSON.stringify({ ...event(), id: "old", at: 5, count: 4 })}\n{"torn`); + const log = open(); + log.record(event({ detail: "new" })); + expect((await log.list()).map((e) => [e.id === "old" ? "old" : "new", e.count])).toEqual([["new", 1], ["old", 4]]); + }); + + it("returns nothing for a missing file", async () => { + expect(await open().list()).toEqual([]); + }); + + it("rotates the file past 256 KB", async () => { + const log = open(); + FS.writeFileSync(file, "x".repeat(256 * 1024 - 10)); + log.record(event()); + await log.flush(); + expect(FS.existsSync(`${file}.1`)).toBe(true); + expect(lines()).toHaveLength(1); + }); + + it("writes at most 60 lines an hour, then resumes", async () => { + const log = open(); + for (let i = 0; i < 70; i++) log.record(event({ detail: `path ${i}` })); + await log.flush(); + expect(lines()).toHaveLength(60); + expect(seen.filter((s) => s.logged)).toHaveLength(60); + expect(log.recent()).toHaveLength(70); + + clock += 60 * 60_000; + log.record(event({ detail: "after an hour" })); + await log.flush(); + expect(lines()).toHaveLength(61); + }); + + it("appends 2 s after a quiet spell, then no more than once every 5 minutes", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const log = open(); + log.record(event({ detail: "first" })); + await vi.advanceTimersByTimeAsync(1_999); + expect(FS.existsSync(file)).toBe(false); + await vi.advanceTimersByTimeAsync(1); + await log.flush(); + expect(lines()).toHaveLength(1); + + clock += 10_000; + log.record(event({ detail: "second" })); + await vi.advanceTimersByTimeAsync(4 * 60_000); + expect(lines()).toHaveLength(1); + await vi.advanceTimersByTimeAsync(60_000); + await log.flush(); + expect(lines()).toHaveLength(2); + }); + + it("still records when the listener throws", () => { + const log = new AgentSecurityLog({ file, onEvent: () => { throw new Error("window closed"); } }); + expect(() => log.record(event())).not.toThrow(); + expect(log.recent()).toHaveLength(1); + }); +}); diff --git a/src/mcp/__tests__/server.test.ts b/src/mcp/__tests__/server.test.ts new file mode 100644 index 00000000..e0a944b6 --- /dev/null +++ b/src/mcp/__tests__/server.test.ts @@ -0,0 +1,1096 @@ +import * as FS from "node:fs"; +import * as OS from "node:os"; +import * as Path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { ErrorCode, McpError, type CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import { z } from "zod"; + +import { + BUILT_IN_MCP_ROLES, + MCP_AGENT_CAPABILITIES, + MCP_SERVER_NAME, + SKILLS_EXTENSION_ID, + type McpAgentCapability, +} from "../../shared/agentAccess"; +import { FixedMcpAuthorizer, McpPolicyStore, PolicyFileAuthorizer, type McpAuthorizer } from "../accessPolicy"; +import { AgentActivityLog } from "../activityLog"; +import { createDiskhoundMcpServer, FREE_UP_SPACE_SKILL, INVESTIGATE_GROWTH_SKILL, TOOL_CAPABILITIES } from "../server"; +import { loadSkillCatalog, type SkillCatalog } from "../skills"; +import { + createFakeBackend, + MEASUREMENT, + NOW, + RecordingActivity, + RecordingSecurity, + roleAuthorization, + ROOT, + SKILLS_DIR, + type FakeBackend, +} from "./fakeBackend"; + +const SKILLS = loadSkillCatalog(SKILLS_DIR); +const Loose = z.object({}).passthrough(); + +const EXPECTED_TOOLS = [ + "diskhound_status", + "diskhound_read_skill", + "diskhound_scan_summary", + "diskhound_list_folder", + "diskhound_search_files", + "diskhound_cleanup_suggestions", + "diskhound_dev_artifacts", + "diskhound_measure_removal", + "diskhound_scan_history", + "diskhound_changes", + "diskhound_duplicates", + "diskhound_start_scan", + "diskhound_cancel_scan", + "diskhound_find_duplicates", + "diskhound_show", + "diskhound_reveal_path", + "diskhound_move_to_trash", + "diskhound_delete_permanently", +]; +const READ_TOOLS = [ + "diskhound_status", + "diskhound_read_skill", + "diskhound_scan_summary", + "diskhound_list_folder", + "diskhound_search_files", + "diskhound_cleanup_suggestions", + "diskhound_dev_artifacts", + "diskhound_measure_removal", + "diskhound_scan_history", + "diskhound_changes", + "diskhound_duplicates", +]; + +interface Harness { + client: Client; + server: McpServer; + backend: FakeBackend; + activity: RecordingActivity; +} + +const open: Harness[] = []; + +async function connect(options: { + roleId?: string; + authorizer?: McpAuthorizer; + skills?: SkillCatalog; + backend?: FakeBackend; + granted?: readonly McpAgentCapability[]; + security?: RecordingSecurity; +} = {}): Promise { + const backend = options.backend ?? createFakeBackend(); + const activity = new RecordingActivity(); + const server = createDiskhoundMcpServer({ + backend, + activity, + skills: options.skills ?? SKILLS, + authorizer: options.authorizer ?? new FixedMcpAuthorizer(roleAuthorization(options.roleId ?? "builtin.operator")), + granted: options.granted, + security: options.security, + now: () => NOW, + }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "diskhound-test", version: "1.0.0" }); + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]); + const harness = { client, server, backend, activity }; + open.push(harness); + return harness; +} + +afterEach(async () => { + for (const harness of open.splice(0)) { + await harness.client.close(); + await harness.server.close(); + } +}); + +async function call(client: Client, name: string, args: Record = {}): Promise { + return (await client.callTool({ name, arguments: args })) as CallToolResult; +} + +function text(result: CallToolResult, index = 0): string { + const block = result.content[index]; + if (!block || block.type !== "text") throw new Error(`content[${index}] is not text`); + return block.text; +} + +function structured>(result: CallToolResult): T { + expect(result.isError, result.isError ? text(result) : "").not.toBe(true); + expect(result.structuredContent).toBeDefined(); + return result.structuredContent as T; +} + +async function mcpError(promise: Promise): Promise { + const error = await promise.then( + () => { + throw new Error("expected the request to fail"); + }, + (cause: unknown) => cause, + ); + expect(error).toBeInstanceOf(McpError); + return error as McpError; +} + +describe("initialize", () => { + it("identifies as DiskHound and declares tools, prompts, resources, and the skills extension", async () => { + const { client } = await connect(); + expect(client.getServerVersion()).toMatchObject({ name: MCP_SERVER_NAME, title: "DiskHound", version: "9.9.9-test" }); + const capabilities = client.getServerCapabilities(); + expect(capabilities?.tools).toBeDefined(); + expect(capabilities?.prompts).toBeDefined(); + expect(capabilities?.resources).toBeDefined(); + expect(capabilities?.extensions?.[SKILLS_EXTENSION_ID]).toEqual({ directoryRead: true }); + }); + + it("sends platform-specific instructions that point at both skills", async () => { + const { client } = await connect(); + const instructions = client.getInstructions() ?? ""; + expect(instructions).toContain("macOS"); + expect(instructions).toContain(FREE_UP_SPACE_SKILL); + expect(instructions).toContain(INVESTIGATE_GROWTH_SKILL); + expect(instructions).toContain("diskhound_move_to_trash"); + }); +}); + +describe("tools/list", () => { + it("lists every DiskHound tool with a title, description, and object input schema", async () => { + const { client } = await connect(); + const { tools } = await client.listTools(); + expect(tools.map((tool) => tool.name).sort()).toEqual([...EXPECTED_TOOLS].sort()); + for (const tool of tools) { + expect(tool.title, tool.name).toBeTruthy(); + expect(tool.description?.length, tool.name).toBeGreaterThan(20); + expect(tool.inputSchema.type, tool.name).toBe("object"); + } + }); + + it("defines all four annotation hints on every tool", async () => { + const { client } = await connect(); + const { tools } = await client.listTools(); + for (const tool of tools) { + const annotations = tool.annotations ?? {}; + for (const hint of ["readOnlyHint", "destructiveHint", "idempotentHint", "openWorldHint"] as const) { + expect(typeof annotations[hint], `${tool.name}.${hint}`).toBe("boolean"); + } + expect(annotations.openWorldHint, tool.name).toBe(false); + } + }); + + it("marks read tools read-only and only the trash and delete tools destructive", async () => { + const { client } = await connect(); + const { tools } = await client.listTools(); + const byName = new Map(tools.map((tool) => [tool.name, tool])); + for (const name of READ_TOOLS) { + expect(byName.get(name)?.annotations?.readOnlyHint, name).toBe(true); + expect(byName.get(name)?.annotations?.destructiveHint, name).toBe(false); + } + for (const name of EXPECTED_TOOLS.filter((tool) => !READ_TOOLS.includes(tool))) { + expect(byName.get(name)?.annotations?.readOnlyHint, name).toBe(false); + } + const destructive = tools.filter((tool) => tool.annotations?.destructiveHint).map((tool) => tool.name); + expect(destructive).toEqual(["diskhound_move_to_trash", "diskhound_delete_permanently"]); + }); + + it("requires paths for list_folder, move_to_trash and delete_permanently", async () => { + const { client } = await connect(); + const { tools } = await client.listTools(); + const byName = new Map(tools.map((tool) => [tool.name, tool])); + expect(byName.get("diskhound_list_folder")?.inputSchema.required).toEqual(["path"]); + expect(byName.get("diskhound_move_to_trash")?.inputSchema.required).toEqual(["paths"]); + expect(byName.get("diskhound_delete_permanently")?.inputSchema.required).toEqual(["paths"]); + }); +}); + +describe("read tools", () => { + it("diskhound_status returns structured content plus a text summary and its JSON", async () => { + const { client, backend } = await connect({ roleId: "builtin.guide" }); + const result = await call(client, "diskhound_status"); + const value = structured(result); + expect(value.app).toEqual({ name: "DiskHound", version: "9.9.9-test", platform: "darwin" }); + expect(value.session).toEqual({ + name: "Test Agent", + role: "Cleanup Guide", + capabilities: ["disk.read", "scan.run", "app.navigate"], + }); + expect(value.drives).toEqual([ + expect.objectContaining({ drive: "/", usedPercent: 76, free: "120 GB", total: "500 GB" }), + ]); + expect(value.scannedRoots).toEqual([ + expect.objectContaining({ rootPath: ROOT, age: "1 h ago", scansKept: 3, size: "70.0 GB" }), + ]); + expect(value.currentRoot).toBe(ROOT); + expect(value.skills).toEqual([FREE_UP_SPACE_SKILL, INVESTIGATE_GROWTH_SKILL]); + expect(value.note).toContain("APFS"); + + expect(result.content).toHaveLength(2); + expect(text(result)).toContain("Drives: / 120 GB free of 500 GB."); + expect(text(result)).toContain(`Scanned roots: ${ROOT} (1 h ago).`); + expect(text(result)).toContain(`read ${FREE_UP_SPACE_SKILL} with diskhound_read_skill`); + expect(JSON.parse(text(result, 1))).toEqual(value); + expect(backend.navigate).not.toHaveBeenCalled(); + }); + + it("diskhound_scan_summary uses the current root and caps each list", async () => { + const { client, backend } = await connect({ roleId: "builtin.reader" }); + const value = structured(await call(client, "diskhound_scan_summary", { limit: 1 })); + expect(value.rootPath).toBe(ROOT); + expect(value.totals).toMatchObject({ files: 120_000, size: "70.0 GB" }); + expect(value.largestFiles).toHaveLength(1); + // Sorted by size, not by the snapshot's order. + expect(value.heaviestFolders).toEqual([expect.objectContaining({ path: `${ROOT}/Library` })]); + expect(backend.latestSnapshot).toHaveBeenCalledWith(ROOT); + }); + + it("diskhound_list_folder drills into a folder, largest first", async () => { + const { client, backend } = await connect({ roleId: "builtin.reader" }); + const value = structured(await call(client, "diskhound_list_folder", { path: `${ROOT}/Developer/` })); + expect(backend.folderChildren).toHaveBeenCalledWith(ROOT, `${ROOT}/Developer`); + expect(value.path).toBe(`${ROOT}/Developer`); + expect(value.folders.map((dir: { name: string }) => dir.name)).toEqual(["app", "scratch"]); + expect(value.folders[0].percent).toBe(90); + expect(value.hiddenByProtectedFolders).toEqual({ count: 1, bytes: 64 * 1024 ** 2, size: "64.0 MB" }); + expect(value.truncated).toBe(false); + }); + + it("diskhound_list_folder reports paths outside any scan as a tool error", async () => { + const { client } = await connect({ roleId: "builtin.reader" }); + const outside = await call(client, "diskhound_list_folder", { path: "/Volumes/External" }); + expect(outside.isError).toBe(true); + expect(text(outside)).toContain("diskhound_start_scan"); + + const empty = await call(client, "diskhound_list_folder", { path: `${ROOT}/Nothing/Here` }); + expect(empty.isError).toBe(true); + expect(text(empty)).toContain("nothing recorded"); + }); + + it("diskhound_search_files normalizes the extension and defaults the query to the separator", async () => { + const { client, backend } = await connect({ roleId: "builtin.reader" }); + const value = structured(await call(client, "diskhound_search_files", { extension: "ISO", minSizeBytes: 1024 })); + expect(backend.searchIndex).toHaveBeenCalledWith(ROOT, { query: "/", extension: ".iso", minSizeBytes: 1024, limit: 50 }); + expect(value.results.map((hit: { sizeBytes: number }) => hit.sizeBytes)).toEqual([5 * 1024 ** 3, 3 * 1024 ** 3]); + expect(value.matched).toBe("8.0 GB"); + }); + + it("diskhound_changes picks the baseline from `since` and summarizes the diff", async () => { + const { client, backend } = await connect({ roleId: "builtin.reader" }); + const value = structured(await call(client, "diskhound_changes", { since: "1w" })); + expect(backend.diff).toHaveBeenCalledWith("scan-1", "scan-3"); + expect(value.net).toBe("+10.0 GB"); + expect(value.folders[0]).toMatchObject({ path: `${ROOT}/Downloads`, delta: "+5.0 GB" }); + + const byDefault = structured(await call(client, "diskhound_changes")); + expect(byDefault.baselineId).toBe("scan-2"); + + const files = structured(await call(client, "diskhound_changes", { detail: "files", baselineId: "scan-2", limit: 1 })); + expect(backend.fullDiff).toHaveBeenCalledWith("scan-2", "scan-3", 1); + expect(files.changes).toHaveLength(1); + }); + + it("diskhound_changes warns when the hardlink accounting differs between scans", async () => { + const { client, backend } = await connect({ roleId: "builtin.reader" }); + const plain = await backend.diff("scan-1", "scan-3"); + backend.diff.mockResolvedValueOnce(plain && { ...plain, hardlinkAccountingChanged: true }); + const result = await call(client, "diskhound_changes", { since: "1w" }); + expect(structured(result).hardlinkAccountingChanged).toBe(true); + expect(text(result)).toContain("Part of this change is accounting"); + }); + + it("diskhound_changes warns when one scan walked the macOS Data volume twice", async () => { + const { client, backend } = await connect({ roleId: "builtin.reader" }); + const plain = await backend.diff("scan-1", "scan-3"); + backend.diff.mockResolvedValueOnce(plain && { ...plain, volumeAccountingChanged: true }); + const result = await call(client, "diskhound_changes", { since: "1w" }); + expect(structured(result).volumeAccountingChanged).toBe(true); + expect(text(result)).toContain("walked the macOS Data volume twice"); + }); + + // SDK 1.30.0's McpServer parses tools/call `arguments` as given, so + // omitting it (optional in the spec) fails here. The HTTP layer + // defaults it to {} (withDefaultArguments, covered in + // agentAccessServer.test.ts); this pins the SDK behavior so we notice + // when an upgrade makes that shim unnecessary. + it.fails("the bare SDK rejects a tools/call without `arguments`", async () => { + const { client } = await connect({ roleId: "builtin.reader" }); + const result = (await client.callTool({ name: "diskhound_status" })) as CallToolResult; + expect(result.isError).not.toBe(true); + }); + + it("diskhound_duplicates explains when no search has run", async () => { + const { client } = await connect({ roleId: "builtin.reader" }); + const result = await call(client, "diskhound_duplicates"); + expect(structured(result)).toEqual({ rootPath: ROOT, running: false, progress: null }); + expect(text(result)).toContain("diskhound_find_duplicates"); + }); +}); + +describe("authorization", () => { + let tempDir: string; + + beforeEach(() => { + tempDir = FS.mkdtempSync(Path.join(OS.tmpdir(), "diskhound-mcp-server-test-")); + }); + + afterEach(() => { + FS.rmSync(tempDir, { recursive: true, force: true }); + }); + + it("returns isError (not a protocol error) when the authorizer lacks a capability", async () => { + const { client, backend } = await connect({ roleId: "builtin.reader" }); + const result = await call(client, "diskhound_move_to_trash", { paths: [`${ROOT}/Downloads/ubuntu.iso`] }); + expect(result.isError).toBe(true); + expect(text(result)).toContain("files.trash"); + expect(result.structuredContent).toBeUndefined(); + expect(backend.confirmAndTrash).not.toHaveBeenCalled(); + }); + + it("tells the agent to ask the user to change the role in Settings (policy-file authorizer)", async () => { + const store = new McpPolicyStore(Path.join(tempDir, "mcp-policy.json")); + const { token } = store.createSession("Codex", "builtin.reader", { + clientId: "client_1", + scopes: [...MCP_AGENT_CAPABILITIES], + }); + const { client, backend } = await connect({ authorizer: new PolicyFileAuthorizer(store, token) }); + + const status = structured(await call(client, "diskhound_status")); + expect(status.session).toMatchObject({ name: "Codex", role: "Disk Explorer" }); + + const trash = await call(client, "diskhound_move_to_trash", { paths: [`${ROOT}/Downloads/ubuntu.iso`] }); + expect(trash.isError).toBe(true); + expect(text(trash)).toContain("files.trash"); + expect(text(trash)).toContain("Settings"); + expect(backend.confirmAndTrash).not.toHaveBeenCalled(); + }); + + it("applies a revoke in Settings to the very next tool call", async () => { + const store = new McpPolicyStore(Path.join(tempDir, "mcp-policy.json")); + const { session, token } = store.createSession("Codex", "builtin.guide", { + clientId: "client_1", + scopes: [...MCP_AGENT_CAPABILITIES], + }); + const { client } = await connect({ authorizer: new PolicyFileAuthorizer(store, token) }); + expect((await call(client, "diskhound_status")).isError).not.toBe(true); + store.revokeSession(session.id); + const after = await call(client, "diskhound_status"); + expect(after.isError).toBe(true); + expect(text(after)).toContain("revoked"); + }); + + it("requires app.navigate only when showInApp is set", async () => { + const { client, backend } = await connect({ roleId: "builtin.reader" }); + expect((await call(client, "diskhound_list_folder", { path: ROOT })).isError).not.toBe(true); + const shown = await call(client, "diskhound_list_folder", { path: ROOT, showInApp: true }); + expect(shown.isError).toBe(true); + expect(text(shown)).toContain("app.navigate"); + expect(backend.navigate).not.toHaveBeenCalled(); + }); + + it("start_scan needs app.navigate by default because showInApp defaults to true", async () => { + const { client, backend } = await connect({ roleId: "builtin.reader" }); + const result = await call(client, "diskhound_start_scan", { rootPath: ROOT }); + expect(result.isError).toBe(true); + expect(text(result)).toContain("scan.run"); + expect(backend.startScan).not.toHaveBeenCalled(); + }); +}); + +describe("showInApp", () => { + it("navigates the Folders tab to the listed folder when showInApp is true", async () => { + const { client, backend } = await connect({ roleId: "builtin.guide" }); + await call(client, "diskhound_list_folder", { path: `${ROOT}/Downloads`, showInApp: true }); + expect(backend.navigate).toHaveBeenCalledTimes(1); + expect(backend.navigate).toHaveBeenCalledWith( + expect.objectContaining({ view: "folders", rootPath: ROOT, folderPath: `${ROOT}/Downloads` }), + ); + }); + + it("does not navigate when showInApp is false or omitted", async () => { + const { client, backend } = await connect({ roleId: "builtin.guide" }); + await call(client, "diskhound_list_folder", { path: `${ROOT}/Downloads`, showInApp: false }); + await call(client, "diskhound_list_folder", { path: `${ROOT}/Downloads` }); + await call(client, "diskhound_scan_summary", {}); + expect(backend.navigate).not.toHaveBeenCalled(); + }); + + it("start_scan switches the window to the root unless told not to", async () => { + const { client, backend } = await connect({ roleId: "builtin.guide" }); + const started = structured(await call(client, "diskhound_start_scan", { rootPath: "/Volumes/Data/" })); + expect(started).toMatchObject({ rootPath: "/Volumes/Data", started: true, status: "running" }); + expect(backend.startScan).toHaveBeenCalledWith("/Volumes/Data"); + expect(backend.navigate).toHaveBeenCalledWith({ view: "overview", rootPath: "/Volumes/Data" }); + + backend.navigate.mockClear(); + await call(client, "diskhound_start_scan", { rootPath: "/Volumes/Data", showInApp: false }); + expect(backend.navigate).not.toHaveBeenCalled(); + }); + + it("rejects relative paths instead of resolving them against DiskHound's working directory", async () => { + const { client, backend } = await connect({ roleId: "builtin.guide" }); + const result = await call(client, "diskhound_start_scan", { rootPath: "Downloads" }); + expect(result.isError).toBe(true); + expect(text(result)).toContain("absolute path"); + expect(backend.startScan).not.toHaveBeenCalled(); + }); + + it("treats a bare Windows drive letter (as diskhound_status reports it) as the drive root", async () => { + const backend = createFakeBackend(); + backend.platform = "win32"; + const { client } = await connect({ roleId: "builtin.guide", backend }); + await call(client, "diskhound_start_scan", { rootPath: "C:", showInApp: false }); + expect(backend.startScan).toHaveBeenCalledWith("C:\\"); + }); + + it("start_scan refuses to restart a running scan unless restart is true", async () => { + const backend = createFakeBackend(); + backend.activeScans.mockResolvedValue([{ ...(await backend.startScan(ROOT)), filesVisited: 42 }]); + backend.startScan.mockClear(); + const { client } = await connect({ roleId: "builtin.guide", backend }); + const value = structured(await call(client, "diskhound_start_scan", { rootPath: ROOT })); + expect(value).toMatchObject({ started: false, alreadyRunning: true, filesVisited: 42 }); + expect(backend.startScan).not.toHaveBeenCalled(); + + await call(client, "diskhound_start_scan", { rootPath: ROOT, restart: true }); + expect(backend.startScan).toHaveBeenCalledWith(ROOT); + }); + + it("diskhound_show resolves the scan root for a folder and passes focus through", async () => { + const { client, backend } = await connect({ roleId: "builtin.guide" }); + const value = structured(await call(client, "diskhound_show", { view: "folders", folderPath: `${ROOT}/Developer/app` })); + expect(value).toEqual({ view: "folders", rootPath: ROOT, folderPath: `${ROOT}/Developer/app` }); + expect(backend.navigate).toHaveBeenCalledWith({ + view: "folders", + rootPath: ROOT, + folderPath: `${ROOT}/Developer/app`, + focus: false, + }); + }); + + it("diskhound_reveal_path surfaces a backend failure as a tool error", async () => { + const { client, backend } = await connect({ roleId: "builtin.guide" }); + backend.revealPath.mockResolvedValueOnce({ ok: false, message: "Nothing exists at /nope." }); + const result = await call(client, "diskhound_reveal_path", { path: "/nope" }); + expect(result.isError).toBe(true); + expect(text(result)).toBe("Nothing exists at /nope."); + }); +}); + +describe("diskhound_move_to_trash", () => { + it("passes the Session name, de-duplicated absolute paths, and reason to confirmAndTrash", async () => { + const { client, backend } = await connect({ roleId: "builtin.operator" }); + const result = await call(client, "diskhound_move_to_trash", { + paths: [`${ROOT}/Downloads/ubuntu.iso`, `${ROOT}/Downloads/../Downloads/ubuntu.iso`, `${ROOT}/Downloads/installer.dmg`], + reason: "Old installers", + }); + expect(backend.confirmAndTrash).toHaveBeenCalledWith( + expect.objectContaining({ + sessionName: "Test Agent", + paths: [`${ROOT}/Downloads/ubuntu.iso`, `${ROOT}/Downloads/installer.dmg`], + reason: "Old installers", + }), + ); + // The host re-checks the Session right before its dialog. + const [request] = backend.confirmAndTrash.mock.calls[0]!; + await expect(request.recheck?.()).resolves.toBeUndefined(); + const value = structured(result); + expect(value).toMatchObject({ confirmed: true, movedCount: 2, movedBytes: 200 * 1024 ** 2, moved: "200 MB" }); + expect(text(result)).toContain("Moved 2 of 2 items (200 MB)"); + expect(text(result)).toContain("Trash"); + }); + + it("reports sizes in the units the user picked, so they match the window", async () => { + const backend = createFakeBackend(); + Object.assign(backend, { sizeUnitBase: () => 1000 as const }); + const { client } = await connect({ roleId: "builtin.operator", backend }); + const result = await call(client, "diskhound_move_to_trash", { paths: [`${ROOT}/Downloads/ubuntu.iso`, `${ROOT}/Downloads/installer.dmg`] }); + // 200 MiB is 210 MB in decimal units (macOS Finder's default). + expect(text(result)).toContain("Moved 2 of 2 items (210 MB)"); + }); + + it("reports a declined confirmation without claiming anything moved", async () => { + const { client, backend, activity } = await connect({ roleId: "builtin.operator" }); + backend.confirmAndTrash.mockResolvedValueOnce({ confirmed: false, results: [] }); + const result = await call(client, "diskhound_move_to_trash", { paths: [`${ROOT}/Movies/trip.mov`] }); + expect(result.isError).not.toBe(true); + expect(structured(result)).toEqual({ confirmed: false, results: [] }); + expect(text(result)).toBe("The user declined. Nothing was moved."); + expect(activity.entries.at(-1)).toMatchObject({ tool: "diskhound_move_to_trash", ok: true, summary: expect.stringContaining("declined") }); + }); + + it("lists items the backend could not move", async () => { + const { client, backend } = await connect({ roleId: "builtin.operator" }); + backend.confirmAndTrash.mockResolvedValueOnce({ + confirmed: true, + results: [ + { path: "/a", ok: true, message: "Moved.", sizeBytes: 1024 }, + { path: "/b", ok: false, message: "Protected folder", sizeBytes: null }, + ], + }); + const result = await call(client, "diskhound_move_to_trash", { paths: ["/a", "/b"] }); + expect(structured(result)).toMatchObject({ movedCount: 1, movedBytes: 1024 }); + expect(text(result)).toContain("Not moved: /b (Protected folder)"); + }); + + it("never reports an unknown size as 0 B", async () => { + const { client, backend } = await connect({ roleId: "builtin.operator" }); + backend.confirmAndTrash.mockResolvedValueOnce({ + confirmed: true, + results: [{ path: "/outside", ok: true, message: "Moved.", sizeBytes: null }], + }); + const unknown = await call(client, "diskhound_move_to_trash", { paths: ["/outside"] }); + expect(structured(unknown)).toMatchObject({ movedCount: 1, moved: "size unknown" }); + expect(text(unknown)).toContain("(size unknown)"); + backend.confirmAndTrash.mockResolvedValueOnce({ + confirmed: true, + results: [ + { path: "/a", ok: true, message: "Moved.", sizeBytes: 1024 }, + { path: "/outside", ok: true, message: "Moved.", sizeBytes: null }, + ], + }); + const partly = await call(client, "diskhound_move_to_trash", { paths: ["/a", "/outside"] }); + expect(structured(partly)).toMatchObject({ movedCount: 2, moved: "at least 1.0 KB" }); + }); + + it("rejects an empty path list at the schema", async () => { + const { client, backend } = await connect({ roleId: "builtin.operator" }); + const result = await call(client, "diskhound_move_to_trash", { paths: [] }); + expect(result.isError).toBe(true); + expect(backend.confirmAndTrash).not.toHaveBeenCalled(); + }); +}); + +describe("diskhound_delete_permanently", () => { + it("passes the Session, de-duplicated paths and reason to confirmAndDelete, and rechecks files.delete", async () => { + const { client, backend } = await connect({ roleId: "builtin.admin" }); + const result = await call(client, "diskhound_delete_permanently", { + paths: [`${ROOT}/Downloads/ubuntu.iso`, `${ROOT}/Downloads/./ubuntu.iso`], + reason: "Too big for the Trash", + }); + expect(backend.confirmAndDelete).toHaveBeenCalledWith( + expect.objectContaining({ sessionName: "Test Agent", roleName: "Cleanup Admin", paths: [`${ROOT}/Downloads/ubuntu.iso`], reason: "Too big for the Trash" }), + ); + const [request] = backend.confirmAndDelete.mock.calls[0]!; + await expect(request.recheck?.()).resolves.toBeUndefined(); + expect(backend.confirmAndTrash).not.toHaveBeenCalled(); + expect(structured(result)).toMatchObject({ confirmed: true, deletedCount: 1 }); + expect(text(result)).toMatch(/^Deleted 1 of 1 item \(.+\) permanently\./); + }); + + it("reports a declined confirmation without claiming anything was deleted", async () => { + const { client, backend, activity } = await connect({ roleId: "builtin.admin" }); + backend.confirmAndDelete.mockResolvedValueOnce({ confirmed: false, results: [] }); + const result = await call(client, "diskhound_delete_permanently", { paths: [`${ROOT}/Movies/trip.mov`] }); + expect(text(result)).toBe("The user declined. Nothing was deleted."); + expect(activity.entries.at(-1)).toMatchObject({ tool: "diskhound_delete_permanently", ok: true, summary: expect.stringContaining("declined") }); + }); + + it("refuses an operator session before any dialog, and logs it", async () => { + const security = new RecordingSecurity(); + const { client, backend } = await connect({ roleId: "builtin.operator", security }); + const result = await call(client, "diskhound_delete_permanently", { paths: ["/a"] }); + expect(result.isError).toBe(true); + expect(backend.confirmAndDelete).not.toHaveBeenCalled(); + expect(security.events).toEqual([ + expect.objectContaining({ + kind: "tool_not_allowed", + tool: "diskhound_delete_permanently", + roleName: "Cleanup Operator", + detail: "Tried to delete items permanently; Cleanup Operator doesn't allow it.", + }), + ]); + }); +}); + +describe("role filtering", () => { + const listed = async (roleId: string) => { + const role = BUILT_IN_MCP_ROLES.find((candidate) => candidate.id === roleId)!; + const { client } = await connect({ roleId, granted: role.permissions }); + const { tools } = await client.listTools(); + return { client, role, names: tools.map((tool) => tool.name), tools }; + }; + + it.each(BUILT_IN_MCP_ROLES.map((role) => role.id))("lists only the tools %s grants", async (roleId) => { + const { role, names } = await listed(roleId); + const expected = Object.entries(TOOL_CAPABILITIES) + .filter(([, needs]) => needs.every((capability) => role.permissions.includes(capability))) + .map(([name]) => name); + expect(names.sort()).toEqual(expected.sort()); + }); + + it("hides both removal tools from the default Cleanup Guide and says so in its instructions", async () => { + const { client, names } = await listed("builtin.guide"); + expect(names).not.toContain("diskhound_move_to_trash"); + expect(names).not.toContain("diskhound_delete_permanently"); + expect(client.getInstructions()).toContain("This session can't move or delete files."); + }); + + it("shows the Trash but not permanent delete to Cleanup Operator", async () => { + const { client, names } = await listed("builtin.operator"); + expect(names).toContain("diskhound_move_to_trash"); + expect(names).not.toContain("diskhound_delete_permanently"); + expect(client.getInstructions()).toContain("this session can't delete permanently"); + }); + + it("drops showInApp from a Disk Explorer's tools, since it can't steer the window", async () => { + const { tools } = await listed("builtin.reader"); + const list = tools.find((tool) => tool.name === "diskhound_list_folder")!; + expect(Object.keys(list.inputSchema.properties ?? {})).not.toContain("showInApp"); + }); + + it("logs a call that its role lost after the tool list was built", async () => { + // The server was built for an Operator; the policy now says Reader. + const security = new RecordingSecurity(); + const { client, backend, activity } = await connect({ + granted: roleAuthorization("builtin.operator").capabilities, + authorizer: new FixedMcpAuthorizer(roleAuthorization("builtin.reader")), + security, + }); + const result = await call(client, "diskhound_move_to_trash", { paths: ["/a"] }); + expect(result.isError).toBe(true); + expect(backend.confirmAndTrash).not.toHaveBeenCalled(); + expect(security.events).toEqual([ + expect.objectContaining({ kind: "tool_not_allowed", tool: "diskhound_move_to_trash", roleName: "Disk Explorer" }), + ]); + expect(activity.entries.at(-1)).toMatchObject({ tool: "diskhound_move_to_trash", ok: false }); + }); + + it("maps every registered tool to the capabilities it needs", async () => { + const { client } = await connect(); + const { tools } = await client.listTools(); + expect(tools.map((tool) => tool.name).sort()).toEqual(Object.keys(TOOL_CAPABILITIES).sort()); + }); +}); + +describe("activity feed", () => { + it("records one entry per successful or failed tool call", async () => { + const { client, activity } = await connect({ roleId: "builtin.guide" }); + await call(client, "diskhound_status"); + await call(client, "diskhound_list_folder", { path: `${ROOT}/Downloads`, showInApp: true }); + await call(client, "diskhound_list_folder", { path: "/Volumes/External" }); + expect(activity.entries).toEqual([ + { sessionId: "session_builtin.guide", sessionName: "Test Agent", tool: "diskhound_status", summary: "Checked drives and scan status", ok: true }, + { sessionId: "session_builtin.guide", sessionName: "Test Agent", tool: "diskhound_list_folder", summary: `Listed ${ROOT}/Downloads (5.0 GB)`, ok: true }, + { + sessionId: "session_builtin.guide", + sessionName: "Test Agent", + tool: "diskhound_list_folder", + summary: expect.stringContaining("no scan covering /Volumes/External"), + ok: false, + }, + ]); + }); + + it("uses the first line of the summary when a tool gives no activity text", async () => { + const { client, activity } = await connect({ roleId: "builtin.guide" }); + await call(client, "diskhound_cancel_scan", { rootPath: ROOT }); + expect(activity.entries).toEqual([ + expect.objectContaining({ tool: "diskhound_cancel_scan", ok: true, summary: `Cancelled the scan of ${ROOT} (if one was running).` }), + ]); + }); + + it("feeds AgentActivityLog newest-first with ids and timestamps", async () => { + const seen: string[] = []; + let clock = 1_000; + const log = new AgentActivityLog((entry) => seen.push(entry.id), 2, () => clock++); + log.record({ sessionId: "s", sessionName: "S", tool: "a", summary: "a", ok: true }); + log.record({ sessionId: "s", sessionName: "S", tool: "b", summary: "b", ok: false }); + log.record({ sessionId: "s", sessionName: "S", tool: "c", summary: "c", ok: true }); + expect(log.list().map((entry) => [entry.id, entry.tool, entry.at])).toEqual([ + ["agent-3", "c", 1002], + ["agent-2", "b", 1001], + ]); + expect(seen).toEqual(["agent-1", "agent-2", "agent-3"]); + + const throwing = new AgentActivityLog(() => { + throw new Error("window closed"); + }); + expect(() => throwing.record({ sessionId: "s", sessionName: "S", tool: "a", summary: "a", ok: true })).not.toThrow(); + }); + + it("records calls rejected for a missing capability", async () => { + const { client, activity } = await connect({ roleId: "builtin.reader" }); + const result = await call(client, "diskhound_move_to_trash", { paths: ["/a"] }); + expect(result.isError).toBe(true); + expect(activity.entries).toEqual([ + expect.objectContaining({ + sessionName: "Test Agent", + tool: "diskhound_move_to_trash", + ok: false, + summary: expect.stringContaining("files.trash"), + }), + ]); + }); + + it("does not record calls from a revoked Session (it no longer has an identity to show)", async () => { + const tempDir = FS.mkdtempSync(Path.join(OS.tmpdir(), "diskhound-mcp-activity-test-")); + try { + const store = new McpPolicyStore(Path.join(tempDir, "mcp-policy.json")); + const { session, token } = store.createSession("Codex", "builtin.reader", { clientId: "client_1", scopes: [...MCP_AGENT_CAPABILITIES] }); + const { client, activity } = await connect({ authorizer: new PolicyFileAuthorizer(store, token) }); + store.revokeSession(session.id); + expect((await call(client, "diskhound_status")).isError).toBe(true); + expect(activity.entries).toEqual([]); + } finally { + FS.rmSync(tempDir, { recursive: true, force: true }); + } + }); +}); + +describe("skills extension (SEP-2640)", () => { + it("skills/list returns every skill with frontmatter and a digest manifest", async () => { + const { client } = await connect(); + const result = await client.request({ method: "skills/list", params: {} }, Loose); + const skills = (result as { skills: { uri: string; frontmatter: Record; resources: { uri: string; digest: string; size: number }[] }[] }).skills; + expect((result as { resultType?: string }).resultType).toBe("complete"); + expect(skills.map((skill) => skill.uri)).toEqual([FREE_UP_SPACE_SKILL, INVESTIGATE_GROWTH_SKILL]); + expect(skills[0]!.frontmatter.name).toBe("diskhound-free-up-space"); + expect(skills[0]!.resources).toHaveLength(5); + for (const resource of skills.flatMap((skill) => skill.resources)) { + expect(resource.uri).toMatch(/^skill:\/\/diskhound-[a-z-]+\//); + expect(resource.digest).toMatch(/^sha256:[0-9a-f]{64}$/); + expect(resource.size).toBeGreaterThan(0); + } + }); + + it("skills/list works with no params at all", async () => { + const { client } = await connect(); + const result = (await client.request({ method: "skills/list" }, Loose)) as { skills: unknown[] }; + expect(result.skills).toHaveLength(2); + }); + + it("skills/get returns one skill and rejects unknown URIs with InvalidParams", async () => { + const { client } = await connect(); + const result = (await client.request({ method: "skills/get", params: { uri: INVESTIGATE_GROWTH_SKILL } }, Loose)) as { + skill: { uri: string; frontmatter: Record }; + }; + expect(result.skill.uri).toBe(INVESTIGATE_GROWTH_SKILL); + expect(result.skill.frontmatter.name).toBe("diskhound-investigate-growth"); + + const unknown = await mcpError(client.request({ method: "skills/get", params: { uri: "skill://nope/SKILL.md" } }, Loose)); + expect(unknown.code).toBe(ErrorCode.InvalidParams); + + // The skill's root directory URI is not a skill URI. + const root = await mcpError(client.request({ method: "skills/get", params: { uri: "skill://diskhound-free-up-space" } }, Loose)); + expect(root.code).toBe(ErrorCode.InvalidParams); + }); + + it("resources/directory/read lists a skill's children and its subdirectories", async () => { + const { client } = await connect(); + const top = (await client.request( + { method: "resources/directory/read", params: { uri: "skill://diskhound-free-up-space" } }, + Loose, + )) as { resources: { uri: string; name: string; mimeType: string }[] }; + expect(top.resources.map((child) => [child.name, child.mimeType]).sort()).toEqual([ + ["SKILL.md", "text/markdown"], + ["references", "inode/directory"], + ]); + + const references = (await client.request( + { method: "resources/directory/read", params: { uri: "skill://diskhound-free-up-space/references" } }, + Loose, + )) as { resources: { uri: string }[] }; + expect(references.resources.map((child) => child.uri).sort()).toEqual([ + "skill://diskhound-free-up-space/references/developer-caches.md", + "skill://diskhound-free-up-space/references/linux.md", + "skill://diskhound-free-up-space/references/macos.md", + "skill://diskhound-free-up-space/references/windows.md", + ]); + + for (const uri of ["skill://nope", "skill://diskhound-free-up-space/SKILL.md", "skill://diskhound-free-up-space/scripts"]) { + const error = await mcpError(client.request({ method: "resources/directory/read", params: { uri } }, Loose)); + expect(error.code, uri).toBe(ErrorCode.InvalidParams); + } + }); + + it("serves every skill file through resources/list and resources/read", async () => { + const { client } = await connect(); + const { resources } = await client.listResources(); + const expected = SKILLS.skills.flatMap((skill) => skill.files.map((file) => file.uri)); + expect(resources.map((resource) => resource.uri).sort()).toEqual([...expected].sort()); + const skillMd = resources.find((resource) => resource.uri === FREE_UP_SPACE_SKILL); + expect(skillMd).toMatchObject({ name: "diskhound-free-up-space", mimeType: "text/markdown", title: "Skill: diskhound-free-up-space" }); + + const read = await client.readResource({ uri: FREE_UP_SPACE_SKILL }); + const onDisk = FS.readFileSync(Path.join(SKILLS_DIR, "diskhound-free-up-space", "SKILL.md"), "utf8"); + expect(read.contents).toEqual([{ uri: FREE_UP_SPACE_SKILL, mimeType: "text/markdown", text: onDisk }]); + + const reference = await client.readResource({ uri: "skill://diskhound-free-up-space/references/macos.md" }); + expect((reference.contents[0] as { text: string }).text).toContain("## APFS clones"); + }); + + it("rejects unknown skill resource URIs with InvalidParams", async () => { + const { client } = await connect(); + const error = await mcpError(client.readResource({ uri: "skill://diskhound-free-up-space/references/solaris.md" })); + expect(error.code).toBe(ErrorCode.InvalidParams); + }); +}); + +describe("diskhound_read_skill", () => { + // Claude Desktop hands an extension's tools to its chats and Code + // sessions, but not its resources. + it("lists the skills and their files when called without a uri", async () => { + const { client } = await connect({ roleId: "builtin.reader" }); + const value = structured(await call(client, "diskhound_read_skill")); + expect(value.skills.map((skill: { uri: string }) => skill.uri)).toEqual([FREE_UP_SPACE_SKILL, INVESTIGATE_GROWTH_SKILL]); + expect(value.skills[0].files).toContain("skill://diskhound-free-up-space/references/macos.md"); + }); + + it("returns a skill file's text first, the same text resources/read serves", async () => { + const { client, activity } = await connect(); + const result = await call(client, "diskhound_read_skill", { uri: FREE_UP_SPACE_SKILL }); + const value = structured(result); + const read = await client.readResource({ uri: FREE_UP_SPACE_SKILL }); + expect(text(result)).toBe((read.contents[0] as { text: string }).text); + expect(value).toMatchObject({ uri: FREE_UP_SPACE_SKILL, mimeType: "text/markdown" }); + expect(value.otherFiles).toContain("skill://diskhound-free-up-space/references/developer-caches.md"); + expect(value).not.toHaveProperty("text"); + expect(activity.entries.at(-1)).toMatchObject({ tool: "diskhound_read_skill", summary: "Read the diskhound-free-up-space skill", ok: true }); + + const reference = await call(client, "diskhound_read_skill", { uri: "skill://diskhound-free-up-space/references/macos.md/" }); + expect(text(reference)).toContain("## APFS clones"); + }); + + it("lists a skill folder's children", async () => { + const { client } = await connect(); + const result = await call(client, "diskhound_read_skill", { uri: "skill://diskhound-free-up-space/references" }); + expect(text(result).split("\n")).toContain("skill://diskhound-free-up-space/references/linux.md"); + }); + + it("reports an unknown uri as a tool error that says how to list them", async () => { + const { client } = await connect(); + const result = await call(client, "diskhound_read_skill", { uri: "skill://diskhound-free-up-space/references/solaris.md" }); + expect(result.isError).toBe(true); + expect(text(result)).toContain("Call diskhound_read_skill without a uri"); + }); + + it("says so when the build has no skills", async () => { + const { client } = await connect({ skills: { skills: [] } }); + expect(text(await call(client, "diskhound_read_skill"))).toBe("This DiskHound build has no skills."); + expect(text(await call(client, "diskhound_status"))).not.toContain("diskhound_read_skill"); + }); +}); + +describe("prompts", () => { + it("lists both prompt fallbacks with their optional arguments", async () => { + const { client } = await connect(); + const { prompts } = await client.listPrompts(); + expect(prompts.map((prompt) => prompt.name).sort()).toEqual(["free-up-space", "investigate-growth"]); + const freeUp = prompts.find((prompt) => prompt.name === "free-up-space"); + expect(freeUp?.arguments?.map((argument) => [argument.name, argument.required ?? false])).toEqual([ + ["goal", false], + ["path", false], + ]); + }); + + it("free-up-space embeds SKILL.md as a resource and then asks", async () => { + const { client } = await connect(); + const result = await client.getPrompt({ name: "free-up-space", arguments: { goal: "free 50 GB", path: "/" } }); + expect(result.messages).toHaveLength(2); + const [skill, ask] = result.messages; + expect(skill!.content).toEqual({ + type: "resource", + resource: { uri: FREE_UP_SPACE_SKILL, mimeType: "text/markdown", text: SKILLS.skills[0]!.files.find((file) => file.relativePath === "SKILL.md")!.text }, + }); + expect(ask!.content.type).toBe("text"); + expect((ask!.content as { text: string }).text).toContain("on / โ€” goal: free 50 GB"); + }); + + it("investigate-growth embeds its SKILL.md and works without arguments", async () => { + const { client } = await connect(); + const result = await client.getPrompt({ name: "investigate-growth", arguments: {} }); + const resource = result.messages[0]!.content as { type: string; resource: { uri: string; text: string } }; + expect(resource.type).toBe("resource"); + expect(resource.resource.uri).toBe(INVESTIGATE_GROWTH_SKILL); + expect(resource.resource.text).toContain("name: diskhound-investigate-growth"); + }); + + // Same SDK behavior as tools/call above; the HTTP layer defaults it. + it.fails("the bare SDK rejects a prompts/get without `arguments`", async () => { + const { client } = await connect(); + const result = await client.getPrompt({ name: "free-up-space" }); + expect(result.messages).toHaveLength(2); + }); + + it("omits the prompts when their skills are missing", async () => { + const { client } = await connect({ skills: { skills: [SKILLS.skills[1]!] } }); + const { prompts } = await client.listPrompts(); + expect(prompts.map((prompt) => prompt.name)).toEqual(["investigate-growth"]); + }); +}); + +describe("empty skill catalog", () => { + // electronHost.ts falls back to `{ skills: [] }` when the skills + // directory fails to load. The server then advertises only tools, so + // clients never call list methods that have nothing behind them. + it("advertises tools only, without prompts, resources, or the skills extension", async () => { + const { client } = await connect({ skills: { skills: [] } }); + const capabilities = client.getServerCapabilities(); + expect(capabilities?.tools).toBeDefined(); + expect(capabilities?.prompts).toBeUndefined(); + expect(capabilities?.resources).toBeUndefined(); + expect(capabilities?.extensions?.[SKILLS_EXTENSION_ID]).toBeUndefined(); + }); + + it("still lists every tool", async () => { + const { client } = await connect({ skills: { skills: [] } }); + expect((await client.listTools()).tools.map((tool) => tool.name)).toContain("diskhound_status"); + }); +}); + +describe("scan completeness and shared storage", () => { + it("reports the backend's uncapped visible folder count", async () => { + const { client, backend } = await connect(); + const children = await backend.folderChildren(ROOT, ROOT); + backend.folderChildren.mockResolvedValue({ ...children, visibleDirCount: 800, + dirs: Array.from({ length: 200 }, (_, i) => ({ path: `${ROOT}/dir-${i}`, size: i, fileCount: 1 })) }); + const result = await call(client, "diskhound_list_folder", { path: ROOT, limit: 200 }); + expect(structured(result)).toMatchObject({ folderCount: 800, truncated: true }); + expect(structured(result).folders).toHaveLength(200); + expect(text(result)).toContain("800 folders"); + }); + + it("ranks groups by reclaimable bytes and preserves per-file sharing facts", async () => { + const { client, backend } = await connect(); + const files = (sharing?: "clone" | "hardlink", reclaimableBytes?: number) => [0, 1].map((i) => ({ + path: `${ROOT}/${sharing ?? "ordinary"}-${i}`, name: `copy-${i}`, parentPath: ROOT, + modifiedAt: NOW, sharing, reclaimableBytes, + })); + backend.duplicates.mockReturnValue({ running: false, progress: null, analysis: { + rootPath: ROOT, analyzedAt: NOW, totalGroups: 4, totalDuplicateFiles: 8, totalWastedBytes: 120, filesWalked: 8, filesHashed: 8, elapsedMs: 10, + groups: [ + { hash: "clone", size: 1000, reclaimableBytes: 0, files: files("clone", 0) }, + { hash: "hardlink", size: 2000, reclaimableBytes: 0, files: files("hardlink", 0) }, + { hash: "private", size: 1000, reclaimableBytes: 20, files: files("clone", 20) }, + { hash: "legacy", size: 100, files: files() }, + ], + } }); + const result = structured(await call(client, "diskhound_duplicates")); + expect(result.reclaimableBytes).toBe(120); + expect(result.groups.map((group: { reclaimableBytes: number }) => group.reclaimableBytes)).toEqual([100, 20, 0, 0]); + expect(result.groups[0].files[0]).toMatchObject({ reclaimableBytes: 100, sharing: null }); + expect(result.groups[1].files[0]).toMatchObject({ reclaimableBytes: 20, sharing: "clone" }); + expect(result.groups[2].files[0]).toMatchObject({ reclaimableBytes: 0, sharing: "clone" }); + expect(result.groups[3].files[0]).toMatchObject({ reclaimableBytes: 0, sharing: "hardlink" }); + }); + + it("diskhound_dev_artifacts says what each tree frees alone and bounds the listed set together", async () => { + const G = 1024 ** 3; + const { client, backend } = await connect(); + const report = (await backend.devArtifacts(ROOT))!; + const tree = (path: string, kind: "node-modules" | "rust-target" | "package-cache", size: number) => ({ + path, kind, projectPath: null, projectName: Path.basename(path), size, fileCount: 1, previousSize: null, deltaBytes: null, + }); + backend.devArtifacts.mockResolvedValue({ + ...report, + artifacts: [ + { + ...tree(`${ROOT}/Developer/app/node_modules`, "node-modules", 2 * G), + // 0.5 GB ordinary + 0.1 GB rewritten clone + 0.2 GB of groups it owns. + clone: { + cloneSize: 1.5 * G, clonePrivateSize: 0.1 * G, cloneInternalSize: 0.2 * G, + cloneSharedSize: 1.2 * G, cloneSharedBlocks: 0.6 * G, + sharedRoots: 1, sharedWith: [`${ROOT}/Library/pnpm/store`], + }, + }, + { + ...tree(`${ROOT}/Developer/app/target`, "rust-target", 6 * G), + clone: { cloneSize: 0, clonePrivateSize: 0, cloneInternalSize: 0, cloneSharedSize: 0, cloneSharedBlocks: 0, sharedRoots: 0, sharedWith: [] }, + }, + // No clone data: counted at its size, with the path's hint. + tree(`${ROOT}/Library/pnpm/store`, "package-cache", 1 * G), + ], + }); + const result = await call(client, "diskhound_dev_artifacts", {}); + const value = structured(result); + const byPath = new Map(value.artifacts.map((artifact: { path: string }) => [artifact.path, artifact])); + expect(byPath.get(`${ROOT}/Developer/app/node_modules`)).toMatchObject({ + sizeBytes: 2 * G, freesAloneBytes: 0.8 * G, sharedBytes: 1.2 * G, sharedWith: [`${ROOT}/Library/pnpm/store`], + }); + expect(byPath.get(`${ROOT}/Developer/app/target`)).toMatchObject({ freesAloneBytes: 6 * G, sharedBytes: 0 }); + expect(byPath.get(`${ROOT}/Library/pnpm/store`)).not.toHaveProperty("freesAloneBytes"); + expect(byPath.get(`${ROOT}/Library/pnpm/store`)).toHaveProperty("sharingHint", expect.stringContaining("pnpm store")); + expect(value.listed).toEqual({ + count: 3, + sizeBytes: 9 * G, + size: "9.0 GB", + freesTogether: { atLeastBytes: 7.8 * G, atMostBytes: 8.4 * G, atLeast: "7.8 GB", atMost: "8.4 GB" }, + }); + expect(text(result)).toContain( + "Removing the 3 listed (9.0 GB) frees 7.8 GBโ€“8.4 GB, after APFS clones.\nFor the exact figure for the trees you pick, call diskhound_measure_removal with their paths.", + ); + expect(value.notes[0]).toContain("freesAlone is what removing only that tree frees"); + }); + + it("diskhound_dev_artifacts leaves out the freed-space fields when no tree was measured", async () => { + const { client } = await connect(); + const value = structured(await call(client, "diskhound_dev_artifacts", {})); + expect(value).not.toHaveProperty("listed"); + expect(value.artifacts[0]).not.toHaveProperty("freesAloneBytes"); + }); +}); + +describe("diskhound_measure_removal", () => { + const G = 1024 ** 3; + + it("passes de-duplicated absolute paths and reports the set, then each path, most freed first", async () => { + const { client, backend, activity } = await connect({ roleId: "builtin.reader" }); + const result = await call(client, "diskhound_measure_removal", { + paths: [`${ROOT}/wt/one`, `${ROOT}/wt/two`, `${ROOT}/wt/one`], + }); + const value = structured(result); + expect(backend.measureRemoval).toHaveBeenCalledWith([`${ROOT}/wt/one`, `${ROOT}/wt/two`], undefined); + expect(value.total).toMatchObject({ + sizeBytes: 9 * G, size: "9.0 GB", freesBytes: 4 * G, frees: "4.0 GB", + freesOneAtATimeBytes: 3 * G, heldElsewhereBytes: 2 * G, heldElsewhere: "2.0 GB", + }); + expect(value.paths.map((path: { path: string }) => path.path)).toEqual([`${ROOT}/wt/two`, `${ROOT}/wt/one`]); + expect(value.paths[0]).toMatchObject({ freesAloneBytes: 2 * G, freesAlone: "2.0 GB", sharedBytes: 3 * G }); + expect(value.measuredAt).toBe(new Date(NOW).toISOString()); + const summary = text(result); + expect(summary).toContain("Removing these 2 items together frees 4.0 GB of the 9.0 GB they take up (3,000 files)."); + expect(summary).toContain("2.0 GB stays in use because files outside them share it"); + expect(summary).toContain("One at a time they'd free 3.0 GB; together frees 1.0 GB more"); + expect(value.notes.join(" ")).toContain("Time Machine local snapshot"); + expect(activity.entries.at(-1)).toMatchObject({ tool: "diskhound_measure_removal", summary: "Measured what removing 2 items frees", ok: true }); + }); + + it("says when clones weren't checked and when some bytes are uncertain", async () => { + const { client, backend } = await connect(); + backend.measureRemoval.mockResolvedValue({ + ...MEASUREMENT, + cloneMetadata: false, + total: { ...MEASUREMENT.total, uncertainBytes: G }, + missing: [`${ROOT}/gone`], + }); + const result = await call(client, "diskhound_measure_removal", { paths: [`${ROOT}/wt/one`, `${ROOT}/gone`], limit: 1 }); + const value = structured(result); + expect(value.paths).toHaveLength(1); + expect(value.truncated).toBe(true); + expect(value.notes.join(" ")).toContain("clones weren't checked"); + expect(value.notes.join(" ")).toContain("uncertainBytes"); + expect(text(result)).toContain("Up to 1.0 GB more might come back"); + expect(text(result)).toContain(`Not found: ${ROOT}/gone.`); + }); + + it("refuses a whole drive and relative paths before measuring", async () => { + const { client, backend } = await connect(); + const drive = await call(client, "diskhound_measure_removal", { paths: ["/"] }); + expect(drive.isError).toBe(true); + expect(text(drive)).toContain("is a whole drive"); + const relative = await call(client, "diskhound_measure_removal", { paths: ["wt/one"] }); + expect(relative.isError).toBe(true); + expect(backend.measureRemoval).not.toHaveBeenCalled(); + }); + + it("isn't offered where the backend can't measure (Windows)", async () => { + const backend = createFakeBackend(); + const { measureRemoval: _unused, ...windows } = backend; + const { client } = await connect({ backend: { ...windows, platform: "win32" } as unknown as FakeBackend }); + expect((await client.listTools()).tools.map((tool) => tool.name)).not.toContain("diskhound_measure_removal"); + }); +}); diff --git a/src/mcp/__tests__/serverScaling.test.ts b/src/mcp/__tests__/serverScaling.test.ts new file mode 100644 index 00000000..82fe8cfd --- /dev/null +++ b/src/mcp/__tests__/serverScaling.test.ts @@ -0,0 +1,111 @@ +import { expect, it } from "vitest"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { FixedMcpAuthorizer } from "../accessPolicy"; +import { createDiskhoundMcpServer } from "../server"; +import { loadSkillCatalog } from "../skills"; +import { createFakeBackend, NOW, ROOT, SKILLS_DIR, roleAuthorization } from "./fakeBackend"; + +const skills = loadSkillCatalog(SKILLS_DIR); + +/** Count array slots and record fields throughout backend results, including nested + * lists. Set up outside measurement; count the actual MCP request, not fixture work. */ +function counter() { + let reads = 0; + const cache = new WeakMap(); + function wrap(value: T): T { + if (value === null || typeof value !== "object") return value; + const cached = cache.get(value); + if (cached) return cached as T; + const proxy = new Proxy(value, { + get(target, key, receiver) { reads++; return wrap(Reflect.get(target, key, receiver)); }, + }); + cache.set(value, proxy); + return proxy; + } + return { wrap, reset: () => { reads = 0; }, reads: () => reads }; +} + +/** Scramble sort keys so an already sorted fixture cannot hide sort work. */ +function rows(template: T, n: number): T[] { + return Array.from({ length: n }, (_, i) => ({ ...template, + ...("size" in template ? { size: (i * 31337) % n + 1 } : {}), + ...("deltaBytes" in template ? { deltaBytes: (i * 31337) % n - n / 2 } : {}), + })); +} + +const cases = [ + "diskhound_status", "diskhound_scan_summary", "diskhound_list_folder", "diskhound_search_files", + "diskhound_cleanup_suggestions", "diskhound_dev_artifacts", "diskhound_scan_history", + "diskhound_changes", "diskhound_changes_files", "diskhound_duplicates", "diskhound_measure_removal", +] as const; + +async function measure(name: typeof cases[number], factor: number) { + const n = 128 * factor; + // Limits grow eightfold along with files/folders, rather than masking N*limit. + const limit = 8 * factor; + const c = counter(); + const backend = createFakeBackend(); + const snapshot = (await backend.latestSnapshot(ROOT))!; + const children = await backend.folderChildren(ROOT, ROOT); + const history = backend.scanHistory(ROOT); + const cleanup = await backend.cleanupSuggestions(ROOT); + const dev = (await backend.devArtifacts(ROOT))!; + const diff = (await backend.diff("scan-2", "scan-3"))!; + const full = (await backend.fullDiff("scan-2", "scan-3", 200))!; + const measured = await backend.measureRemoval(["/x"]); + backend.scannedRoots.mockReturnValue(c.wrap(rows(history[0]!, n))); + backend.activeScans.mockResolvedValue(c.wrap(rows(snapshot, n))); + backend.scanHistory.mockReturnValue(c.wrap(rows(history[0]!, n).map((entry, i) => ({ ...entry, + id: `scan-${i}`, scannedAt: NOW - (i + 1) * 3600_000 })))); + backend.latestSnapshot.mockResolvedValue(c.wrap({ ...snapshot, + largestFiles: rows(snapshot.largestFiles[0]!, n), hottestDirectories: rows(snapshot.hottestDirectories[0]!, n), + topExtensions: rows(snapshot.topExtensions[0]!, n) })); + backend.folderChildren.mockResolvedValue(c.wrap({ ...children, visibleDirCount: n, + dirs: rows(children.dirs[0]!, n), files: rows(children.files[0]!, n) })); + backend.searchIndex.mockResolvedValue(c.wrap({ hits: rows(children.files[0]!, n), truncated: false, filesScanned: n })); + // A fixed set of categories each holds a growing collection of paths; both + // that collection and pathsPerSuggestion grow 8x (total input grows 8x). + backend.cleanupSuggestions.mockResolvedValue(c.wrap({ ...cleanup, + suggestions: Array.from({ length: 4 }, () => ({ ...cleanup.suggestions[0]!, + paths: Array.from({ length: n }, (_, i) => `${ROOT}/file-${i}`) })) })); + backend.devArtifacts.mockResolvedValue(c.wrap({ ...dev, artifacts: rows(dev.artifacts[0]!, n), + kindTotals: rows(dev.kindTotals[0]!, n), projectCount: n })); + backend.diff.mockResolvedValue(c.wrap({ ...diff, fileDeltas: rows(diff.fileDeltas[0]!, n), + directoryDeltas: rows(diff.directoryDeltas[0]!, n), extensionDeltas: rows(diff.extensionDeltas[0]!, n) })); + backend.fullDiff.mockResolvedValue(c.wrap({ ...full, changes: rows(full.changes[0]!, n) })); + backend.measureRemoval.mockResolvedValue(c.wrap({ ...measured, + paths: Array.from({ length: n }, (_, i) => ({ ...measured.paths[0]!, path: `${ROOT}/wt/${i}`, + freesAloneBytes: (i * 31337) % n, sizeBytes: n - i })) })); + backend.duplicates.mockReturnValue(c.wrap({ running: false, progress: null, analysis: { + rootPath: ROOT, analyzedAt: NOW, filesWalked: n * 16, filesHashed: n * 16, elapsedMs: 1, + totalGroups: n, totalDuplicateFiles: n * 16, totalWastedBytes: n * 100, + groups: Array.from({ length: n }, (_, i) => ({ hash: `hash-${i}`, size: i + 1, + reclaimableBytes: (i * 31337) % n, + files: Array.from({ length: 16 }, (_, j) => ({ path: `${ROOT}/${i}/${j}`, name: `${j}`, parentPath: `${ROOT}/${i}`, + modifiedAt: NOW, reclaimableBytes: j, sharing: "clone" as const })) })), + } })); + const server = createDiskhoundMcpServer({ backend, skills, activity: { record: () => undefined }, authorizer: new FixedMcpAuthorizer(roleAuthorization("builtin.reader")), now: () => NOW }); + const client = new Client({ name: "scaling-test", version: "1" }); + const [ct, st] = InMemoryTransport.createLinkedPair(); + await Promise.all([server.connect(st), client.connect(ct)]); + try { + c.reset(); + const result = await client.callTool({ name: name === "diskhound_changes_files" ? "diskhound_changes" : name, + arguments: { path: ROOT, query: "file", limit, pathsPerSuggestion: 4 * factor, paths: [`${ROOT}/wt`], + ...(name.startsWith("diskhound_changes") ? { baselineId: "scan-1", currentId: "scan-0", detail: name.endsWith("_files") ? "files" : "summary" } : {}) } }); + expect(result.isError, JSON.stringify(result.content)).not.toBe(true); + expect(result.structuredContent).toBeDefined(); + return c.reads(); + } finally { await client.close(); await server.close(); } +} + +it.each(cases)("%s projections stay near linear as collections and limits grow 8x", async (name) => { + const small = await measure(name, 1); + const large = await measure(name, 8); + if (process.env.MCP_SCALING_REPORT) console.log(`${name}: ${small} -> ${large} (${(large / small).toFixed(2)}x)`); + expect(small).toBeGreaterThan(0); + expect(large).toBeGreaterThan(small); + expect(large).toBeLessThanOrEqual(small * 16); + expect(large).toBeLessThanOrEqual(100_000); +}); diff --git a/src/mcp/__tests__/skills.test.ts b/src/mcp/__tests__/skills.test.ts new file mode 100644 index 00000000..984e93ac --- /dev/null +++ b/src/mcp/__tests__/skills.test.ts @@ -0,0 +1,305 @@ +import { createHash } from "node:crypto"; +import * as FS from "node:fs"; +import * as OS from "node:os"; +import * as Path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { FREE_UP_SPACE_SKILL, INVESTIGATE_GROWTH_SKILL } from "../server"; +import { + loadSkillCatalog, + parseSkillFrontmatter, + readSkillDirectory, + skillListEntry, + type SkillCatalog, +} from "../skills"; +import { SERVER_SOURCE, SKILLS_DIR } from "./fakeBackend"; + +/** GitHub-style heading anchor: lowercase, drop punctuation, spaces โ†’ hyphens. */ +function headingSlug(heading: string): string { + return heading + .trim() + .toLowerCase() + .replace(/[^\p{L}\p{N}\s-]/gu, "") + .replace(/\s/g, "-"); +} + +function headingSlugs(markdown: string): Set { + return new Set( + markdown + .split(/\r?\n/) + .map((line) => /^#{1,6}\s+(.+?)\s*#*\s*$/.exec(line)?.[1]) + .filter((heading): heading is string => heading !== undefined) + .map(headingSlug), + ); +} + +/** Every `skill://โ€ฆ` mention in a text, minus any `#fragment` and trailing prose punctuation. */ +function skillUris(text: string): string[] { + return [...text.matchAll(/skill:\/\/[A-Za-z0-9._\/#-]+/g)] + .map((match) => match[0].replace(/[.,;:]+$/, "").split("#")[0]!) + .filter((uri) => !uri.includes("โ€ฆ/")); +} + +describe("bundled skill catalog", () => { + const catalog = loadSkillCatalog(SKILLS_DIR); + const fileUris = new Set(catalog.skills.flatMap((skill) => skill.files.map((file) => file.uri))); + + it("loads every skill directory, named after its directory", () => { + const directories = FS.readdirSync(SKILLS_DIR, { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")) + .map((entry) => entry.name) + .sort(); + expect(directories).toEqual(["diskhound-free-up-space", "diskhound-investigate-growth"]); + expect(catalog.skills.map((skill) => skill.name)).toEqual(directories); + for (const skill of catalog.skills) { + expect(skill.frontmatter.name).toBe(skill.name); + expect(skill.uri).toBe(`skill://${skill.name}/SKILL.md`); + expect(skill.rootUri).toBe(`skill://${skill.name}`); + expect(skill.files.some((file) => file.relativePath === "SKILL.md")).toBe(true); + } + }); + + it("gives every skill a description of at most 1024 characters", () => { + for (const skill of catalog.skills) { + const description = skill.frontmatter.description ?? ""; + expect(description.length, skill.name).toBeGreaterThan(0); + expect(description.length, skill.name).toBeLessThanOrEqual(1024); + } + }); + + it("serves exactly the files on disk, with URIs, sizes, and sha256 digests matching their bytes", () => { + const freeUp = catalog.skills.find((skill) => skill.name === "diskhound-free-up-space")!; + // Order comes from localeCompare, so compare as a sorted list. + expect(freeUp.files.map((file) => file.relativePath).sort()).toEqual([ + "SKILL.md", + "references/developer-caches.md", + "references/linux.md", + "references/macos.md", + "references/windows.md", + ]); + for (const skill of catalog.skills) { + for (const file of skill.files) { + const bytes = FS.readFileSync(Path.join(SKILLS_DIR, skill.name, ...file.relativePath.split("/"))); + expect(file.uri).toBe(`skill://${skill.name}/${file.relativePath}`); + expect(file.size).toBe(bytes.byteLength); + expect(file.digest).toMatch(/^sha256:[0-9a-f]{64}$/); + expect(file.digest).toBe(`sha256:${createHash("sha256").update(bytes).digest("hex")}`); + expect(file.text).toBe(bytes.toString("utf8")); + expect(file.mimeType).toBe("text/markdown"); + } + } + }); + + it("has no broken relative markdown links (including #anchors)", () => { + const problems: string[] = []; + for (const skill of catalog.skills) { + const byPath = new Map(skill.files.map((file) => [file.relativePath, file])); + for (const file of skill.files) { + for (const match of file.text.matchAll(/\[[^\]]*\]\(([^)\s]+)\)/g)) { + const target = match[1]!; + if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith("#")) continue; + const [targetPath, fragment] = target.split("#") as [string, string | undefined]; + const resolved = Path.posix.normalize(Path.posix.join(Path.posix.dirname(file.relativePath), targetPath)); + const linked = byPath.get(resolved); + if (!linked) { + problems.push(`${skill.name}/${file.relativePath}: ${target} โ†’ ${resolved} (missing)`); + continue; + } + if (fragment && !headingSlugs(linked.text).has(fragment)) { + problems.push(`${skill.name}/${file.relativePath}: ${target} (no heading #${fragment})`); + } + } + } + } + expect(problems).toEqual([]); + }); + + it("resolves every skill:// URI mentioned in the skills and in server.ts", () => { + const directoryUris = new Set( + catalog.skills.flatMap((skill) => [ + skill.rootUri, + ...skill.files + .map((file) => file.relativePath.split("/").slice(0, -1)) + .filter((parts) => parts.length > 0) + .map((parts) => `${skill.rootUri}/${parts.join("/")}`), + ]), + ); + const sources = [ + ...catalog.skills.flatMap((skill) => skill.files.map((file) => ({ where: file.uri, text: file.text }))), + { where: "src/mcp/server.ts", text: FS.readFileSync(SERVER_SOURCE, "utf8") }, + ]; + const mentioned = sources.flatMap(({ where, text }) => skillUris(text).map((uri) => ({ where, uri }))); + // Sanity: the scan actually finds the mentions we know exist. + expect(mentioned.some(({ uri }) => uri === "skill://diskhound-free-up-space/references/macos.md")).toBe(true); + expect(mentioned.some(({ where }) => where === "src/mcp/server.ts")).toBe(true); + + const unresolved = mentioned.filter(({ uri }) => !fileUris.has(uri) && !directoryUris.has(uri.replace(/\/+$/, ""))); + expect(unresolved).toEqual([]); + + expect(fileUris.has(FREE_UP_SPACE_SKILL)).toBe(true); + expect(fileUris.has(INVESTIGATE_GROWTH_SKILL)).toBe(true); + }); + + it("lists each skill with its verbatim frontmatter and a full resource manifest", () => { + for (const skill of catalog.skills) { + const entry = skillListEntry(skill); + expect(entry.uri).toBe(skill.uri); + expect(entry.frontmatter).toEqual(skill.frontmatter); + expect(entry.frontmatter).not.toBe(skill.frontmatter); + expect(entry.resources).toEqual(skill.files.map((file) => ({ uri: file.uri, digest: file.digest, size: file.size }))); + } + }); + + it("navigates skill directories", () => { + const byName = (a: { name: string }, b: { name: string }) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0); + expect(readSkillDirectory(catalog, "skill://diskhound-free-up-space")?.sort(byName)).toEqual([ + { + uri: "skill://diskhound-free-up-space/SKILL.md", + name: "SKILL.md", + mimeType: "text/markdown", + description: catalog.skills[0]!.frontmatter.description, + }, + { uri: "skill://diskhound-free-up-space/references", name: "references", mimeType: "inode/directory" }, + ]); + const references = readSkillDirectory(catalog, "skill://diskhound-free-up-space/references/"); + expect(references?.map((child) => child.uri).sort()).toEqual([ + "skill://diskhound-free-up-space/references/developer-caches.md", + "skill://diskhound-free-up-space/references/linux.md", + "skill://diskhound-free-up-space/references/macos.md", + "skill://diskhound-free-up-space/references/windows.md", + ]); + expect(references?.every((child) => child.description === undefined)).toBe(true); + + expect(readSkillDirectory(catalog, "skill://diskhound-free-up-space/SKILL.md")).toBeNull(); + expect(readSkillDirectory(catalog, "skill://diskhound-free-up-space/refer")).toBeNull(); + expect(readSkillDirectory(catalog, "skill://diskhound-free-up")).toBeNull(); + expect(readSkillDirectory(catalog, "skill://nope")).toBeNull(); + expect(readSkillDirectory(catalog, "file:///etc")).toBeNull(); + }); +}); + +describe("parseSkillFrontmatter", () => { + it("parses flat key: value pairs and strips matching quotes", () => { + const markdown = [ + "---", + "name: my-skill", + 'description: "Does things: carefully"', + "license: 'MIT'", + "# a comment", + "", + "compatibility: Needs: the app", + "---", + "# Body", + ].join("\n"); + expect(parseSkillFrontmatter(markdown)).toEqual({ + name: "my-skill", + description: "Does things: carefully", + license: "MIT", + compatibility: "Needs: the app", + }); + }); + + it("accepts CRLF line endings", () => { + expect(parseSkillFrontmatter("---\r\nname: crlf\r\ndescription: ok\r\n---\r\nBody")).toEqual({ + name: "crlf", + description: "ok", + }); + }); + + it("rejects anything that is not flat single-line scalars", () => { + expect(() => parseSkillFrontmatter("# No frontmatter")).toThrow(/must begin with YAML frontmatter/); + expect(() => parseSkillFrontmatter("---\nname: a\ndescription: |\n multi\n---\n")).toThrow(); + expect(() => parseSkillFrontmatter("---\nname: a\ndescription: >-\n---\n")).toThrow(/single-line scalar/); + expect(() => parseSkillFrontmatter("---\nname: a\ndescription:\n---\n")).toThrow(/single-line scalar/); + expect(() => parseSkillFrontmatter("---\nname: a\nname: b\n---\n")).toThrow(/Duplicate frontmatter field/); + expect(() => parseSkillFrontmatter("---\nname: a\n - list\n---\n")).toThrow(/Unsupported frontmatter line/); + }); +}); + +describe("loadSkillCatalog fixtures", () => { + let root: string; + + beforeEach(() => { + root = FS.mkdtempSync(Path.join(OS.tmpdir(), "diskhound-skills-test-")); + }); + + afterEach(() => { + FS.rmSync(root, { recursive: true, force: true }); + }); + + function writeSkill(directory: string, files: Record): void { + for (const [relative, text] of Object.entries(files)) { + const target = Path.join(root, directory, ...relative.split("/")); + FS.mkdirSync(Path.dirname(target), { recursive: true }); + FS.writeFileSync(target, text); + } + } + + const skillMd = (name: string, description = "A test skill.") => + `---\nname: ${name}\ndescription: ${description}\n---\n# ${name}\n`; + + it("returns an empty catalog when the skills directory does not exist", () => { + expect(loadSkillCatalog(Path.join(root, "missing"))).toEqual({ skills: [] }); + }); + + it("loads nested files and skips dotfiles and directories without SKILL.md", () => { + writeSkill("alpha", { + "SKILL.md": skillMd("alpha"), + "scripts/run.sh": "echo hi\n", + "references/b.md": "# B\n", + "references/a.md": "# A\n", + "data.json": "{}", + "blob.bin": "\u0000", + ".DS_Store": "junk", + }); + writeSkill("not-a-skill", { "README.md": "# nope\n" }); + writeSkill(".hidden", { "SKILL.md": skillMd(".hidden") }); + + const catalog: SkillCatalog = loadSkillCatalog(root); + expect(catalog.skills.map((skill) => skill.name)).toEqual(["alpha"]); + const files = catalog.skills[0]!.files; + expect(files.map((file) => [file.relativePath, file.mimeType]).sort()).toEqual([ + ["SKILL.md", "text/markdown"], + ["blob.bin", "application/octet-stream"], + ["data.json", "application/json"], + ["references/a.md", "text/markdown"], + ["references/b.md", "text/markdown"], + ["scripts/run.sh", "text/x-shellscript"], + ]); + }); + + it("rejects a frontmatter name that does not match its directory", () => { + writeSkill("alpha", { "SKILL.md": skillMd("beta") }); + expect(() => loadSkillCatalog(root)).toThrow(/must match its directory/); + }); + + it("rejects a missing description", () => { + writeSkill("alpha", { "SKILL.md": "---\nname: alpha\n---\n# alpha\n" }); + expect(() => loadSkillCatalog(root)).toThrow(/description is required/); + }); + + it("rejects a description over 1024 characters", () => { + writeSkill("alpha", { "SKILL.md": skillMd("alpha", "x".repeat(1025)) }); + expect(() => loadSkillCatalog(root)).toThrow(/at most 1024 characters/); + }); + + it("accepts a description of exactly 1024 characters", () => { + writeSkill("alpha", { "SKILL.md": skillMd("alpha", "x".repeat(1024)) }); + expect(loadSkillCatalog(root).skills[0]!.frontmatter.description).toHaveLength(1024); + }); + + it("rejects names that are not lowercase-hyphenated", () => { + writeSkill("Alpha", { "SKILL.md": skillMd("Alpha") }); + expect(() => loadSkillCatalog(root)).toThrow(/lowercase letters, digits, and single hyphens/); + }); + + it("rejects double hyphens and names over 64 characters", () => { + writeSkill("a--b", { "SKILL.md": skillMd("a--b") }); + expect(() => loadSkillCatalog(root)).toThrow(/single hyphens/); + FS.rmSync(Path.join(root, "a--b"), { recursive: true }); + + const long = "a".repeat(65); + writeSkill(long, { "SKILL.md": skillMd(long) }); + expect(() => loadSkillCatalog(root)).toThrow(/1-64/); + }); +}); diff --git a/src/mcp/__tests__/trashGuard.test.ts b/src/mcp/__tests__/trashGuard.test.ts new file mode 100644 index 00000000..7793d6b5 --- /dev/null +++ b/src/mcp/__tests__/trashGuard.test.ts @@ -0,0 +1,143 @@ +import * as FS from "node:fs"; +import * as FSP from "node:fs/promises"; +import * as OS from "node:os"; +import * as Path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { agentTrashRefusal, canonicalPath, configuredTrashGuard, outermostPaths } from "../trashGuard"; + +vi.mock("node:fs/promises", async (original) => ({ ...await original() })); + +describe("canonicalPath", () => { + let dir: string; + + beforeEach(() => { + // .native, like canonicalPath: it also expands Windows 8.3 names + // such as RUNNER~1, which the JS realpath leaves alone. + dir = FS.realpathSync.native(FS.mkdtempSync(Path.join(OS.tmpdir(), "diskhound-trash-guard-"))); + FS.mkdirSync(Path.join(dir, "Photos", "2020"), { recursive: true }); + FS.symlinkSync(Path.join(dir, "Photos"), Path.join(dir, "PhotosLink")); + }); + + afterEach(() => { + FS.rmSync(dir, { recursive: true, force: true }); + }); + + it("resolves symlinks in parent folders", async () => { + expect(await canonicalPath(Path.join(dir, "PhotosLink", "2020"))).toBe(Path.join(dir, "Photos", "2020")); + }); + + it("keeps a symlink itself, since trashing it moves only the link", async () => { + expect(await canonicalPath(Path.join(dir, "PhotosLink"))).toBe(Path.join(dir, "PhotosLink")); + }); + + it.runIf(process.platform === "darwin" || process.platform === "win32")( + "restores on-disk letter case on case-insensitive volumes", + async () => { + expect(await canonicalPath(Path.join(dir, "photos", "2020"))).toBe(Path.join(dir, "Photos", "2020")); + expect(await canonicalPath(Path.join(dir, "photoslink"))).toBe(Path.join(dir, "PhotosLink")); + }, + ); + + it("protects descendants and ancestors of exclusions with symlinked parents", async () => { + const excluded = Path.join(dir, "PhotosLink", "2020"); + const guard = await configuredTrashGuard([excluded]); + const requested = Path.join(excluded, "file.jpg"); + FS.writeFileSync(requested, "photo"); + const target = await canonicalPath(requested); + expect(guard(requested, target)).toContain("Protected folder"); + expect(guard(target, target)).toContain("Protected folder"); + expect(guard(Path.join(dir, "Photos"), Path.join(dir, "Photos"))).toContain("contains"); + expect(guard(Path.join(dir, "Photos", "2021"), Path.join(dir, "Photos", "2021"))).toBeNull(); + }); + + it("resolves a protected alias itself and preserves original-path protections", async () => { + const alias = Path.join(dir, "PhotosLink"); + const target = Path.join(dir, "Photos", "2020"); + const guard = await configuredTrashGuard([alias]); + expect(guard(target, target)).toContain("Protected folder"); + expect(guard(alias, await canonicalPath(alias))).toContain("Protected folder"); + const missing = Path.join(alias, "missing"); + const missingGuard = await configuredTrashGuard([missing]); + expect(missingGuard(missing, Path.join(dir, "Photos", "missing"))).toContain("Protected folder"); + }); + + it("throws when nothing exists at the path", async () => { + await expect(canonicalPath(Path.join(dir, "missing"))).rejects.toThrow(); + }); +}); + +describe("agentTrashRefusal", () => { + const keep = ["/Users/test", "/Users/test/Documents", "/Users/test/Library", "/Users"]; + + it("allows ordinary paths, including ones inside kept folders", () => { + expect(agentTrashRefusal("/Users/test/Documents/old.zip", keep, "darwin")).toBeNull(); + expect(agentTrashRefusal("/Users/test/github/app/node_modules", keep, "darwin")).toBeNull(); + expect(agentTrashRefusal("/opt/cache", keep, "linux")).toBeNull(); + }); + + it("refuses a kept folder itself, ignoring case on macOS", () => { + expect(agentTrashRefusal("/Users/test/Documents", keep, "darwin")).toContain("never"); + expect(agentTrashRefusal("/users/test/documents/", keep, "darwin")).toContain("never"); + }); + + it("refuses anything that contains a kept folder", () => { + expect(agentTrashRefusal("/Users", ["/Users/test"], "darwin")).toBe("it contains /Users/test"); + }); + + it("is case-sensitive on Linux", () => { + expect(agentTrashRefusal("/home/Test", ["/home/test"], "linux")).toBeNull(); + }); + + it("refuses drive roots", () => { + expect(agentTrashRefusal("/", [], "linux")).toBe("it is a drive root"); + expect(agentTrashRefusal("D:\\", [], "win32")).toBe("it is a drive root"); + }); + + it("refuses network and device paths on Windows", () => { + expect(agentTrashRefusal("\\\\localhost\\C$\\Windows", [], "win32")).toContain("network"); + expect(agentTrashRefusal("\\\\?\\C:\\Windows", [], "win32")).toContain("network"); + }); + + it("compares Windows paths case-insensitively", () => { + expect(agentTrashRefusal("c:\\users\\test\\appdata", ["C:\\Users\\test\\AppData"], "win32")).toContain("never"); + expect(agentTrashRefusal("C:\\Users\\test\\AppData\\Local\\Temp\\x", ["C:\\Users\\test\\AppData"], "win32")).toBeNull(); + }); +}); + +describe("outermostPaths", () => { + it("drops duplicates and paths inside another requested path", () => { + expect(outermostPaths(["/a/b", "/a", "/a/b/c", "/ab", "/a"], "linux")).toEqual(["/a", "/ab"]); + }); + + it("matches case-insensitively on macOS", () => { + expect(outermostPaths(["/Users/test/Build", "/users/test/build/out"], "darwin")).toEqual(["/Users/test/Build"]); + }); +}); + + +describe("configured protections scaling", () => { + it("resolves each exclusion once per batch and scales with folder count", async () => { + async function measure(n: number) { + let operations = 0; + const folders = new Proxy(Array.from({ length: n }, (_, i) => `/protected/${i}`), { + get(target, property, receiver) { operations++; return Reflect.get(target, property, receiver); }, + }); + const realpath = vi.spyOn(FSP, "realpath").mockImplementation(async (path) => { + operations++; + return String(path); + }); + try { + const guard = await configuredTrashGuard(folders); + // MCP limits a Trash batch to 20 targets, independent of exclusions. + for (let i = 0; i < 20; i++) expect(guard(`/allowed/${i}`, `/allowed/${i}`)).toBeNull(); + expect(realpath).toHaveBeenCalledTimes(n); + return operations; + } finally { realpath.mockRestore(); } + } + const small = await measure(128); + const large = await measure(1024); + expect(large).toBeLessThanOrEqual(small * 16); + expect(large).toBeLessThanOrEqual(200_000); + }); +}); diff --git a/src/mcp/accessPolicy.ts b/src/mcp/accessPolicy.ts new file mode 100644 index 00000000..00cf1717 --- /dev/null +++ b/src/mcp/accessPolicy.ts @@ -0,0 +1,316 @@ +import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; +import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; + +import { + BUILT_IN_MCP_ROLES, + MCP_AGENT_CAPABILITIES, + type AgentClientVia, + type McpAgentCapability, + type McpAgentRole, + type McpAgentSession, +} from "../shared/agentAccess"; + +/** + * Session store for local agents, ported from PwrGit's MCP policy file. + * + * - Only a SHA-256 of each bearer token is written; the token itself is + * handed to the agent once, at OAuth code exchange, and never again. + * - Every authorization re-reads the file, so a revoke or role change + * in Settings applies to the very next tool call without a restart. + * - Roles live in code (BUILT_IN_MCP_ROLES). The file holds Sessions. + * - Writes are temp-file + rename with 0600 perms in a 0700 directory. + */ + +export const MCP_POLICY_PROTOCOL = "diskhound.mcp-policy/v1" as const; +export const MCP_POLICY_VERSION = 1 as const; + +const MAX_SESSIONS = 256; +const ID_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/; +const TOKEN_PREFIX = "dhmcp_"; + +interface McpAgentSessionRecord extends McpAgentSession { + tokenHash: string; +} + +interface McpPolicyFile { + protocol: typeof MCP_POLICY_PROTOCOL; + version: typeof MCP_POLICY_VERSION; + sessions: McpAgentSessionRecord[]; +} + +export interface McpAuthorization { + sessionId: string; + sessionName: string; + roleId: string; + roleName: string; + capabilities: readonly McpAgentCapability[]; + /** The OAuth client that holds this session's token, if it signed in with OAuth. */ + oauthClientId?: string; +} + +export interface McpAuthorizer { + authorize(capabilities?: readonly McpAgentCapability[]): Promise; +} + +export type McpAccessErrorCode = + | "policy_unavailable" + | "invalid_policy" + | "invalid_session" + | "revoked_session" + | "invalid_role" + | "missing_capability" + | "invalid_input"; + +export class McpAccessError extends Error { + constructor(readonly code: McpAccessErrorCode, message: string) { + super(message); + this.name = "McpAccessError"; + } +} + +export function isCapability(value: unknown): value is McpAgentCapability { + return typeof value === "string" && (MCP_AGENT_CAPABILITIES as readonly string[]).includes(value); +} + +export function findRole(roleId: string): McpAgentRole | undefined { + return BUILT_IN_MCP_ROLES.find((role) => role.id === roleId); +} + +function tokenHash(token: string): Buffer { + return createHash("sha256").update(token, "utf8").digest(); +} + +function publicSession(session: McpAgentSessionRecord): McpAgentSession { + return { + id: session.id, + name: session.name, + roleId: session.roleId, + createdAt: session.createdAt, + updatedAt: session.updatedAt, + revokedAt: session.revokedAt, + ...(session.oauth ? { oauth: { clientId: session.oauth.clientId, scopes: [...session.oauth.scopes] } } : {}), + ...(session.client ? { client: { name: session.client.name, via: session.client.via } } : {}), + }; +} + +function parseSession(value: unknown): McpAgentSessionRecord { + if (value === null || typeof value !== "object" || Array.isArray(value)) { + throw new McpAccessError("invalid_policy", "policy contains an invalid session"); + } + const session = value as Partial; + if ( + typeof session.id !== "string" || !ID_PATTERN.test(session.id) || + typeof session.name !== "string" || session.name.trim().length === 0 || session.name.length > 200 || + typeof session.roleId !== "string" || !ID_PATTERN.test(session.roleId) || + typeof session.tokenHash !== "string" || !/^[a-f0-9]{64}$/.test(session.tokenHash) || + typeof session.createdAt !== "string" || + typeof session.updatedAt !== "string" || + !(session.revokedAt === null || typeof session.revokedAt === "string") + ) { + throw new McpAccessError("invalid_policy", "policy contains an invalid session"); + } + if (session.oauth !== undefined && ( + session.oauth === null || typeof session.oauth !== "object" || + typeof session.oauth.clientId !== "string" || !ID_PATTERN.test(session.oauth.clientId) || + !Array.isArray(session.oauth.scopes) || !session.oauth.scopes.every(isCapability) + )) { + throw new McpAccessError("invalid_policy", "invalid OAuth session binding"); + } + if (session.client !== undefined && ( + session.client === null || typeof session.client !== "object" || + typeof session.client.name !== "string" || session.client.name.length > 200 || + (session.client.via !== "stdio" && session.client.via !== "http") + )) { + throw new McpAccessError("invalid_policy", "invalid session client"); + } + return session as McpAgentSessionRecord; +} + +function parsePolicy(value: unknown): McpPolicyFile { + if (value === null || typeof value !== "object" || Array.isArray(value)) { + throw new McpAccessError("invalid_policy", "MCP policy must be a JSON object"); + } + const input = value as Partial; + if ( + input.protocol !== MCP_POLICY_PROTOCOL || + input.version !== MCP_POLICY_VERSION || + !Array.isArray(input.sessions) || + input.sessions.length > MAX_SESSIONS + ) { + throw new McpAccessError("invalid_policy", "MCP policy protocol, version, or session limit is invalid"); + } + const sessions = input.sessions.map(parseSession); + if (new Set(sessions.map((session) => session.id)).size !== sessions.length) { + throw new McpAccessError("invalid_policy", "MCP policy contains duplicate session ids"); + } + return { protocol: MCP_POLICY_PROTOCOL, version: MCP_POLICY_VERSION, sessions }; +} + +function emptyPolicy(): McpPolicyFile { + return { protocol: MCP_POLICY_PROTOCOL, version: MCP_POLICY_VERSION, sessions: [] }; +} + +export class McpPolicyStore { + constructor( + readonly filePath: string, + private readonly now: () => Date = () => new Date(), + ) {} + + sessions(): McpAgentSession[] { + return this.read().sessions.map(publicSession); + } + + createSession( + nameInput: string, + roleId: string, + oauth: { clientId: string; scopes: McpAgentCapability[] }, + client?: { name: string; via: AgentClientVia }, + ): { session: McpAgentSession; token: string } { + const policy = this.read(); + const name = nameInput.trim(); + if (name.length === 0 || name.length > 200) { + throw new McpAccessError("invalid_input", "session name must contain 1 to 200 characters"); + } + if (!findRole(roleId)) { + throw new McpAccessError("invalid_input", "selected role does not exist"); + } + // Keep revoked history, but never let it crowd out new approvals. + if (policy.sessions.length >= MAX_SESSIONS) { + const revokedIndex = policy.sessions.findIndex((session) => session.revokedAt !== null); + if (revokedIndex < 0) throw new McpAccessError("invalid_input", `session limit reached (${MAX_SESSIONS})`); + policy.sessions.splice(revokedIndex, 1); + } + const timestamp = this.now().toISOString(); + const token = `${TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`; + const record: McpAgentSessionRecord = { + id: `session_${randomUUID()}`, + name, + roleId, + tokenHash: tokenHash(token).toString("hex"), + createdAt: timestamp, + updatedAt: timestamp, + revokedAt: null, + oauth: { clientId: oauth.clientId, scopes: [...oauth.scopes] }, + ...(client ? { client: { name: client.name.trim().slice(0, 200), via: client.via } } : {}), + }; + policy.sessions.push(record); + this.write(policy); + return { session: publicSession(record), token }; + } + + revokeSession(id: string): McpAgentSession { + const policy = this.read(); + const session = policy.sessions.find((candidate) => candidate.id === id); + if (!session) throw new McpAccessError("invalid_input", "session does not exist"); + if (session.revokedAt !== null) return publicSession(session); + const timestamp = this.now().toISOString(); + session.revokedAt ??= timestamp; + session.updatedAt = timestamp; + this.write(policy); + return publicSession(session); + } + + assignRole(sessionId: string, roleId: string): McpAgentSession { + const policy = this.read(); + const session = policy.sessions.find((candidate) => candidate.id === sessionId); + if (!session) throw new McpAccessError("invalid_input", "session does not exist"); + if (!findRole(roleId)) throw new McpAccessError("invalid_input", "selected role does not exist"); + if (session.roleId === roleId) return publicSession(session); + session.roleId = roleId; + session.updatedAt = this.now().toISOString(); + this.write(policy); + return publicSession(session); + } + + /** Drop revoked sessions from the file entirely. */ + forgetRevoked(): number { + const policy = this.read(); + const before = policy.sessions.length; + policy.sessions = policy.sessions.filter((session) => session.revokedAt === null); + if (policy.sessions.length !== before) this.write(policy); + return before - policy.sessions.length; + } + + authorize(token: string, required: readonly McpAgentCapability[] = []): McpAuthorization { + const policy = this.read(); + const supplied = tokenHash(token); + const session = policy.sessions.find((candidate) => { + const stored = Buffer.from(candidate.tokenHash, "hex"); + return stored.length === supplied.length && timingSafeEqual(stored, supplied); + }); + if (!session) throw new McpAccessError("invalid_session", "MCP session token is invalid"); + if (session.revokedAt !== null) throw new McpAccessError("revoked_session", "MCP session has been revoked"); + const role = findRole(session.roleId); + if (!role) throw new McpAccessError("invalid_role", "MCP session has no valid role"); + const permissions = role.permissions.filter((capability) => + session.oauth === undefined || session.oauth.scopes.includes(capability), + ); + const missing = required.filter((capability) => !permissions.includes(capability)); + if (missing.length > 0) { + throw new McpAccessError( + "missing_capability", + `This DiskHound Session (${role.name}) does not grant: ${missing.join(", ")}. ` + + "The user can change the Session's role in DiskHound โ†’ Settings โ†’ AI Agents.", + ); + } + return { + sessionId: session.id, + sessionName: session.name, + roleId: role.id, + roleName: role.name, + capabilities: [...permissions], + ...(session.oauth ? { oauthClientId: session.oauth.clientId } : {}), + }; + } + + private read(): McpPolicyFile { + let contents: string; + try { + contents = readFileSync(this.filePath, "utf8"); + } catch (cause) { + if ((cause as NodeJS.ErrnoException).code === "ENOENT") return emptyPolicy(); + throw new McpAccessError("policy_unavailable", `MCP policy is unavailable at ${this.filePath}`); + } + try { + return parsePolicy(JSON.parse(contents) as unknown); + } catch (cause) { + if (cause instanceof McpAccessError) throw cause; + throw new McpAccessError("invalid_policy", "MCP policy is not valid JSON"); + } + } + + private write(policy: McpPolicyFile): void { + mkdirSync(dirname(this.filePath), { recursive: true, mode: 0o700 }); + const temporary = `${this.filePath}.${process.pid}.tmp`; + writeFileSync(temporary, `${JSON.stringify(policy, null, 2)}\n`, { encoding: "utf8", mode: 0o600 }); + renameSync(temporary, this.filePath); + if (process.platform !== "win32") chmodSync(this.filePath, 0o600); + } + + exists(): boolean { + return existsSync(this.filePath); + } +} + +/** Authorizer bound to one bearer token; used per MCP request. */ +export class PolicyFileAuthorizer implements McpAuthorizer { + constructor(private readonly store: McpPolicyStore, private readonly token: string) {} + + async authorize(capabilities: readonly McpAgentCapability[] = []): Promise { + return this.store.authorize(this.token, capabilities); + } +} + +/** Fixed authorization for tests and trusted in-process embedders. */ +export class FixedMcpAuthorizer implements McpAuthorizer { + constructor(private readonly authorization: McpAuthorization) {} + + async authorize(capabilities: readonly McpAgentCapability[] = []): Promise { + const missing = capabilities.filter((capability) => !this.authorization.capabilities.includes(capability)); + if (missing.length > 0) { + throw new McpAccessError("missing_capability", `MCP role does not grant: ${missing.join(", ")}`); + } + return this.authorization; + } +} diff --git a/src/mcp/activityLog.ts b/src/mcp/activityLog.ts new file mode 100644 index 00000000..aa43e374 --- /dev/null +++ b/src/mcp/activityLog.ts @@ -0,0 +1,33 @@ +import type { AgentActivityEntry } from "../shared/agentAccess"; +import type { AgentActivitySink } from "./backend"; + +/** + * In-memory feed of what agents did, newest first. Powers the header + * pill ("Claude Code is workingโ€ฆ") and Settings โ†’ AI Agents โ†’ Recent + * agent actions. Not persisted: it describes this app session only. + */ +export class AgentActivityLog implements AgentActivitySink { + private entries: AgentActivityEntry[] = []; + private seq = 0; + + constructor( + private readonly onEntry: (entry: AgentActivityEntry) => void, + private readonly limit = 100, + private readonly now: () => number = Date.now, + ) {} + + record(entry: Omit): void { + const full: AgentActivityEntry = { ...entry, id: `agent-${++this.seq}`, at: this.now() }; + this.entries.unshift(full); + if (this.entries.length > this.limit) this.entries.length = this.limit; + try { + this.onEntry(full); + } catch { + // A closing window must never fail the tool call that triggered it. + } + } + + list(): AgentActivityEntry[] { + return this.entries.map((entry) => ({ ...entry })); + } +} diff --git a/src/mcp/agentAccessServer.ts b/src/mcp/agentAccessServer.ts new file mode 100644 index 00000000..832b619b --- /dev/null +++ b/src/mcp/agentAccessServer.ts @@ -0,0 +1,362 @@ +import { createServer, type Server as HttpServer } from "node:http"; + +import express, { type NextFunction, type Request, type Response } from "express"; +import { authorizationHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/authorize.js"; +import { clientRegistrationHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/register.js"; +import { revocationHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/revoke.js"; +import { tokenHandler } from "@modelcontextprotocol/sdk/server/auth/handlers/token.js"; +import { mcpAuthMetadataRouter } from "@modelcontextprotocol/sdk/server/auth/router.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; + +import { AGENT_ACCESS_HOST, AGENT_ACCESS_PORT, MCP_AGENT_CAPABILITIES, agentAccessMcpUrl } from "../shared/agentAccess"; +import { McpPolicyStore, PolicyFileAuthorizer, type McpAuthorization } from "./accessPolicy"; +import { AgentOAuth, type RequestConsent } from "./agentOAuth"; +import type { AgentActivitySink, DiskhoundAgentBackend } from "./backend"; +import type { AgentSecuritySink } from "./securityLog"; +import { createDiskhoundMcpServer, TOOL_CAPABILITIES, toolActionText } from "./server"; +import type { SkillCatalog } from "./skills"; + +/** + * The session's permissions on every /mcp response. The stdio helper + * compares it between calls and tells its client to reload the tool + * list (notifications/tools/list_changed) when a role changes. + */ +export const CAPABILITIES_HEADER = "DiskHound-Capabilities"; + +export interface AgentAccessServerOptions { + backend: DiskhoundAgentBackend; + activity: AgentActivitySink; + security?: AgentSecuritySink; + skills: SkillCatalog; + policy: McpPolicyStore; + clientsFile: string; + requestConsent: RequestConsent; + onChanged: () => void; + /** Tests pass 0 for an ephemeral port. */ + port?: number; +} + +/** Per-token queue depth before we answer 429. */ +const MAX_PENDING_PER_TOKEN = 16; + +/** + * Loopback-only MCP endpoint with its own OAuth authorization server. + * + * Ported from PwrGit's AgentAccessServer with PwrSnap's refinements: + * - Host must equal the bound `127.0.0.1:` exactly (DNS + * rebinding), the TCP peer must be loopback, and any Origin must be + * a loopback origin. Checked before every route. + * - `/mcp` is POST-only and says so before auth. Claude Code and + * Codex open a GET stream on connect; letting the SDK accept it + * leaves a never-ending response pinned to the process. + * - Stateless Streamable HTTP: one short-lived McpServer per POST, + * bound to that request's bearer token. DiskHound keeps no + * per-agent state between calls, so there is nothing to reclaim + * when a Session is revoked. + */ +export class AgentAccessServer { + private http: HttpServer | undefined; + private oauth: AgentOAuth | undefined; + private boundPort: number; + private readonly pendingByToken = new Map(); + /** One per in-flight /mcp request; stop() aborts them all. */ + private readonly inFlight = new Set(); + + constructor(private readonly options: AgentAccessServerOptions) { + this.boundPort = options.port ?? AGENT_ACCESS_PORT; + } + + get port(): number { + return this.boundPort; + } + get mcpUrl(): string { + return agentAccessMcpUrl(this.boundPort); + } + get listening(): boolean { + return this.http?.listening === true; + } + + async start(): Promise { + if (this.http) return; + const app = express(); + app.disable("x-powered-by"); + app.use((req, res, next) => { + if (!isLoopbackAddress(req.socket.remoteAddress)) { + res.status(403).json({ error: "non_loopback_client" }); + return; + } + if (req.headers.host !== `${AGENT_ACCESS_HOST}:${this.boundPort}` || !allowedOrigin(req.headers.origin)) { + res.status(403).json({ error: "forbidden_origin" }); + return; + } + res.setHeader("Cache-Control", "no-store"); + next(); + }); + + const http = createServer(app); + this.http = http; + try { + await new Promise((resolve, reject) => { + http.once("error", reject); + http.listen(this.boundPort, AGENT_ACCESS_HOST, () => { + http.off("error", reject); + const address = http.address(); + if (address && typeof address !== "string") this.boundPort = address.port; + resolve(); + }); + }); + + const resource = new URL(this.mcpUrl); + const issuer = new URL(resource.origin); + const oauth = new AgentOAuth({ + policy: this.options.policy, + clientsFile: this.options.clientsFile, + resource, + requestConsent: this.options.requestConsent, + onChanged: this.options.onChanged, + }); + this.oauth = oauth; + + app.get("/authorize/status", (req, res) => { + oauth.status(typeof req.query.id === "string" ? req.query.id : "", res); + }); + // The stdio helper withdraws its request when its client hangs up. + // The same answer either way, so it reveals nothing about ids. + app.post("/authorize/cancel", express.urlencoded({ extended: false, limit: "1kb" }), (req, res) => { + const id = (req.body as { id?: unknown } | undefined)?.id; + oauth.cancel(typeof id === "string" ? id : ""); + res.status(204).end(); + }); + app.all("/authorize", (req, res, next) => { + if (req.method !== "GET") { + res.setHeader("Allow", "GET"); + res.status(405).end(); + return; + } + // URL parameters can request authorization, never decide it. + if (["decision", "diskhound_decision", "approve", "consent_transaction"].some((key) => key in req.query)) { + res.status(400).json({ error: "invalid_request" }); + return; + } + next(); + }); + app.use("/authorize", authorizationHandler({ provider: oauth })); + app.use("/register", clientRegistrationHandler({ clientsStore: oauth.clientsStore, clientIdGeneration: false })); + app.use("/token", tokenHandler({ provider: oauth })); + app.use("/revoke", revocationHandler({ provider: oauth })); + app.use(mcpAuthMetadataRouter({ + resourceServerUrl: resource, + resourceName: "DiskHound", + scopesSupported: [...MCP_AGENT_CAPABILITIES], + oauthMetadata: { + issuer: issuer.href, + authorization_endpoint: new URL("/authorize", issuer).href, + token_endpoint: new URL("/token", issuer).href, + registration_endpoint: new URL("/register", issuer).href, + revocation_endpoint: new URL("/revoke", issuer).href, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code"], + token_endpoint_auth_methods_supported: ["none"], + revocation_endpoint_auth_methods_supported: ["none"], + code_challenge_methods_supported: ["S256"], + scopes_supported: [...MCP_AGENT_CAPABILITIES], + }, + })); + app.all("/mcp", (req, res, next) => { + if (req.method !== "POST") { + res.setHeader("Allow", "POST"); + res.status(405).json({ error: "method_not_allowed" }); + return; + } + next(); + }); + app.post("/mcp", express.json({ limit: "256kb" }), (req, res, next) => { + void this.handleMcp(req, res, oauth).catch(next); + }); + app.use((_req, res) => { + res.status(404).json({ error: "not_found" }); + }); + // Last: never fall back to Express's HTML error page (with stack). + app.use((error: unknown, _req: Request, res: Response, _next: NextFunction) => { + const status = (error as { status?: number }).status; + if (res.headersSent) { + res.end(); + return; + } + res.status(status === 413 ? 413 : status === 400 ? 400 : 500).json({ error: "request_failed" }); + }); + } catch (cause) { + await this.stop(); + throw cause; + } + } + + private async handleMcp(req: Request, res: Response, oauth: AgentOAuth): Promise { + const token = /^Bearer\s+(.+)$/i.exec(req.headers.authorization?.trim() ?? "")?.[1]; + // What this session may do right now decides which tools the + // per-request server registers. Tool calls re-check on their own. + let session: McpAuthorization; + try { + if (!token) throw new Error("missing token"); + session = oauth.authorizeToken(token); + } catch { + res.setHeader( + "WWW-Authenticate", + `Bearer resource_metadata="${new URL(this.mcpUrl).origin}/.well-known/oauth-protected-resource/mcp", ` + + `scope="${MCP_AGENT_CAPABILITIES.join(" ")}"`, + ); + res.status(401).json({ error: "unauthorized" }); + return; + } + res.setHeader(CAPABILITIES_HEADER, [...session.capabilities].sort().join(",")); + if (this.refuseHiddenTool(req.body, session, res)) return; + + const pending = this.pendingByToken.get(token) ?? 0; + if (pending >= MAX_PENDING_PER_TOKEN) { + res.status(429).json({ error: "too_many_requests" }); + return; + } + this.pendingByToken.set(token, pending + 1); + // A trash request can wait minutes for its dialog. If the agent hangs + // up or the server stops (closeAllConnections), drop it rather than + // ask the user on behalf of nobody. + const closed = new AbortController(); + this.inFlight.add(closed); + res.once("close", () => { + if (!res.writableFinished) closed.abort(); + }); + const mcp = createDiskhoundMcpServer({ + backend: this.options.backend, + activity: this.options.activity, + skills: this.options.skills, + authorizer: new PolicyFileAuthorizer(this.options.policy, token), + granted: session.capabilities, + security: this.options.security, + signal: closed.signal, + }); + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true }); + try { + await mcp.connect(transport); + await transport.handleRequest(req, res, withDefaultArguments(req.body)); + } finally { + this.inFlight.delete(closed); + const left = (this.pendingByToken.get(token) ?? 1) - 1; + if (left <= 0) this.pendingByToken.delete(token); + else this.pendingByToken.set(token, left); + await transport.close().catch(() => undefined); + await mcp.close().catch(() => undefined); + } + } + + /** + * A call to a DiskHound tool this session's role doesn't grant. The + * tool isn't in the session's tools/list, so the agent has a stale + * list (its role was lowered) or guessed. Answer it as a failed tool + * call that says why, and log it for the user. + */ + private refuseHiddenTool(body: unknown, session: McpAuthorization, res: Response): boolean { + // A batch gets the SDK's own "unknown tool" answers, but each hidden + // call in it is still logged for the user. + if (Array.isArray(body)) { + for (const message of body) { + const hidden = hiddenTool(message, session); + if (hidden) this.recordHiddenTool(hidden.name, session); + } + return false; + } + const hidden = hiddenTool(body, session); + if (!hidden) return false; + const { name, missing, id } = hidden; + this.recordHiddenTool(name, session); + res.status(200).json({ + jsonrpc: "2.0", + id, + result: { + isError: true, + content: [{ + type: "text", + text: `${name} isn't available to this DiskHound session (${session.roleName} doesn't grant ${missing.join(", ")}). ` + + "Nothing was changed, and DiskHound logged the attempt. Ask the user to change this session's role in " + + "DiskHound โ†’ Settings โ†’ AI Agents if they want you to do this, then reload your tool list.", + }], + }, + }); + return true; + } + + private recordHiddenTool(name: string, session: McpAuthorization): void { + this.options.security?.record({ + sessionId: session.sessionId, + sessionName: session.sessionName, + roleName: session.roleName, + kind: "tool_not_allowed", + tool: name, + detail: `Tried to ${toolActionText(name)}; ${session.roleName} doesn't allow it.`, + }); + this.options.activity.record({ + sessionId: session.sessionId, + sessionName: session.sessionName, + tool: name, + summary: `Blocked: tried to ${toolActionText(name)} (${session.roleName})`, + ok: false, + }); + } + + async stop(): Promise { + for (const request of this.inFlight) request.abort(); + this.inFlight.clear(); + this.oauth?.close(); + this.oauth = undefined; + const http = this.http; + this.http = undefined; + if (!http) return; + http.closeAllConnections(); + await new Promise((resolve) => http.close(() => resolve())); + } +} + +export function isLoopbackAddress(address: string | undefined): boolean { + return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1"; +} + +export function allowedOrigin(origin: string | undefined): boolean { + // CLI agents send no Origin. Browsers must come from loopback; + // opaque ("null") origins from sandboxed frames fail. + if (origin === undefined) return true; + try { + const url = new URL(origin); + return ["http:", "https:"].includes(url.protocol) && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); + } catch { + return false; + } +} + +/** A tools/call for a DiskHound tool the session's role doesn't grant. */ +function hiddenTool( + body: unknown, + session: McpAuthorization, +): { name: string; missing: string[]; id: unknown } | null { + const message = body as { id?: unknown; method?: unknown; params?: { name?: unknown } } | null; + if (!message || typeof message !== "object" || Array.isArray(message) || message.method !== "tools/call") return null; + const name = message.params?.name; + if (typeof name !== "string") return null; + const required = TOOL_CAPABILITIES[name]; + if (!required) return null; + const missing = required.filter((capability) => !session.capabilities.includes(capability)); + return missing.length === 0 ? null : { name, missing, id: message.id ?? null }; +} + +/** + * `arguments` is optional on tools/call and prompts/get, and rmcp-based + * clients (Codex) leave it out for tools that take none. SDK 1.30 + * validates it as given, so a missing object fails even when every + * field is optional. Default it to {} (per message, batches included). + */ +export function withDefaultArguments(body: unknown): unknown { + if (Array.isArray(body)) return body.map(withDefaultArguments); + if (!body || typeof body !== "object") return body; + const message = body as { method?: unknown; params?: Record }; + if (message.method !== "tools/call" && message.method !== "prompts/get") return body; + if (!message.params || typeof message.params !== "object" || message.params.arguments !== undefined) return body; + return { ...message, params: { ...message.params, arguments: {} } }; +} diff --git a/src/mcp/agentAccessService.ts b/src/mcp/agentAccessService.ts new file mode 100644 index 00000000..e65f8c8c --- /dev/null +++ b/src/mcp/agentAccessService.ts @@ -0,0 +1,59 @@ +import type { AgentAccessStatus } from "../shared/agentAccess"; +import { AgentAccessServer, type AgentAccessServerOptions } from "./agentAccessServer"; + +/** + * On/off switch for the MCP listener. Start/stop is serialized through + * a promise tail so a fast onโ†’offโ†’on in Settings can never leave the + * port bound by a server the UI thinks is stopped. + */ +export class AgentAccessService { + private readonly server: AgentAccessServer; + private enabled = false; + private error: string | undefined; + private tail: Promise = Promise.resolve(); + + constructor( + private readonly options: AgentAccessServerOptions & { saveEnabled: (enabled: boolean) => void | Promise }, + ) { + this.server = new AgentAccessServer(options); + } + + status(): AgentAccessStatus { + return { + enabled: this.enabled, + listening: this.server.listening, + mcpUrl: this.server.mcpUrl, + port: this.server.port, + ...(this.error ? { error: this.error } : {}), + }; + } + + setEnabled(enabled: boolean, persist = true): Promise { + const operation = this.tail.then(async () => { + this.error = undefined; + if (enabled) { + try { + await this.server.start(); + } catch (cause) { + const code = (cause as NodeJS.ErrnoException).code; + this.error = code === "EADDRINUSE" + ? `Port ${this.server.port} is already in use by another program. Quit it (or the other DiskHound) and toggle this again.` + : cause instanceof Error ? cause.message : String(cause); + } + } else { + await this.server.stop(); + } + this.enabled = enabled; + if (persist) await this.options.saveEnabled(enabled); + this.options.onChanged(); + return this.status(); + }); + this.tail = operation.catch(() => undefined); + return operation; + } + + async dispose(): Promise { + await this.tail; + await this.server.stop(); + } +} diff --git a/src/mcp/agentOAuth.ts b/src/mcp/agentOAuth.ts new file mode 100644 index 00000000..692baf8f --- /dev/null +++ b/src/mcp/agentOAuth.ts @@ -0,0 +1,394 @@ +import { randomBytes } from "node:crypto"; +import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; + +import type { Response } from "express"; +import type { OAuthRegisteredClientsStore } from "@modelcontextprotocol/sdk/server/auth/clients.js"; +import { + InvalidGrantError, + InvalidRequestError, + InvalidScopeError, + InvalidTargetError, + InvalidTokenError, +} from "@modelcontextprotocol/sdk/server/auth/errors.js"; +import type { AuthorizationParams, OAuthServerProvider } from "@modelcontextprotocol/sdk/server/auth/provider.js"; +import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js"; +import { + OAuthClientInformationFullSchema, + type OAuthClientInformationFull, + type OAuthTokens, +} from "@modelcontextprotocol/sdk/shared/auth.js"; + +import { MCP_AGENT_CAPABILITIES, type AgentClientVia, type McpAgentCapability } from "../shared/agentAccess"; +import { findRole, isCapability, type McpAuthorization, type McpPolicyStore } from "./accessPolicy"; + +/** + * OAuth 2.1 authorization server for local agents, ported from PwrGit / + * PwrSnap. The shape of the flow: + * + * 1. The agent registers itself (RFC 7591 DCR). Registration grants + * nothing โ€” every client is public (no secret, PKCE required). + * 2. `/authorize` opens DiskHound's native approval window and + * answers the browser with an inert waiting page. No browser form, + * script, or URL parameter can approve access; the page only + * polls `/authorize/status` for the decision the native window + * makes. + * 3. After approval the status page 302s to the agent's redirect with + * a single-use code, which `/token` exchanges for a bearer token. + * Tokens do not expire or refresh; they are revoked in Settings. + */ + +const TTL_MS = 5 * 60_000; +const PENDING_LIMIT = 64; +/** + * The waiting client checks /authorize/status every 0.5โ€“1 s (the stdio + * helper and the browser page). Silence this long means it gave up, + * usually a client's connect timeout, so an approval now reaches nobody. + */ +const STALE_AFTER_MS = 10_000; +/** software_id the bundled stdio helper registers with. */ +export const STDIO_HELPER_SOFTWARE_ID = "diskhound-mcp"; +const CLIENT_LIMIT = 256; +const opaque = () => randomBytes(32).toString("base64url"); + +/** + * Scopes for a client that doesn't ask for any. The requested scopes + * only cap the Session; the user picks the actual role in the approval + * window (and can change it later in Settings within that cap), so a + * client that omits `scope` gets the full menu rather than being stuck + * read-only until it re-authenticates. + */ +const DEFAULT_SCOPES: McpAgentCapability[] = [...MCP_AGENT_CAPABILITIES]; + +export interface ConsentRequest { + clientName: string; + via: AgentClientVia; + scopes: McpAgentCapability[]; + signal: AbortSignal; + /** False once the waiting client stops checking for the decision. */ + clientWaiting: () => boolean; +} +export interface ConsentDecision { + decision: "allow" | "deny"; + sessionName: string; + roleId: string; +} +export type RequestConsent = (request: ConsentRequest) => Promise; + +class Clients implements OAuthRegisteredClientsStore { + private readonly clients = new Map(); + + constructor(private readonly file: string, private readonly policy: McpPolicyStore) { + try { + const saved: unknown = JSON.parse(readFileSync(file, "utf8")); + if (!Array.isArray(saved) || saved.length > CLIENT_LIMIT) throw new Error("Invalid OAuth client store"); + for (const value of saved) { + const client = OAuthClientInformationFullSchema.parse(value); + this.clients.set(client.client_id, client); + } + } catch (cause) { + // A corrupt store only costs agents a re-registration; don't let it + // stop the listener from starting. + if ((cause as NodeJS.ErrnoException).code !== "ENOENT") this.clients.clear(); + } + } + + getClient(id: string) { + return this.clients.get(id); + } + + registerClient: NonNullable = async (input) => { + const client: OAuthClientInformationFull = { + ...input, + client_id: opaque(), + client_id_issued_at: Math.floor(Date.now() / 1000), + token_endpoint_auth_method: "none", + grant_types: ["authorization_code"], + response_types: ["code"], + }; + delete client.client_secret; + delete client.client_secret_expires_at; + if (this.clients.size >= CLIENT_LIMIT) { + const approved = new Set( + this.policy.sessions().filter((s) => s.revokedAt === null).map((s) => s.oauth?.clientId), + ); + const evict = [...this.clients.keys()].find((id) => !approved.has(id)); + if (evict === undefined) throw new InvalidRequestError("OAuth client limit reached"); + this.clients.delete(evict); + } + this.clients.set(client.client_id, client); + mkdirSync(dirname(this.file), { recursive: true, mode: 0o700 }); + const temporary = `${this.file}.tmp`; + writeFileSync(temporary, JSON.stringify([...this.clients.values()]), { mode: 0o600 }); + renameSync(temporary, this.file); + return client; + }; +} + +interface IssuedCode { + clientId: string; + params: AuthorizationParams; + decision: ConsentDecision; + scopes: McpAgentCapability[]; + expires: number; +} +interface BrowserApproval { + controller: AbortController; + expires: number; + redirect?: string; + /** Last time the client asked for the decision (or started the request). */ + lastPolledAt: number; + clientName: string; + /** Same client, PKCE challenge, state and redirect: the same login. */ + key: string; +} + +function clientVia(client: OAuthClientInformationFull): AgentClientVia { + return client.software_id === STDIO_HELPER_SOFTWARE_ID ? "stdio" : "http"; +} + +function clientLabel(client: OAuthClientInformationFull): string { + return client.client_name?.trim().slice(0, 200) || "Local MCP client"; +} + +function escapeHtml(text: string): string { + return text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); +} + +export class AgentOAuth implements OAuthServerProvider { + readonly clientsStore: OAuthRegisteredClientsStore; + private readonly codes = new Map(); + private readonly approvals = new Map(); + + constructor(private readonly options: { + policy: McpPolicyStore; + clientsFile: string; + resource: URL; + requestConsent: RequestConsent; + onChanged: () => void; + }) { + this.clientsStore = new Clients(options.clientsFile, options.policy); + } + + async authorize(client: OAuthClientInformationFull, params: AuthorizationParams, response: Response): Promise { + this.prune(); + this.validateResource(params.resource); + if (!/^[A-Za-z0-9_-]{43}$/.test(params.codeChallenge)) { + throw new InvalidRequestError("A valid S256 code challenge is required"); + } + const scopes = params.scopes?.length ? params.scopes : DEFAULT_SCOPES; + if (!scopes.every(isCapability)) throw new InvalidScopeError("Unknown DiskHound permission"); + // A reloaded tab, or a client that opens the URL itself and prints + // it too, is the same login: show its waiting page again rather + // than queue a second approval the user has to deny. + const key = [client.client_id, params.codeChallenge, params.state ?? "", params.redirectUri].join("\n"); + for (const [existingId, existing] of this.approvals) { + if (existing.key !== key) continue; + existing.lastPolledAt = Date.now(); + this.waitingPage(response, existingId, existing.clientName); + return; + } + if (this.approvals.size >= PENDING_LIMIT || this.codes.size >= PENDING_LIMIT) { + throw new InvalidRequestError("Too many pending approvals"); + } + const id = opaque(); + const record: BrowserApproval = { + controller: new AbortController(), + expires: Date.now() + TTL_MS, + lastPolledAt: Date.now(), + clientName: clientLabel(client), + key, + }; + this.approvals.set(id, record); + const timer = setTimeout(() => { + record.controller.abort(); + this.approvals.delete(id); + }, TTL_MS); + timer.unref(); + + const finish = (decision: ConsentDecision) => { + clearTimeout(timer); + if (record.controller.signal.aborted || Date.now() >= record.expires) return; + const callback = new URL(params.redirectUri); + if (params.state !== undefined) callback.searchParams.set("state", params.state); + const role = findRole(decision.roleId); + const name = decision.sessionName.trim(); + if ( + decision.decision !== "allow" || !role || + name.length === 0 || name.length > 200 || + !role.permissions.every((permission) => scopes.includes(permission)) + ) { + callback.searchParams.set("error", "access_denied"); + } else { + const code = opaque(); + this.codes.set(code, { + clientId: client.client_id, + params, + decision: { ...decision, sessionName: name }, + // Keep what the client asked for, not just the chosen role: + // Settings can move the Session to a bigger role later, and + // this is the ceiling for that. + scopes: [...scopes] as McpAgentCapability[], + expires: Date.now() + TTL_MS, + }); + callback.searchParams.set("code", code); + } + record.redirect = callback.href; + }; + + void this.options.requestConsent({ + clientName: record.clientName, + via: clientVia(client), + scopes: scopes as McpAgentCapability[], + signal: record.controller.signal, + clientWaiting: () => Date.now() - record.lastPolledAt < STALE_AFTER_MS, + }) + .then(finish) + .catch(() => finish({ decision: "deny", sessionName: "", roleId: "" })); + this.waitingPage(response, id, record.clientName); + } + + status(id: string, response: Response): void { + this.prune(); + const record = this.approvals.get(id); + if (!record) { + response.status(404).type("text").send("Approval expired. Start a new DiskHound login from your agent."); + return; + } + record.lastPolledAt = Date.now(); + if (!record.redirect) { + this.waitingPage(response, id, record.clientName); + return; + } + this.approvals.delete(id); + response.setHeader("Cache-Control", "no-store"); + response.redirect(302, record.redirect); + } + + /** + * The requester gave up before the user decided (the stdio helper's + * client hung up). Withdraw the request so its approval sheet closes + * rather than waiting to be denied. Knowing the opaque id is the + * permission; once decided, there is nothing left to withdraw. + */ + cancel(id: string): void { + const record = this.approvals.get(id); + if (!record || record.redirect) return; + this.approvals.delete(id); + record.controller.abort(); + } + + private waitingPage(response: Response, id: string, clientName: string) { + // No browser form or script can approve access. The opaque status + // URL only retrieves a PKCE-bound redirect after the native window + // has decided. + response.setHeader("Cache-Control", "no-store"); + response.setHeader("Referrer-Policy", "no-referrer"); + response.setHeader( + "Content-Security-Policy", + "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'", + ); + response.type("html").send( + `` + + `` + + `Continue in DiskHound` + + `` + + `

Continue in DiskHound

` + + `

${escapeHtml(clientName)} is waiting for your approval. Choose what it may do in the DiskHound window. This page updates on its own once you decide.

` + + `
`, + ); + } + + async challengeForAuthorizationCode(client: OAuthClientInformationFull, code: string): Promise { + return this.requireCode(client, code).params.codeChallenge; + } + + async exchangeAuthorizationCode( + client: OAuthClientInformationFull, + code: string, + _verifier?: string, + redirect?: string, + resource?: URL, + ): Promise { + const record = this.requireCode(client, code); + if (redirect !== record.params.redirectUri) throw new InvalidGrantError("Redirect does not match"); + this.validateResource(resource); + this.codes.delete(code); + const role = findRole(record.decision.roleId); + if (!role || !role.permissions.every((permission) => record.scopes.includes(permission))) { + throw new InvalidGrantError("Approved role changed; authorize again"); + } + const issued = this.options.policy.createSession( + record.decision.sessionName, + record.decision.roleId, + { clientId: client.client_id, scopes: record.scopes }, + { name: clientLabel(client), via: clientVia(client) }, + ); + this.options.onChanged(); + return { access_token: issued.token, token_type: "bearer", scope: record.scopes.join(" ") }; + } + + async exchangeRefreshToken(): Promise { + throw new InvalidGrantError("DiskHound tokens do not expire or refresh"); + } + + async verifyAccessToken(token: string): Promise { + const auth = this.authorizeToken(token); + return { token, clientId: auth.oauthClientId!, scopes: [...auth.capabilities], resource: this.options.resource }; + } + + /** The OAuth session a bearer token belongs to, from one read of the policy file. */ + authorizeToken(token: string): McpAuthorization { + try { + const auth = this.options.policy.authorize(token); + if (!auth.oauthClientId) throw new Error("OAuth Session required"); + return auth; + } catch { + throw new InvalidTokenError("Invalid or revoked DiskHound Session"); + } + } + + async revokeToken(client: OAuthClientInformationFull, request: { token: string }): Promise { + try { + const auth = this.options.policy.authorize(request.token); + if (auth.oauthClientId === client.client_id) { + this.options.policy.revokeSession(auth.sessionId); + this.options.onChanged(); + } + } catch { + /* RFC 7009: unknown or already-revoked tokens also succeed. */ + } + } + + close() { + for (const record of this.approvals.values()) record.controller.abort(); + this.approvals.clear(); + this.codes.clear(); + } + + private validateResource(resource?: URL) { + if (resource?.href !== this.options.resource.href) { + throw new InvalidTargetError(`resource must be ${this.options.resource.href}`); + } + } + + private requireCode(client: OAuthClientInformationFull, code: string): IssuedCode { + this.prune(); + const record = this.codes.get(code); + if (!record || record.clientId !== client.client_id) throw new InvalidGrantError("Invalid or expired authorization code"); + return record; + } + + private prune() { + const now = Date.now(); + for (const [id, record] of this.codes) if (record.expires <= now) this.codes.delete(id); + for (const [id, record] of this.approvals) { + if (record.expires <= now) { + record.controller.abort(); + this.approvals.delete(id); + } + } + } +} + +export const SUPPORTED_SCOPES: readonly string[] = MCP_AGENT_CAPABILITIES; diff --git a/src/mcp/agentRuntime.ts b/src/mcp/agentRuntime.ts new file mode 100644 index 00000000..8ab81e21 --- /dev/null +++ b/src/mcp/agentRuntime.ts @@ -0,0 +1,8 @@ +/** + * Entry point for the lazily loaded half of agent access. Built as its + * own bundle (dist-electron/mcp/agentRuntime.cjs, see tsdown.config.ts) + * so the MCP SDK, Express, and zod are required only when the user + * turns AI Agents on โ€” not on every DiskHound launch. + */ +export { AgentAccessService } from "./agentAccessService"; +export { loadSkillCatalog } from "./skills"; diff --git a/src/mcp/backend.ts b/src/mcp/backend.ts new file mode 100644 index 00000000..8a581d2e --- /dev/null +++ b/src/mcp/backend.ts @@ -0,0 +1,135 @@ +import type { + AppView, + CleanupAnalysis, + DevArtifactReport, + DiskSpaceInfo, + DuplicateAnalysis, + DuplicateScanProgress, + FullDiffResult, + IndexSearchQuery, + IndexSearchResult, + PathActionResult, + ScanDiffResult, + ScanFileRecord, + ScanHistoryEntry, + ScanSnapshot, + WindowViewState, +} from "../shared/contracts"; +import type { AgentActivityEntry } from "../shared/agentAccess"; +import type { RemovalMeasurement } from "./removalMeasure"; + +/** + * Everything the MCP tool layer needs from DiskHound's main process. + * + * main.ts implements this over the same closures its IPC handlers use, + * so an agent sees exactly what the UI sees and anything the agent + * starts (a scan, a duplicate search) streams into the window through + * the existing broadcast channels. The tool layer (server.ts) owns + * validation, limits, formatting, and authorization; the backend owns + * no policy. + */ +export interface DiskhoundAgentBackend { + readonly platform: NodeJS.Platform; + readonly appVersion: string; + /** 1000 or 1024, from Settings โ†’ General โ†’ size units. Defaults to 1024. */ + sizeUnitBase?(): 1000 | 1024; + + listDrives(): Promise; + /** Roots with an in-flight scan, plus the live snapshot for each. */ + activeScans(): Promise; + /** Every root that has at least one completed scan in history. */ + scannedRoots(): ScanHistoryEntry[]; + /** Newest-first history for one root. */ + scanHistory(rootPath: string): ScanHistoryEntry[]; + latestSnapshot(rootPath: string): Promise; + /** The root the window is showing right now, if any. */ + currentRoot(): Promise; + /** The tab and root the main window reported last (null before it loads). */ + windowView?(): WindowViewState | null; + + folderChildren(rootPath: string, parentPath: string): Promise; + searchIndex(rootPath: string, query: IndexSearchQuery): Promise; + cleanupSuggestions(rootPath: string): Promise; + devArtifacts(rootPath: string): Promise; + diff(baselineId: string, currentId: string): Promise; + fullDiff(baselineId: string, currentId: string, limit: number): Promise; + duplicates(rootPath: string): DuplicateState; + + startScan(rootPath: string): Promise; + cancelScan(rootPath: string): Promise; + startDuplicateScan(rootPath: string, minSizeBytes?: number): void; + + navigate(request: NavigateRequest): Promise; + revealPath(targetPath: string): Promise; + /** + * Walk the paths now and say what removing them together frees, with + * APFS clones and hardlinks counted once. Missing on Windows, where the + * scan already counts each file once. + */ + measureRemoval?(paths: readonly string[], signal?: AbortSignal): Promise; + /** + * Show a native confirmation dialog in DiskHound and, only if the + * user accepts, move each path to the Trash / Recycle Bin through the + * same protected-folder checks the UI uses. Throws when none of the + * paths can be offered (missing, or refused for agents). + */ + confirmAndTrash(request: TrashRequest): Promise; + /** + * Same checks and a sterner confirmation, then delete each path + * permanently (not to the Trash) with DiskHound's own delete. + */ + confirmAndDelete(request: TrashRequest): Promise; +} + +export interface FolderChildren { + /** Visible directories before the backend caps its result. */ + visibleDirCount: number; + dirs: { path: string; size: number; fileCount: number }[]; + files: ScanFileRecord[]; + totalSize: number; + totalItemCount: number; + hiddenExcludedCount: number; + hiddenExcludedBytes: number; +} + +export interface DuplicateState { + running: boolean; + progress: DuplicateScanProgress | null; + analysis: DuplicateAnalysis | null; +} + +export interface NavigateRequest { + view: AppView; + rootPath?: string; + folderPath?: string; + /** Bring the window to the front. Off by default so agents don't steal focus. */ + focus?: boolean; + /** With view 'settings', a section to scroll to. */ + section?: "ai-agents"; +} + +export interface TrashRequest { + sessionId: string; + sessionName: string; + roleName: string; + paths: string[]; + reason?: string; + /** + * Throws if the session may no longer trash. Requests queue behind + * each other's dialogs, so the user may revoke the session (or change + * its role) before this one's dialog would appear. + */ + recheck?: () => Promise; + /** Aborted when the agent's request goes away or the MCP server stops. */ + signal?: AbortSignal; +} + +export interface TrashOutcome { + confirmed: boolean; + results: { path: string; ok: boolean; message: string; sizeBytes: number | null }[]; +} + +/** Sink for the Settings "Recent agent actions" feed + header pill. */ +export interface AgentActivitySink { + record(entry: Omit): void; +} diff --git a/src/mcp/claudeExtension.ts b/src/mcp/claudeExtension.ts new file mode 100644 index 00000000..67ad2bfb --- /dev/null +++ b/src/mcp/claudeExtension.ts @@ -0,0 +1,129 @@ +import * as FS from "node:fs/promises"; +import * as Path from "node:path"; +import { promisify } from "node:util"; +import * as Zlib from "node:zlib"; + +import { AGENT_ACCESS_PORT, MCP_SERVER_NAME } from "../shared/agentAccess"; + +const deflateRaw = promisify(Zlib.deflateRaw); + +/** + * Claude Desktop adds local MCP servers from MCP Bundles (.mcpb, + * https://github.com/modelcontextprotocol/mcpb): a zip holding a + * manifest.json and the server. Opening one in Claude shows Claude's own + * install dialog, so DiskHound never edits Claude's configuration. + * + * The bundle carries a copy of the stdio helper, which Claude runs from + * its extensions folder. DiskHound builds it from its own helper when the + * user asks, so the copy matches the app that made it. + */ +export function claudeExtensionManifest(version: string, port: number, platform: NodeJS.Platform, icon: boolean) { + const binary = platform === "win32" ? "diskhound-mcp.exe" : "diskhound-mcp"; + return { + manifest_version: "0.2", + name: MCP_SERVER_NAME, + display_name: "DiskHound", + version, + description: "Let Claude see what is using your disk and help clean it up, with DiskHound open alongside.", + long_description: "Connects Claude to the DiskHound app on this computer. DiskHound asks you to approve the connection, " + + "and the role you choose there decides what Claude can do: read scan results, run scans, or move files to the Trash. " + + "DiskHound must be running with Settings > AI Agents turned on.", + author: { name: "DiskHound" }, + homepage: "https://github.com/tzarebczan/diskhound", + ...(icon ? { icon: "icon.png" } : {}), + server: { + type: "binary", + entry_point: `server/${binary}`, + mcp_config: { + command: `\${__dirname}/server/${binary}`, + args: port === AGENT_ACCESS_PORT ? [] : ["--port", String(port)], + env: {}, + }, + }, + // The tools depend on the role the user grants, after approval. + tools_generated: true, + compatibility: { platforms: [platform] }, + license: "MIT", + }; +} + +export interface ZipEntry { + name: string; + data: Buffer; + /** Unix mode bits, so the helper stays executable once Claude unpacks it. */ + mode: number; +} + +/** A deflated zip, without zip64: a bundle is a few MB. */ +export async function zip(entries: readonly ZipEntry[], at = new Date()): Promise { + const time = (at.getHours() << 11) | (at.getMinutes() << 5) | (at.getSeconds() >> 1); + const date = ((at.getFullYear() - 1980) << 9) | ((at.getMonth() + 1) << 5) | at.getDate(); + const locals: Buffer[] = []; + const centrals: Buffer[] = []; + let offset = 0; + for (const entry of entries) { + const name = Buffer.from(entry.name, "utf8"); + const data = await deflateRaw(entry.data); + const crc = Zlib.crc32(entry.data); + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); // version needed: deflate + local.writeUInt16LE(0x0800, 6); // UTF-8 names + local.writeUInt16LE(8, 8); // deflate + local.writeUInt16LE(time, 10); + local.writeUInt16LE(date, 12); + local.writeUInt32LE(crc, 14); + local.writeUInt32LE(data.length, 18); + local.writeUInt32LE(entry.data.length, 22); + local.writeUInt16LE(name.length, 26); + const central = Buffer.alloc(46); + central.writeUInt32LE(0x02014b50, 0); + central.writeUInt16LE((3 << 8) | 20, 4); // made by Unix, so unzip honors the mode + central.writeUInt16LE(20, 6); + central.writeUInt16LE(0x0800, 8); + central.writeUInt16LE(8, 10); + central.writeUInt16LE(time, 12); + central.writeUInt16LE(date, 14); + central.writeUInt32LE(crc, 16); + central.writeUInt32LE(data.length, 20); + central.writeUInt32LE(entry.data.length, 24); + central.writeUInt16LE(name.length, 28); + central.writeUInt32LE(((0o100000 | entry.mode) << 16) >>> 0, 38); // regular file + mode + central.writeUInt32LE(offset, 42); + locals.push(local, name, data); + centrals.push(central, name); + offset += local.length + name.length + data.length; + } + const directory = Buffer.concat(centrals); + const end = Buffer.alloc(22); + end.writeUInt32LE(0x06054b50, 0); + end.writeUInt16LE(entries.length, 8); + end.writeUInt16LE(entries.length, 10); + end.writeUInt32LE(directory.length, 12); + end.writeUInt32LE(offset, 16); + return Buffer.concat([...locals, directory, end]); +} + +export interface ClaudeExtensionSource { + helperPath: string; + iconPath: string | null; + version: string; + port: number; + platform: NodeJS.Platform; +} + +/** Build DiskHound's Claude extension from its own helper and write it to `file`. */ +export async function writeClaudeExtension(file: string, source: ClaudeExtensionSource): Promise { + const [helper, icon] = await Promise.all([ + FS.readFile(source.helperPath), + source.iconPath ? FS.readFile(source.iconPath).catch(() => null) : null, + ]); + const manifest = claudeExtensionManifest(source.version, source.port, source.platform, icon !== null); + const bundle = await zip([ + { name: "manifest.json", data: Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`), mode: 0o644 }, + ...(icon ? [{ name: "icon.png", data: icon, mode: 0o644 }] : []), + { name: manifest.server.entry_point, data: helper, mode: 0o755 }, + ]); + await FS.mkdir(Path.dirname(file), { recursive: true }); + await FS.writeFile(file, bundle); +} diff --git a/src/mcp/consentBroker.ts b/src/mcp/consentBroker.ts new file mode 100644 index 00000000..7c6d5052 --- /dev/null +++ b/src/mcp/consentBroker.ts @@ -0,0 +1,274 @@ +import { randomUUID } from "node:crypto"; + +import { + BUILT_IN_MCP_ROLES, + DEFAULT_CONSENT_ROLE_ID, + type AgentConsentDecision, + type AgentConsentPrompt, + type AgentConsentState, + type AgentPendingApproval, +} from "../shared/agentAccess"; +import type { ConsentDecision, RequestConsent } from "./agentOAuth"; + +/** The slice of a BrowserWindow the broker needs (kept small for tests). */ +export interface ConsentWindow { + readonly webContentsId: number; + onClosed(listener: () => void): void; + close(): void; + isDestroyed(): boolean; + /** Bring the sheet (and the window it's attached to) to the front. */ + focus?(): void; + /** Push a state change to the approval UI. */ + send?(channel: string, payload: unknown): void; +} + +/** Who sent an IPC message: the webContents id and whether it was the main frame. */ +export interface ConsentSender { + webContentsId: number; + isMainFrame: boolean; +} + +interface Pending { + prompt: AgentConsentPrompt; + requestedAt: number; + stale: boolean; + clientWaiting: () => boolean; + /** Set once this request's approval window exists. */ + window: ConsentWindow | null; + finish: (decision: ConsentDecision) => void; +} + +const MAX_PENDING = 8; +const STALE_CHECK_MS = 2_000; +export const AGENT_CONSENT_STATE_CHANNEL = "diskhound:agent-consent-state"; + +/** + * Native approval for agent logins, ported from PwrGit's ConsentBroker. + * + * Only the main frame of the window created for a request can read or + * decide it. Request ids, the browser waiting page, and the main + * DiskHound window confer no authority. Closing the window, or the + * OAuth request expiring, is a deny. + * + * Requests are shown one at a time, in order, as a sheet on the main + * window; the rest wait in `pending()` so Settings can list them. While + * one is up, the broker checks every 2 s whether the agent is still + * waiting for the answer and tells the sheet when it isn't (a client + * that timed out can't receive an approval). + */ +export class ConsentBroker { + private readonly pendingById = new Map(); + private readonly queue: string[] = []; + private showing: string | null = null; + private staleTimer: ReturnType | null = null; + + constructor( + private readonly createWindow: () => ConsentWindow | Promise, + private readonly activeSessionNames: () => string[], + private readonly onChanged: () => void = () => {}, + ) {} + + request: RequestConsent = async ({ clientName, via, scopes, signal, clientWaiting }) => { + const denied: ConsentDecision = { decision: "deny", sessionName: "", roleId: "" }; + if (signal.aborted || this.pendingById.size >= MAX_PENDING) return denied; + // Offer only roles that fit inside what the agent asked for, so the + // user can never grant more than the client requested. + const roles = BUILT_IN_MCP_ROLES.filter((role) => role.permissions.every((p) => scopes.includes(p))); + const names = new Set([ + ...this.activeSessionNames(), + ...[...this.pendingById.values()].map((pending) => pending.prompt.sessionName), + ]); + const base = clientName.slice(0, 180); + let sessionName = base; + for (let suffix = 2; names.has(sessionName); suffix++) sessionName = `${base} ${suffix}`; + const defaultRoleId = roles.some((role) => role.id === DEFAULT_CONSENT_ROLE_ID) + ? DEFAULT_CONSENT_ROLE_ID + : roles[roles.length - 1]?.id ?? ""; + const prompt: AgentConsentPrompt = { + requestId: randomUUID(), + clientName, + via, + sessionName, + requestedScopes: [...scopes], + roles: roles.map((role) => ({ ...role, permissions: [...role.permissions] })), + defaultRoleId, + }; + return new Promise((resolve) => { + const id = prompt.requestId; + const abort = () => finish(denied); + const finish = (decision: ConsentDecision) => { + const pending = this.pendingById.get(id); + if (!pending) return; + this.pendingById.delete(id); + const queued = this.queue.indexOf(id); + if (queued >= 0) this.queue.splice(queued, 1); + signal.removeEventListener("abort", abort); + resolve(decision); + if (pending.window && !pending.window.isDestroyed()) pending.window.close(); + if (this.showing === id) { + this.showing = null; + void this.showNext(); + } else { + this.pushShowingState(); + } + this.onChanged(); + }; + this.pendingById.set(id, { + prompt, + requestedAt: Date.now(), + stale: false, + clientWaiting, + window: null, + finish, + }); + signal.addEventListener("abort", abort, { once: true }); + this.queue.push(id); + this.onChanged(); + this.pushShowingState(); + if (signal.aborted) abort(); + else void this.showNext(); + }); + }; + + /** Open the approval sheet for the oldest waiting request, if none is up. */ + private async showNext(): Promise { + if (this.showing !== null) return; + const id = this.queue.shift(); + if (id === undefined) { + this.stopStaleChecks(); + return; + } + const pending = this.pendingById.get(id); + if (!pending) return this.showNext(); + this.showing = id; + let window: ConsentWindow; + try { + window = await this.createWindow(); + } catch { + pending.finish({ decision: "deny", sessionName: "", roleId: "" }); + return; + } + // Decided or aborted while the window was being made. + if (!this.pendingById.has(id)) { + if (!window.isDestroyed()) window.close(); + return; + } + pending.window = window; + window.onClosed(() => pending.finish({ decision: "deny", sessionName: "", roleId: "" })); + this.startStaleChecks(); + } + + /** The client whose request is shown after the current one. */ + private nextClientName(): string | null { + for (const id of this.queue) { + const pending = this.pendingById.get(id); + if (pending) return pending.prompt.clientName; + } + return null; + } + + private stateOf(pending: Pending): AgentConsentState { + return { requestId: pending.prompt.requestId, stale: pending.stale, next: this.nextClientName() }; + } + + /** Tell the sheet on screen that the queue behind it changed. */ + private pushShowingState(): void { + const pending = this.showing ? this.pendingById.get(this.showing) : undefined; + if (pending?.window) pending.window.send?.(AGENT_CONSENT_STATE_CHANNEL, this.stateOf(pending)); + } + + private startStaleChecks(): void { + if (this.staleTimer) return; + this.staleTimer = setInterval(() => this.checkStale(), STALE_CHECK_MS); + this.staleTimer.unref?.(); + } + + private stopStaleChecks(): void { + if (!this.staleTimer) return; + clearInterval(this.staleTimer); + this.staleTimer = null; + } + + /** Exposed for tests; the timer calls it every 2 s while a request waits. */ + checkStale(): void { + let changed = false; + for (const pending of this.pendingById.values()) { + const stale = !pending.clientWaiting(); + if (stale === pending.stale) continue; + pending.stale = stale; + changed = true; + pending.window?.send?.(AGENT_CONSENT_STATE_CHANNEL, this.stateOf(pending)); + } + if (changed) this.onChanged(); + if (this.pendingById.size === 0) this.stopStaleChecks(); + } + + private trusted(sender: ConsentSender): Pending | undefined { + if (!sender.isMainFrame) return undefined; + return [...this.pendingById.values()].find( + (pending) => pending.window !== null && pending.window.webContentsId === sender.webContentsId, + ); + } + + read(sender: ConsentSender): (AgentConsentPrompt & Omit) | null { + const pending = this.trusted(sender); + if (!pending) return null; + const { stale, next } = this.stateOf(pending); + return { ...pending.prompt, stale, next }; + } + + decide(sender: ConsentSender, request: AgentConsentDecision): { ok: boolean; message?: string } { + const pending = this.trusted(sender); + if (!pending || request?.requestId !== pending.prompt.requestId) { + return { ok: false, message: "Approval is only available in the DiskHound window that asked for it." }; + } + if (request.decision !== "allow" && request.decision !== "deny") { + return { ok: false, message: "Unknown decision." }; + } + if (request.decision === "allow" && ( + typeof request.sessionName !== "string" || + !request.sessionName.trim() || + request.sessionName.trim().length > 200 || + !pending.prompt.roles.some((role) => role.id === request.roleId) + )) { + return { ok: false, message: "Enter a Session name and choose one of the offered roles." }; + } + pending.finish({ decision: request.decision, sessionName: request.sessionName, roleId: request.roleId }); + return { ok: true }; + } + + /** Requests waiting for the user, oldest first (the one on screen first). */ + pending(): AgentPendingApproval[] { + return [...this.pendingById.values()] + .sort((a, b) => a.requestedAt - b.requestedAt) + .map((pending) => ({ + requestId: pending.prompt.requestId, + clientName: pending.prompt.clientName, + via: pending.prompt.via, + requestedAt: pending.requestedAt, + stale: pending.stale, + })); + } + + /** Bring the sheet for the request on screen to the front. */ + focus(): boolean { + const pending = this.showing ? this.pendingById.get(this.showing) : undefined; + if (!pending?.window || pending.window.isDestroyed()) return false; + pending.window.focus?.(); + return true; + } + + /** Deny one waiting request, e.g. from Settings. */ + dismiss(requestId: string): void { + this.pendingById.get(requestId)?.finish({ decision: "deny", sessionName: "", roleId: "" }); + } + + close(): void { + // Nothing queued may open a sheet while the rest are denied. + this.queue.length = 0; + for (const pending of [...this.pendingById.values()]) { + pending.finish({ decision: "deny", sessionName: "", roleId: "" }); + } + this.stopStaleChecks(); + } +} diff --git a/src/mcp/electronHost.ts b/src/mcp/electronHost.ts new file mode 100644 index 00000000..ef8e849c --- /dev/null +++ b/src/mcp/electronHost.ts @@ -0,0 +1,785 @@ +import * as FS from "node:fs/promises"; +import { createRequire } from "node:module"; +import * as OS from "node:os"; +import * as Path from "node:path"; + +import { app, BrowserWindow, dialog, ipcMain, shell } from "electron"; + +import type { + AppSettings, + CleanupAnalysis, + DevArtifactReport, + DiskSpaceInfo, + DuplicateAnalysis, + DuplicateScanProgress, + FullDiffResult, + IndexSearchQuery, + IndexSearchResult, + NavigateViewPayload, + PathActionResult, + ScanDiffResult, + ScanHistoryEntry, + ScanSnapshot, + ToastMessage, + WindowViewState, +} from "../shared/contracts"; +import { + AGENT_ACCESS_PORT, + BUILT_IN_MCP_ROLES, + MCP_SERVER_NAME, + agentAccessMcpUrl, + type AddToClaudeResult, + type AgentAccessSnapshot, + type AgentAccessStatus, + type AgentConsentDecision, +} from "../shared/agentAccess"; +import { normPath } from "../shared/pathUtils"; +import { powerEfficiencyWorkers } from "../shared/powerEfficiency"; +import { formatSizeBytes, resolveSizeUnitBase } from "../shared/sizeUnits"; +import { McpPolicyStore } from "./accessPolicy"; +import type { AgentAccessService } from "./agentAccessService"; +import { AgentActivityLog } from "./activityLog"; +import type { DiskhoundAgentBackend, FolderChildren, NavigateRequest, TrashOutcome, TrashRequest } from "./backend"; +import { writeClaudeExtension } from "./claudeExtension"; +import { ConsentBroker, type ConsentWindow } from "./consentBroker"; +import { resolveNativeScannerBinary } from "../nativeScanner"; +import { isInside } from "./paths"; +import { nativeRemovalMeasurer, RemovalMeasurements } from "./removalMeasure"; +import { AgentSecurityLog } from "./securityLog"; +import type { SkillCatalog } from "./skills"; +import { agentTrashRefusal, canonicalPath, configuredTrashGuard, outermostPaths } from "./trashGuard"; + +const NAVIGATE_VIEW_CHANNEL = "diskhound:navigate-view"; +const PATHS_TRASHED_CHANNEL = "diskhound:paths-trashed"; +const PATHS_DELETED_CHANNEL = "diskhound:paths-deleted"; +const AGENT_ACCESS_CHANGED_CHANNEL = "diskhound:agent-access-changed"; +const AGENT_ACTIVITY_CHANNEL = "diskhound:agent-activity"; +const AGENT_SECURITY_CHANNEL = "diskhound:agent-security"; + +/** + * The closures from main.ts that the agent host needs. main.ts owns + * the scan pipeline and its caches; this module only adapts them to + * the MCP backend contract and adds the Electron-specific pieces + * (approval window, trash confirmation, navigation, Settings IPC). + */ +export interface AgentHostDeps { + projectRoot: string; + preloadPath: string; + getMainWindow(): BrowserWindow | null; + ensureMainWindow(): Promise; + loadRenderer(window: BrowserWindow, mode: "consent"): Promise; + getSettings(): AppSettings; + setAgentsEnabled(enabled: boolean): Promise; + toast(level: ToastMessage["level"], title: string, body?: string): void; + log(tag: string, message: string): void; + + listDrives(): Promise; + activeScans(): ScanSnapshot[]; + currentSnapshotRoot(): Promise; + allHistory(): ScanHistoryEntry[]; + scanHistory(rootPath: string): ScanHistoryEntry[]; + loadSnapshot(id: string): Promise; + startScan(rootPath: string): Promise; + cancelScan(rootPath: string): Promise; + folderChildren(rootPath: string, parentPath: string): Promise; + searchIndex(rootPath: string, query: IndexSearchQuery): Promise; + cleanupSuggestions(rootPath: string): Promise; + devArtifacts(rootPath: string): Promise; + diff(baselineId: string, currentId: string): Promise; + fullDiff(baselineId: string, currentId: string, limit: number): Promise; + duplicates(rootPath: string): { running: boolean; progress: DuplicateScanProgress | null; analysis: DuplicateAnalysis | null }; + startDuplicateScan(rootPath: string, minSizeBytes?: number): void; + trashPath(targetPath: string): Promise; + /** DiskHound's own permanent delete (worker for folders), as the UI uses it. */ + permanentDeletePath(targetPath: string): Promise; +} + +export interface AgentHost { + /** Start the MCP server if Settings has AI Agents on. */ + start(): Promise; + /** Open Settings โ†’ AI Agents in the main window (menus, tray). */ + showSettings(): Promise; + /** Files were removed from the UI: removal measurements are stale. */ + pathsRemoved(): void; + dispose(): Promise; +} + +function skillsDirectory(projectRoot: string): string { + // Packaged: electron-builder copies skills/ to resources/skills (plain + // files, not inside app.asar). Dev: the repo checkout. + return app.isPackaged ? Path.join(process.resourcesPath, "skills") : Path.join(projectRoot, "skills"); +} + +type AgentRuntime = typeof import("./agentRuntime"); + +/** + * Require the separately bundled runtime by path. A static import would + * make the bundler inline it (and hoist the SDK/Express requires to the + * top of main.cjs, where they'd load on every launch). + */ +function loadAgentRuntime(): AgentRuntime { + const runtimePath = Path.join(__dirname, "mcp", "agentRuntime.cjs"); + return createRequire(__filename)(runtimePath) as AgentRuntime; +} + +function trashName(): string { + return process.platform === "win32" ? "Recycle Bin" : "Trash"; +} + +/** + * Folders an agent may never move to the Trash, nor anything containing + * them: the home folder and its standard folders, the folder holding + * every user's home, DiskHound's data, and the app itself. + */ +async function keepFolders(): Promise { + const names = ["home", "desktop", "documents", "downloads", "music", "pictures", "videos", "appData", "userData"] as const; + const folders: string[] = []; + for (const name of names) { + try { + folders.push(app.getPath(name)); + } catch { + /* not defined on this OS */ + } + } + const home = app.getPath("home"); + folders.push(Path.dirname(home), Path.dirname(app.getPath("exe"))); + if (process.platform === "darwin") folders.push(Path.join(home, "Library"), "/Applications"); + if (process.platform === "win32") folders.push(Path.join(home, "AppData")); + return Promise.all(folders.map((folder) => canonicalPath(folder).catch(() => folder))); +} + +/** + * DISKHOUND_AGENT_PORT moves the MCP server off 51735. The E2E suite + * gives each launch its own port, so it never collides with a DiskHound + * the developer runs with agents turned on. + */ +function agentAccessPort(): number { + const raw = process.env.DISKHOUND_AGENT_PORT?.trim(); + if (!raw) return AGENT_ACCESS_PORT; + const port = Number(raw); + return Number.isInteger(port) && port > 0 && port < 65536 ? port : AGENT_ACCESS_PORT; +} + +/** + * Registers the agent IPC handlers right away (the renderer asks for + * agent state as soon as it mounts). The MCP server itself starts in + * `start()`, after the main window is up. + */ +export function createAgentHost(deps: AgentHostDeps): AgentHost { + const userData = app.getPath("userData"); + const policy = new McpPolicyStore(Path.join(userData, "mcp-policy.json")); + const clientsFile = Path.join(userData, "mcp-oauth-clients.json"); + const port = agentAccessPort(); + + const mainWindowSend = (channel: string, payload: unknown) => { + const main = deps.getMainWindow(); + if (!main || main.isDestroyed()) return; + try { + main.webContents.send(channel, payload); + } catch { + /* best effort */ + } + }; + + let viewState: WindowViewState | null = null; + // The main window's renderer is listening once it reports its view + // (App's mount effect). Navigation sent before that is held until then, + // e.g. when an agent's call recreated the window from the tray. + let readyRendererId: number | null = null; + let pendingNavigation: NavigateViewPayload | null = null; + ipcMain.on("diskhound:report-view-state", (event, state: WindowViewState) => { + const main = deps.getMainWindow(); + if (!main || event.sender.id !== main.webContents.id) return; + viewState = state && typeof state.view === "string" ? state : null; + readyRendererId = event.sender.id; + if (pendingNavigation) { + const payload = pendingNavigation; + pendingNavigation = null; + mainWindowSend(NAVIGATE_VIEW_CHANNEL, payload); + } + }); + + const activity = new AgentActivityLog((entry) => mainWindowSend(AGENT_ACTIVITY_CHANNEL, entry)); + + // What agents tried and weren't allowed to do. Read from disk only once + // agents have been turned on (never while the feature is unused). + const security = new AgentSecurityLog({ + file: Path.join(userData, "agent-security.log"), + onEvent: (event, { repeated, logged }) => { + mainWindowSend(AGENT_SECURITY_CHANNEL, event); + if (repeated) return; + if (logged) deps.log("agent-security", `${event.kind} session="${event.sessionName}" tool=${event.tool} ${event.detail}`); + if (event.tool === "diskhound_move_to_trash" || event.tool === "diskhound_delete_permanently") { + deps.toast("warning", `Blocked a request from ${event.sessionName}`, event.detail); + } + }, + }); + let securityLoaded = false; + const loadSecurityEvents = async () => { + if (securityLoaded) return; + securityLoaded = true; + await security.list(); + }; + + // โ”€โ”€ Backend โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + /** Latest scan (newest first) per distinct root. */ + const scannedRoots = (): ScanHistoryEntry[] => { + const newest = new Map(); + for (const entry of deps.allHistory()) { + const key = normPath(entry.rootPath); + const current = newest.get(key); + if (!current || entry.scannedAt > current.scannedAt) newest.set(key, entry); + } + return [...newest.values()].sort((a, b) => b.scannedAt - a.scannedAt); + }; + + const navigate = async (request: NavigateRequest) => { + await deps.ensureMainWindow(); + const main = deps.getMainWindow(); + if (!main || main.isDestroyed()) return; + if (request.focus) { + if (!main.isVisible()) main.show(); + if (main.isMinimized()) main.restore(); + main.focus(); + } else if (!main.isVisible()) { + // Hidden to the tray: show it, but leave focus with the agent's terminal. + main.showInactive(); + } + const payload: NavigateViewPayload = { + view: request.view, + ...(request.rootPath ? { scanRoot: request.rootPath } : {}), + ...(request.folderPath ? { folderPath: request.folderPath } : {}), + ...(request.section ? { section: request.section } : {}), + }; + if (readyRendererId === main.webContents.id && !main.webContents.isLoading()) { + mainWindowSend(NAVIGATE_VIEW_CHANNEL, payload); + } else { + pendingNavigation = payload; + } + }; + + /** Size DiskHound recorded for a path, from the folder tree of its scan. */ + const recordedSize = async (target: string): Promise => { + const root = scannedRoots() + .map((entry) => entry.rootPath) + .filter((candidate) => isInside(candidate, target)) + .sort((a, b) => b.length - a.length)[0]; + if (root && normPath(root) !== normPath(target)) { + try { + const children = await deps.folderChildren(root, Path.dirname(target)); + const key = normPath(target); + const dir = children.dirs.find((d) => normPath(d.path) === key); + if (dir) return dir.size; + const file = children.files.find((f) => normPath(f.path) === key); + if (file) return file.size; + } catch { + /* fall through */ + } + } + try { + const stat = await FS.lstat(target); + if (!stat.isDirectory()) return process.platform === "win32" ? stat.size : stat.blocks * 512; + } catch { + /* missing */ + } + return null; + }; + + /** The units the window shows, so the dialog's sizes match it. */ + const sizeUnitBase = () => resolveSizeUnitBase(deps.getSettings().general.sizeUnits, process.platform); + const formatSize = (bytes: number | null) => { + if (bytes === null) return "size unknown"; + if (bytes <= 0) return "0 B"; + return formatSizeBytes(bytes, sizeUnitBase()); + }; + + const refusedText = (why: string | null) => (why ? `Refused: ${why}.` : null); + const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`; + + // One confirmation dialog at a time; later requests queue behind it. + let removalTail: Promise = Promise.resolve(); + const confirmAndRemove = (request: TrashRequest, mode: "trash" | "delete"): Promise => { + const verb = mode === "trash" ? "moved" : "deleted"; + const hungUp = () => + new Error(`The agent's request closed before DiskHound asked the user. Nothing was ${verb}.`); + const run = async (): Promise => { + // This request may have waited behind other dialogs. If the agent + // hung up, the server stopped, or the user revoked the session or + // changed its role meanwhile, don't ask on its behalf. + if (request.signal?.aborted) throw hungUp(); + await request.recheck?.(); + + // Resolve each path to its on-disk spelling so the protected-folder + // check (a string compare in main) sees what would actually move. + const keep = await keepFolders(); + const protectedFolder = await configuredTrashGuard(deps.getSettings().scanning.excludedFolderPaths); + const refused: TrashOutcome["results"] = []; + const offered: string[] = []; + for (const requested of request.paths) { + let target: string; + try { + target = await canonicalPath(requested); + } catch { + refused.push({ path: requested, ok: false, message: "Nothing exists at this path.", sizeBytes: null }); + continue; + } + const why = protectedFolder(requested, target) ?? agentTrashRefusal(target, keep); + if (why) { + refused.push({ path: target, ok: false, message: `Refused: ${why}.`, sizeBytes: null }); + security.record({ + sessionId: request.sessionId, + sessionName: request.sessionName, + roleName: request.roleName, + kind: "protected_path", + tool: mode === "trash" ? "diskhound_move_to_trash" : "diskhound_delete_permanently", + detail: `Asked to ${mode === "trash" ? `move ${target} to the ${trashName()}` : `delete ${target} permanently`}; refused: ${why.replace(/\.$/, "")}.`, + }); + } else { + offered.push(target); + } + } + const targets = outermostPaths(offered); + if (targets.length === 0) { + throw new Error(`Nothing to ask the user about. ${refused.map((r) => `${r.path}: ${r.message}`).join(" ")}`); + } + + const sizes = await Promise.all(targets.map((p) => recordedSize(p))); + await deps.ensureMainWindow(); + const main = deps.getMainWindow(); + if (!main || main.isDestroyed()) return { confirmed: false, results: [] }; + if (!main.isVisible()) main.show(); + if (main.isMinimized()) main.restore(); + if (process.platform === "darwin") app.focus({ steal: true }); + main.focus(); + + // Paths outside every scan have no recorded folder size. + const known = sizes.filter((size): size is number => size !== null); + const total = known.reduce((sum, size) => sum + size, 0); + const totalText = known.length === 0 ? "" : ` (${known.length < sizes.length ? "at least " : ""}${formatSize(total)})`; + // Every item, never "โ€ฆand N more": the server caps a request at 20. + const listed = targets.map((p, i) => `โ€ข ${p} (${formatSize(sizes[i] ?? null)})`); + // The user should know what else the agent asked for, and why it isn't here. + const skipped = refused.length === 0 + ? "" + : `\n\nNot included:\n${refused.map((r) => `โ€ข ${r.path}: ${r.message.replace(/^Refused: /, "")}`).join("\n")}`; + const bin = trashName(); + const { response } = await dialog.showMessageBox(main, mode === "trash" + ? { + type: "warning", + title: "DiskHound โ€” agent request", + message: `โ€œ${request.sessionName}โ€ wants to move ${plural(targets.length, "item")}${totalText} to the ${bin}.`, + detail: + (request.reason ? `Reason: ${request.reason}\n\n` : "") + + `${listed.join("\n")}${skipped}\n\nYou can restore items from the ${bin} until it is emptied.`, + buttons: [`Move to ${bin}`, "Cancel"], + defaultId: 1, + cancelId: 1, + noLink: true, + // Closes the dialog (as Cancel) if the agent hangs up or agents are turned off. + signal: request.signal, + } + : { + type: "warning", + title: "DiskHound โ€” agent request", + message: `โ€œ${request.sessionName}โ€ wants to permanently delete ${plural(targets.length, "item")}${totalText}.`, + detail: + (request.reason ? `Reason: ${request.reason}\n\n` : "") + + `${listed.join("\n")}${skipped}\n\nThese won't go to the ${bin}. Deleted items can't be restored.`, + buttons: ["Delete Permanently", "Cancel"], + defaultId: 1, + cancelId: 1, + noLink: true, + signal: request.signal, + }); + if (request.signal?.aborted) throw hungUp(); + if (response !== 0) { + deps.log(`agent-${mode}`, `declined session="${request.sessionName}" paths=${targets.length}`); + return { confirmed: false, results: [] }; + } + // The session's role, Settings and the paths themselves may have + // changed while the confirmation was open. Check everything again: + // a folder above a target swapped for a link would otherwise send + // the removal somewhere the user never saw. + await request.recheck?.(); + const results: TrashOutcome["results"] = [...refused]; + const currentProtection = await configuredTrashGuard(deps.getSettings().scanning.excludedFolderPaths); + const currentKeep = await keepFolders(); + for (const [index, target] of targets.entries()) { + const now = await canonicalPath(target).catch(() => null); + const blocked = now === null + ? "Nothing exists at this path any more." + : now !== target + ? "This path changed after you confirmed, so DiskHound left it alone." + : currentProtection(target, target) ?? refusedText(agentTrashRefusal(target, currentKeep)); + const result = blocked + ? { ok: false, message: blocked } + : mode === "trash" + ? await deps.trashPath(target) + : await deps.permanentDeletePath(target); + results.push({ path: target, ok: result.ok, message: result.message, sizeBytes: sizes[index] ?? null }); + } + const done = results.filter((r) => r.ok); + if (done.length > 0) measurements?.invalidate(); + deps.log(`agent-${mode}`, `session="${request.sessionName}" ${verb}=${done.length}/${results.length}`); + if (done.length > 0) { + mainWindowSend(mode === "trash" ? PATHS_TRASHED_CHANNEL : PATHS_DELETED_CHANNEL, done.map((r) => r.path)); + const known = done.flatMap((r) => (r.sizeBytes === null ? [] : [r.sizeBytes])); + const freedBytes = known.reduce((s, size) => s + size, 0); + // Paths outside every scan have no size: never claim "0 B" for them. + const freed = known.length === 0 + ? null + : `${known.length < done.length ? "at least " : ""}${formatSize(freedBytes)}`; + deps.toast( + "success", + mode === "trash" + ? `Moved ${plural(done.length, "item")} to the ${bin}` + : `Deleted ${plural(done.length, "item")} permanently`, + mode === "trash" + ? `Requested by ${request.sessionName}. Empty the ${bin} to free ${freed ?? "the space"}.` + : `Requested by ${request.sessionName}.${freed ? ` Freed ${freed}.` : ""}`, + ); + } + return { confirmed: true, results }; + }; + const operation = removalTail.then(run, run); + removalTail = operation.catch(() => undefined); + return operation; + }; + + // What removing paths frees, measured by the native scanner (APFS + // clones and hardlinks). Windows scans already count each file once. + let measurements: RemovalMeasurements | null = null; + const measureRemoval = async (paths: readonly string[], signal?: AbortSignal) => { + if (!measurements) { + const binary = resolveNativeScannerBinary(deps.projectRoot); + if (!binary) { + throw new Error("DiskHound's scanner is missing, so it can't measure. Reinstall DiskHound, or in a source checkout build native/diskhound-native-scanner."); + } + measurements = new RemovalMeasurements( + nativeRemovalMeasurer(binary, () => { + const preset = deps.getSettings().scanning.powerEfficiency; + return preset ? powerEfficiencyWorkers(preset, OS.availableParallelism()) : undefined; + }), + ); + } + return measurements.measure(paths, signal); + }; + + const backend: DiskhoundAgentBackend = { + platform: process.platform, + appVersion: app.getVersion(), + sizeUnitBase, + listDrives: () => deps.listDrives(), + activeScans: async () => deps.activeScans(), + scannedRoots, + scanHistory: (rootPath) => deps.scanHistory(rootPath), + latestSnapshot: async (rootPath) => { + const latest = deps.scanHistory(rootPath)[0]; + return latest ? deps.loadSnapshot(latest.id) : null; + }, + currentRoot: async () => viewState?.rootPath ?? (await deps.currentSnapshotRoot()), + windowView: () => (viewState ? { ...viewState } : null), + folderChildren: (rootPath, parentPath) => deps.folderChildren(rootPath, parentPath), + searchIndex: (rootPath, query) => deps.searchIndex(rootPath, query), + cleanupSuggestions: (rootPath) => deps.cleanupSuggestions(rootPath), + devArtifacts: (rootPath) => deps.devArtifacts(rootPath), + diff: (baselineId, currentId) => deps.diff(baselineId, currentId), + fullDiff: (baselineId, currentId, limit) => deps.fullDiff(baselineId, currentId, limit), + duplicates: (rootPath) => deps.duplicates(rootPath), + startScan: (rootPath) => deps.startScan(rootPath), + cancelScan: (rootPath) => deps.cancelScan(rootPath), + startDuplicateScan: (rootPath, minSizeBytes) => deps.startDuplicateScan(rootPath, minSizeBytes), + navigate, + revealPath: async (targetPath) => { + try { + await FS.lstat(targetPath); + } catch { + return { ok: false, message: `Nothing exists at ${targetPath}.` }; + } + shell.showItemInFolder(targetPath); + return { ok: true, message: "Revealed." }; + }, + ...(process.platform === "win32" ? {} : { measureRemoval }), + confirmAndTrash: (request) => confirmAndRemove(request, "trash"), + confirmAndDelete: (request) => confirmAndRemove(request, "delete"), + }; + + // โ”€โ”€ Approval sheet โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + /** + * The approval UI is a sheet on the main window (a modal child window + * elsewhere), so it reads as DiskHound asking and blocks the window + * until the user answers. Its own webContents is what the broker + * trusts; the main window's renderer can't approve anything. + */ + const createConsentWindow = async (): Promise => { + await deps.ensureMainWindow(); + const main = deps.getMainWindow(); + if (!main || main.isDestroyed()) throw new Error("DiskHound's window is not available"); + if (!main.isVisible()) main.show(); + if (main.isMinimized()) main.restore(); + // The agent's login starts in a terminal or browser; pull DiskHound + // forward so the user sees the request. + if (process.platform === "darwin") app.focus({ steal: true }); + main.focus(); + + const width = 560; + const height = 640; + const parentBounds = main.getBounds(); + const window = new BrowserWindow({ + width, + height, + // macOS attaches a modal child as a sheet; elsewhere center it on + // the main window rather than on the screen. + ...(process.platform === "darwin" + ? {} + : { + x: Math.round(parentBounds.x + (parentBounds.width - width) / 2), + y: Math.round(parentBounds.y + Math.max(40, (parentBounds.height - height) / 3)), + }), + parent: main, + modal: true, + show: false, + resizable: false, + title: "DiskHound โ€” Approve agent access", + backgroundColor: "#0a0a0f", + minimizable: false, + maximizable: false, + fullscreenable: false, + webPreferences: { + preload: deps.preloadPath, + contextIsolation: true, + nodeIntegration: false, + sandbox: true, + }, + }); + if (process.platform !== "darwin") window.setMenuBarVisibility(false); + // The approval prompt opens nothing and goes nowhere while it's up. + window.webContents.setWindowOpenHandler(() => ({ action: "deny" })); + window.webContents.on("will-navigate", (event) => event.preventDefault()); + window.once("ready-to-show", () => { + if (window.isDestroyed()) return; + window.show(); + window.focus(); + }); + void deps.loadRenderer(window, "consent").catch((err) => { + deps.log("agent-consent", `load failed: ${err instanceof Error ? err.message : String(err)}`); + // It would never show; closing it denies the request now instead + // of leaving the agent's login waiting out the timeout. + if (!window.isDestroyed()) window.close(); + }); + return { + webContentsId: window.webContents.id, + onClosed: (listener) => window.once("closed", listener), + close: () => window.close(), + isDestroyed: () => window.isDestroyed(), + focus: () => { + if (window.isDestroyed()) return; + const parent = deps.getMainWindow(); + if (parent && !parent.isDestroyed()) { + if (!parent.isVisible()) parent.show(); + if (parent.isMinimized()) parent.restore(); + } + if (process.platform === "darwin") app.focus({ steal: true }); + window.focus(); + }, + send: (channel, payload) => { + if (!window.isDestroyed()) window.webContents.send(channel, payload); + }, + }; + }; + + const broker = new ConsentBroker( + createConsentWindow, + () => policy.sessions().filter((session) => session.revokedAt === null).map((session) => session.name), + () => broadcast(), + ); + + const senderOf = (event: Electron.IpcMainInvokeEvent) => ({ + webContentsId: event.sender.id, + isMainFrame: event.senderFrame === event.sender.mainFrame, + }); + ipcMain.handle("diskhound:agent-consent-read", (event) => broker.read(senderOf(event))); + ipcMain.handle("diskhound:agent-consent-decide", (event, decision: AgentConsentDecision) => + broker.decide(senderOf(event), decision), + ); + + // โ”€โ”€ Service + Settings IPC โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + // The MCP SDK, Express, and the skill catalog load on first enable. + // Requiring them costs ~150 ms, and most users never turn this on. + let service: AgentAccessService | null = null; + let servicePromise: Promise | null = null; + /** Why the runtime didn't load; Settings shows it with Try again. */ + let loadError: string | null = null; + const ensureService = (): Promise => { + servicePromise ??= (async () => { + const { AgentAccessService, loadSkillCatalog } = loadAgentRuntime(); + let skills: SkillCatalog = { skills: [] }; + try { + skills = loadSkillCatalog(skillsDirectory(deps.projectRoot)); + deps.log("agent-access", `loaded ${skills.skills.length} skill(s): ${skills.skills.map((s) => s.name).join(", ")}`); + } catch (err) { + deps.log("agent-access", `skills failed to load: ${err instanceof Error ? err.message : String(err)}`); + } + service = new AgentAccessService({ + backend, + activity, + security, + skills, + policy, + clientsFile, + requestConsent: broker.request, + onChanged: broadcast, + port, + saveEnabled: (enabled) => deps.setAgentsEnabled(enabled), + }); + loadError = null; + return service; + })().catch((err: unknown) => { + servicePromise = null; + loadError = `DiskHound couldn't load agent access: ${err instanceof Error ? err.message : String(err)}`; + broadcast(); + throw err; + }); + return servicePromise; + }; + const status = (): AgentAccessStatus => + service?.status() ?? { + enabled: deps.getSettings().agents.enabled, + listening: false, + mcpUrl: agentAccessMcpUrl(port), + port, + ...(loadError ? { error: loadError } : {}), + }; + // DISKHOUND_MCP_PATH swaps in another helper, as DISKHOUND_NATIVE_SCANNER_PATH does for the scanner. + const stdioPath = () => process.env.DISKHOUND_MCP_PATH?.trim() || Path.join( + app.isPackaged ? Path.join(process.resourcesPath, "native") : Path.join(deps.projectRoot, "native", "diskhound-mcp", "target", "debug"), + process.platform === "win32" ? "diskhound-mcp.exe" : "diskhound-mcp", + ); + const snapshot = (): AgentAccessSnapshot => ({ + status: status(), + roles: BUILT_IN_MCP_ROLES.map((role) => ({ ...role, permissions: [...role.permissions] })), + sessions: (() => { + try { + return policy.sessions(); + } catch { + return []; + } + })(), + activity: activity.list(), + pending: broker.pending(), + security: security.recent(), + policyFile: policy.filePath, + securityLogFile: security.filePath, + stdioPath: stdioPath(), + platform: process.platform, + }); + const broadcast = () => mainWindowSend(AGENT_ACCESS_CHANGED_CHANNEL, snapshot()); + + // Only Settings in the main window reads or changes agent access. The + // widget and approval windows share the preload, so check the sender. + const requireMainWindow = (event: Electron.IpcMainInvokeEvent) => { + const main = deps.getMainWindow(); + if (!main || main.isDestroyed() || event.sender.id !== main.webContents.id || event.senderFrame !== event.sender.mainFrame) { + throw new Error("Agent access is managed from the DiskHound main window."); + } + }; + + ipcMain.handle("diskhound:agent-access-get", async (event) => { + requireMainWindow(event); + // The log on disk is only worth reading once agents are in use. + if (deps.getSettings().agents.enabled || policy.exists()) await loadSecurityEvents(); + return snapshot(); + }); + ipcMain.handle("diskhound:agent-access-set-enabled", async (event, enabled: boolean) => { + requireMainWindow(event); + if (!enabled && !service) { + await deps.setAgentsEnabled(false); + broadcast(); + return snapshot(); + } + await (await ensureService()).setEnabled(Boolean(enabled)); + if (enabled) await loadSecurityEvents(); + return snapshot(); + }); + ipcMain.handle("diskhound:agent-access-revoke", (event, sessionId: string) => { + requireMainWindow(event); + policy.revokeSession(sessionId); + broadcast(); + return snapshot(); + }); + ipcMain.handle("diskhound:agent-access-assign-role", (event, sessionId: string, roleId: string) => { + requireMainWindow(event); + policy.assignRole(sessionId, roleId); + broadcast(); + return snapshot(); + }); + ipcMain.handle("diskhound:agent-access-forget-revoked", (event) => { + requireMainWindow(event); + policy.forgetRevoked(); + broadcast(); + return snapshot(); + }); + ipcMain.handle("diskhound:agent-access-focus-approval", (event) => { + requireMainWindow(event); + return broker.focus(); + }); + ipcMain.handle("diskhound:agent-access-dismiss-approval", (event, requestId: string) => { + requireMainWindow(event); + broker.dismiss(String(requestId)); + return snapshot(); + }); + // Claude Desktop's extension, built from this app's helper and opened + // in Claude, which asks the user to install it. Claude copies it on + // install, so the file in temp only has to last until then. + ipcMain.handle("diskhound:agent-access-add-to-claude", async (event): Promise => { + requireMainWindow(event); + const file = Path.join(app.getPath("temp"), "DiskHound", "DiskHound.mcpb"); + try { + await writeClaudeExtension(file, { + helperPath: stdioPath(), + iconPath: app.isPackaged ? Path.join(process.resourcesPath, "icon.png") : Path.join(deps.projectRoot, "build", "icon.png"), + // Unpackaged, Electron reports its own version. + version: app.isPackaged + ? app.getVersion() + : JSON.parse(await FS.readFile(Path.join(deps.projectRoot, "package.json"), "utf8")).version, + port, + platform: process.platform, + }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + deps.log("agent-access", `couldn't build the Claude extension: ${message}`); + return { + ok: false, + error: (error as NodeJS.ErrnoException).code === "ENOENT" + ? "DiskHound's helper is missing. Reinstall DiskHound, or in a source checkout run bun run build:mcp:debug." + : `Couldn't build the extension: ${message}`, + }; + } + const failed = await shell.openPath(file); + if (failed) deps.log("agent-access", `couldn't open the Claude extension: ${failed}`); + return failed ? { ok: false, error: `Couldn't open it in Claude: ${failed}`, file } : { ok: true, file }; + }); + + const showSettings = async () => { + await navigate({ view: "settings", section: "ai-agents", focus: true }); + }; + + return { + start: async () => { + if (!deps.getSettings().agents.enabled) return; + const started = await (await ensureService()).setEnabled(true, false); + deps.log("agent-access", started.listening ? `listening on ${started.mcpUrl}` : `failed to start: ${started.error ?? "unknown"}`); + }, + showSettings, + pathsRemoved: () => measurements?.invalidate(), + dispose: async () => { + broker.close(); + measurements?.dispose(); + await service?.dispose(); + await security.flush(); + }, + }; +} diff --git a/src/mcp/paths.ts b/src/mcp/paths.ts new file mode 100644 index 00000000..28ebc49a --- /dev/null +++ b/src/mcp/paths.ts @@ -0,0 +1,42 @@ +import * as OS from "node:os"; +import * as Path from "node:path"; + +import { normPath } from "../shared/pathUtils"; + +/** + * Whether `candidate` is `root` or inside it. Case-insensitive on + * Windows (via normPath); separator-aware so `/Users/a` does not + * contain `/Users/ab`. + */ +export function isInside(root: string, candidate: string): boolean { + const r = normPath(root); + const c = normPath(candidate); + // normPath strips trailing separators, so a POSIX "/" root becomes "". + if (r === "") return c === "" || c.startsWith("/"); + return c === r || c.startsWith(`${r}/`) || c.startsWith(`${r}\\`); +} + +/** + * The absolute path an agent meant. `~` expands to the home folder, and + * a bare drive letter ("C:", which diskhound_status reports on Windows) + * becomes that drive's root. Anything else relative is refused: it + * would resolve against DiskHound's working directory (on Windows, + * `Path.resolve("C:")` is that directory, not the drive). + */ +export function agentPath(input: string, platform: NodeJS.Platform = process.platform, home = OS.homedir()): string { + const api = platform === "win32" ? Path.win32 : Path.posix; + let value = input.trim(); + if (value === "~" || value.startsWith("~/") || (platform === "win32" && value.startsWith("~\\"))) { + value = api.join(home, value.slice(1)); + } + if (platform === "win32") { + if (/^[A-Za-z]:$/.test(value)) value = `${value}\\`; + // "\\foo" is absolute to Path.win32 but means "on the current drive". + if (!/^[A-Za-z]:[\\/]/.test(value) && !/^[\\/]{2}[^\\/]/.test(value)) { + throw new Error(`Use an absolute path such as C:\\Users (got "${input}").`); + } + } else if (!api.isAbsolute(value)) { + throw new Error(`Use an absolute path such as /Users (got "${input}").`); + } + return api.resolve(value); +} diff --git a/src/mcp/removalMeasure.ts b/src/mcp/removalMeasure.ts new file mode 100644 index 00000000..74c171e7 --- /dev/null +++ b/src/mcp/removalMeasure.ts @@ -0,0 +1,173 @@ +import { spawn } from "node:child_process"; +import * as Path from "node:path"; +import * as Readline from "node:readline"; + +/** + * What removing a set of paths together would free, measured on disk by + * the native scanner's `--mode=measure-removal` (see + * native/diskhound-native-scanner/src/measure.rs). It counts APFS clone + * groups and hardlinked files once, and frees their blocks only when + * every clone or name is in the set. + */ +export interface RemovalPathTotals { + path: string; + kind: "folder" | "file"; + files: number; + sizeBytes: number; + freesAloneBytes: number; + sharedBytes: number; + uncertainBytes: number; +} + +export interface RemovalMeasurement { + paths: RemovalPathTotals[]; + total: { + files: number; + sizeBytes: number; + freesBytes: number; + heldElsewhereBytes: number; + uncertainBytes: number; + }; + missing: string[]; + nested: { path: string; within: string }[]; + skippedEntries: number; + /** False off APFS, where no clone data exists. */ + cloneMetadata: boolean; + elapsedMs: number; + /** When the walk finished (epoch ms). */ + measuredAt: number; +} + +export type RemovalMeasurer = (paths: readonly string[], signal: AbortSignal) => Promise; + +/** Runs the scanner binary in measure mode; it reads metadata only. */ +export function nativeRemovalMeasurer( + binary: string, + workers: () => number | undefined = () => undefined, + now: () => number = Date.now, +): RemovalMeasurer { + return (paths, signal) => + new Promise((resolve, reject) => { + const args = ["--mode=measure-removal", ...paths.flatMap((path) => ["--path", path])]; + const count = workers(); + if (count) args.push("--workers", String(count)); + const child = spawn(binary, args, { cwd: Path.dirname(binary), stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); + let result: RemovalMeasurement | null = null; + let failure: string | null = null; + let stderr = ""; + const abort = () => child.kill("SIGTERM"); + signal.addEventListener("abort", abort, { once: true }); + child.stderr.setEncoding("utf8"); + child.stderr.on("data", (chunk: string) => { + stderr = (stderr + chunk).slice(-2_000); + }); + Readline.createInterface({ input: child.stdout, crlfDelay: Infinity }).on("line", (line) => { + if (!line.startsWith("{")) return; + try { + const message = JSON.parse(line) as { type?: string; message?: string }; + if (message.type === "removal-measurement") result = { ...(message as unknown as RemovalMeasurement), measuredAt: now() }; + else if (message.type === "error") failure = message.message ?? "unknown error"; + } catch { + // A partial line from a killed process. + } + }); + child.on("error", (error) => { + signal.removeEventListener("abort", abort); + reject(error); + }); + child.on("close", (code) => { + signal.removeEventListener("abort", abort); + if (signal.aborted) reject(new Error("The measurement was cancelled.")); + else if (result && code === 0) resolve(result); + else reject(new Error(`DiskHound couldn't measure those paths: ${failure ?? (stderr.trim().split("\n").at(-1) || `scanner exited with ${code}`)}`)); + }); + }); +} + +interface Job { + promise: Promise; + controller: AbortController; + /** Set once the job succeeds. */ + doneAt: number | null; + /** A removal went through while it ran, so its result is never kept. */ + stale: boolean; +} + +/** + * The measurements agents ask for. A big set (millions of files) can + * outlast a client's tool timeout, so a measurement keeps going when the + * caller gives up, and the same set asked again within `ttlMs` gets that + * result instead of another walk. One walk runs at a time. + */ +export class RemovalMeasurements { + private readonly jobs = new Map(); + private tail: Promise = Promise.resolve(); + + constructor( + private readonly run: RemovalMeasurer, + private readonly options: { ttlMs?: number; maxKept?: number; now?: () => number } = {}, + ) {} + + private get now() { + return this.options.now ?? Date.now; + } + + async measure(paths: readonly string[], signal?: AbortSignal): Promise { + const unique = [...new Set(paths)].sort(); + const key = unique.join("\0"); + this.expire(); + let job = this.jobs.get(key); + if (!job) { + const controller = new AbortController(); + // dispose() may abort a job still waiting its turn: never start that walk. + const promise = this.tail.then(() => + controller.signal.aborted ? Promise.reject(new Error("The measurement was cancelled.")) : this.run(unique, controller.signal), + ); + job = { promise, controller, doneAt: null, stale: false }; + const started = job; + this.jobs.set(key, started); + this.tail = promise.catch(() => undefined); + promise.then( + () => { + started.doneAt = this.now(); + if (started.stale && this.jobs.get(key) === started) this.jobs.delete(key); + }, + () => { + if (this.jobs.get(key) === started) this.jobs.delete(key); + }, + ); + } + if (!signal) return job.promise; + if (signal.aborted) throw new Error("The agent stopped waiting."); + return new Promise((resolve, reject) => { + const stop = () => reject(new Error("The agent stopped waiting.")); + signal.addEventListener("abort", stop, { once: true }); + job.promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop)); + }); + } + + /** Files changed (a removal went through): measure afresh next time. */ + invalidate(): void { + for (const [key, job] of this.jobs) { + if (job.doneAt !== null) this.jobs.delete(key); + else job.stale = true; + } + } + + dispose(): void { + for (const job of this.jobs.values()) job.controller.abort(); + this.jobs.clear(); + } + + private expire(): void { + const ttl = this.options.ttlMs ?? 5 * 60_000; + const done = [...this.jobs].filter(([, job]) => job.doneAt !== null); + const cutoff = this.now() - ttl; + for (const [key, job] of done) { + if (job.doneAt! < cutoff) this.jobs.delete(key); + } + const keep = this.options.maxKept ?? 8; + const fresh = done.filter(([, job]) => job.doneAt! >= cutoff).sort((a, b) => a[1].doneAt! - b[1].doneAt!); + for (const [key] of fresh.slice(0, Math.max(0, fresh.length - keep))) this.jobs.delete(key); + } +} diff --git a/src/mcp/securityLog.ts b/src/mcp/securityLog.ts new file mode 100644 index 00000000..4fc8b6b9 --- /dev/null +++ b/src/mcp/securityLog.ts @@ -0,0 +1,196 @@ +import * as FS from "node:fs/promises"; + +import type { AgentSecurityEvent } from "../shared/agentAccess"; + +/** Identical events inside this window bump a count instead of adding a line. */ +const COALESCE_MS = 60_000; +/** Bursts (one Trash request naming 20 protected folders) become one append. */ +const FLUSH_MS = 2_000; +/** + * After an append, the next waits at least this long, so an agent that + * keeps getting refused costs at most 288 appends a day. Settings shows + * each refusal live either way; only the file lags. + */ +const MIN_APPEND_GAP_MS = 5 * 60_000; +/** Rotate to `.1` past this size, so loading the log stays cheap. */ +const MAX_BYTES = 256 * 1024; +/** Events kept in memory for Settings, newest first. */ +const LIMIT = 200; +/** Lines per hour that reach disk; a looping agent can't fill the SSD. */ +const MAX_LINES_PER_HOUR = 60; + +export type SecurityEventInput = Omit; + +export interface AgentSecuritySink { + record(event: SecurityEventInput): void; +} + +/** + * What agents tried that their session doesn't allow: a tool their role + * doesn't grant (hidden from their tool list, so calling it means a stale + * list or a guess), or a Trash / delete request naming a folder agents + * may never remove. + * + * Kept in `agent-security.log` (NDJSON, 0600) so it survives restarts, + * and in memory for Settings โ†’ AI Agents. Writes only happen when an + * agent is refused; see securityLog.ioBudget.test.ts for the + * counts. + */ +export class AgentSecurityLog implements AgentSecuritySink { + private events: AgentSecurityEvent[] = []; + private loaded: Promise | null = null; + private queued: AgentSecurityEvent[] = []; + private timer: ReturnType | null = null; + private writing: Promise = Promise.resolve(); + private bytesOnDisk: number | null = null; + private seq = 0; + private hourStart = -Infinity; + private linesThisHour = 0; + private lastAppendAt = -Infinity; + + constructor(private readonly options: { + file: string; + /** + * Called for every new event and every repeat. `logged` says whether + * it went to the file (the hourly cap wasn't reached), so a mirror + * in crash.log can follow the same cap. + */ + onEvent?: (event: AgentSecurityEvent, info: { repeated: boolean; logged: boolean }) => void; + now?: () => number; + flushMs?: number; + }) {} + + get filePath(): string { + return this.options.file; + } + + private now(): number { + return (this.options.now ?? Date.now)(); + } + + record(input: SecurityEventInput): void { + const now = this.now(); + const same = this.events.find((event) => + now - event.at < COALESCE_MS && + event.sessionId === input.sessionId && + event.kind === input.kind && + event.tool === input.tool && + event.detail === input.detail, + ); + if (same) { + same.count += 1; + same.at = now; + this.events = [same, ...this.events.filter((event) => event !== same)]; + // A queued line is this same object, so it goes out with the new + // count. One already on disk gets a newer line with the same id; + // load() keeps the last. + const logged = this.queued.includes(same) || this.enqueue(same, now); + this.notify(same, { repeated: true, logged }); + return; + } + const event: AgentSecurityEvent = { ...input, id: `security-${now}-${++this.seq}`, at: now, count: 1 }; + this.events.unshift(event); + if (this.events.length > LIMIT) this.events.length = LIMIT; + const logged = this.enqueue(event, now); + this.notify(event, { repeated: false, logged }); + } + + private enqueue(event: AgentSecurityEvent, now: number): boolean { + if (now - this.hourStart >= 60 * 60_000) { + this.hourStart = now; + this.linesThisHour = 0; + } + if (this.linesThisHour >= MAX_LINES_PER_HOUR) return false; + this.linesThisHour += 1; + this.queued.push(event); + this.schedule(now); + return true; + } + + private notify(event: AgentSecurityEvent, info: { repeated: boolean; logged: boolean }): void { + try { + this.options.onEvent?.({ ...event }, info); + } catch { + // The window may be closing; a refusal must still be refused. + } + } + + private schedule(now: number): void { + if (this.timer) return; + const delay = Math.max(this.options.flushMs ?? FLUSH_MS, this.lastAppendAt + MIN_APPEND_GAP_MS - now); + this.timer = setTimeout(() => { + this.timer = null; + void this.flush(); + }, delay); + this.timer.unref?.(); + } + + /** Newest first, including what earlier runs of DiskHound logged. */ + async list(): Promise { + this.loaded ??= this.load(); + await this.loaded; + return this.events.map((event) => ({ ...event })); + } + + /** Events recorded in memory so far, without reading the file. */ + recent(): AgentSecurityEvent[] { + return this.events.map((event) => ({ ...event })); + } + + private async load(): Promise { + let text: string; + try { + text = await FS.readFile(this.options.file, "utf8"); + } catch { + return; + } + this.bytesOnDisk = Buffer.byteLength(text); + const onDisk: AgentSecurityEvent[] = []; + for (const line of text.split("\n")) { + if (!line.trim()) continue; + try { + const event = JSON.parse(line) as AgentSecurityEvent; + if (typeof event.id === "string" && typeof event.at === "number" && typeof event.detail === "string") { + onDisk.push({ ...event, count: typeof event.count === "number" ? event.count : 1 }); + } + } catch { + /* a torn last line after a crash */ + } + } + // A repeat's later line (same id, higher count) replaces the first. + const latest = new Map(); + for (const event of onDisk) latest.set(event.id, event); + const known = new Set(this.events.map((event) => event.id)); + const older = [...latest.values()].filter((event) => !known.has(event.id)); + this.events = [...this.events, ...older].sort((a, b) => b.at - a.at).slice(0, LIMIT); + } + + /** Append what's queued. Called on a short timer and at quit. */ + flush(): Promise { + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + const batch = this.queued; + this.queued = []; + if (batch.length === 0) return this.writing; + this.lastAppendAt = this.now(); + const data = batch.map((event) => JSON.stringify(event)).join("\n") + "\n"; + this.writing = this.writing.then(async () => { + try { + if (this.bytesOnDisk === null) { + this.bytesOnDisk = await FS.stat(this.options.file).then((stat) => stat.size, () => 0); + } + if (this.bytesOnDisk + Buffer.byteLength(data) > MAX_BYTES) { + await FS.rename(this.options.file, `${this.options.file}.1`).catch(() => undefined); + this.bytesOnDisk = 0; + } + await FS.appendFile(this.options.file, data, { encoding: "utf8", mode: 0o600 }); + this.bytesOnDisk += Buffer.byteLength(data); + } catch { + // Losing a log line must never break the refusal itself. + } + }); + return this.writing; + } +} diff --git a/src/mcp/server.ts b/src/mcp/server.ts new file mode 100644 index 00000000..c2d6395b --- /dev/null +++ b/src/mcp/server.ts @@ -0,0 +1,1431 @@ +import * as Path from "node:path"; + +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { ShapeOutput, ZodRawShapeCompat } from "@modelcontextprotocol/sdk/server/zod-compat.js"; +import type { CallToolResult, GetPromptResult, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js"; +import { z } from "zod"; + +import { duplicateGroupReclaimable, entryReclaimable } from "../shared/duplicateReclaim"; +import { devArtifactSharing, summarizeDevSharing } from "../shared/storageSharing"; +import type { AppView, ScanHistoryEntry, ScanSnapshot } from "../shared/contracts"; +import { MCP_SERVER_NAME, type McpAgentCapability } from "../shared/agentAccess"; +import { normPath } from "../shared/pathUtils"; +import type { McpAccessError, McpAuthorization, McpAuthorizer } from "./accessPolicy"; +import type { AgentActivitySink, DiskhoundAgentBackend } from "./backend"; +import type { AgentSecuritySink } from "./securityLog"; +import { agentPath, isInside } from "./paths"; +import { readSkillDirectory, registerSkills, type SkillCatalog } from "./skills"; + +/** + * DiskHound's MCP surface: tools that read the same scan data the + * window shows, a few that start work or steer the window, two that + * ask the user to move items to the Trash or delete them, the SEP-2640 + * skills, and prompt fallbacks for hosts that don't load MCP skills yet. + * + * One server is built per HTTP request (stateless Streamable HTTP, as + * in PwrSnap), bound to that request's bearer token and to what that + * session may do right now: a tool its role doesn't grant is not + * registered, so it is missing from tools/list. Every tool call still + * re-authorizes against the policy file, so a revoke or role change in + * Settings applies to the next call, and a refusal goes to the + * security log. + */ + +export const FREE_UP_SPACE_SKILL = "skill://diskhound-free-up-space/SKILL.md"; +export const INVESTIGATE_GROWTH_SKILL = "skill://diskhound-investigate-growth/SKILL.md"; + +/** Items per trash request. The dialog lists every one, so keep it readable. */ +const MAX_TRASH_PATHS = 20; + +/** + * What each tool needs, before its arguments add anything (showInApp + * adds app.navigate). A session that lacks any of these doesn't see the + * tool, and agentAccessServer refuses and logs a call to it. + */ +export const TOOL_CAPABILITIES: Readonly> = { + diskhound_status: ["disk.read"], + diskhound_read_skill: ["disk.read"], + diskhound_scan_summary: ["disk.read"], + diskhound_list_folder: ["disk.read"], + diskhound_search_files: ["disk.read"], + diskhound_cleanup_suggestions: ["disk.read"], + diskhound_dev_artifacts: ["disk.read"], + diskhound_measure_removal: ["disk.read"], + diskhound_scan_history: ["disk.read"], + diskhound_changes: ["disk.read"], + diskhound_duplicates: ["disk.read"], + diskhound_start_scan: ["scan.run"], + diskhound_cancel_scan: ["scan.run"], + diskhound_find_duplicates: ["scan.run"], + diskhound_show: ["app.navigate"], + diskhound_reveal_path: ["app.navigate"], + diskhound_move_to_trash: ["files.trash"], + diskhound_delete_permanently: ["files.delete"], +}; + +/** Plain words for a refusal the user reads in Settings. */ +const TOOL_ACTION: Readonly> = { + diskhound_move_to_trash: "move items to the Trash", + diskhound_delete_permanently: "delete items permanently", + diskhound_start_scan: "start a scan", + diskhound_cancel_scan: "cancel a scan", + diskhound_find_duplicates: "start a duplicate search", + diskhound_show: "steer the DiskHound window", + diskhound_reveal_path: "reveal an item in the file manager", +}; + +export function toolActionText(tool: string): string { + return TOOL_ACTION[tool] ?? `use ${tool}`; +} + +const VIEWS = ["overview", "files", "folders", "dev", "duplicates", "easyMove", "changes", "settings"] as const; + +const readOnly: ToolAnnotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }; +const startsWork: ToolAnnotations = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }; +const steersApp: ToolAnnotations = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }; +const trashes: ToolAnnotations = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }; +const deletes: ToolAnnotations = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }; + +export interface DiskhoundMcpServerOptions { + backend: DiskhoundAgentBackend; + authorizer: McpAuthorizer; + activity: AgentActivitySink; + skills: SkillCatalog; + /** + * What this request's session may do. Tools and arguments it can't use + * are left out of the server. Omitted in tests that want every tool. + */ + granted?: readonly McpAgentCapability[]; + /** Where refusals go (Settings โ†’ AI Agents โ†’ Blocked requests). */ + security?: AgentSecuritySink; + /** Aborted when the HTTP request behind this server closes. */ + signal?: AbortSignal; + now?: () => number; +} + +// โ”€โ”€ Formatting helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +/** Sizes in the units the user picked in Settings, so the agent's numbers match the window's. */ +export function bytesText(bytes: number, base: 1000 | 1024 = 1024): string { + if (!Number.isFinite(bytes) || bytes <= 0) return "0 B"; + const units = ["B", "KB", "MB", "GB", "TB", "PB"]; + const exp = Math.min(Math.floor(Math.log(bytes) / Math.log(base)), units.length - 1); + const value = bytes / base ** exp; + return `${value.toFixed(value >= 100 || exp === 0 ? 0 : 1)} ${units[exp]}`; +} +const bytesTextIn = bytesText; + +export function ageText(fromMs: number, nowMs: number): string { + const minutes = Math.max(0, Math.round((nowMs - fromMs) / 60_000)); + if (minutes < 1) return "just now"; + if (minutes < 60) return `${minutes} min ago`; + const hours = Math.round(minutes / 60); + if (hours < 48) return `${hours} h ago`; + return `${Math.round(hours / 24)} days ago`; +} + +function success(value: Record, summary: string): CallToolResult { + // MCP: a tool returning structuredContent SHOULD also serialize it + // into a text block for clients that ignore structured output. + return { + content: [ + { type: "text", text: summary }, + { type: "text", text: JSON.stringify(value) }, + ], + structuredContent: value, + }; +} + +const SINCE_MS: Record = { + "1h": 3_600_000, + "6h": 6 * 3_600_000, + "1d": 86_400_000, + "1w": 7 * 86_400_000, + "1M": 30 * 86_400_000, + "3M": 90 * 86_400_000, +}; + +function platformSpaceNote(platform: NodeJS.Platform): string { + if (platform === "darwin") { + return "Trashed items keep using space until the Trash is emptied. On APFS, cloned files (e.g. pnpm node_modules, Finder duplicates) share blocks, and Time Machine local snapshots pin deleted data until they expire โ€” free space can lag. See skill://diskhound-free-up-space/references/macos.md."; + } + if (platform === "win32") { + return "Recycle Bin items keep using space until the bin is emptied. System Restore / Volume Shadow Copies can pin deleted data. See skill://diskhound-free-up-space/references/windows.md."; + } + return "Trashed items keep using space until the Trash is emptied. btrfs/ZFS snapshots and hardlinks (e.g. pnpm stores) can keep space in use after deletion. See skill://diskhound-free-up-space/references/linux.md."; +} + +export function serverInstructions( + platform: NodeJS.Platform, + granted: readonly McpAgentCapability[] = ["disk.read", "scan.run", "app.navigate", "files.trash", "files.delete"], +): string { + const os = platform === "darwin" ? "macOS" : platform === "win32" ? "Windows" : "Linux"; + const can = (capability: McpAgentCapability) => granted.includes(capability); + const removal = can("files.delete") + ? "Never remove anything on your own. diskhound_move_to_trash and diskhound_delete_permanently ask the user to confirm in DiskHound; prefer the Trash, and delete permanently only when the user asks for it." + : can("files.trash") + ? "Never remove anything on your own. diskhound_move_to_trash asks the user to confirm in DiskHound; this session can't delete permanently." + : "This session can't move or delete files. Recommend what to remove and let the user do it, or ask them to give this session a bigger role in DiskHound โ†’ Settings โ†’ AI Agents."; + return [ + `DiskHound is a disk-space analyzer running on the user's ${os} computer. Use DiskHound for disk usage, full drives, large files, duplicates, caches, cleanup, or disk growth. If tools are deferred, search your host's tool catalog for DiskHound and the task before calling them.`, + can("scan.run") + ? "Start with diskhound_status (drives, scanned roots, active scans). If the drive has no recent scan, call diskhound_start_scan and poll diskhound_status until it finishes." + : "Start with diskhound_status (drives, scanned roots, active scans). This session can't start scans; if the data is old, ask the user to rescan in DiskHound.", + "Drill down with diskhound_list_folder from the scan root. Targeted views: diskhound_dev_artifacts (node_modules, build output, caches, worktrees), diskhound_cleanup_suggestions, diskhound_duplicates, diskhound_search_files, and diskhound_changes (what grew between scans).", + `Before recommending deletions, read the skill ${FREE_UP_SPACE_SKILL} (resources/read, or diskhound_read_skill if your host only passes tools on). It covers cases where deleting files does not free space: APFS clones, Time Machine local snapshots, hardlinks, shadow copies, and snapshots on btrfs/ZFS. For "why did my disk fill up?", read ${INVESTIGATE_GROWTH_SKILL}.`, + ...(can("app.navigate") + ? ["The user may be watching DiskHound. Pass showInApp: true, or call diskhound_show, so the window follows along."] + : []), + `${removal} Sizes are bytes on disk (allocated), not logical file length.`, + ].join("\n\n"); +} + +// โ”€โ”€ Server โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +export function createDiskhoundMcpServer(options: DiskhoundMcpServerOptions): McpServer { + const { backend, authorizer, activity, skills, security } = options; + const now = options.now ?? Date.now; + const sizeBase = backend.sizeUnitBase?.() ?? 1024; + const bytesText = (bytes: number) => bytesTextIn(bytes, sizeBase); + /** Removed items' total. Paths outside every scan have no size, so never "0 B" for them. */ + const removedText = (results: readonly { sizeBytes: number | null }[]) => { + const known = results.filter((result) => result.sizeBytes !== null); + if (known.length === 0) return "size unknown"; + const total = known.reduce((sum, result) => sum + (result.sizeBytes ?? 0), 0); + return `${known.length < results.length ? "at least " : ""}${bytesText(total)}`; + }; + const granted = options.granted; + const allows = (capability: McpAgentCapability) => !granted || granted.includes(capability); + const canNavigate = allows("app.navigate"); + + const mcp = new McpServer( + { name: MCP_SERVER_NAME, title: "DiskHound", version: backend.appVersion }, + { + // prompts and resources are added by the SDK when the first one + // registers. Declaring them up front would advertise list methods + // with no handler behind them when the skill catalog is empty. + // listChanged: the stdio helper announces role changes. + capabilities: { tools: { listChanged: true } }, + instructions: serverInstructions(backend.platform, granted), + }, + ); + + /** + * `showInApp` only for sessions that may steer the window. The types + * always include it; without the field, zod strips the argument and + * the handler sees undefined. + */ + const showInAppField = (description: string) => + (canNavigate ? { showInApp: z.boolean().optional().describe(description) } : {}) as { + showInApp: z.ZodOptional; + }; + const showInAppByDefault = (description: string) => + (canNavigate ? { showInApp: z.boolean().default(true).describe(description) } : {}) as { + showInApp: z.ZodDefault; + }; + + type ToolOutcome = { value: Record; summary: string; activity?: string }; + + /** + * Register a tool that authorizes, runs, and records itself in the + * activity feed. Failures (including authorization) are recorded and + * then rethrown so the SDK returns them as `isError` tool results. + */ + const tool = ( + name: string, + config: { title: string; description: string; inputSchema: Shape; annotations: ToolAnnotations }, + capabilities: (input: ShapeOutput) => McpAgentCapability[], + run: (input: ShapeOutput, auth: McpAuthorization) => Promise, + ) => { + const required = TOOL_CAPABILITIES[name]; + if (!required) throw new Error(`${name} is missing from TOOL_CAPABILITIES`); + if (!required.every(allows)) return; + mcp.registerTool(name, config, (async (input: ShapeOutput) => { + let auth: McpAuthorization | null = null; + try { + auth = await authorizer.authorize(capabilities(input)); + const outcome = await run(input, auth); + activity.record({ + sessionId: auth.sessionId, + sessionName: auth.sessionName, + tool: name, + summary: outcome.activity ?? outcome.summary.split("\n")[0]!.slice(0, 200), + ok: true, + }); + return success(outcome.value, outcome.summary); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + // A role that lacks the capability is worth showing in the feed: + // it's the moment the user may want to change the Session's role. + // Match on the code, not instanceof: the policy store lives in + // main.cjs and this module in the lazily loaded runtime bundle, + // so each has its own copy of McpAccessError. + if (!auth && (error as Partial | null)?.code === "missing_capability") { + auth = await authorizer.authorize([]).catch(() => null); + // The role changed after this server was built (its tool list + // is stale). Same refusal as a hidden tool. + if (auth) { + security?.record({ + sessionId: auth.sessionId, + sessionName: auth.sessionName, + roleName: auth.roleName, + kind: "tool_not_allowed", + tool: name, + detail: `Tried to ${toolActionText(name)}; ${auth.roleName} doesn't allow it.`, + }); + } + } + if (auth) { + activity.record({ + sessionId: auth.sessionId, + sessionName: auth.sessionName, + tool: name, + summary: message.slice(0, 200), + ok: false, + }); + } + throw error; + } + }) as never); + }; + + const withNavigate = (showInApp: boolean | undefined): McpAgentCapability[] => + showInApp ? ["disk.read", "app.navigate"] : ["disk.read"]; + + /** Map any path (or nothing) to the scan root whose data covers it. */ + const resolveRoot = async (pathInput?: string): Promise => { + const roots = backend.scannedRoots().map((entry) => entry.rootPath); + if (pathInput) { + const target = agentPath(pathInput, backend.platform); + const covering = roots + .filter((root) => isInside(root, target)) + .sort((a, b) => b.length - a.length)[0]; + if (covering) return covering; + const active = (await backend.activeScans()).find((snap) => snap.rootPath && isInside(snap.rootPath, target)); + if (active?.rootPath) return active.rootPath; + throw new Error( + `DiskHound has no scan covering ${target}. Call diskhound_start_scan with a drive or folder that contains it.`, + ); + } + const current = await backend.currentRoot(); + if (current) return current; + if (roots[0]) return roots[0]; + throw new Error("DiskHound has not scanned anything yet. Call diskhound_status to see drives, then diskhound_start_scan."); + }; + + const requireSnapshot = async (rootPath: string): Promise => { + const snapshot = await backend.latestSnapshot(rootPath); + if (!snapshot) { + throw new Error(`No completed scan for ${rootPath}. Call diskhound_start_scan first.`); + } + return snapshot; + }; + + const navigateIf = async (showInApp: boolean | undefined, request: Parameters[0]) => { + if (showInApp) await backend.navigate(request); + }; + + // โ”€โ”€ Read tools โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + tool( + "diskhound_status", + { + title: "DiskHound status", + description: + "Start here. Returns every drive's capacity and free space, which roots DiskHound has scanned (and how long ago), scans in progress, what this Session is allowed to do, and the skills to read before recommending cleanup (diskhound_read_skill reads them).", + inputSchema: {}, + annotations: readOnly, + }, + () => ["disk.read"], + async (_input, auth) => { + const [drives, active, current] = await Promise.all([ + backend.listDrives(), + backend.activeScans(), + backend.currentRoot(), + ]); + const roots = backend.scannedRoots(); + const nowMs = now(); + const value = { + app: { name: "DiskHound", version: backend.appVersion, platform: backend.platform }, + session: { name: auth.sessionName, role: auth.roleName, capabilities: [...auth.capabilities] }, + drives: drives.map((drive) => ({ + drive: drive.drive, + totalBytes: drive.totalBytes, + freeBytes: drive.freeBytes, + usedBytes: drive.usedBytes, + usedPercent: Math.round(drive.usedPercent * 10) / 10, + free: bytesText(drive.freeBytes), + total: bytesText(drive.totalBytes), + })), + activeScans: active.map((snap) => ({ + rootPath: snap.rootPath, + phase: snap.scanPhase ?? null, + filesVisited: snap.filesVisited, + bytesSeen: snap.bytesSeen, + seen: bytesText(snap.bytesSeen), + elapsedMs: snap.startedAt ? nowMs - snap.startedAt : snap.elapsedMs, + })), + scannedRoots: roots.map((entry) => ({ + rootPath: entry.rootPath, + lastScannedAt: new Date(entry.scannedAt).toISOString(), + age: ageText(entry.scannedAt, nowMs), + bytesSeen: entry.bytesSeen, + size: bytesText(entry.bytesSeen), + files: entry.filesVisited, + scansKept: backend.scanHistory(entry.rootPath).length, + })), + currentRoot: current, + window: backend.windowView?.() ?? null, + skills: [FREE_UP_SPACE_SKILL, INVESTIGATE_GROWTH_SKILL], + note: platformSpaceNote(backend.platform), + }; + const driveLine = drives + .map((drive) => `${drive.drive} ${bytesText(drive.freeBytes)} free of ${bytesText(drive.totalBytes)}`) + .join("; "); + const rootLine = roots.length + ? roots.map((entry) => `${entry.rootPath} (${ageText(entry.scannedAt, nowMs)})`).join(", ") + : "none yet"; + const summary = [ + `Drives: ${driveLine || "none detected"}.`, + `Scanned roots: ${rootLine}.`, + active.length ? `Scanning now: ${active.map((snap) => snap.rootPath).join(", ")}.` : "No scans running.", + value.window + ? `The DiskHound window shows the ${value.window.view} tab${value.window.rootPath ? ` for ${value.window.rootPath}` : ""}.` + : null, + `Session "${auth.sessionName}" (${auth.roleName}) may: ${auth.capabilities.join(", ")}.`, + skills.skills.length ? `Before recommending cleanup, read ${FREE_UP_SPACE_SKILL} with diskhound_read_skill.` : null, + ].filter(Boolean).join("\n"); + return { value, summary, activity: "Checked drives and scan status" }; + }, + ); + + // Claude Desktop passes an extension's tools on to its chats and Code + // sessions, but not its resources, so a skill has to be reachable as a + // tool too. Same text as resources/read. + tool( + "diskhound_read_skill", + { + title: "Read a DiskHound skill", + description: + "DiskHound's skills: how to free up space without being misled by APFS clones, snapshots or hardlinks, and how to find out what made a disk grow. " + + "Pass a skill:// URI from diskhound_status or from another skill file; omit it to list the skills. " + + "Use this when your host can't read MCP resources. resources/read returns the same text.", + inputSchema: { + uri: z + .string() + .min(1) + .max(512) + .optional() + .describe("A skill:// file or folder, e.g. skill://diskhound-free-up-space/SKILL.md. Omit to list every skill."), + }, + annotations: readOnly, + }, + () => ["disk.read"], + async (input) => { + if (!input.uri) { + const value = { + skills: skills.skills.map((skill) => ({ + uri: skill.uri, + name: skill.name, + description: skill.frontmatter.description ?? "", + files: skill.files.map((file) => file.uri), + })), + }; + const summary = value.skills.length + ? value.skills.map((skill) => `${skill.uri}: ${skill.description}`).join("\n") + : "This DiskHound build has no skills."; + return { value, summary, activity: "Listed DiskHound's skills" }; + } + const uri = input.uri.trim().replace(/\/+$/, ""); + for (const skill of skills.skills) { + const file = skill.files.find((candidate) => candidate.uri === uri); + if (!file) continue; + const value = { + uri: file.uri, + mimeType: file.mimeType, + size: file.size, + digest: file.digest, + otherFiles: skill.files.filter((other) => other !== file).map((other) => other.uri), + }; + const name = file.relativePath === "SKILL.md" ? `the ${skill.name} skill` : `${skill.name}/${file.relativePath}`; + return { value, summary: file.text, activity: `Read ${name}` }; + } + const children = readSkillDirectory(skills, uri); + if (children) { + return { + value: { uri, children }, + summary: children.map((child) => `${child.uri}${child.mimeType === "inode/directory" ? "/" : ""}`).join("\n"), + activity: `Listed ${uri.slice("skill://".length)}`, + }; + } + throw new Error(`DiskHound has no skill file at ${uri}. Call diskhound_read_skill without a uri to list them.`); + }, + ); + + tool( + "diskhound_scan_summary", + { + title: "Scan summary", + description: + "Overview of the latest completed scan for a root: totals, the largest files, the heaviest folders, and the file types using the most space. Omit rootPath to use the root the DiskHound window is showing.", + inputSchema: { + rootPath: z.string().min(1).max(4096).optional().describe("A scanned root, or any path inside one."), + limit: z.number().int().min(1).max(100).default(15).describe("Rows per list (default 15)."), + ...showInAppField("Also switch the DiskHound window to this root's Overview."), + }, + annotations: readOnly, + }, + (input) => withNavigate(input.showInApp), + async (input) => { + const rootPath = await resolveRoot(input.rootPath); + const snapshot = await requireSnapshot(rootPath); + await navigateIf(input.showInApp, { view: "overview", rootPath }); + const nowMs = now(); + const scannedAt = snapshot.finishedAt ?? snapshot.lastUpdatedAt; + const value = { + rootPath, + status: snapshot.status, + scannedAt: new Date(scannedAt).toISOString(), + age: ageText(scannedAt, nowMs), + engine: snapshot.engine, + sizeSemantics: snapshot.sizeSemantics ?? "allocated", + totals: { + bytes: snapshot.bytesSeen, + size: bytesText(snapshot.bytesSeen), + files: snapshot.filesVisited, + directories: snapshot.directoriesVisited, + skippedEntries: snapshot.skippedEntries, + }, + largestFiles: snapshot.largestFiles.slice(0, input.limit).map((file) => ({ + path: file.path, + sizeBytes: file.size, + size: bytesText(file.size), + modifiedAt: new Date(file.modifiedAt).toISOString(), + })), + heaviestFolders: [...snapshot.hottestDirectories] + .sort((a, b) => b.size - a.size) + .slice(0, input.limit) + .map((dir) => ({ path: dir.path, sizeBytes: dir.size, size: bytesText(dir.size), fileCount: dir.fileCount })), + topFileTypes: snapshot.topExtensions.slice(0, input.limit).map((bucket) => ({ + extension: bucket.extension, + sizeBytes: bucket.size, + size: bytesText(bucket.size), + count: bucket.count, + })), + }; + const top = value.heaviestFolders.slice(0, 5).map((dir) => `${dir.path} (${dir.size})`).join(", "); + const summary = + `${rootPath}: ${bytesText(snapshot.bytesSeen)} in ${snapshot.filesVisited.toLocaleString()} files, scanned ${value.age}.` + + (top ? `\nHeaviest folders: ${top}.` : ""); + return { value, summary, activity: `Summarized ${rootPath}` }; + }, + ); + + tool( + "diskhound_list_folder", + { + title: "List folder", + description: + "Immediate subfolders and files of one folder from the latest scan, largest first, with sizes on disk. This is the main drill-down tool: start at the scan root and follow the biggest folders. Uses scan data, so it is instant and does not touch the disk.", + inputSchema: { + path: z.string().min(1).max(4096).describe("Absolute path of the folder to list (must be inside a scanned root)."), + limit: z.number().int().min(1).max(200).default(30).describe("Max folders and max files to return (default 30 each)."), + includeFiles: z.boolean().default(true).describe("Include loose files in this folder (default true)."), + ...showInAppField("Also open this folder in DiskHound's Folders tab."), + }, + annotations: readOnly, + }, + (input) => withNavigate(input.showInApp), + async (input) => { + const folderPath = agentPath(input.path, backend.platform); + const rootPath = await resolveRoot(folderPath); + const children = await backend.folderChildren(rootPath, folderPath); + if (children.totalItemCount === 0 && normPath(folderPath) !== normPath(rootPath)) { + throw new Error( + `The latest scan of ${rootPath} has nothing recorded under ${folderPath}. Check the path with diskhound_list_folder on its parent.`, + ); + } + await navigateIf(input.showInApp, { view: "folders", rootPath, folderPath }); + const total = children.totalSize || 1; + const folders = [...children.dirs].sort((a, b) => b.size - a.size); + const files = [...children.files].sort((a, b) => b.size - a.size); + const value = { + rootPath, + path: folderPath, + totalBytes: children.totalSize, + total: bytesText(children.totalSize), + folderCount: children.visibleDirCount, + fileCount: files.length, + folders: folders.slice(0, input.limit).map((dir) => ({ + path: dir.path, + name: Path.basename(dir.path), + sizeBytes: dir.size, + size: bytesText(dir.size), + percent: Math.round((dir.size / total) * 1000) / 10, + fileCount: dir.fileCount, + })), + files: input.includeFiles + ? files.slice(0, input.limit).map((file) => ({ + path: file.path, + name: file.name, + sizeBytes: file.size, + size: bytesText(file.size), + modifiedAt: new Date(file.modifiedAt).toISOString(), + })) + : [], + truncated: children.visibleDirCount > Math.min(input.limit, folders.length) || (input.includeFiles && files.length > input.limit), + hiddenByProtectedFolders: + children.hiddenExcludedCount > 0 + ? { count: children.hiddenExcludedCount, bytes: children.hiddenExcludedBytes, size: bytesText(children.hiddenExcludedBytes) } + : null, + }; + const top = value.folders.slice(0, 6).map((dir) => `${dir.name} ${dir.size}`).join(", "); + const summary = + `${folderPath}: ${value.total} in ${value.folderCount} folders and ${files.length} files.` + + (top ? `\nLargest: ${top}.` : ""); + return { value, summary, activity: `Listed ${folderPath} (${value.total})` }; + }, + ); + + tool( + "diskhound_search_files", + { + title: "Search files", + description: + "Search every file in the latest scan index by path substring, extension, and minimum size; returns the largest matches first. Omit query to match all files (useful with minSizeBytes to find everything over, say, 1 GB).", + inputSchema: { + query: z.string().max(512).optional().describe("Case-insensitive substring of the full path, e.g. 'Downloads' or '.iso'."), + rootPath: z.string().min(1).max(4096).optional().describe("A scanned root, or any path inside one."), + extension: z.string().max(32).optional().describe("Only this extension, e.g. '.mov'."), + minSizeBytes: z.number().int().min(0).optional().describe("Only files at least this large."), + limit: z.number().int().min(1).max(500).default(50).describe("Max results (default 50)."), + }, + annotations: readOnly, + }, + () => ["disk.read"], + async (input) => { + const rootPath = await resolveRoot(input.rootPath); + const extension = input.extension + ? (input.extension.startsWith(".") ? input.extension : `.${input.extension}`).toLowerCase() + : undefined; + const result = await backend.searchIndex(rootPath, { + query: input.query?.trim() || (backend.platform === "win32" ? "\\" : "/"), + extension, + minSizeBytes: input.minSizeBytes, + limit: input.limit, + }); + const hits = [...result.hits].sort((a, b) => b.size - a.size); + const matchedBytes = hits.reduce((sum, hit) => sum + hit.size, 0); + const value = { + rootPath, + filesScanned: result.filesScanned, + truncated: result.truncated, + matchedBytes, + matched: bytesText(matchedBytes), + results: hits.map((hit) => ({ + path: hit.path, + sizeBytes: hit.size, + size: bytesText(hit.size), + modifiedAt: new Date(hit.modifiedAt).toISOString(), + })), + }; + const summary = `${hits.length}${result.truncated ? "+" : ""} matches in ${rootPath} totalling ${value.matched}.`; + return { value, summary, activity: `Searched ${rootPath}${input.query ? ` for "${input.query}"` : ""}` }; + }, + ); + + tool( + "diskhound_cleanup_suggestions", + { + title: "Cleanup suggestions", + description: + "DiskHound's rule-based cleanup suggestions for a root (temp files, caches, old downloads, installers, logs, large media) with a risk level and reasoning for each. Treat these as leads to verify with the user, not a delete list.", + inputSchema: { + rootPath: z.string().min(1).max(4096).optional().describe("A scanned root, or any path inside one."), + pathsPerSuggestion: z.number().int().min(1).max(50).default(8).describe("Example paths per suggestion (default 8)."), + }, + annotations: readOnly, + }, + () => ["disk.read"], + async (input) => { + const rootPath = await resolveRoot(input.rootPath); + const analysis = await backend.cleanupSuggestions(rootPath); + const suggestions = [...analysis.suggestions].sort((a, b) => b.totalSize - a.totalSize); + const value = { + rootPath, + totalReclaimableBytes: analysis.totalReclaimableBytes, + totalReclaimable: bytesText(analysis.totalReclaimableBytes), + suggestions: suggestions.map((suggestion) => ({ + title: suggestion.title, + category: suggestion.category, + risk: suggestion.risk, + sizeBytes: suggestion.totalSize, + size: bytesText(suggestion.totalSize), + fileCount: suggestion.fileCount, + description: suggestion.description, + reasoning: suggestion.reasoning, + examplePaths: suggestion.paths.slice(0, input.pathsPerSuggestion), + morePaths: Math.max(0, suggestion.paths.length - input.pathsPerSuggestion), + })), + note: platformSpaceNote(backend.platform), + }; + const summary = + `${suggestions.length} suggestions for ${rootPath}, up to ${value.totalReclaimable} reclaimable.` + + (suggestions.length + ? `\n${suggestions.slice(0, 5).map((s) => `${s.title}: ${bytesText(s.totalSize)} (${s.risk} risk)`).join("\n")}` + : ""); + return { value, summary, activity: `Reviewed cleanup suggestions for ${rootPath}` }; + }, + ); + + tool( + "diskhound_dev_artifacts", + { + title: "Developer artifacts", + description: + "Developer disk hogs found in the latest scan, grouped by kind: git worktrees, node_modules, Rust target/, JS build output, Python venvs, Go/JVM/.NET caches, package caches, compiler caches. Each entry names its project, size, and growth since the previous scan. On APFS it also says what removing that tree alone frees once clones are counted, and the result bounds what removing every listed tree together frees.", + inputSchema: { + rootPath: z.string().min(1).max(4096).optional().describe("A scanned root, or any path inside one."), + kind: z + .enum(["worktree", "node-modules", "package-cache", "rust-target", "cargo-registry", "js-build", "python", "go-module", "jvm", "dotnet", "compiler-cache", "cmake-build", "diag-logs"]) + .optional() + .describe("Only this kind."), + limit: z.number().int().min(1).max(200).default(30).describe("Max artifacts (default 30)."), + ...showInAppField("Also open DiskHound's Dev Artifacts tab."), + }, + annotations: readOnly, + }, + (input) => withNavigate(input.showInApp), + async (input) => { + const rootPath = await resolveRoot(input.rootPath); + const report = await backend.devArtifacts(rootPath); + await navigateIf(input.showInApp, { view: "dev", rootPath }); + if (!report) { + return { + value: { rootPath, artifacts: [], kindTotals: [], totalBytes: 0 }, + summary: `No developer artifacts recorded for ${rootPath}. Re-scan the root to build the Dev Artifacts index.`, + }; + } + const artifacts = report.artifacts + .filter((artifact) => !input.kind || artifact.kind === input.kind) + .sort((a, b) => b.size - a.size); + const listed = artifacts.slice(0, input.limit); + const together = summarizeDevSharing(listed); + const notes: string[] = []; + if (together.measuredTrees > 0) { + notes.push( + "freesAlone is what removing only that tree frees: its own blocks, plus clone groups whose every copy is inside it. sharedBytes are blocks it shares with files outside it; sharedWith names up to three other Dev Artifacts trees that hold copies. listed.freesTogether bounds what removing every listed tree frees; the low end assumes no two of them share a clone, the high end that they share every one. Both are before the Trash and Time Machine local snapshots.", + ); + } else if (backend.platform === "darwin" && artifacts.some((a) => a.kind === "node-modules" || a.kind === "package-cache")) { + notes.push( + "On APFS, pnpm (and other tools using clonefile) clone package files from a shared store, so node_modules trees share blocks with the store and each other. Deleting one tree frees only its unshared blocks; the space returns when the last clone (including the store copy, via `pnpm store prune`) is gone.", + ); + } + if (backend.platform !== "darwin" && backend.platform !== "win32" && artifacts.some((a) => a.kind === "node-modules")) { + notes.push( + "On Linux, pnpm hardlinks node_modules files to its store. DiskHound counts each link, so node_modules sizes can overstate what deleting them frees; prune the store (`pnpm store prune`) to release shared data.", + ); + } + const value = { + rootPath, + totalBytes: report.totalBytes, + total: bytesText(report.totalBytes), + projectCount: report.projectCount, + kindTotals: report.kindTotals + .slice() + .sort((a, b) => b.size - a.size) + .map((bucket) => ({ kind: bucket.kind, sizeBytes: bucket.size, size: bytesText(bucket.size), count: bucket.count })), + artifacts: listed.map((artifact) => { + const sharing = devArtifactSharing(artifact); + return { + path: artifact.path, + kind: artifact.kind, + project: artifact.projectName, + projectPath: artifact.projectPath, + sizeBytes: artifact.size, + size: bytesText(artifact.size), + ...(sharing.measured && sharing.freesBytes !== null + ? { + freesAloneBytes: sharing.freesBytes, + freesAlone: bytesText(sharing.freesBytes), + sharedBytes: sharing.sharedBytes, + sharedWith: sharing.sharedWith, + } + : sharing.hint + ? { sharingHint: sharing.hint.detail } + : {}), + fileCount: artifact.fileCount, + growthSincePreviousScan: artifact.deltaBytes === null ? null : bytesText(Math.abs(artifact.deltaBytes)) + (artifact.deltaBytes < 0 ? " smaller" : " larger"), + }; + }), + ...(together.measuredTrees > 0 + ? { + listed: { + count: listed.length, + sizeBytes: together.totalBytes, + size: bytesText(together.totalBytes), + freesTogether: { + atLeastBytes: together.freesBytes, + atMostBytes: together.freesAtMostBytes, + atLeast: bytesText(together.freesBytes), + atMost: bytesText(together.freesAtMostBytes), + }, + }, + } + : {}), + truncated: artifacts.length > input.limit, + notes, + }; + const summary = + `${value.total} of developer artifacts across ${report.projectCount} projects in ${rootPath}.` + + `\n${value.kindTotals.slice(0, 6).map((bucket) => `${bucket.kind}: ${bucket.size} (${bucket.count})`).join(", ")}` + + (value.listed + ? `\nRemoving the ${value.listed.count} listed (${value.listed.size}) frees ${ + together.freesBytes === together.freesAtMostBytes + ? value.listed.freesTogether.atLeast + : `${value.listed.freesTogether.atLeast}โ€“${value.listed.freesTogether.atMost}` + }, after APFS clones.` + : "") + + (value.listed && backend.measureRemoval + ? "\nFor the exact figure for the trees you pick, call diskhound_measure_removal with their paths." + : ""); + return { value, summary, activity: `Reviewed dev artifacts in ${rootPath}` }; + }, + ); + + // Missing on Windows, where the scan counts each file once already. + const measureRemoval = backend.measureRemoval?.bind(backend); + if (measureRemoval) { + tool( + "diskhound_measure_removal", + { + title: "Measure what removing items frees", + description: + "How much space removing a set of files and folders together would free, measured on disk now. Sizes overstate it when blocks are shared: " + + "an APFS clone's blocks come back only when every clone is gone, including clones outside the set and outside any scan, and a hardlinked file only when every name is gone. " + + "Returns the total for the whole set and what each path frees alone. Use it before saying what a cleanup frees, or to pick the items that free the most. " + + "Reads metadata only. Millions of files take a minute or two; if your client times out, call again with the same paths and DiskHound answers from the measurement it finished.", + inputSchema: { + paths: z + .array(z.string().min(1).max(4096)) + .min(1) + .max(1000) + .describe("Absolute paths of the files and folders to measure as one set."), + limit: z.number().int().min(1).max(1000).default(50).describe("Paths to list, most freed first (default 50). The totals cover every path."), + }, + annotations: readOnly, + }, + () => ["disk.read"], + async (input) => { + const paths = [...new Set(input.paths.map((path) => agentPath(path, backend.platform)))]; + const root = paths.find((path) => normPath(path) === normPath(Path.parse(path).root)); + if (root) { + throw new Error(`${root} is a whole drive. Measure the folders you might remove; diskhound_scan_summary covers the drive.`); + } + const measured = await measureRemoval(paths, options.signal); + const { total } = measured; + const ranked = [...measured.paths].sort((a, b) => b.freesAloneBytes - a.freesAloneBytes || b.sizeBytes - a.sizeBytes); + const aloneBytes = ranked.reduce((sum, path) => sum + path.freesAloneBytes, 0); + const notes: string[] = []; + if (backend.platform === "darwin") { + if (!measured.cloneMetadata) notes.push("These paths aren't on APFS, so clones weren't checked."); + notes.push( + "Blocks come back once the Trash is emptied (DiskHound's permanent delete skips it), and a Time Machine local snapshot can hold them until it expires.", + ); + } else { + notes.push("Hardlinks are counted. btrfs/XFS reflinks and snapshots aren't, so the space may come back later than this says."); + } + if (total.uncertainBytes > 0) { + notes.push( + "uncertainBytes belong to rewritten clones: they share them with clones DiskHound can't identify, so removal frees between freesBytes and freesBytes + uncertainBytes.", + ); + } + const value = { + measuredAt: new Date(measured.measuredAt).toISOString(), + elapsedMs: measured.elapsedMs, + total: { + files: total.files, + sizeBytes: total.sizeBytes, + size: bytesText(total.sizeBytes), + freesBytes: total.freesBytes, + frees: bytesText(total.freesBytes), + freesOneAtATimeBytes: aloneBytes, + heldElsewhereBytes: total.heldElsewhereBytes, + heldElsewhere: bytesText(total.heldElsewhereBytes), + uncertainBytes: total.uncertainBytes, + }, + paths: ranked.slice(0, input.limit).map((path) => ({ + path: path.path, + kind: path.kind, + files: path.files, + sizeBytes: path.sizeBytes, + size: bytesText(path.sizeBytes), + freesAloneBytes: path.freesAloneBytes, + freesAlone: bytesText(path.freesAloneBytes), + sharedBytes: path.sharedBytes, + uncertainBytes: path.uncertainBytes, + })), + truncated: ranked.length > input.limit, + missing: measured.missing, + nested: measured.nested, + skippedEntries: measured.skippedEntries, + notes, + }; + const count = plural(ranked.length, "item"); + const summary = [ + `Removing these ${count} together frees ${bytesText(total.freesBytes)} of the ${bytesText(total.sizeBytes)} they take up (${total.files.toLocaleString()} files).`, + total.heldElsewhereBytes > 0 + ? `${bytesText(total.heldElsewhereBytes)} stays in use because files outside them share it (APFS clones or hardlinks).` + : null, + total.freesBytes > aloneBytes && ranked.length > 1 + ? `One at a time they'd free ${bytesText(aloneBytes)}; together frees ${bytesText(total.freesBytes - aloneBytes)} more, because they share clones or hardlinks with each other.` + : null, + total.uncertainBytes > 0 ? `Up to ${bytesText(total.uncertainBytes)} more might come back (rewritten clones).` : null, + ...ranked.slice(0, 5).map((path) => `${path.path}: frees ${bytesText(path.freesAloneBytes)} alone (${bytesText(path.sizeBytes)} on disk)`), + measured.missing.length ? `Not found: ${measured.missing.join(", ")}.` : null, + ].filter(Boolean).join("\n"); + return { value, summary, activity: `Measured what removing ${count} frees` }; + }, + ); + } + + tool( + "diskhound_scan_history", + { + title: "Scan history", + description: "Completed scans DiskHound kept for a root, newest first, with totals. Use the ids with diskhound_changes.", + inputSchema: { + rootPath: z.string().min(1).max(4096).optional().describe("A scanned root, or any path inside one."), + }, + annotations: readOnly, + }, + () => ["disk.read"], + async (input) => { + const rootPath = await resolveRoot(input.rootPath); + const nowMs = now(); + const history = backend.scanHistory(rootPath); + const value = { + rootPath, + scans: history.map((entry) => ({ + id: entry.id, + scannedAt: new Date(entry.scannedAt).toISOString(), + age: ageText(entry.scannedAt, nowMs), + bytesSeen: entry.bytesSeen, + size: bytesText(entry.bytesSeen), + files: entry.filesVisited, + engine: entry.engine ?? null, + })), + }; + const summary = `${history.length} scans kept for ${rootPath}` + + (history.length ? `, newest ${ageText(history[0]!.scannedAt, nowMs)}, oldest ${ageText(history[history.length - 1]!.scannedAt, nowMs)}.` : "."); + return { value, summary, activity: `Read scan history for ${rootPath}` }; + }, + ); + + tool( + "diskhound_changes", + { + title: "Changes between scans", + description: + "What grew, shrank, appeared, or disappeared between two scans of a root. By default compares the latest scan with the one before it; pass since (1h, 6h, 1d, 1w, 1M, 3M) or explicit scan ids from diskhound_scan_history. detail='summary' gives the biggest folder, file, and file-type deltas; detail='files' walks the full per-file index (slower on big drives).", + inputSchema: { + rootPath: z.string().min(1).max(4096).optional().describe("A scanned root, or any path inside one."), + since: z.enum(["1h", "6h", "1d", "1w", "1M", "3M"]).optional().describe("Compare against the newest scan at least this old."), + baselineId: z.string().max(200).optional().describe("Older scan id."), + currentId: z.string().max(200).optional().describe("Newer scan id (default: latest)."), + detail: z.enum(["summary", "files"]).default("summary"), + limit: z.number().int().min(1).max(200).default(25).describe("Rows per list (default 25)."), + ...showInAppField("Also open DiskHound's Changes tab."), + }, + annotations: readOnly, + }, + (input) => withNavigate(input.showInApp), + async (input) => { + const rootPath = await resolveRoot(input.rootPath); + const history = backend.scanHistory(rootPath); + const current: ScanHistoryEntry | undefined = input.currentId + ? history.find((entry) => entry.id === input.currentId) + : history[0]; + if (!current) throw new Error(`No scan ${input.currentId ?? ""} for ${rootPath}.`); + let baseline: ScanHistoryEntry | undefined; + if (input.baselineId) { + baseline = history.find((entry) => entry.id === input.baselineId); + } else if (input.since) { + const cutoff = current.scannedAt - SINCE_MS[input.since]!; + baseline = history.find((entry) => entry.scannedAt <= cutoff) ?? history[history.length - 1]; + } else { + baseline = history.find((entry) => entry.scannedAt < current.scannedAt); + } + if (!baseline || baseline.id === current.id) { + throw new Error(`Only one scan of ${rootPath} is kept, so there is nothing to compare yet. Run another scan later.`); + } + await navigateIf(input.showInApp, { view: "changes", rootPath }); + const span = `${ageText(baseline.scannedAt, now())} โ†’ ${ageText(current.scannedAt, now())}`; + if (input.detail === "files") { + const full = await backend.fullDiff(baseline.id, current.id, input.limit); + if (!full) throw new Error("The per-file index for one of these scans is missing; try detail='summary'."); + const value = { + rootPath, + baselineId: baseline.id, + currentId: current.id, + span, + totals: { + changes: full.totalChanges, + added: full.totalAdded, + removed: full.totalRemoved, + grew: full.totalGrew, + shrank: full.totalShrank, + bytesAdded: full.totalBytesAdded, + bytesRemoved: full.totalBytesRemoved, + net: `${full.totalBytesAdded >= full.totalBytesRemoved ? "+" : "-"}${bytesText(Math.abs(full.totalBytesAdded - full.totalBytesRemoved))}`, + }, + changes: full.changes.map((change) => ({ + path: change.path, + kind: change.kind, + deltaBytes: change.deltaBytes, + delta: `${change.deltaBytes >= 0 ? "+" : "-"}${bytesText(Math.abs(change.deltaBytes))}`, + size: bytesText(change.size), + })), + truncated: full.truncated, + }; + return { + value, + summary: `${full.totalChanges.toLocaleString()} file changes in ${rootPath} (${span}), net ${value.totals.net}.`, + activity: `Compared scans of ${rootPath} (${span})`, + }; + } + const diff = await backend.diff(baseline.id, current.id); + if (!diff) throw new Error("One of these scans could not be loaded."); + const signed = (bytes: number) => `${bytes >= 0 ? "+" : "-"}${bytesText(Math.abs(bytes))}`; + const value = { + rootPath, + baselineId: baseline.id, + currentId: current.id, + span, + netBytes: diff.totalBytesDelta, + net: signed(diff.totalBytesDelta), + filesDelta: diff.totalFilesDelta, + sizeSemanticsChanged: diff.sizeSemanticsChanged, + hardlinkAccountingChanged: diff.hardlinkAccountingChanged, + volumeAccountingChanged: diff.volumeAccountingChanged, + folders: [...diff.directoryDeltas] + .sort((a, b) => Math.abs(b.deltaBytes) - Math.abs(a.deltaBytes)) + .slice(0, input.limit) + .map((dir) => ({ path: dir.path, kind: dir.kind, deltaBytes: dir.deltaBytes, delta: signed(dir.deltaBytes), size: bytesText(dir.size) })), + files: [...diff.fileDeltas] + .sort((a, b) => Math.abs(b.deltaBytes) - Math.abs(a.deltaBytes)) + .slice(0, input.limit) + .map((file) => ({ path: file.path, kind: file.kind, deltaBytes: file.deltaBytes, delta: signed(file.deltaBytes), size: bytesText(file.size) })), + fileTypes: [...diff.extensionDeltas] + .sort((a, b) => Math.abs(b.deltaBytes) - Math.abs(a.deltaBytes)) + .slice(0, input.limit) + .map((ext) => ({ extension: ext.extension, deltaBytes: ext.deltaBytes, delta: signed(ext.deltaBytes) })), + note: "Folder and file lists are the top movers DiskHound tracks per scan; use detail='files' for every file.", + }; + const top = value.folders.slice(0, 5).map((dir) => `${dir.path} ${dir.delta}`).join(", "); + // Same caveats the Changes tab shows: a change in accounting moves + // the totals without any file changing. + const caveat = diff.sizeSemanticsChanged + ? "\nThese scans measured sizes differently (file size vs size on disk), so the totals aren't comparable. Compare two scans taken after the next one." + : diff.hardlinkAccountingChanged + ? "\nThe older scan counted a hardlinked file once per link; newer scans count it once. Part of this change is accounting, not space freed or used." + : diff.volumeAccountingChanged + ? "\nThe older scan walked the macOS Data volume twice and counted other mounted disks; newer scans count each folder once and stay on their disk. Part of this change is accounting, not space freed or used." + : ""; + return { + value, + summary: `${rootPath} changed ${value.net} (${span}).` + (top ? `\nBiggest folder moves: ${top}.` : "") + caveat, + activity: `Compared scans of ${rootPath} (${span})`, + }; + }, + ); + + tool( + "diskhound_duplicates", + { + title: "Duplicate files", + description: + "Results of the most recent duplicate-file search for a root (content-hash matches), largest reclaimable groups first, or its progress if still running. Start one with diskhound_find_duplicates.", + inputSchema: { + rootPath: z.string().min(1).max(4096).optional().describe("The root the duplicate search ran on."), + limit: z.number().int().min(1).max(200).default(20).describe("Max groups (default 20)."), + ...showInAppField("Also open DiskHound's Duplicates tab."), + }, + annotations: readOnly, + }, + (input) => withNavigate(input.showInApp), + async (input) => { + const rootPath = input.rootPath ? agentPath(input.rootPath, backend.platform) : await resolveRoot(); + const state = backend.duplicates(rootPath); + await navigateIf(input.showInApp, { view: "duplicates", rootPath }); + if (!state.analysis) { + const progress = state.progress; + return { + value: { + rootPath, + running: state.running, + progress: progress + ? { status: progress.status, filesWalked: progress.filesWalked, filesHashed: progress.filesHashed, groupsConfirmed: progress.groupsConfirmed, errorMessage: progress.errorMessage } + : null, + }, + summary: state.running + ? `Duplicate search on ${rootPath} is running (${progress?.filesHashed ?? 0} files hashed). Check again shortly.` + : `No duplicate search results for ${rootPath}. Start one with diskhound_find_duplicates.`, + }; + } + const analysis = state.analysis; + const groups = [...analysis.groups] + .map((group) => ({ group, wasted: duplicateGroupReclaimable(group) })) + .sort((a, b) => b.wasted - a.wasted); + const value = { + rootPath: analysis.rootPath, + running: state.running, + analyzedAt: new Date(analysis.analyzedAt).toISOString(), + totalGroups: analysis.totalGroups, + totalDuplicateFiles: analysis.totalDuplicateFiles, + reclaimableBytes: analysis.totalWastedBytes, + reclaimable: bytesText(analysis.totalWastedBytes), + groups: groups.slice(0, input.limit).map(({ group, wasted }) => ({ + fileSizeBytes: group.size, + fileSize: bytesText(group.size), + copies: group.files.length, + reclaimableBytes: wasted, + reclaimable: bytesText(wasted), + files: group.files.slice(0, 12).map((file) => ({ + path: file.path, + modifiedAt: new Date(file.modifiedAt).toISOString(), + reclaimableBytes: entryReclaimable(file, group.size), + sharing: file.sharing ?? null, + })), + })), + truncated: groups.length > input.limit, + note: + backend.platform === "darwin" + ? "Identical content is not always duplicated storage: APFS clones and hardlinks share blocks, so deleting one copy may free nothing. Confirm with the user before removing copies." + : "Identical content is not always duplicated storage: hardlinks (and reflinks on btrfs/XFS/ReFS) share blocks. Keep the copy the user actually uses.", + }; + return { + value, + summary: `${analysis.totalGroups} duplicate groups in ${analysis.rootPath}, ${value.reclaimable} reclaimable if extra copies are removed.`, + activity: `Reviewed duplicates in ${analysis.rootPath}`, + }; + }, + ); + + // โ”€โ”€ Tools that start work โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + tool( + "diskhound_start_scan", + { + title: "Start scan", + description: + "Scan a drive or folder (metadata only; no files are changed). Repeat scans of the same root are incremental and fast. Returns immediately; poll diskhound_status until the root leaves activeScans, then use the read tools. Refuses to restart a running scan unless restart is true.", + inputSchema: { + rootPath: z.string().min(1).max(4096).describe("Drive root (e.g. '/', 'C:\\\\') or any folder."), + restart: z.boolean().default(false).describe("Cancel and restart if this root is already scanning."), + ...showInAppByDefault("Switch the DiskHound window to this root so the user sees progress (default true)."), + }, + annotations: startsWork, + }, + (input) => (input.showInApp ? ["scan.run", "app.navigate"] : ["scan.run"]), + async (input) => { + const rootPath = agentPath(input.rootPath, backend.platform); + const running = (await backend.activeScans()).find((snap) => snap.rootPath && normPath(snap.rootPath) === normPath(rootPath)); + if (running && !input.restart) { + return { + value: { rootPath, started: false, alreadyRunning: true, filesVisited: running.filesVisited, bytesSeen: running.bytesSeen }, + summary: `A scan of ${rootPath} is already running (${running.filesVisited.toLocaleString()} files so far). Poll diskhound_status.`, + activity: `Checked running scan of ${rootPath}`, + }; + } + const snapshot = await backend.startScan(rootPath); + await navigateIf(input.showInApp, { view: "overview", rootPath }); + const finished = snapshot.status === "done"; + return { + value: { rootPath, started: true, status: snapshot.status, engine: snapshot.engine }, + summary: finished + ? `Nothing changed on ${rootPath} since the last scan; DiskHound reused it. Read results now.` + : `Scan of ${rootPath} started (${snapshot.engine}). Poll diskhound_status until it finishes.`, + activity: `Started a scan of ${rootPath}`, + }; + }, + ); + + tool( + "diskhound_cancel_scan", + { + title: "Cancel scan", + description: "Cancel the running scan for a root. The previous completed scan stays available.", + inputSchema: { + rootPath: z.string().min(1).max(4096).describe("The root being scanned."), + }, + annotations: steersApp, + }, + () => ["scan.run"], + async (input) => { + const rootPath = agentPath(input.rootPath, backend.platform); + await backend.cancelScan(rootPath); + return { value: { rootPath, cancelled: true }, summary: `Cancelled the scan of ${rootPath} (if one was running).` }; + }, + ); + + tool( + "diskhound_find_duplicates", + { + title: "Find duplicate files", + description: + "Start a duplicate-file search (content hashing) under a folder or drive. Uses the latest scan index when one covers the path, which is much faster than walking the disk. Returns immediately; read results with diskhound_duplicates. Hashing a whole drive can take many minutes โ€” prefer a specific folder like Downloads or a media library.", + inputSchema: { + rootPath: z.string().min(1).max(4096).describe("Folder or drive to search."), + minSizeBytes: z.number().int().min(0).default(1024 * 1024).describe("Ignore files smaller than this (default 1 MiB)."), + ...showInAppByDefault("Open DiskHound's Duplicates tab on this root (default true)."), + }, + annotations: startsWork, + }, + (input) => (input.showInApp ? ["scan.run", "app.navigate"] : ["scan.run"]), + async (input) => { + const rootPath = agentPath(input.rootPath, backend.platform); + const state = backend.duplicates(rootPath); + if (state.running) { + return { + value: { rootPath, started: false, alreadyRunning: true }, + summary: `A duplicate search on ${rootPath} is already running. Read progress with diskhound_duplicates.`, + }; + } + backend.startDuplicateScan(rootPath, input.minSizeBytes); + await navigateIf(input.showInApp, { view: "duplicates", rootPath }); + return { + value: { rootPath, started: true, minSizeBytes: input.minSizeBytes }, + summary: `Duplicate search started on ${rootPath}. Poll diskhound_duplicates for progress and results.`, + activity: `Started a duplicate search in ${rootPath}`, + }; + }, + ); + + // โ”€โ”€ Tools that steer the window โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + tool( + "diskhound_show", + { + title: "Show in DiskHound", + description: + "Point the DiskHound window at something so the user can see it: a tab (overview, files, folders, dev, duplicates, easyMove, changes, settings), optionally a scan root, and for the Folders tab a folder to open. Does not steal focus unless focus is true.", + inputSchema: { + view: z.enum(VIEWS).describe("Tab to show."), + rootPath: z.string().min(1).max(4096).optional().describe("Scan root to show (default: current)."), + folderPath: z.string().min(1).max(4096).optional().describe("With view='folders', the folder to open."), + focus: z.boolean().default(false).describe("Bring the window to the front."), + }, + annotations: steersApp, + }, + () => ["app.navigate"], + async (input) => { + const folderPath = input.folderPath ? agentPath(input.folderPath, backend.platform) : undefined; + const rootPath = input.rootPath + ? agentPath(input.rootPath, backend.platform) + : folderPath + ? await resolveRoot(folderPath) + : undefined; + await backend.navigate({ view: input.view as AppView, rootPath, folderPath, focus: input.focus }); + const target = folderPath ?? rootPath; + return { + value: { view: input.view, rootPath: rootPath ?? null, folderPath: folderPath ?? null }, + summary: `DiskHound is showing ${input.view}${target ? ` for ${target}` : ""}.`, + }; + }, + ); + + tool( + "diskhound_reveal_path", + { + title: "Reveal in file manager", + description: "Open Finder / Explorer / the Linux file manager with this file or folder selected, so the user can inspect it themselves.", + inputSchema: { + path: z.string().min(1).max(4096).describe("Absolute path to reveal."), + }, + annotations: steersApp, + }, + () => ["app.navigate"], + async (input) => { + const target = agentPath(input.path, backend.platform); + const result = await backend.revealPath(target); + if (!result.ok) throw new Error(result.message); + return { value: { path: target, revealed: true }, summary: `Revealed ${target}.` }; + }, + ); + + // โ”€โ”€ Trash and delete (user-confirmed) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`; + const bin = backend.platform === "win32" ? "Recycle Bin" : "Trash"; + + tool( + "diskhound_move_to_trash", + { + title: "Move to Trash (asks the user)", + description: + "Ask the user to move files or folders to the Trash / Recycle Bin. DiskHound shows a confirmation dialog listing every item and its size; nothing moves unless the user clicks Move to Trash, and the user can restore items until the Trash is emptied. Protected folders from DiskHound settings are always refused, and so are drive roots, the home folder and its standard folders (Documents, Downloads, Library, AppDataโ€ฆ), and anything containing them. Explain to the user what you are proposing and why before calling this.", + inputSchema: { + paths: z.array(z.string().min(1).max(4096)).min(1).max(MAX_TRASH_PATHS).describe("Absolute paths to move to the Trash."), + reason: z.string().max(500).optional().describe("One sentence shown in the dialog explaining why."), + }, + annotations: trashes, + }, + () => ["files.trash"], + async (input, auth) => { + const paths = [...new Set(input.paths.map((p) => agentPath(p, backend.platform)))]; + const outcome = await backend.confirmAndTrash({ + sessionId: auth.sessionId, + sessionName: auth.sessionName, + roleName: auth.roleName, + paths, + reason: input.reason, + recheck: async () => { + await authorizer.authorize(["files.trash"]); + }, + signal: options.signal, + }); + if (!outcome.confirmed) { + return { + value: { confirmed: false, results: [] }, + summary: "The user declined. Nothing was moved.", + activity: `Asked to move ${plural(paths.length, "item")} to the ${bin}; declined`, + }; + } + const moved = outcome.results.filter((result) => result.ok); + const movedBytes = moved.reduce((sum, result) => sum + (result.sizeBytes ?? 0), 0); + return { + value: { + confirmed: true, + movedCount: moved.length, + movedBytes, + moved: removedText(moved), + results: outcome.results, + note: platformSpaceNote(backend.platform), + }, + summary: + `Moved ${moved.length} of ${plural(outcome.results.length, "item")} (${removedText(moved)}) to the ${bin}.` + + (moved.length < outcome.results.length + ? `\nNot moved: ${outcome.results.filter((r) => !r.ok).map((r) => `${r.path} (${r.message})`).join("; ")}` + : "") + + `\n${platformSpaceNote(backend.platform)}`, + activity: `Moved ${plural(moved.length, "item")} (${removedText(moved)}) to the ${bin}`, + }; + }, + ); + + tool( + "diskhound_delete_permanently", + { + title: "Delete permanently (asks the user)", + description: + `Ask the user to delete files or folders permanently, without the ${bin}. DiskHound shows a confirmation dialog listing every item and its size; nothing is deleted unless the user clicks Delete Permanently, and deleted items can't be restored. Use diskhound_move_to_trash instead unless the user asked for a permanent delete (for example to free space right away, or for items too large for the ${bin}). The same folders are refused as for the ${bin}. Explain to the user what you are proposing and why before calling this.`, + inputSchema: { + paths: z.array(z.string().min(1).max(4096)).min(1).max(MAX_TRASH_PATHS).describe("Absolute paths to delete permanently."), + reason: z.string().max(500).optional().describe("One sentence shown in the dialog explaining why."), + }, + annotations: deletes, + }, + () => ["files.delete"], + async (input, auth) => { + const paths = [...new Set(input.paths.map((p) => agentPath(p, backend.platform)))]; + const outcome = await backend.confirmAndDelete({ + sessionId: auth.sessionId, + sessionName: auth.sessionName, + roleName: auth.roleName, + paths, + reason: input.reason, + recheck: async () => { + await authorizer.authorize(["files.delete"]); + }, + signal: options.signal, + }); + if (!outcome.confirmed) { + return { + value: { confirmed: false, results: [] }, + summary: "The user declined. Nothing was deleted.", + activity: `Asked to delete ${plural(paths.length, "item")} permanently; declined`, + }; + } + const deleted = outcome.results.filter((result) => result.ok); + const deletedBytes = deleted.reduce((sum, result) => sum + (result.sizeBytes ?? 0), 0); + return { + value: { + confirmed: true, + deletedCount: deleted.length, + deletedBytes, + deleted: removedText(deleted), + results: outcome.results, + }, + summary: + `Deleted ${deleted.length} of ${plural(outcome.results.length, "item")} (${removedText(deleted)}) permanently.` + + (deleted.length < outcome.results.length + ? `\nNot deleted: ${outcome.results.filter((r) => !r.ok).map((r) => `${r.path} (${r.message})`).join("; ")}` + : "") + + (backend.platform === "darwin" + ? "\nOn APFS, cloned files and Time Machine local snapshots can keep some of this space in use." + : ""), + activity: `Deleted ${plural(deleted.length, "item")} (${removedText(deleted)}) permanently`, + }; + }, + ); + + // โ”€โ”€ Skills (SEP-2640) + prompt fallbacks โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + registerSkills(mcp, skills); + + const skillText = (uri: string) => + skills.skills.find((skill) => skill.uri === uri)?.files.find((file) => file.relativePath === "SKILL.md")?.text; + + const promptFromSkill = (uri: string, ask: string): GetPromptResult => { + const text = skillText(uri); + return { + messages: [ + ...(text + ? [{ role: "user" as const, content: { type: "resource" as const, resource: { uri, mimeType: "text/markdown", text } } }] + : []), + { role: "user" as const, content: { type: "text" as const, text: ask } }, + ], + }; + }; + + if (skillText(FREE_UP_SPACE_SKILL)) { + mcp.registerPrompt( + "free-up-space", + { + title: "Free up disk space with DiskHound", + description: "Loads DiskHound's cleanup skill and starts a guided hunt for reclaimable space.", + argsSchema: { + goal: z.string().max(200).optional().describe("e.g. 'free 50 GB' or 'make room for Xcode'"), + path: z.string().max(4096).optional().describe("Drive or folder to focus on"), + }, + }, + ({ goal, path }) => + promptFromSkill( + FREE_UP_SPACE_SKILL, + `Follow the DiskHound skill above to help me free up disk space${path ? ` on ${path}` : ""}${goal ? ` โ€” goal: ${goal}` : ""}. ` + + "Start with diskhound_status, show your findings in the DiskHound window as you go, and ask before moving anything to the Trash.", + ), + ); + } + if (skillText(INVESTIGATE_GROWTH_SKILL)) { + mcp.registerPrompt( + "investigate-growth", + { + title: "Why did my disk fill up?", + description: "Loads DiskHound's growth-investigation skill and compares scans to find what grew.", + argsSchema: { + since: z.string().max(20).optional().describe("How far back to look, e.g. 1d, 1w, 1M"), + path: z.string().max(4096).optional().describe("Drive or folder to investigate"), + }, + }, + ({ since, path }) => + promptFromSkill( + INVESTIGATE_GROWTH_SKILL, + `Follow the DiskHound skill above to find out what has been using up space${path ? ` on ${path}` : ""}${since ? ` over the last ${since}` : ""}.`, + ), + ); + } + + return mcp; +} diff --git a/src/mcp/skills.ts b/src/mcp/skills.ts new file mode 100644 index 00000000..d0dbac47 --- /dev/null +++ b/src/mcp/skills.ts @@ -0,0 +1,277 @@ +import { createHash } from "node:crypto"; +import { readdirSync, readFileSync, statSync } from "node:fs"; +import * as Path from "node:path"; + +import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { z } from "zod"; + +import { SKILLS_EXTENSION_ID } from "../shared/agentAccess"; + +/** + * Agent Skills served over MCP per SEP-2640 ("Skills Extension"). + * + * Skills are plain directories under `/skills//` with a + * `SKILL.md` at the root (agentskills.io format). At startup we read + * every file once, compute its SHA-256, and expose it three ways: + * + * - as a resource at `skill:///` (resources/read), + * - through `skills/list` / `skills/get`, which return each skill's + * verbatim frontmatter plus a complete `{uri, digest, size}` + * manifest so hosts can verify what they load, + * - through `resources/directory/read`, so a SKILL.md that says "see + * references/" can be navigated without enumerating the server. + * + * Content is static for the life of the process, so digests are stable + * and `resources` is always the enumerated array form (never "dynamic"). + */ + +export interface SkillFile { + uri: string; + relativePath: string; + mimeType: string; + text: string; + size: number; + digest: string; +} + +export interface SkillEntry { + name: string; + /** `skill:///SKILL.md` */ + uri: string; + /** `skill://` โ€” the skill's root directory resource. */ + rootUri: string; + frontmatter: Record; + files: SkillFile[]; +} + +export interface SkillCatalog { + skills: SkillEntry[]; +} + +interface DirectoryChild { + uri: string; + name: string; + mimeType: string; + description?: string; +} + +// agentskills.io: 1โ€“64 chars, lowercase alnum + single hyphens. +const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; +const MAX_FILES_PER_SKILL = 512; +const MAX_BYTES_PER_SKILL = 16 * 1024 * 1024; + +const MIME_BY_EXTENSION: Record = { + ".md": "text/markdown", + ".txt": "text/plain", + ".json": "application/json", + ".sh": "text/x-shellscript", + ".ps1": "text/plain", +}; + +/** + * Parse the flat `key: value` YAML frontmatter our skills use. This is + * deliberately not a general YAML parser: anything beyond flat scalars + * throws, and the catalog test runs every bundled skill through it, so + * an unsupported construct fails CI instead of shipping a skill whose + * `frontmatter` isn't a verbatim copy of what's on disk. + */ +export function parseSkillFrontmatter(markdown: string): Record { + const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown); + if (!match) throw new Error("SKILL.md must begin with YAML frontmatter"); + const fields: Record = {}; + for (const rawLine of match[1]!.split(/\r?\n/)) { + if (rawLine.trim() === "" || rawLine.trimStart().startsWith("#")) continue; + const line = /^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/.exec(rawLine); + if (!line) throw new Error(`Unsupported frontmatter line: ${rawLine}`); + const key = line[1]!; + let value = line[2]!.trim(); + if (value === "" || value === "|" || value === ">" || value.startsWith("|") || value.startsWith(">")) { + throw new Error(`Frontmatter field "${key}" must be a single-line scalar`); + } + if ((value.startsWith("\"") && value.endsWith("\"")) || (value.startsWith("'") && value.endsWith("'"))) { + value = value.slice(1, -1); + } + if (key in fields) throw new Error(`Duplicate frontmatter field "${key}"`); + fields[key] = value; + } + return fields; +} + +function listFiles(directory: string, prefix = ""): string[] { + const out: string[] = []; + for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) { + if (entry.name.startsWith(".")) continue; + const relative = prefix ? `${prefix}/${entry.name}` : entry.name; + const full = Path.join(directory, entry.name); + if (entry.isDirectory()) out.push(...listFiles(full, relative)); + else if (entry.isFile()) out.push(relative); + } + return out; +} + +export function loadSkillCatalog(skillsRoot: string): SkillCatalog { + let names: string[]; + try { + names = readdirSync(skillsRoot, { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")) + .map((entry) => entry.name) + .sort(); + } catch { + return { skills: [] }; + } + + const skills: SkillEntry[] = []; + for (const directoryName of names) { + const directory = Path.join(skillsRoot, directoryName); + try { + statSync(Path.join(directory, "SKILL.md")); + } catch { + continue; + } + const skillMd = readFileSync(Path.join(directory, "SKILL.md"), "utf8"); + const frontmatter = parseSkillFrontmatter(skillMd); + const name = frontmatter.name; + const description = frontmatter.description; + if (!name || !SKILL_NAME.test(name) || name.length > 64) { + throw new Error(`Skill ${directoryName}: name must be 1-64 lowercase letters, digits, and single hyphens`); + } + if (name !== directoryName) { + throw new Error(`Skill ${directoryName}: frontmatter name "${name}" must match its directory`); + } + if (!description || description.length > 1024) { + throw new Error(`Skill ${name}: description is required and must be at most 1024 characters`); + } + + const files: SkillFile[] = listFiles(directory).map((relativePath) => { + const bytes = readFileSync(Path.join(directory, ...relativePath.split("/"))); + return { + uri: `skill://${name}/${relativePath}`, + relativePath, + mimeType: MIME_BY_EXTENSION[Path.extname(relativePath).toLowerCase()] ?? "application/octet-stream", + text: bytes.toString("utf8"), + size: bytes.byteLength, + digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`, + }; + }); + if (files.length > MAX_FILES_PER_SKILL) throw new Error(`Skill ${name}: more than ${MAX_FILES_PER_SKILL} files`); + if (files.reduce((sum, file) => sum + file.size, 0) > MAX_BYTES_PER_SKILL) { + throw new Error(`Skill ${name}: larger than 16 MiB`); + } + + skills.push({ + name, + uri: `skill://${name}/SKILL.md`, + rootUri: `skill://${name}`, + frontmatter, + files, + }); + } + return { skills }; +} + +/** The `skills/list` / `skills/get` entry shape from SEP-2640. */ +export function skillListEntry(skill: SkillEntry) { + return { + uri: skill.uri, + frontmatter: { ...skill.frontmatter }, + resources: skill.files.map((file) => ({ uri: file.uri, digest: file.digest, size: file.size })), + }; +} + +/** + * Direct children of a directory resource (`skill://name` or + * `skill://name/references`). Returns null when the URI isn't a + * directory we serve. + */ +export function readSkillDirectory(catalog: SkillCatalog, uri: string): DirectoryChild[] | null { + const trimmed = uri.replace(/\/+$/, ""); + const skill = catalog.skills.find((candidate) => trimmed === candidate.rootUri || trimmed.startsWith(`${candidate.rootUri}/`)); + if (!skill) return null; + const prefix = trimmed === skill.rootUri ? "" : trimmed.slice(skill.rootUri.length + 1); + const children = new Map(); + let isDirectory = prefix === ""; + for (const file of skill.files) { + if (prefix && !file.relativePath.startsWith(`${prefix}/`)) continue; + isDirectory = true; + const rest = prefix ? file.relativePath.slice(prefix.length + 1) : file.relativePath; + const [head, ...tail] = rest.split("/"); + if (!head) continue; + if (tail.length === 0) { + children.set(head, { + uri: file.uri, + name: head, + mimeType: file.mimeType, + ...(file.relativePath === "SKILL.md" ? { description: skill.frontmatter.description } : {}), + }); + } else if (!children.has(head)) { + children.set(head, { + uri: `${skill.rootUri}/${prefix ? `${prefix}/` : ""}${head}`, + name: head, + mimeType: "inode/directory", + }); + } + } + return isDirectory ? [...children.values()] : null; +} + +const SkillsListRequestSchema = z.object({ + method: z.literal("skills/list"), + params: z.object({ cursor: z.string().optional() }).passthrough().optional(), +}); +const SkillsGetRequestSchema = z.object({ + method: z.literal("skills/get"), + params: z.object({ uri: z.string() }).passthrough(), +}); +const DirectoryReadRequestSchema = z.object({ + method: z.literal("resources/directory/read"), + params: z.object({ uri: z.string(), cursor: z.string().optional() }).passthrough(), +}); + +/** + * Declare the extension and wire its three methods plus one resource + * per skill file. Must run before `connect()` โ€” capabilities are fixed + * at initialize time. + */ +export function registerSkills(mcp: McpServer, catalog: SkillCatalog): void { + // Nothing to serve: don't advertise resources or the skills extension. + if (catalog.skills.length === 0) return; + mcp.server.registerCapabilities({ + resources: {}, + extensions: { [SKILLS_EXTENSION_ID]: { directoryRead: true } }, + }); + + for (const skill of catalog.skills) { + for (const file of skill.files) { + const isSkillMd = file.relativePath === "SKILL.md"; + mcp.registerResource( + isSkillMd ? skill.name : `${skill.name}/${file.relativePath}`, + file.uri, + { + mimeType: file.mimeType, + ...(isSkillMd + ? { title: `Skill: ${skill.name}`, description: skill.frontmatter.description } + : { description: `Supporting file for the ${skill.name} skill.` }), + }, + async () => ({ contents: [{ uri: file.uri, mimeType: file.mimeType, text: file.text }] }), + ); + } + } + + mcp.server.setRequestHandler(SkillsListRequestSchema, async () => ({ + resultType: "complete", + skills: catalog.skills.map(skillListEntry), + })); + + mcp.server.setRequestHandler(SkillsGetRequestSchema, async (request) => { + const skill = catalog.skills.find((candidate) => candidate.uri === request.params.uri); + if (!skill) throw new McpError(ErrorCode.InvalidParams, `Unknown skill: ${request.params.uri}`); + return { resultType: "complete", skill: skillListEntry(skill) }; + }); + + mcp.server.setRequestHandler(DirectoryReadRequestSchema, async (request) => { + const children = readSkillDirectory(catalog, request.params.uri); + if (!children) throw new McpError(ErrorCode.InvalidParams, `Not a directory resource: ${request.params.uri}`); + return { resultType: "complete", resources: children }; + }); +} diff --git a/src/mcp/trashGuard.ts b/src/mcp/trashGuard.ts new file mode 100644 index 00000000..03f342f4 --- /dev/null +++ b/src/mcp/trashGuard.ts @@ -0,0 +1,83 @@ +import * as FS from "node:fs/promises"; +import * as Path from "node:path"; + +import { findExcludedFolderActionBlocker } from "../shared/pathProtection"; + +/** + * Extra checks for paths an agent asks to move to the Trash. The user's + * Protected Folders check compares strings, which was fine while paths + * came from scan data; an agent can type any spelling it likes + * (`/users/me/photos`, a symlink, `C:\PROGRA~1`), so resolve each path + * to the one on disk first, then refuse folders no cleanup should + * remove even with the user's click. + */ + +/** + * The on-disk spelling of `target`: symlinks in its parent folders + * resolved, true letter case on macOS and Windows, long names instead + * of 8.3 ones. A symlink itself is kept (trashing it moves the link, + * not what it points to), but its name is re-cased from the directory + * listing. Throws if nothing exists at `target`. + */ +export async function canonicalPath(target: string): Promise { + const stat = await FS.lstat(target); + if (!stat.isSymbolicLink()) return FS.realpath(target); + const parent = await FS.realpath(Path.dirname(target)); + const name = Path.basename(target); + const entries = await FS.readdir(parent); + const onDisk = entries.includes(name) ? name : entries.find((entry) => entry.toLowerCase() === name.toLowerCase()); + return Path.join(parent, onDisk ?? name); +} + +function key(path: string, platform: NodeJS.Platform): string { + const trimmed = path.length > 1 ? path.replace(/[\\/]+$/, "") : path; + // APFS and NTFS are case-insensitive by default. + return platform === "win32" || platform === "darwin" ? trimmed.toLowerCase() : trimmed; +} + +/** `candidate` is `folder` or inside it. */ +function within(folder: string, candidate: string, platform: NodeJS.Platform): boolean { + const f = key(folder, platform); + const c = key(candidate, platform); + const sep = platform === "win32" ? "\\" : "/"; + return c === f || c.startsWith(f.endsWith(sep) ? f : f + sep); +} + +/** + * Why an agent may not trash or delete `target` (already canonical), or null. + * Refuses drive roots, network and device paths, and anything that is + * or contains one of `keep`: the home folder, its standard folders, + * DiskHound's own data and install folder. + */ +export function agentTrashRefusal( + target: string, + keep: readonly string[], + platform: NodeJS.Platform = process.platform, +): string | null { + const api = platform === "win32" ? Path.win32 : Path.posix; + if (platform === "win32" && /^[\\/]{2}/.test(target)) return "agents can't remove network or device paths"; + if (api.dirname(target) === target) return "it is a drive root"; + const folder = keep.find((candidate) => within(target, candidate, platform)); + if (!folder) return null; + return key(folder, platform) === key(target, platform) + ? "DiskHound never lets agents remove this folder" + : `it contains ${folder}`; +} + +/** Drop paths that sit inside another requested path; the outer one covers them. */ +export function outermostPaths(paths: readonly string[], platform: NodeJS.Platform = process.platform): string[] { + const unique = [...new Map(paths.map((path) => [key(path, platform), path])).values()]; + return unique.filter((path) => !unique.some((other) => other !== path && within(other, path, platform))); +} + +/** Resolve protections once per batch, retaining lexical checks even for missing folders. + * Resolve the final symlink too: protecting an alias protects its contents. */ +export async function configuredTrashGuard(excluded: readonly string[]) { + const canonical = await Promise.all(excluded.map((folder) => FS.realpath(folder).catch(() => folder))); + return (requested: string, target: string): string | null => { + const block = findExcludedFolderActionBlocker(requested, excluded) + ?? findExcludedFolderActionBlocker(target, excluded) + ?? findExcludedFolderActionBlocker(target, canonical); + return block ? `Protected folder: this path ${block.reason === "inside" ? "is inside" : "contains"} excluded folder "${block.folder}".` : null; + }; +} diff --git a/src/preload.ts b/src/preload.ts index 556284dd..72de2944 100644 --- a/src/preload.ts +++ b/src/preload.ts @@ -1,5 +1,3 @@ -import * as OS from "node:os"; - import { contextBridge, ipcRenderer } from "electron"; import type { @@ -17,6 +15,7 @@ import type { ToastMessage, UpdateStatus, } from "./shared/contracts"; +import type { AgentAccessSnapshot, AgentActivityEntry, AgentConsentState, AgentSecurityEvent } from "./shared/agentAccess"; // Normalize node's rich NodeJS.Platform union down to the three // platforms we actually ship binaries for. FreeBSD / AIX / SunOS are @@ -39,10 +38,19 @@ const PERMANENT_DELETE_PROGRESS_CHANNEL = "diskhound:permanent-delete-progress"; const SETTINGS_UPDATED_CHANNEL = "diskhound:settings-updated"; const NAVIGATE_VIEW_CHANNEL = "diskhound:navigate-view"; const WINDOW_SHOWN_CHANNEL = "diskhound:window-shown"; +const PATHS_TRASHED_CHANNEL = "diskhound:paths-trashed"; +const PATHS_DELETED_CHANNEL = "diskhound:paths-deleted"; +const AGENT_ACCESS_CHANGED_CHANNEL = "diskhound:agent-access-changed"; +const AGENT_ACTIVITY_CHANNEL = "diskhound:agent-activity"; +const AGENT_SECURITY_CHANNEL = "diskhound:agent-security"; +const AGENT_CONSENT_STATE_CHANNEL = "diskhound:agent-consent-state"; const api: DiskhoundNativeApi = { platform, - cpuCount: OS.availableParallelism(), + // The sandboxed agent approval window cannot require node:os. + cpuCount: process.sandboxed + ? navigator.hardwareConcurrency || 1 + : (require("node:os") as typeof import("node:os")).availableParallelism(), // Scan pickRootPath: () => ipcRenderer.invoke("diskhound:pick-root"), @@ -265,6 +273,62 @@ const api: DiskhoundNativeApi = { ipcRenderer.on(NAVIGATE_VIEW_CHANNEL, wrapped); return () => { ipcRenderer.removeListener(NAVIGATE_VIEW_CHANNEL, wrapped); }; }, + reportViewState: (state) => ipcRenderer.send("diskhound:report-view-state", state), + onPathsTrashed: (listener) => { + const wrapped = (_event: Electron.IpcRendererEvent, paths: string[]) => { + listener(paths); + }; + ipcRenderer.on(PATHS_TRASHED_CHANNEL, wrapped); + return () => { ipcRenderer.removeListener(PATHS_TRASHED_CHANNEL, wrapped); }; + }, + onPathsDeleted: (listener) => { + const wrapped = (_event: Electron.IpcRendererEvent, paths: string[]) => { + listener(paths); + }; + ipcRenderer.on(PATHS_DELETED_CHANNEL, wrapped); + return () => { ipcRenderer.removeListener(PATHS_DELETED_CHANNEL, wrapped); }; + }, + + // Local AI agent access (MCP) + getAgentAccess: () => ipcRenderer.invoke("diskhound:agent-access-get"), + setAgentAccessEnabled: (enabled) => ipcRenderer.invoke("diskhound:agent-access-set-enabled", enabled), + revokeAgentSession: (sessionId) => ipcRenderer.invoke("diskhound:agent-access-revoke", sessionId), + assignAgentSessionRole: (sessionId, roleId) => + ipcRenderer.invoke("diskhound:agent-access-assign-role", sessionId, roleId), + forgetRevokedAgentSessions: () => ipcRenderer.invoke("diskhound:agent-access-forget-revoked"), + onAgentAccessChanged: (listener) => { + const wrapped = (_event: Electron.IpcRendererEvent, snapshot: AgentAccessSnapshot) => { + listener(snapshot); + }; + ipcRenderer.on(AGENT_ACCESS_CHANGED_CHANNEL, wrapped); + return () => { ipcRenderer.removeListener(AGENT_ACCESS_CHANGED_CHANNEL, wrapped); }; + }, + onAgentActivity: (listener) => { + const wrapped = (_event: Electron.IpcRendererEvent, entry: AgentActivityEntry) => { + listener(entry); + }; + ipcRenderer.on(AGENT_ACTIVITY_CHANNEL, wrapped); + return () => { ipcRenderer.removeListener(AGENT_ACTIVITY_CHANNEL, wrapped); }; + }, + onAgentSecurityEvent: (listener) => { + const wrapped = (_event: Electron.IpcRendererEvent, event: AgentSecurityEvent) => { + listener(event); + }; + ipcRenderer.on(AGENT_SECURITY_CHANNEL, wrapped); + return () => { ipcRenderer.removeListener(AGENT_SECURITY_CHANNEL, wrapped); }; + }, + focusAgentApproval: () => ipcRenderer.invoke("diskhound:agent-access-focus-approval"), + dismissAgentApproval: (requestId) => ipcRenderer.invoke("diskhound:agent-access-dismiss-approval", requestId), + addAgentToClaude: () => ipcRenderer.invoke("diskhound:agent-access-add-to-claude"), + agentConsentRead: () => ipcRenderer.invoke("diskhound:agent-consent-read"), + agentConsentDecide: (decision) => ipcRenderer.invoke("diskhound:agent-consent-decide", decision), + onAgentConsentState: (listener) => { + const wrapped = (_event: Electron.IpcRendererEvent, state: AgentConsentState) => { + listener(state); + }; + ipcRenderer.on(AGENT_CONSENT_STATE_CHANNEL, wrapped); + return () => { ipcRenderer.removeListener(AGENT_CONSENT_STATE_CHANNEL, wrapped); }; + }, }; contextBridge.exposeInMainWorld("diskhound", api); diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index 6e28c1ca..b58f5182 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -20,7 +20,8 @@ import { formatScanRoot } from "../shared/pathUtils"; import { formatDriveSpace, driveSpaceLabel, driveUsedPercent } from "./lib/driveSpace"; import { formatBytes } from "./lib/format"; import { useSizeUnitBase } from "./lib/sizeUnitSettings"; -import { clearDeletedPaths } from "./lib/deletedPaths"; +import { focusAgentSettings, type AgentSettingsTarget } from "./lib/agentAccessStore"; +import { clearDeletedPaths, markDeletedPaths } from "./lib/deletedPaths"; import { appendDuplicateProgress } from "./lib/duplicateStream"; import { useLiveDiskSpace } from "./lib/hooks"; import { setColorBlindPalette } from "./lib/treemap"; @@ -29,6 +30,7 @@ import { dispatchSettingsUpdated, SETTINGS_UPDATED_EVENT } from "./lib/uiEvents" import { nativeApi } from "./nativeApi"; import { ChangesView } from "./components/ChangesView"; +import { AgentButton } from "./components/AgentButton"; import { DiskPicker } from "./components/DiskPicker"; import { DevBranchChip } from "./components/DevBranchChip"; import { DevView } from "./components/DevView"; @@ -173,10 +175,18 @@ export function App() { const [scanOptions, setScanOptions] = useState(defaultScanOptions()); const [view, setView] = useState("overview"); + /** Folder an agent asked the Folders tab to open (MCP navigation). */ + const [folderFocus, setFolderFocus] = useState<{ path: string; nonce: number } | null>(null); + const folderFocusNonce = useRef(0); const [devTabMounted, setDevTabMounted] = useState(false); useEffect(() => { if (view === "dev") setDevTabMounted(true); }, [view]); + // Tell main what this window shows, so an agent's diskhound_status + // knows which tab and drive the user is looking at. + useEffect(() => { + nativeApi.reportViewState({ view, rootPath: snapshot.rootPath ?? (currentRoot || null) }); + }, [view, snapshot.rootPath, currentRoot]); const { drives, refresh: refreshDiskSpace } = useLiveDiskSpace(); const [filterExt, setFilterExt] = useState(); // null = still loading the initial snapshot; prevents a flash of the picker @@ -556,12 +566,35 @@ export function App() { // the widget's "C:" drive row drops the user into Overview pre-pointed // at C:; then switch the tab. Skip the picker โ€” user's intent was to // see this view immediately, not pick a drive. - const unsubNavigate = nativeApi.onNavigateView(({ view, scanRoot }) => { + const unsubNavigate = nativeApi.onNavigateView(({ view, scanRoot, folderPath, section }) => { if (scanRoot) { setCurrentRoot(scanRoot); + // A root this window hasn't shown yet (an agent asking for an + // older scan): load its latest saved snapshot, never clobbering + // a live one that's already here. + const key = rootKey(scanRoot); + void nativeApi.getLatestSnapshotForRoot(scanRoot).then((latest) => { + if (!latest) return; + setSnapshotsByRoot((prev) => (prev.has(key) ? prev : new Map(prev).set(key, latest))); + }); + } + if (folderPath) { + folderFocusNonce.current += 1; + setFolderFocus({ path: folderPath, nonce: folderFocusNonce.current }); } setShowPicker(false); setView(view); + // App menu "Connect an AI Agentโ€ฆ" and the tray's "AI Agentsโ€ฆ". + if (section === "ai-agents") focusAgentSettings("section"); + }); + + // Paths an agent moved to the Trash or deleted (the user confirmed + // each batch in a native dialog): strike them through like in-app ones. + const unsubPathsTrashed = nativeApi.onPathsTrashed((paths) => { + markDeletedPaths(paths, "trash"); + }); + const unsubPathsDeleted = nativeApi.onPathsDeleted((paths) => { + markDeletedPaths(paths, "delete"); }); // โ”€โ”€ Duplicate scan IPC wiring โ”€โ”€ @@ -658,6 +691,8 @@ export function App() { unsub(); unsubUpdate(); unsubNavigate(); + unsubPathsTrashed(); + unsubPathsDeleted(); unsubDupProgress(); unsubDupResult(); unsubEasyMoveProgress(); @@ -786,6 +821,16 @@ export function App() { * drive click, which wiped running state and triggered duplicate * scan-complete toasts when users switched around. */ + /** + * Settings โ†’ AI Agents, from the header agent button, the drive picker + * and the menus. The picker stays wanted: leaving Settings without a + * scan goes back to it. + */ + const openAgentSettings = (target: AgentSettingsTarget) => { + setView("settings"); + focusAgentSettings(target); + }; + const handleScanDrive = async (drivePath: string) => { // Normalize "C:" โ†’ "C:\\" so Path.resolve doesn't use CWD const normalized = /^[A-Za-z]:$/.test(drivePath) ? drivePath + "\\" : drivePath; @@ -1162,6 +1207,9 @@ export function App() { * weight without stealing horizontal real estate from * the pills next to them. */}
+ {/* AI agents (MCP): the way in, and which agent is driving. */} + + {/* Search toggle */} + ) : ( + + )} + {open && anchor && ( + setOpen(false)} /> + )} +
+ ); +} + +/** A small robot head: 1px strokes like the header's other icons. */ +export function AgentGlyph() { + return ( + + ); +} + +function AgentPopover({ snapshot, now, anchor, onGo, onClose }: { + snapshot: AgentAccessSnapshot; + now: number; + anchor: { top: number; right: number }; + onGo: (target: AgentSettingsTarget) => void; + onClose: () => void; +}) { + const { status } = snapshot; + const sessions = activeSessions(snapshot); + const last = lastActionBySession(snapshot.activity); + const blockedToday = [...blockedBySession(snapshot, now - DAY_MS).values()].reduce((sum, n) => sum + n, 0); + const rolesById = new Map(snapshot.roles.map((role) => [role.id, role])); + const ordered = [...sessions].sort((a, b) => (last.get(b.id)?.at ?? 0) - (last.get(a.id)?.at ?? 0)); + const chip = status.error ? "error" : status.listening ? "on" : "off"; + + return ( +
+
+ AI agents + {status.error ? "Error" : status.listening ? "On" : "Off"} +
+ + {!status.enabled ? ( +
+

+ Let Claude Code, Claude Desktop, Codex or another MCP client read your scans and steer this + window while it helps you free up space. Nothing listens until you turn it on. +

+ +
+ ) : ( + <> + {status.error &&
{status.error}
} + {snapshot.pending.map((pending) => ( +
+ +
+
{pending.clientName}
+
{pendingText(pending, now)}
+
+ +
+ ))} + {ordered.slice(0, 5).map((session) => { + const action = last.get(session.id); + const recent = action ? now - action.at : Infinity; + const dot = action && recent < VISIBLE_MS && !action.ok ? "failed" : recent < ACTIVE_MS ? "active" : ""; + return ( +
+ +
+
{session.name}
+
+ {action ? `${action.summary} ยท ${relativeTime(action.at)}` : "No actions yet"} +
+
+ {roleShortName(rolesById.get(session.roleId))} +
+ ); + })} + {sessions.length > 5 &&
and {sessions.length - 5} more in Settings
} + {sessions.length === 0 && snapshot.pending.length === 0 && ( +
No agents connected yet.
+ )} + {blockedToday > 0 && ( + + )} + + )} + +
+ {status.enabled && } + +
+
+ ); +} diff --git a/src/renderer/components/AgentConsentWindow.tsx b/src/renderer/components/AgentConsentWindow.tsx new file mode 100644 index 00000000..43173d91 --- /dev/null +++ b/src/renderer/components/AgentConsentWindow.tsx @@ -0,0 +1,252 @@ +import { useEffect, useRef, useState } from "preact/hooks"; + +import { + MCP_AGENT_CAPABILITY_DETAILS, + type AgentConsentPrompt, + type McpAgentCapability, + type McpAgentRole, +} from "../../shared/agentAccess"; +import type { GeneralSettings } from "../../shared/contracts"; +import { capabilityChip } from "../lib/agentDisplay"; +import { nativeApi } from "../nativeApi"; + +/** + * The approval sheet main attaches to DiskHound's main window when an + * agent signs in (the stdio helper, or Codex's browser tab). The agent's + * side only waits; the decision is made here, in a window only DiskHound + * controls. Closing it counts as Deny. + */ +export function AgentConsentWindow() { + const [prompt, setPrompt] = useState(null); + const [name, setName] = useState(""); + const [roleId, setRoleId] = useState(""); + const [stale, setStale] = useState(false); + const [next, setNext] = useState(null); + const [details, setDetails] = useState(false); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + const deltaRef = useRef(null); + + // The sheet scrolls, so a role that adds permissions brings its + // warning into view above the buttons before the user approves. + useEffect(() => { + deltaRef.current?.querySelector(".agent-consent-delta")?.scrollIntoView({ block: "nearest", behavior: "smooth" }); + }, [roleId]); + + useEffect(() => { + document.body.classList.add("agent-consent-body"); + // index.html's would otherwise replace the window title main set. + document.title = "Approve agent access โ€” DiskHound"; + void nativeApi.getSettings().then((settings) => { + const root = document.documentElement; + root.classList.remove("dark", "light"); + root.classList.add(resolveTheme(settings.general.theme)); + }); + let requestId: string | null = null; + const off = nativeApi.onAgentConsentState((state) => { + if (requestId !== null && state.requestId !== requestId) return; + setStale(state.stale); + setNext(state.next); + }); + void nativeApi.agentConsentRead().then((read) => { + if (!read) { + setError("This request is no longer waiting for approval."); + return; + } + requestId = read.requestId; + setPrompt(read); + setStale(read.stale); + setNext(read.next); + setName(read.sessionName); + setRoleId(read.roles.some((role) => role.id === read.defaultRoleId) + ? read.defaultRoleId + : read.roles[0]?.id ?? ""); + }); + return () => { + off(); + document.body.classList.remove("agent-consent-body"); + }; + }, []); + + const role = prompt?.roles.find((candidate) => candidate.id === roleId); + const defaultRole = prompt?.roles.find((candidate) => candidate.id === prompt.defaultRoleId); + const client = prompt?.clientName ?? "An agent"; + + const decide = async (decision: "allow" | "deny") => { + if (!prompt || busy) return; + setBusy(true); + const result = await nativeApi.agentConsentDecide({ + requestId: prompt.requestId, + decision, + sessionName: name.trim(), + roleId, + }); + // On success main closes this sheet. + if (!result.ok) { + setError(result.message ?? "DiskHound couldn't record that decision."); + setBusy(false); + } + }; + + return ( + <main className="agent-consent"> + <header className="agent-consent-header"> + <div className="agent-consent-eyebrow"> + Agent sign-in{prompt ? ` ยท via ${prompt.via === "stdio" ? "stdio helper" : "HTTP"}` : ""} + </div> + <h1>Approve {client}?</h1> + <p> + <strong>{client}</strong> wants to use DiskHound. Choose what this session may do. + </p> + </header> + + {stale && ( + <div className="agent-consent-stale" role="status"> + <span className="agent-consent-stale-dot" /> + <span> + <strong>{client} stopped waiting for this answer.</strong> It may have timed out or quit, so + approving now would connect nothing. Deny it, then reconnect from {client}. + </span> + </div> + )} + {error && <div className="agent-consent-error" role="alert">{error}</div>} + + {prompt && ( + <> + <label className="agent-consent-field"> + <span>Session name</span> + <input + className="filter-input" + autoFocus + maxLength={200} + value={name} + onInput={(e) => setName((e.target as HTMLInputElement).value)} + /> + </label> + + <div className="agent-consent-field" id="agent-consent-role-label">Role</div> + {prompt.roles.length === 0 ? ( + <p className="agent-consent-role-desc">No role fits the permissions this agent requested.</p> + ) : ( + <div className="agent-role-cards" role="radiogroup" aria-labelledby="agent-consent-role-label"> + {prompt.roles.map((candidate) => ( + <RoleCard + key={candidate.id} + role={candidate} + selected={candidate.id === roleId} + disabled={busy} + onSelect={() => setRoleId(candidate.id)} + /> + ))} + </div> + )} + + {role && ( + <> + <div ref={deltaRef}> + <Delta role={role} base={defaultRole} /> + </div> + <button className="agent-consent-more" onClick={() => setDetails(!details)} aria-expanded={details}> + <span className={`agent-disclose-chevron ${details ? "open" : ""}`} /> + What each permission allows + </button> + {details && ( + <ul className="agent-consent-permissions"> + {role.permissions.map((permission) => { + const detail = MCP_AGENT_CAPABILITY_DETAILS[permission]; + return ( + <li key={permission} className={detail.danger}> + <div className="agent-consent-permission-label">{detail.label}</div> + <div className="agent-consent-permission-detail">{detail.detail}</div> + </li> + ); + })} + </ul> + )} + </> + )} + + <p className="agent-consent-footnote"> + Change the role or revoke this session any time in Settings โ†’ AI Agents. + </p> + + <div className="agent-consent-actions"> + {next && <span className="agent-consent-queue">Next: {next}</span>} + <button className={`action-btn ${stale ? "agent-consent-default" : ""}`} disabled={busy} onClick={() => void decide("deny")}> + Deny + </button> + <button + className="scan-btn scan-btn-primary agent-consent-approve" + disabled={busy || stale || !name.trim() || !role} + title={stale ? `${client} is no longer waiting` : undefined} + onClick={() => void decide("allow")} + > + {role ? `Approve as ${role.name}` : "Approve"} + </button> + </div> + </> + )} + </main> + ); +} + +function RoleCard({ role, selected, disabled, onSelect }: { + role: McpAgentRole; + selected: boolean; + disabled: boolean; + onSelect: () => void; +}) { + const deletes = role.permissions.includes("files.delete"); + return ( + <button + role="radio" + aria-checked={selected} + disabled={disabled} + className={`agent-role-card ${selected ? (deletes ? "selected destructive" : "selected") : ""}`} + onClick={onSelect} + > + <span className="agent-role-radio" /> + <span className="agent-role-body"> + <span className="agent-role-name">{role.name}</span> + <span className="agent-role-line">{role.description}</span> + <span className="agent-role-caps"> + {role.permissions.map((permission) => ( + <span key={permission} className={`agent-cap ${MCP_AGENT_CAPABILITY_DETAILS[permission].danger}`}> + {capabilityChip(permission, nativeApi.platform)} + </span> + ))} + </span> + </span> + </button> + ); +} + +/** What the picked role adds over the default, when it adds anything. */ +function Delta({ role, base }: { role: McpAgentRole; base: McpAgentRole | undefined }) { + if (!base || role.id === base.id) return null; + const added = role.permissions.filter((permission) => !base.permissions.includes(permission)); + if (added.length === 0) return null; + const destructive = added.some((permission) => MCP_AGENT_CAPABILITY_DETAILS[permission].danger === "destructive"); + const deletes = added.includes("files.delete"); + const bin = nativeApi.platform === "win32" ? "Recycle Bin" : "Trash"; + const verbs = added.map((permission) => MCP_AGENT_CAPABILITY_DETAILS[permission].verb.replace("Trash", bin)); + return ( + <div className={`agent-consent-delta ${deletes ? "destructive" : ""}`}> + <span className="agent-consent-delta-plus">+</span> + <span> + More than the default <strong>{base.name}</strong>: this session can {destructive ? "ask to " : ""} + {verbs.join(" and ")}. + {deletes ? " Deleted items can't be restored." : ""} + {destructive ? " You confirm every request." : ""} + </span> + </div> + ); +} + +function resolveTheme(theme: GeneralSettings["theme"]): "dark" | "light" { + if (theme === "light") return "light"; + if (theme === "system") { + return window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark"; + } + return "dark"; +} diff --git a/src/renderer/components/AgentsSection.tsx b/src/renderer/components/AgentsSection.tsx new file mode 100644 index 00000000..08711886 --- /dev/null +++ b/src/renderer/components/AgentsSection.tsx @@ -0,0 +1,684 @@ +import { useEffect, useRef, useState } from "preact/hooks"; + +import { + agentClientGuides, + agentSetupPrompt, + MCP_AGENT_CAPABILITY_DETAILS, + sessionPermissions, + type AddToClaudeResult, + type AgentAccessSnapshot, + type AgentActivityEntry, + type AgentClientGuide, + type AgentClientId, + type AgentSetupStep, + type McpAgentSession, +} from "../../shared/agentAccess"; +import { + setAgentAccess, + useAgentAccess, + useAgentSettingsFocus, + type AgentSettingsTarget, +} from "../lib/agentAccessStore"; +import { + activeSessions, + blockedBySession, + capabilityChip, + isGuideClient, + lastActionBySession, + pendingText, + sessionClientName, + viaLabel, +} from "../lib/agentDisplay"; +import { relativeTime } from "../lib/format"; +import { useVisibleInterval } from "../lib/visiblePoll"; +import { nativeApi } from "../nativeApi"; +import { toast } from "./Toasts"; + +const ACTIVE_MS = 30_000; +const RECENT_MS = 10 * 60_000; + +/** + * Settings โ†’ AI Agents: turn the loopback MCP server on and off, connect + * a client (one tab per client, numbered steps, a last step that shows + * whether it got through), approve or deny waiting sign-ins, change a + * session's role or revoke it, and see what agents did and what they + * were refused. + * + * Sessions and roles live in mcp-policy.json (main process), not in + * AppSettings, so this section talks to its own IPC instead of the + * shared settings `save`. The snapshot comes from the shared agent store + * the header button already loaded, so opening Settings asks main for + * nothing. + */ +export function AgentsSection() { + const snapshot = useAgentAccess(); + const [busy, setBusy] = useState(false); + // null: open while nothing is connected, folded once something is. + const [connectOpen, setConnectOpen] = useState<boolean | null>(null); + const [guideId, setGuideId] = useState<AgentClientId>("claude-code"); + const [scrollTarget, setScrollTarget] = useState<AgentSettingsTarget | null>(null); + const [now, setNow] = useState(() => Date.now()); + const sectionRef = useRef<HTMLDivElement>(null); + const connectRef = useRef<HTMLDivElement>(null); + const blockedRef = useRef<HTMLDivElement>(null); + + useAgentSettingsFocus((target) => { + if (target === "connect") setConnectOpen(true); + setScrollTarget(target); + }); + + // Scroll once the section (and an opened Connect) has rendered. + useEffect(() => { + if (!scrollTarget || !snapshot) return; + const frame = window.requestAnimationFrame(() => { + const element = scrollTarget === "connect" + ? connectRef.current + : scrollTarget === "blocked" + ? blockedRef.current + : sectionRef.current; + element?.scrollIntoView({ block: "start" }); + setScrollTarget(null); + }); + return () => window.cancelAnimationFrame(frame); + }, [scrollTarget, snapshot !== null]); + + // Waiting times on pending sign-ins count up. + useVisibleInterval(() => setNow(Date.now()), snapshot && snapshot.pending.length > 0 ? 1_000 : null); + useEffect(() => { + setNow(Date.now()); + }, [snapshot]); + + if (!snapshot) return null; + + const { status } = snapshot; + const active = activeSessions(snapshot); + const revoked = snapshot.sessions.filter((session) => session.revokedAt !== null); + const last = lastActionBySession(snapshot.activity); + const blocked = blockedBySession(snapshot); + const sessions = [...active].sort((a, b) => + (last.get(b.id)?.at ?? Date.parse(b.createdAt)) - (last.get(a.id)?.at ?? Date.parse(a.createdAt))); + const showConnect = connectOpen ?? active.length === 0; + + const run = async (action: () => Promise<AgentAccessSnapshot>, failure: string): Promise<AgentAccessSnapshot | null> => { + setBusy(true); + try { + const next = await action(); + setAgentAccess(next); + return next; + } catch (err) { + toast("error", failure, err instanceof Error ? err.message : String(err)); + return null; + } finally { + setBusy(false); + } + }; + + const statusText = status.error + ? status.error + : status.listening + ? `Listening on ${status.mcpUrl}. Only this computer can connect, and every agent needs your approval.` + : "Off. Nothing listens until you turn this on."; + + return ( + <div className="settings-section" id="settings-ai-agents" ref={sectionRef}> + <div className="settings-section-title">AI Agents</div> + <div className="settings-section-note"> + Let Claude Code, Claude Desktop, Codex or another MCP client read your scans, run scans and steer + this window while it helps you free up space. DiskHound also gives connected agents its cleanup + procedures (MCP skills), including the APFS clone and Time Machine snapshot checks on macOS. + </div> + + <div className={`setting-row ${busy ? "setting-row-disabled" : ""}`}> + <div> + <div className="setting-label"> + Allow local AI agents + <span className={`agent-status-chip ${status.error ? "error" : status.listening ? "on" : "off"}`}> + {status.error ? "Error" : status.listening ? "On" : "Off"} + </span> + </div> + <div className={`setting-desc ${status.error ? "agent-status-error" : ""}`}>{statusText}</div> + </div> + <div className="agent-toggle-group"> + {status.error && status.enabled && ( + <button + className="action-btn" + disabled={busy} + onClick={() => void run(() => nativeApi.setAgentAccessEnabled(true), "Couldn't start AI agent access")} + > + Try again + </button> + )} + <label className="toggle"> + <input + type="checkbox" + checked={status.enabled} + disabled={busy} + onChange={(e) => { + const enabled = (e.target as HTMLInputElement).checked; + void run(() => nativeApi.setAgentAccessEnabled(enabled), "Couldn't change AI agent access"); + }} + /> + <div className="toggle-track" /> + <div className="toggle-thumb" /> + </label> + </div> + </div> + + {snapshot.pending.length > 0 && ( + <> + <div className="agent-subtitle">Waiting for approval</div> + {snapshot.pending.map((pending, index) => ( + <div key={pending.requestId} className={`agent-pending-row ${pending.stale ? "stale" : ""}`}> + <span className={`agent-pill-dot ${pending.stale ? "" : "waiting"}`} /> + <div className="protected-folder-info"> + <div className="agent-session-name">{pending.clientName}</div> + <div className="agent-session-meta"> + {viaLabel(pending.via)} + {" ยท "} + {index === 0 ? pendingText(pending, now) : `Next after ${snapshot.pending[0]!.clientName}`} + </div> + </div> + {index === 0 ? ( + <button className="action-btn agent-review-btn" onClick={() => void nativeApi.focusAgentApproval()}> + Review + </button> + ) : <span />} + <button + className="action-btn" + disabled={busy} + onClick={() => void run(() => nativeApi.dismissAgentApproval(pending.requestId), "Couldn't deny the request")} + > + Deny + </button> + </div> + ))} + </> + )} + + <div className="agent-subtitle">Sessions</div> + <div className="agent-session-list"> + {sessions.length === 0 ? ( + <div className="protected-folder-empty"> + No agents approved yet.{status.enabled ? " Connect one below." : ""} + </div> + ) : ( + sessions.map((session) => ( + <SessionRow + key={session.id} + session={session} + snapshot={snapshot} + last={last.get(session.id)} + blocked={blocked.get(session.id) ?? 0} + now={now} + busy={busy} + onShowBlocked={() => setScrollTarget("blocked")} + onAssign={(roleId) => { + const before = new Set(sessionPermissions(session, snapshot.roles)); + void run( + () => nativeApi.assignAgentSessionRole(session.id, roleId), + "Couldn't change the role", + ).then((next) => { + const updated = next?.sessions.find((candidate) => candidate.id === session.id); + if (updated) announceRoleChange(updated, before, next!); + }); + }} + onRevoke={() => void run( + () => nativeApi.revokeAgentSession(session.id), + "Couldn't revoke the session", + )} + /> + )) + )} + </div> + {revoked.length > 0 && ( + <div className="agent-revoked"> + <span> + {revoked.length} revoked session{revoked.length === 1 ? "" : "s"} + {" "}({revoked.map((session) => session.name).join(", ")}) + </span> + <button + className="action-btn" + disabled={busy} + onClick={() => void run(() => nativeApi.forgetRevokedAgentSessions(), "Couldn't clear revoked sessions")} + > + Forget revoked + </button> + </div> + )} + + <div className="agent-subtitle" ref={connectRef}>Connect an agent</div> + {showConnect ? ( + <ConnectGuide + snapshot={snapshot} + guideId={guideId} + onGuide={setGuideId} + last={last} + now={now} + busy={busy} + onTurnOn={() => void run(() => nativeApi.setAgentAccessEnabled(true), "Couldn't start AI agent access")} + /> + ) : ( + <button className="agent-disclose" onClick={() => setConnectOpen(true)} aria-expanded={false}> + <span className="agent-disclose-chevron" /> + Connect another agent: {agentClientGuides(status.port, snapshot.stdioPath, snapshot.platform) + .filter((guide) => guide.id !== "other").map((guide) => guide.name).join(", ")}, other clients + </button> + )} + + {(status.enabled || snapshot.security.length > 0) && ( + <> + <div className="agent-subtitle" ref={blockedRef}>Blocked requests</div> + <div className="agent-activity-list"> + {snapshot.security.length === 0 ? ( + <div className="protected-folder-empty"> + Nothing blocked. When an agent asks for something its role doesn't allow, DiskHound refuses it and + lists it here. + </div> + ) : ( + snapshot.security.slice(0, 8).map((event) => ( + <div key={event.id} className="agent-activity-row agent-blocked-row"> + <span className="agent-activity-time">{relativeTime(event.at)}</span> + <span className="agent-activity-session">{event.sessionName}</span> + <span className="agent-activity-summary" title={`${event.tool}: ${event.detail}`}>{event.detail}</span> + <span className="agent-blocked-count">{event.count > 1 ? `ร—${event.count}` : ""}</span> + </div> + )) + )} + </div> + {snapshot.security.length > 0 && ( + <div className="agent-revoked"> + <span>Kept in agent-security.log, across restarts.</span> + <button + className="action-btn" + onClick={() => { + void nativeApi.revealPath(snapshot.securityLogFile).then((result) => { + if (!result.ok) toast("info", "Nothing saved yet", "DiskHound writes blocked requests a few seconds after they happen."); + }); + }} + > + Show file + </button> + </div> + )} + </> + )} + + {snapshot.activity.length > 0 && ( + <> + <div className="agent-subtitle">Recent agent actions</div> + <div className="agent-activity-list"> + {snapshot.activity.slice(0, 12).map((entry) => ( + <div key={entry.id} className={`agent-activity-row ${entry.ok ? "" : "failed"}`}> + <span className="agent-activity-time">{relativeTime(entry.at)}</span> + <span className="agent-activity-session">{entry.sessionName}</span> + <span className="agent-activity-summary" title={`${entry.tool}: ${entry.summary}`}> + {entry.summary} + </span> + <span /> + </div> + ))} + </div> + </> + )} + </div> + ); +} + +/** Say what a role change did, and when the agent will notice it. */ +function announceRoleChange(session: McpAgentSession, before: Set<string>, snapshot: AgentAccessSnapshot) { + const role = snapshot.roles.find((candidate) => candidate.id === session.roleId); + if (!role) return; + const after = sessionPermissions(session, snapshot.roles); + const added = after.filter((permission) => !before.has(permission)); + const removed = [...before].filter((permission) => !after.includes(permission as never)); + const client = sessionClientName(session); + // Claude Desktop keeps the tool list it got when it connected. + const reload = client === "Claude Desktop" + ? "Claude Desktop picks up the new tools after you turn DiskHound off and on in Claude's Settings โ†’ Extensions. Until then DiskHound refuses anything the role doesn't allow." + : session.client?.via === "stdio" + ? `${client} reloads its tools on its own.` + : `${client} sees the change in its tool list after it reconnects; until then DiskHound refuses anything the role doesn't allow.`; + if (added.length === 0 && removed.length === 0) { + toast("info", `${session.name} is now ${role.name}`, "Nothing changed: this agent didn't ask for the extra permissions when it signed in."); + return; + } + const destructive = added.filter((permission) => MCP_AGENT_CAPABILITY_DETAILS[permission].danger === "destructive"); + const detail = destructive.length > 0 + ? `It can now ask to ${destructive.map((p) => MCP_AGENT_CAPABILITY_DETAILS[p].verb).join(" and ")}. You confirm every request. ${reload}` + : reload; + toast("info", `${session.name} is now ${role.name}`, detail); +} + +function SessionRow({ session, snapshot, last, blocked, now, busy, onShowBlocked, onAssign, onRevoke }: { + session: McpAgentSession; + snapshot: AgentAccessSnapshot; + last: AgentActivityEntry | undefined; + blocked: number; + now: number; + busy: boolean; + onShowBlocked: () => void; + onAssign: (roleId: string) => void; + onRevoke: () => void; +}) { + const role = snapshot.roles.find((candidate) => candidate.id === session.roleId); + // Effective permissions are the role intersected with the scopes the + // agent asked for at sign-in, so a bigger role can't exceed them. + const effective = sessionPermissions(session, snapshot.roles); + const capped = (role?.permissions ?? []).filter((permission) => !effective.includes(permission)); + const client = sessionClientName(session); + const age = last ? now - last.at : Infinity; + const dot = last && !last.ok && age < RECENT_MS ? "failed" : age < ACTIVE_MS ? "active" : ""; + + return ( + <div className="agent-session-row"> + <div className="protected-folder-info"> + <div className="agent-session-name"> + <span className={`agent-pill-dot ${dot}`} /> + <span className="agent-session-title">{session.name}</span> + {session.client && <span className="agent-via">{session.client.via === "stdio" ? "stdio" : "HTTP"}</span>} + </div> + <div className="agent-session-meta"> + {client !== session.name ? `${client} ยท ` : ""} + Approved {relativeTime(Date.parse(session.createdAt))} + </div> + {effective.length > 0 && ( + <div className="agent-role-caps agent-session-caps"> + {effective.map((permission) => ( + <span + key={permission} + className={`agent-cap ${MCP_AGENT_CAPABILITY_DETAILS[permission].danger}`} + title={MCP_AGENT_CAPABILITY_DETAILS[permission].label} + > + {capabilityChip(permission, snapshot.platform)} + </span> + ))} + </div> + )} + <div className={`agent-session-meta ${last && !last.ok ? "agent-session-failed" : ""}`} title={last?.summary}> + {last ? `Last: ${last.summary} ยท ${relativeTime(last.at)}` : "No actions yet"} + {blocked > 0 && ( + <> + {" ยท "} + <button className="agent-blocked-link" onClick={onShowBlocked}>{blocked} blocked</button> + </> + )} + </div> + {capped.length > 0 && ( + <div className="agent-session-meta agent-session-capped"> + {client} didn't ask for: {capped.map((p) => MCP_AGENT_CAPABILITY_DETAILS[p].label).join(", ")}, so this + role can't give it that. Revoke the session and reconnect {client} to ask again. + </div> + )} + </div> + <select + className="setting-select" + value={session.roleId} + disabled={busy} + aria-label={`Role for ${session.name}`} + onChange={(e) => onAssign((e.target as HTMLSelectElement).value)} + > + {snapshot.roles.map((candidate) => ( + <option key={candidate.id} value={candidate.id}>{candidate.name}</option> + ))} + </select> + <button className="action-btn danger" disabled={busy} onClick={onRevoke}> + Revoke + </button> + </div> + ); +} + +function ConnectGuide({ snapshot, guideId, onGuide, last, now, busy, onTurnOn }: { + snapshot: AgentAccessSnapshot; + guideId: AgentClientId; + onGuide: (id: AgentClientId) => void; + last: Map<string, AgentActivityEntry>; + now: number; + busy: boolean; + onTurnOn: () => void; +}) { + const guides = agentClientGuides(snapshot.status.port, snapshot.stdioPath, snapshot.platform); + const guide = guides.find((candidate) => candidate.id === guideId) ?? guides[0]!; + const active = activeSessions(snapshot); + const sessionsFor = (candidate: AgentClientGuide) => + active.filter((session) => isGuideClient(candidate, sessionClientName(session))); + const connected = sessionsFor(guide).sort((a, b) => + (last.get(b.id)?.at ?? Date.parse(b.createdAt)) - (last.get(a.id)?.at ?? Date.parse(a.createdAt)))[0]; + const pending = snapshot.pending.find((candidate) => isGuideClient(guide, candidate.clientName)); + + return ( + <div className="agent-connect"> + <div className="agent-connect-lead"> + <CopyButton + text={agentSetupPrompt(snapshot.status.port, snapshot.stdioPath)} + label="Copy prompt for your agent" + copiedLabel="Prompt copied" + className="scan-btn scan-btn-primary" + /> + <span className="agent-connect-lead-text"> + Paste it into Claude Code, Codex or another agent. The agent sets DiskHound up, and you approve it here. Or follow the steps for your agent: + </span> + </div> + <div className="agent-client-tabs" role="tablist" aria-label="Agent"> + {guides.map((candidate) => ( + <button + key={candidate.id} + role="tab" + aria-selected={candidate.id === guide.id} + className={`chip ${candidate.id === guide.id ? "active" : ""}`} + onClick={() => onGuide(candidate.id)} + > + {sessionsFor(candidate).length > 0 && <span className="agent-tab-dot" />} + {candidate.name} + </button> + ))} + </div> + <ol className="agent-steps"> + {guide.steps.map((step, index) => ( + <SetupStep key={`${guide.id}-${index}`} n={index + 1} step={step} done={Boolean(connected)} /> + ))} + <li className="agent-step"> + <span className={`agent-step-num ${connected ? "done" : ""}`}>{connected ? "โœ“" : guide.steps.length + 1}</span> + <ConnectStatus + snapshot={snapshot} + guide={guide} + connected={connected} + pending={pending} + last={connected ? last.get(connected.id) : undefined} + now={now} + busy={busy} + onTurnOn={onTurnOn} + /> + </li> + </ol> + <div className="agent-try"> + <span>Then ask:</span> + <span className="agent-try-prompt">{guide.firstPrompt}</span> + <CopyButton text={guide.firstPrompt} /> + </div> + {guide.note && <div className="agent-hint">{guide.note}</div>} + {snapshot.platform === "linux" && guide.id !== "codex" && ( + <div className="agent-hint"> + Running DiskHound as an AppImage? Its helper moves on every launch: copy diskhound-mcp from the + AppImage's resources/native folder somewhere stable and use that path instead. + </div> + )} + </div> + ); +} + +function ConnectStatus({ snapshot, guide, connected, pending, last, now, busy, onTurnOn }: { + snapshot: AgentAccessSnapshot; + guide: AgentClientGuide; + connected: McpAgentSession | undefined; + pending: AgentAccessSnapshot["pending"][number] | undefined; + last: AgentActivityEntry | undefined; + now: number; + busy: boolean; + onTurnOn: () => void; +}) { + const { status } = snapshot; + // "Set upโ€ฆ" lands here with the toggle scrolled out of view, so the + // step turns agents on itself. + if (!status.enabled) { + return ( + <div className="agent-live"> + <div className="agent-live-main"> + <div>AI agents are off.</div> + <div className="agent-live-meta">Turn them on so {guide.name} can connect. Only this computer can, and you approve each agent.</div> + </div> + <button className="scan-btn scan-btn-primary" disabled={busy} onClick={onTurnOn}>Turn on</button> + </div> + ); + } + if (status.error) { + return ( + <div className="agent-live failed"> + <div className="agent-live-main"> + <div>DiskHound isn't listening.</div> + <div className="agent-live-meta">{status.error}</div> + </div> + </div> + ); + } + if (pending) { + return ( + <div className="agent-live waiting"> + <span className="agent-pill-dot waiting" /> + <div className="agent-live-main"> + <div>{pending.stale ? `${pending.clientName} stopped waiting` : `${pending.clientName} is waiting for your approval`}</div> + <div className="agent-live-meta">{pendingText(pending, now)} ยท {viaLabel(pending.via)}</div> + </div> + <button className="action-btn agent-review-btn" onClick={() => void nativeApi.focusAgentApproval()}>Review</button> + </div> + ); + } + if (connected) { + const role = snapshot.roles.find((candidate) => candidate.id === connected.roleId); + return ( + <div className="agent-live connected"> + <span className="agent-live-ok" /> + <div className="agent-live-main"> + <div>Connected as {connected.name} ยท {role?.name ?? "no role"}</div> + <div className="agent-live-meta">{last ? `Last: ${last.summary} ยท ${relativeTime(last.at)}` : "No actions yet"}</div> + </div> + </div> + ); + } + if (guide.id === "other") { + return ( + <div className="agent-live"> + <div className="agent-live-main"> + <div>DiskHound asks you to approve each new client here.</div> + <div className="agent-live-meta">Approved clients show under Sessions.</div> + </div> + </div> + ); + } + return ( + <div className="agent-live"> + <span className="agent-live-ring" /> + <div className="agent-live-main"> + <div>Waiting for {guide.name} to connectโ€ฆ</div> + <div className="agent-live-meta">DiskHound asks you to approve it here when it does.</div> + </div> + </div> + ); +} + +function SetupStep({ n, step, done }: { n: number; step: AgentSetupStep; done: boolean }) { + const [showManual, setShowManual] = useState(false); + + return ( + <li className="agent-step"> + <span className={`agent-step-num ${done ? "done" : ""}`}>{done ? "โœ“" : n}</span> + <div className="agent-step-body"> + <div className="agent-step-text">{step.text}</div> + {step.prompt && ( + <div className="agent-command"> + <pre className="agent-command-text agent-prompt-text">{step.prompt}</pre> + <CopyButton text={step.prompt} /> + </div> + )} + {step.action === "add-to-claude" && <AddToClaude />} + {step.manual && ( + <> + <button className="action-btn agent-manual-toggle" onClick={() => setShowManual(!showManual)} aria-expanded={showManual}> + {showManual ? `Hide ${step.manual.toggle}` : `Show ${step.manual.toggle}`} + </button> + {showManual && step.manual.items.map((item) => ( + <div key={item.snippet}> + <div className="agent-manual-text">{item.text}</div> + <div className="agent-command"> + <pre className="agent-command-text">{item.snippet}</pre> + <CopyButton text={item.snippet} /> + </div> + </div> + ))} + </> + )} + </div> + </li> + ); +} + +/** Opens DiskHound's extension in Claude, which asks the user to install it. */ +function AddToClaude() { + const [busy, setBusy] = useState(false); + const [result, setResult] = useState<AddToClaudeResult | null>(null); + const add = async () => { + setBusy(true); + try { + setResult(await nativeApi.addAgentToClaude()); + } catch (error) { + setResult({ ok: false, error: error instanceof Error ? error.message : String(error) }); + } finally { + setBusy(false); + } + }; + return ( + <div className="agent-step-action"> + <button className="scan-btn scan-btn-primary" disabled={busy} onClick={() => void add()}> + {busy ? "Opening Claudeโ€ฆ" : "Add to Claude"} + </button> + {result?.ok && <span className="agent-step-result">Opened in Claude.</span>} + {result && !result.ok && ( + <span className="agent-step-result failed"> + {result.error} + {result.file && " Open the file with Claude to install it."} + </span> + )} + {result && !result.ok && result.file && ( + <button className="action-btn" onClick={() => void nativeApi.revealPath(result.file!)}>Show file</button> + )} + </div> + ); +} + +/** Copy, confirmed on the button itself for two seconds. */ +function CopyButton({ text, label = "Copy", copiedLabel = "Copied", className = "action-btn agent-copy" }: { + text: string; + label?: string; + copiedLabel?: string; + className?: string; +}) { + const [copied, setCopied] = useState(false); + useEffect(() => { + if (!copied) return; + const timer = window.setTimeout(() => setCopied(false), 2_000); + return () => window.clearTimeout(timer); + }, [copied]); + return ( + <button + className={`${className} ${copied ? "copied" : ""}`} + onClick={() => { + void navigator.clipboard.writeText(text).then( + () => setCopied(true), + () => toast("error", "Couldn't copy to the clipboard"), + ); + }} + > + {copied ? copiedLabel : label} + </button> + ); +} diff --git a/src/renderer/components/DiskPicker.tsx b/src/renderer/components/DiskPicker.tsx index bd9ff065..68b26257 100644 --- a/src/renderer/components/DiskPicker.tsx +++ b/src/renderer/components/DiskPicker.tsx @@ -10,9 +10,11 @@ import { MiddleEllipsis } from "./MiddleEllipsis"; interface Props { onScanDrive: (drivePath: string) => void; onScanFolder: (folderPath: string) => void; + /** Settings โ†’ AI Agents โ†’ Connect: the first screen is where new users look. */ + onConnectAgent?: () => void; } -export function DiskPicker({ onScanDrive, onScanFolder }: Props) { +export function DiskPicker({ onScanDrive, onScanFolder, onConnectAgent }: Props) { const { drives, loading } = useLiveDiskSpace(); const [recents, setRecents] = useState<RecentScan[]>([]); const [recentsLoading, setRecentsLoading] = useState(true); @@ -109,8 +111,14 @@ export function DiskPicker({ onScanDrive, onScanFolder }: Props) { </> )} - {/* Footer spacing */} - <div style={{ height: 4 }} /> + {onConnectAgent ? ( + <div className="picker-agent-hint"> + <span>Using Claude or Codex?</span> + <button className="picker-agent-link" onClick={onConnectAgent}>Connect an AI agent โ€บ</button> + </div> + ) : ( + <div style={{ height: 4 }} /> + )} </div> </div> ); diff --git a/src/renderer/components/FolderList.tsx b/src/renderer/components/FolderList.tsx index e0f40044..054fa5e8 100644 --- a/src/renderer/components/FolderList.tsx +++ b/src/renderer/components/FolderList.tsx @@ -1,11 +1,12 @@ -import { useCallback, useEffect, useMemo, useState } from "preact/hooks"; +import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks"; import { FOLDER_CHILDREN_MAX_DIRS, type ScanFileRecord, type ScanSnapshot } from "../../shared/contracts"; import { platformTerminology } from "../../shared/platformTerminology"; import { protectedFolderDisplayName } from "../../shared/pathProtection"; import type { ExcludedFolderActionBlocker } from "../../shared/pathProtection"; -import { formatScanRoot } from "../../shared/pathUtils"; +import { formatScanRoot, normPath } from "../../shared/pathUtils"; import { formatBytes, formatCount } from "../lib/format"; +import { deletedPathLabel, deletedPathTitle, useDeletedPaths, type DeletedPathRecord } from "../lib/deletedPaths"; import { useExcludedFolderProtection, usePathActions } from "../lib/hooks"; import { nativeApi } from "../nativeApi"; import { DisclosureToggle } from "./Disclosure"; @@ -17,6 +18,29 @@ interface Props { snapshot: ScanSnapshot; onStartScan?: () => void; otherScannedRoots?: string[]; + /** + * Open this folder (an AI agent's drill-down, via the MCP navigate + * tools). A new `nonce` re-applies the same path. Applied once the + * snapshot for a root containing it is showing. + */ + focusRequest?: { path: string; nonce: number } | null; + /** The focus request was applied; the caller clears it so a later visit to the tab starts fresh. */ + onFocusApplied?: (nonce: number) => void; +} + +/** + * `target` re-cased to match `root` when it lives under it, else null. + * Windows paths compare case-insensitively, but the breadcrumbs and the + * folder index want the root spelled exactly as the scan recorded it. + */ +function folderUnderRoot(root: string, target: string): string | null { + const r = normPath(root, nativeApi.platform); + const t = normPath(target, nativeApi.platform); + if (t === r) return root; + const inside = r === "" ? t.startsWith("/") : t.startsWith(`${r}/`) || t.startsWith(`${r}\\`); + if (!inside) return null; + const rest = target.replace(/[\\/]+$/, "").slice(root.replace(/[\\/]+$/, "").length).replace(/^[\\/]+/, ""); + return /[\\/]$/.test(root) ? `${root}${rest}` : `${root}${root.includes("\\") ? "\\" : "/"}${rest}`; } /** @@ -95,7 +119,7 @@ function buildBreadcrumbs(currentPath: string, rootPath: string): { label: strin // โ”€โ”€ Component โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -export function FolderList({ snapshot, onStartScan, otherScannedRoots = [] }: Props) { +export function FolderList({ snapshot, onStartScan, otherScannedRoots = [], focusRequest = null, onFocusApplied }: Props) { const rootPath = snapshot.rootPath ?? ""; const [currentPath, setCurrentPath] = useState(rootPath); const [children, setChildren] = useState<FolderChild[]>([]); @@ -118,15 +142,39 @@ export function FolderList({ snapshot, onStartScan, otherScannedRoots = [] }: Pr } | null>(null); const { busy, runAction, handleEasyMove } = usePathActions(); const { findProtectedFolder, findProtectionBlocker } = useExcludedFolderProtection(); + // Folders trashed this session (from the context menu or by an AI + // agent after the user confirmed) stay listed until the next scan. + const { getDeletedRecord } = useDeletedPaths(); + + const focusRef = useRef(focusRequest); + focusRef.current = focusRequest; + const appliedFocusNonce = useRef<number | null>(null); + /** The pending agent focus path if it belongs to `root`; consumes it. */ + const takeFocus = (root: string): string | null => { + const request = focusRef.current; + if (!root || !request || request.nonce === appliedFocusNonce.current) return null; + const target = folderUnderRoot(root, request.path); + if (target) { + appliedFocusNonce.current = request.nonce; + onFocusApplied?.(request.nonce); + } + return target; + }; // Reset navigation when the scan root changes (drive switch etc). + // An agent that switched roots to open a folder lands in that folder. useEffect(() => { if (rootPath) { - setCurrentPath(rootPath); + setCurrentPath(takeFocus(rootPath) ?? rootPath); setShowOtherFiles(false); } }, [rootPath]); + useEffect(() => { + const target = takeFocus(rootPath); + if (target) setCurrentPath(target); + }, [focusRequest?.nonce]); + useEffect(() => { setShowOtherFiles(false); }, [currentPath]); @@ -415,6 +463,7 @@ export function FolderList({ snapshot, onStartScan, otherScannedRoots = [] }: Pr rootPath={rootPath} canDrillIn={hasChildren(child.path)} isBusy={busy.has(child.path)} + deletedRecord={getDeletedRecord(child.path)} protectionBlocker={findProtectionBlocker(child.path)} onNavigate={() => setCurrentPath(child.path)} onReveal={() => void runAction(child.path, () => nativeApi.revealPath(child.path))} @@ -508,6 +557,7 @@ function FolderRow(props: { rootPath: string; canDrillIn: boolean; isBusy: boolean; + deletedRecord: DeletedPathRecord | null; protectionBlocker: ExcludedFolderActionBlocker | null; onNavigate: () => void; onReveal: () => void; @@ -515,7 +565,7 @@ function FolderRow(props: { onEasyMove: () => void; onContextMenu: (x: number, y: number) => void; }) { - const { dir, parentSize, rootPath, canDrillIn, isBusy, protectionBlocker, onNavigate, onReveal, onOpen, onEasyMove, onContextMenu } = props; + const { dir, parentSize, rootPath, canDrillIn, isBusy, deletedRecord, protectionBlocker, onNavigate, onReveal, onOpen, onEasyMove, onContextMenu } = props; const pct = parentSize > 0 ? (dir.size / parentSize) * 100 : 0; const name = protectedFolderDisplayName(dir.path, nativeApi.platform) ?? displayName(dir.path, rootPath); const actionDisabled = isBusy || Boolean(protectionBlocker); @@ -527,7 +577,7 @@ function FolderRow(props: { return ( <div - className={`folder-row ${canDrillIn ? "folder-row-clickable" : ""}`} + className={`folder-row ${canDrillIn ? "folder-row-clickable" : ""} ${deletedRecord ? "deleted" : ""}`} onClick={canDrillIn ? onNavigate : undefined} onContextMenu={(e) => { e.preventDefault(); @@ -551,7 +601,12 @@ function FolderRow(props: { </div> <div className="folder-row-info"> <div className="folder-row-name"> - {name} + <span className="folder-row-name-text">{name}</span> + {deletedRecord && ( + <span className={`deleted-path-badge ${deletedRecord.action}`} title={deletedPathTitle(deletedRecord)}> + {deletedPathLabel(deletedRecord)} + </span> + )} {protectionBlocker && <span className="protected-path-badge" title={protectionTitle}>Protected</span>} {canDrillIn && ( <svg className="folder-row-chevron" width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.3"> diff --git a/src/renderer/components/SettingsView.tsx b/src/renderer/components/SettingsView.tsx index f2499ada..50c09f40 100644 --- a/src/renderer/components/SettingsView.tsx +++ b/src/renderer/components/SettingsView.tsx @@ -18,6 +18,7 @@ import { dispatchSettingsUpdated, SETTINGS_UPDATED_EVENT } from "../lib/uiEvents import { startVisiblePoll } from "../lib/visiblePoll"; import { PowerEfficiencyControl } from "./PowerEfficiencyControl"; import { toast } from "./Toasts"; +import { AgentsSection } from "./AgentsSection"; import { normPath } from "../../shared/pathUtils"; import { basenameForPath, @@ -330,6 +331,9 @@ export function SettingsView() { onChange={(v) => void save({ ...settings, cleanup: { ...settings.cleanup, confirmPermanentDelete: v } })} /> </div> + {/* โ”€โ”€ AI Agents (MCP) โ”€โ”€ */} + <AgentsSection /> + {/* โ”€โ”€ Storage โ”€โ”€ */} <StorageSection settings={settings} diff --git a/src/renderer/index.css b/src/renderer/index.css index c7e12da5..bd6b8e31 100644 --- a/src/renderer/index.css +++ b/src/renderer/index.css @@ -3104,6 +3104,7 @@ button, input, select, textarea { font: inherit; } --hover-actions-bg: linear-gradient(var(--bg-row-selected), var(--bg-row-selected)), var(--bg); } .file-row.deleted, +.folder-row.deleted, .duplicate-file-row.deleted, .changes-row.deleted, .treemap-featured-card.deleted { @@ -3120,6 +3121,7 @@ button, input, select, textarea { font: inherit; } var(--bg-row); } .file-row.deleted .file-name-text, +.folder-row.deleted .folder-row-name-text, .duplicate-file-row.deleted .duplicate-file-path, .changes-row.deleted .changes-row-name-text, .treemap-featured-card.deleted .treemap-featured-name { @@ -3658,6 +3660,11 @@ button, input, select, textarea { font: inherit; } overflow: hidden; text-overflow: ellipsis; } +.folder-row-name-text { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} .folder-row-name-other { color: var(--text-muted); font-weight: 400; @@ -10004,3 +10011,876 @@ body.system-widget-body #app { .dev-summary-actions { margin-left: 0; } .dev-select-bar { padding-left: 12px; padding-right: 12px; } } + + +/* โ”€โ”€ AI Agents (MCP) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + * Settings โ†’ AI Agents, the header agent button and its popover, and + * the approval sheet an agent's sign-in opens (?consent=1). */ + +.agent-status-chip { + display: inline-block; + margin-left: 8px; + padding: 1px 7px; + border-radius: 999px; + font-family: var(--font-mono); + font-size: 9.5px; + font-weight: 700; + text-transform: uppercase; + vertical-align: 1px; +} +.agent-status-chip.on { background: var(--green-glow); color: var(--green); } +.agent-status-chip.off { background: rgba(148, 163, 184, 0.12); color: var(--text-secondary); } +.agent-status-chip.error { background: var(--red-glow); color: var(--red); } +.agent-status-error { color: var(--red); } +.agent-toggle-group { + display: flex; + align-items: center; + gap: 10px; +} + +.agent-subtitle { + margin: 16px 0 8px; + font-size: 11px; + font-weight: 700; + color: var(--text-secondary); + scroll-margin-top: 12px; +} +.agent-hint { + margin-top: 10px; + font-size: 11px; + color: var(--text-tertiary); + line-height: 1.5; +} + +/* Status dots, shared by the pill, the popover and Settings. */ +.agent-pill-dot { + width: 7px; + height: 7px; + flex-shrink: 0; + border-radius: 50%; + background: var(--text-muted); +} +.agent-pill-dot.active, +.agent-pill.active .agent-pill-dot { + background: var(--blue); + animation: agent-pill-pulse 1.4s ease-in-out infinite; +} +.agent-pill-dot.failed, +.agent-pill.failed .agent-pill-dot { background: var(--red); animation: none; } +.agent-pill-dot.waiting { background: var(--amber); } +@keyframes agent-pill-pulse { + 0%, 100% { box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.55); } + 50% { box-shadow: 0 0 0 4px rgba(59, 130, 246, 0); } +} + +/* โ”€โ”€ Header agent button โ”€โ”€ */ +.agent-btn-wrap { + position: relative; + display: flex; + align-items: center; + flex-shrink: 0; +} +.agent-btn { position: relative; } +.agent-btn.waiting { + border-color: rgba(245, 158, 11, 0.35); + background: var(--amber-glow); + color: var(--amber); +} +.agent-btn-listening { + position: absolute; + right: 3px; + bottom: 3px; + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--green); + box-shadow: 0 0 0 1.5px var(--bg); +} +.agent-btn-badge { + position: absolute; + top: -6px; + right: -6px; + min-width: 15px; + height: 15px; + padding: 0 4px; + border-radius: 999px; + background: var(--amber); + color: #1a1206; + font-family: var(--font-mono); + font-size: 9.5px; + font-weight: 700; + line-height: 15px; + text-align: center; +} +.agent-pill { + position: relative; + display: flex; + align-items: center; + gap: 6px; + flex-shrink: 0; + max-width: 180px; + height: 24px; + margin-right: 4px; + padding: 0 9px 0 8px; + border: 1px solid var(--border); + border-radius: 999px; + background: transparent; + color: var(--text-secondary); + font-size: 11px; + cursor: pointer; + -webkit-app-region: no-drag; +} +.agent-pill:hover, +.agent-pill.open { background: var(--bg-row-hover); color: var(--text); } +.agent-pill.active { + border-color: rgba(59, 130, 246, 0.35); + background: rgba(59, 130, 246, 0.08); + color: var(--text); +} +.agent-pill.failed { + border-color: rgba(239, 68, 68, 0.35); + background: rgba(239, 68, 68, 0.08); + color: var(--text); +} +.agent-pill-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +/* Below about 1,100 px the name takes room from the drive pills, so show + the dot alone. The agent's name stays in the tooltip and the + accessible label. */ +@media (max-width: 1100px) { + .agent-pill { + justify-content: center; + width: 24px; + padding: 0; + } + .agent-pill-name { display: none; } +} +.agent-btn:focus-visible, +.agent-pill:focus-visible { outline: 2px solid var(--amber); outline-offset: 1px; } + +/* โ”€โ”€ Popover โ”€โ”€ */ +.agent-pop { + position: fixed; + z-index: 60; + width: 350px; + padding: 6px; + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: var(--radius-lg); + background: var(--bg-panel); + box-shadow: 0 14px 34px rgba(0, 0, 0, 0.55); + backdrop-filter: blur(12px); + -webkit-app-region: no-drag; + animation: power-pop-in 0.12s ease-out; +} +:root.light .agent-pop { border-color: var(--border); box-shadow: 0 14px 34px rgba(0, 0, 0, 0.14); } +.agent-pop-head { + display: flex; + align-items: center; + justify-content: space-between; + padding: 6px 8px 8px; + font-family: var(--font-mono); + font-size: 10px; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--text-muted); +} +.agent-pop-head .agent-status-chip { margin-left: 0; } +.agent-pop-row { + display: grid; + grid-template-columns: 7px minmax(0, 1fr) auto; + gap: 9px; + align-items: start; + padding: 8px; + border-radius: var(--radius-md); +} +.agent-pop-row .agent-pill-dot { margin-top: 5px; } +.agent-pop-row.pending { background: rgba(245, 158, 11, 0.07); } +.agent-pop-main { min-width: 0; } +.agent-pop-name { font-size: 12px; font-weight: 600; color: var(--text); } +.agent-pop-what { + margin-top: 2px; + overflow: hidden; + font-size: 11px; + line-height: 1.4; + color: var(--text-tertiary); + text-overflow: ellipsis; + white-space: nowrap; +} +.agent-pop-what.failed { color: var(--red); } +.agent-role-chip { + padding: 2px 6px; + border: 1px solid var(--border); + border-radius: 999px; + font-family: var(--font-mono); + font-size: 9.5px; + font-weight: 600; + color: var(--text-secondary); + white-space: nowrap; +} +.agent-pop-more, +.agent-pop-empty, +.agent-pop-error { + padding: 6px 8px; + font-size: 11px; + color: var(--text-muted); +} +.agent-pop-error { color: var(--red); } +.agent-pop-off { padding: 2px 8px 8px; } +.agent-pop-off p { + margin: 0 0 10px; + font-size: 11.5px; + line-height: 1.5; + color: var(--text-secondary); +} +.agent-pop-blocked, +.agent-pop-link, +.agent-blocked-link, +.agent-disclose, +.agent-consent-more, +.picker-agent-link { + border: none; + background: none; + font: inherit; + cursor: pointer; +} +.agent-pop-blocked { + display: block; + width: 100%; + padding: 6px 8px; + border-radius: var(--radius-sm); + font-size: 11px; + color: var(--red); + text-align: left; +} +.agent-pop-blocked:hover { background: var(--red-glow); } +.agent-pop-foot { + display: flex; + align-items: center; + justify-content: space-between; + margin-top: 4px; + padding: 6px 4px 2px; + border-top: 1px solid var(--border); +} +.agent-pop-link { + padding: 4px; + border-radius: var(--radius-sm); + font-size: 11px; + color: var(--amber); +} +.agent-pop-link:hover { background: var(--amber-glow); } +.agent-review-btn { + border-color: rgba(245, 158, 11, 0.25); + background: linear-gradient(135deg, rgba(245, 158, 11, 0.2), rgba(249, 115, 22, 0.15)); + color: var(--amber); + font-weight: 600; +} + +/* โ”€โ”€ Settings: waiting approvals, sessions โ”€โ”€ */ +.agent-pending-row { + display: grid; + grid-template-columns: 7px minmax(0, 1fr) auto auto; + gap: 10px; + align-items: center; + margin-bottom: 6px; + padding: 8px 10px; + border: 1px solid rgba(245, 158, 11, 0.25); + border-radius: var(--radius-md); + background: rgba(245, 158, 11, 0.06); +} +.agent-pending-row.stale { + border-color: var(--border); + background: var(--bg-row); +} +.agent-session-list { + border: 1px solid var(--border); + border-radius: var(--radius-md); + overflow: hidden; + background: var(--bg-row); +} +.agent-session-row { + display: grid; + grid-template-columns: minmax(0, 1fr) auto auto; + align-items: center; + gap: 10px; + padding: 8px 10px; + border-bottom: 1px solid var(--border); +} +.agent-session-row:last-child { border-bottom: none; } +.agent-session-name { + display: flex; + align-items: center; + gap: 7px; + min-width: 0; + font-size: 12.5px; + font-weight: 600; + color: var(--text); +} +.agent-session-title { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.agent-via { + display: inline-flex; + align-items: center; + flex-shrink: 0; + height: 16px; + padding: 0 6px; + border: 1px solid var(--border); + border-radius: 999px; + font-family: var(--font-mono); + font-size: 9.5px; + font-weight: 600; + color: var(--text-tertiary); +} +.agent-session-meta { + margin-top: 2px; + overflow: hidden; + font-size: 10.5px; + color: var(--text-tertiary); + line-height: 1.45; + text-overflow: ellipsis; + white-space: nowrap; +} +.agent-session-failed { color: var(--red-dim); } +.agent-session-capped { color: var(--amber-dim); white-space: normal; } +.agent-blocked-link { + padding: 0; + font-size: inherit; + color: var(--red); +} +.agent-blocked-link:hover { text-decoration: underline; } +.agent-revoked { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-top: 8px; + font-size: 11px; + color: var(--text-muted); +} + +/* โ”€โ”€ Settings: Connect โ”€โ”€ */ +.agent-disclose { + display: flex; + align-items: center; + gap: 9px; + width: 100%; + padding: 8px 10px; + border: 1px solid var(--border); + border-radius: var(--radius-md); + background: var(--bg-row); + color: var(--text-secondary); + font-size: 11.5px; + text-align: left; +} +.agent-disclose:hover { background: var(--bg-row-hover); color: var(--text); } +.agent-disclose-chevron { + width: 6px; + height: 6px; + flex-shrink: 0; + border-right: 1.5px solid currentColor; + border-bottom: 1.5px solid currentColor; + transform: rotate(-45deg); + transition: transform 0.12s; +} +.agent-disclose-chevron.open { transform: rotate(45deg); } +.agent-client-tabs { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-bottom: 12px; +} +.agent-client-tabs .chip { display: inline-flex; align-items: center; gap: 6px; } +.agent-tab-dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--green); +} +.agent-steps { + display: flex; + flex-direction: column; + gap: 12px; + margin: 0; + padding: 0; + list-style: none; +} +.agent-step { + display: grid; + grid-template-columns: 20px minmax(0, 1fr); + gap: 10px; +} +.agent-step-num { + width: 20px; + height: 20px; + border: 1px solid var(--border); + border-radius: 50%; + background: var(--bg-raised); + color: var(--text-secondary); + font-family: var(--font-mono); + font-size: 10.5px; + font-weight: 600; + line-height: 18px; + text-align: center; +} +.agent-step-num.done { + border-color: rgba(16, 185, 129, 0.35); + background: var(--green-glow); + color: var(--green); +} +.agent-step-body { min-width: 0; } +.agent-step-text { + padding-top: 2px; + font-size: 12px; + line-height: 1.5; + color: var(--text); +} +.agent-command { + display: flex; + align-items: flex-start; + gap: 8px; + margin-top: 6px; + padding: 7px 8px 7px 10px; + border: 1px solid var(--border); + border-radius: var(--radius-md); + background: var(--bg-input); +} +.agent-command-text { + flex: 1; + min-width: 0; + margin: 0; + font-family: var(--font-mono); + font-size: 11px; + line-height: 1.6; + color: var(--text-secondary); + white-space: pre-wrap; + word-break: break-all; + user-select: text; +} +.agent-copy { flex-shrink: 0; } +.agent-copy.copied { + border-color: rgba(16, 185, 129, 0.3); + background: var(--green-glow); + color: var(--green); +} +.agent-connect-lead { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 12px; +} +.agent-connect-lead .scan-btn { flex-shrink: 0; } +.agent-connect-lead-text { + font-size: 11.5px; + line-height: 1.5; + color: var(--text-tertiary); +} +/* Prose, so it wraps at words; the long helper path still breaks anywhere. */ +.agent-prompt-text { + word-break: normal; + overflow-wrap: anywhere; +} +.agent-manual-toggle { margin-top: 6px; } +.agent-step-action { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px 10px; + margin-top: 8px; +} +.agent-step-result { + font-size: 11px; + line-height: 1.5; + color: var(--text-tertiary); +} +.agent-step-result.failed { color: var(--red); } +.agent-manual-text { + margin-top: 6px; + font-size: 11px; + line-height: 1.5; + color: var(--text-tertiary); +} +.agent-live { + display: flex; + align-items: center; + gap: 9px; + padding: 8px 10px; + border: 1px solid var(--border); + border-radius: var(--radius-md); + background: var(--bg-row); + font-size: 12px; + color: var(--text-secondary); +} +.agent-live.waiting { + border-color: rgba(245, 158, 11, 0.25); + background: rgba(245, 158, 11, 0.06); + color: var(--text); +} +.agent-live.connected { + border-color: rgba(16, 185, 129, 0.25); + background: rgba(16, 185, 129, 0.06); + color: var(--text); +} +.agent-live.failed { + border-color: rgba(239, 68, 68, 0.25); + background: var(--red-glow); + color: var(--text); +} +.agent-live-main { flex: 1; min-width: 0; } +.agent-live-meta { + margin-top: 1px; + overflow: hidden; + font-size: 11px; + color: var(--text-tertiary); + text-overflow: ellipsis; + white-space: nowrap; +} +.agent-live-ring { + width: 12px; + height: 12px; + flex-shrink: 0; + border: 1.5px solid rgba(148, 163, 184, 0.25); + border-top-color: var(--text-secondary); + border-radius: 50%; + animation: agent-spin 0.85s linear infinite; +} +.agent-live-ok { + width: 7px; + height: 7px; + flex-shrink: 0; + border-radius: 50%; + background: var(--green); +} +@keyframes agent-spin { to { transform: rotate(360deg); } } +.agent-try { + display: flex; + align-items: center; + gap: 8px; + margin-top: 14px; + padding-top: 10px; + border-top: 1px solid var(--border); + font-size: 11.5px; + color: var(--text-tertiary); +} +.agent-try-prompt { flex: 1; min-width: 0; color: var(--text); } + +/* โ”€โ”€ Settings: blocked requests and the feed โ”€โ”€ */ +.agent-activity-list { + border: 1px solid var(--border); + border-radius: var(--radius-md); + overflow: hidden; +} +.agent-activity-row { + display: grid; + grid-template-columns: 64px minmax(0, 140px) minmax(0, 1fr) auto; + gap: 10px; + padding: 5px 10px; + border-bottom: 1px solid var(--border); + font-size: 11px; +} +.agent-activity-row:last-child { border-bottom: none; } +.agent-activity-time { color: var(--text-muted); font-family: var(--font-mono); font-size: 10.5px; } +.agent-activity-session { + color: var(--text-secondary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.agent-activity-summary { + color: var(--text); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.agent-activity-row.failed .agent-activity-summary { color: var(--red); } +.agent-blocked-count { + color: var(--red); + font-family: var(--font-mono); + font-size: 10px; + font-weight: 600; +} + +/* โ”€โ”€ Drive picker โ”€โ”€ */ +.picker-agent-hint { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + margin-top: 14px; + padding-top: 10px; + border-top: 1px solid var(--border); + font-size: 11.5px; + color: var(--text-tertiary); +} +.picker-agent-link { + padding: 2px 4px; + border-radius: var(--radius-sm); + font-size: 11.5px; + color: var(--amber); +} +.picker-agent-link:hover { background: var(--amber-glow); } + +@media (prefers-reduced-motion: reduce) { + .agent-pill-dot.active, + .agent-pill.active .agent-pill-dot, + .agent-live-ring { animation: none; } +} + +/* โ”€โ”€ Approval sheet โ”€โ”€ */ +body.agent-consent-body { + overflow-y: auto; + background: var(--black); +} +.agent-consent { + max-width: 520px; + margin: 0 auto; + padding: 24px 26px 0; +} +.agent-consent-eyebrow { + font-size: 10.5px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--amber); +} +.agent-consent h1 { + margin: 6px 0 6px; + font-size: 19px; + font-weight: 650; + color: var(--text); +} +.agent-consent-header p { + font-size: 12.5px; + line-height: 1.55; + color: var(--text-secondary); +} +.agent-consent-header strong { color: var(--text); } +.agent-consent-header { margin-bottom: 14px; } +.agent-consent-error { + margin-bottom: 14px; + padding: 8px 10px; + border: 1px solid rgba(239, 68, 68, 0.25); + border-radius: var(--radius-md); + background: var(--red-glow); + color: var(--red); + font-size: 12px; +} +.agent-consent-stale { + display: grid; + grid-template-columns: 7px minmax(0, 1fr); + gap: 9px; + margin-bottom: 14px; + padding: 9px 12px; + border: 1px solid rgba(148, 163, 184, 0.28); + border-radius: var(--radius-md); + background: rgba(148, 163, 184, 0.08); + font-size: 11.5px; + line-height: 1.5; + color: var(--text-secondary); +} +.agent-consent-stale strong { color: var(--text); font-weight: 600; } +.agent-consent-stale-dot { + width: 7px; + height: 7px; + margin-top: 5px; + border-radius: 50%; + background: var(--text-muted); +} +.agent-consent-field { + display: flex; + flex-direction: column; + gap: 5px; + margin-bottom: 12px; + font-size: 11px; + font-weight: 600; + color: var(--text-secondary); +} +.agent-consent-field .filter-input { + width: 100%; + height: 30px; + font-size: 12.5px; +} +#agent-consent-role-label { margin-bottom: 6px; } +.agent-consent-role-desc { + margin: 2px 0 10px; + font-size: 12px; + line-height: 1.5; + color: var(--text-tertiary); +} +.agent-role-cards { + display: flex; + flex-direction: column; + gap: 6px; + margin-bottom: 8px; +} +.agent-role-card { + display: grid; + grid-template-columns: 14px minmax(0, 1fr); + gap: 10px; + padding: 9px 12px; + border: 1px solid var(--border); + border-radius: var(--radius-md); + background: var(--bg-row); + color: var(--text); + font: inherit; + text-align: left; + cursor: pointer; + transition: all 0.12s; +} +.agent-role-card:hover { background: var(--bg-row-hover); } +.agent-role-card:focus-visible { outline: 2px solid var(--amber); outline-offset: 1px; } +.agent-role-card.selected { + border-color: var(--border-selected); + background: rgba(245, 158, 11, 0.06); +} +.agent-role-card.selected.destructive { + border-color: rgba(239, 68, 68, 0.35); + background: rgba(239, 68, 68, 0.06); +} +.agent-role-radio { + width: 14px; + height: 14px; + margin-top: 1px; + border: 1.5px solid var(--text-muted); + border-radius: 50%; +} +.agent-role-card.selected .agent-role-radio { border: 4px solid var(--amber); } +.agent-role-body { display: flex; flex-direction: column; min-width: 0; } +.agent-role-name { font-size: 12.5px; font-weight: 600; } +.agent-role-line { + margin-top: 2px; + font-size: 11.5px; + line-height: 1.45; + color: var(--text-tertiary); +} +.agent-role-caps { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-top: 6px; +} +.agent-cap { + display: inline-flex; + align-items: center; + height: 18px; + padding: 0 7px; + border: 1px solid var(--border); + border-radius: 999px; + font-size: 10.5px; + color: var(--text-secondary); +} +.agent-session-caps { margin: 3px 0 2px; } +.agent-cap.destructive { + border-color: rgba(239, 68, 68, 0.3); + background: rgba(239, 68, 68, 0.08); + color: var(--red); +} +.agent-consent-more { + display: flex; + align-items: center; + gap: 7px; + margin: 2px 0 10px; + padding: 2px 0; + font-size: 11.5px; + color: var(--text-secondary); +} +.agent-consent-more:hover { color: var(--text); } +.agent-consent-permissions { + list-style: none; + margin: 0 0 10px; + padding: 0; + border: 1px solid var(--border); + border-radius: var(--radius-md); + background: var(--bg-row); + overflow: hidden; +} +.agent-consent-permissions li { + padding: 8px 12px 8px 26px; + border-bottom: 1px solid var(--border); + position: relative; +} +.agent-consent-permissions li:last-child { border-bottom: none; } +.agent-consent-permissions li::before { + content: ""; + position: absolute; + left: 11px; + top: 13px; + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--green); +} +.agent-consent-permissions li.sensitive::before { background: var(--amber); } +.agent-consent-permissions li.destructive::before { background: var(--red); } +.agent-consent-permission-label { + font-size: 12.5px; + font-weight: 600; + color: var(--text); +} +.agent-consent-permission-detail { + margin-top: 2px; + font-size: 11.5px; + line-height: 1.45; + color: var(--text-tertiary); +} +.agent-consent-delta { + display: grid; + grid-template-columns: 14px minmax(0, 1fr); + gap: 8px; + margin-bottom: 10px; + padding: 9px 12px; + border: 1px solid rgba(245, 158, 11, 0.22); + border-radius: var(--radius-md); + background: rgba(245, 158, 11, 0.07); + font-size: 11.5px; + line-height: 1.5; + color: var(--text-secondary); +} +.agent-consent-delta strong { font-weight: 600; color: var(--text); } +.agent-consent-delta.destructive { + border-color: rgba(239, 68, 68, 0.3); + background: rgba(239, 68, 68, 0.07); +} +.agent-consent-delta-plus { + font-family: var(--font-mono); + font-size: 13px; + font-weight: 700; + line-height: 1.2; + color: var(--amber); +} +.agent-consent-delta.destructive .agent-consent-delta-plus { color: var(--red); } +.agent-consent-footnote { + margin: 4px 0 0; + font-size: 11.5px; + line-height: 1.5; + color: var(--text-tertiary); +} +.agent-consent-delta { scroll-margin-bottom: 72px; } +.agent-consent-actions { + position: sticky; + bottom: 0; + border-top: 1px solid var(--border); + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; + padding: 14px 0 20px; + background: var(--black); +} +.agent-consent-actions .action-btn { + height: 30px; + padding: 0 16px; + font-size: 12.5px; +} +.agent-consent-queue { + margin-right: auto; + font-size: 11px; + color: var(--text-tertiary); +} +.agent-consent-approve { height: 30px; font-size: 12.5px; } +.agent-consent-default { box-shadow: 0 0 0 2px var(--black), 0 0 0 4px rgba(245, 158, 11, 0.55); color: var(--text); } diff --git a/src/renderer/lib/agentAccessStore.ts b/src/renderer/lib/agentAccessStore.ts new file mode 100644 index 00000000..bb1ae094 --- /dev/null +++ b/src/renderer/lib/agentAccessStore.ts @@ -0,0 +1,101 @@ +import { useEffect, useRef, useState } from "preact/hooks"; + +import type { AgentAccessSnapshot } from "../../shared/agentAccess"; +import { nativeApi } from "../nativeApi"; + +/** + * One copy of the agent access snapshot for the main window. The header + * agent button and Settings โ†’ AI Agents both read it. Main pushes every + * change (sessions, pending approvals, status), each agent action and + * each blocked request, so opening Settings or the popover asks main for + * nothing after the first load. + */ +let current: AgentAccessSnapshot | null = null; +let loading: Promise<void> | null = null; +let subscribed = false; +const listeners = new Set<(snapshot: AgentAccessSnapshot) => void>(); + +function publish(next: AgentAccessSnapshot): void { + current = next; + for (const listener of [...listeners]) listener(next); +} + +function subscribe(): void { + if (subscribed) return; + subscribed = true; + nativeApi.onAgentAccessChanged(publish); + nativeApi.onAgentActivity((entry) => { + if (!current) return; + publish({ + ...current, + activity: [entry, ...current.activity.filter((e) => e.id !== entry.id)].slice(0, 100), + }); + }); + // A repeat of an event arrives with the same id and a higher count. + nativeApi.onAgentSecurityEvent((event) => { + if (!current) return; + publish({ + ...current, + security: [event, ...current.security.filter((e) => e.id !== event.id)].slice(0, 200), + }); + }); +} + +/** Load once; later callers share the same request. */ +export function loadAgentAccess(): Promise<void> { + subscribe(); + loading ??= nativeApi.getAgentAccess().then(publish, () => { + loading = null; + }); + return loading; +} + +/** Store the snapshot an action (toggle, revoke, role change) returned. */ +export function setAgentAccess(next: AgentAccessSnapshot): void { + publish(next); +} + +/** Where in Settings โ†’ AI Agents a link should land. */ +export type AgentSettingsTarget = "section" | "connect" | "blocked"; + +let focusRequest: AgentSettingsTarget | null = null; +const focusListeners = new Set<(target: AgentSettingsTarget) => void>(); + +/** + * Ask Settings โ†’ AI Agents to show a part of itself. Settings may not be + * mounted yet (the tab is switching), so the request waits until it is. + */ +export function focusAgentSettings(target: AgentSettingsTarget): void { + focusRequest = target; + for (const listener of [...focusListeners]) listener(target); +} + +/** For AgentsSection: the request made before it mounted, and later ones. */ +export function useAgentSettingsFocus(onFocus: (target: AgentSettingsTarget) => void): void { + const latest = useRef(onFocus); + latest.current = onFocus; + useEffect(() => { + const listener = (target: AgentSettingsTarget) => { + focusRequest = null; + latest.current(target); + }; + focusListeners.add(listener); + if (focusRequest) listener(focusRequest); + return () => { + focusListeners.delete(listener); + }; + }, []); +} + +export function useAgentAccess(): AgentAccessSnapshot | null { + const [snapshot, setSnapshot] = useState(current); + useEffect(() => { + listeners.add(setSnapshot); + if (current) setSnapshot(current); + else void loadAgentAccess(); + return () => { + listeners.delete(setSnapshot); + }; + }, []); + return snapshot; +} diff --git a/src/renderer/lib/agentDisplay.ts b/src/renderer/lib/agentDisplay.ts new file mode 100644 index 00000000..6d9777cd --- /dev/null +++ b/src/renderer/lib/agentDisplay.ts @@ -0,0 +1,68 @@ +import { + MCP_AGENT_CAPABILITY_DETAILS, + type AgentAccessSnapshot, + type AgentActivityEntry, + type AgentClientGuide, + type AgentClientVia, + type AgentPendingApproval, + type McpAgentCapability, + type McpAgentRole, + type McpAgentSession, +} from "../../shared/agentAccess"; + +/** "Guide" for Cleanup Guide, "Explorer" for Disk Explorer: for chips. */ +export function roleShortName(role: McpAgentRole | undefined): string { + return role ? role.name.replace(/^(Cleanup|Disk) /, "") : "No role"; +} + +export function viaLabel(via: AgentClientVia | undefined): string { + return via === "stdio" ? "stdio helper" : via === "http" ? "HTTP" : ""; +} + +/** The name a client signed in as (session names can be edited or numbered). */ +export function sessionClientName(session: McpAgentSession): string { + return session.client?.name ?? session.name; +} + +/** Whether `name` (a client or session name) is the client a setup guide is for. */ +export function isGuideClient(guide: AgentClientGuide, name: string): boolean { + if (guide.id === "other") return false; + const want = guide.name.toLowerCase(); + const got = name.trim().toLowerCase(); + return got === want || got.startsWith(`${want} `); +} + +export function activeSessions(snapshot: AgentAccessSnapshot): McpAgentSession[] { + return snapshot.sessions.filter((session) => session.revokedAt === null); +} + +/** The newest action per session, from the activity feed (newest first). */ +export function lastActionBySession(activity: readonly AgentActivityEntry[]): Map<string, AgentActivityEntry> { + const last = new Map<string, AgentActivityEntry>(); + for (const entry of activity) { + if (!last.has(entry.sessionId)) last.set(entry.sessionId, entry); + } + return last; +} + +/** Blocked requests per session, counting repeats. */ +export function blockedBySession(snapshot: AgentAccessSnapshot, since = 0): Map<string, number> { + const counts = new Map<string, number>(); + for (const event of snapshot.security) { + if (event.at < since) continue; + counts.set(event.sessionId, (counts.get(event.sessionId) ?? 0) + event.count); + } + return counts; +} + +export function pendingText(pending: AgentPendingApproval, now: number): string { + if (pending.stale) return "Stopped waiting. It may have timed out."; + const seconds = Math.max(0, Math.round((now - pending.requestedAt) / 1000)); + return `Waiting for your approval ยท ${seconds < 60 ? `${seconds} s` : `${Math.round(seconds / 60)} min`}`; +} + +/** A permission's short chip label, with the Recycle Bin on Windows. */ +export function capabilityChip(permission: McpAgentCapability, platform: string): string { + const short = MCP_AGENT_CAPABILITY_DETAILS[permission].short; + return platform === "win32" ? short.replace("Trash", "Recycle Bin") : short; +} diff --git a/src/renderer/main.tsx b/src/renderer/main.tsx index fedbe236..1fb150a3 100644 --- a/src/renderer/main.tsx +++ b/src/renderer/main.tsx @@ -2,13 +2,19 @@ import { render } from "preact"; import type { AppSettings } from "../shared/contracts"; import { App } from "./App"; +import { AgentConsentWindow } from "./components/AgentConsentWindow"; import { SystemWidget } from "./components/SystemWidget"; import { setSizeUnitPreference } from "./lib/format"; import { SETTINGS_UPDATED_EVENT } from "./lib/uiEvents"; import { nativeApi } from "./nativeApi"; import "./index.css"; -const isWidget = new URLSearchParams(window.location.search).get("widget") === "1"; +const params = new URLSearchParams(window.location.search); +const root = params.get("widget") === "1" + ? <SystemWidget /> + : params.get("consent") === "1" + ? <AgentConsentWindow /> + : <App />; // Subscribe before loading so a late initial read cannot undo a newer setting. let settingsRevision = 0; @@ -24,6 +30,5 @@ const initialRevision = settingsRevision; void nativeApi.getSettings().then((settings) => { if (settings && settingsRevision === initialRevision) applySettings(settings); }).catch(() => { /* use the platform default if settings are unavailable */ }).finally(() => { - render(isWidget ? <SystemWidget /> : <App />, document.getElementById("app") as HTMLElement); + render(root, document.getElementById("app") as HTMLElement); }); - diff --git a/src/shared/__tests__/agentClientGuides.test.ts b/src/shared/__tests__/agentClientGuides.test.ts new file mode 100644 index 00000000..f9f8f45b --- /dev/null +++ b/src/shared/__tests__/agentClientGuides.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; + +import { AGENT_ACCESS_PORT, agentClientGuides, agentSetupPrompt } from "../agentAccess"; + +const helper = "/Applications/DiskHound.app/Contents/Resources/native/diskhound-mcp"; +const guide = (id: string, port = AGENT_ACCESS_PORT, platform = "darwin") => + agentClientGuides(port, helper, platform).find((candidate) => candidate.id === id)!; + +describe("agentClientGuides", () => { + it("asks each agent to add DiskHound to its own user configuration", () => { + expect(guide("claude-code").steps[0]!.prompt).toBe( + `Add diskhound to my Claude Code user configuration using the stdio executable "${helper}", with no arguments. ` + + "Preserve my other MCP servers, then help me connect and approve access in DiskHound.", + ); + expect(guide("codex").steps[0]!.prompt).toBe( + "Add diskhound to my Codex user configuration using the HTTP MCP endpoint http://127.0.0.1:51735/mcp with OAuth. " + + "Preserve my other MCP servers, then help me connect and approve access in DiskHound.", + ); + expect(guide("other").steps[0]!.prompt).toContain("Add diskhound to this agent's user configuration"); + expect(agentSetupPrompt(AGENT_ACCESS_PORT, helper)).toBe( + `Set up diskhound as a user-level MCP server for this agent. For Claude, use the stdio executable "${helper}" with no arguments. ` + + "For other clients, use the HTTP MCP endpoint http://127.0.0.1:51735/mcp with OAuth. " + + "Preserve my other MCP servers, then help me connect and approve access in DiskHound.", + ); + }); + + it("keeps the command for doing it by hand behind a Show button", () => { + const code = guide("claude-code").steps[0]!.manual!; + expect(code.toggle).toBe("command"); + expect(code.items[0]!.snippet).toBe(`claude mcp add --scope user --transport stdio diskhound -- '${helper}'`); + expect(guide("codex").steps[0]!.manual!.items[0]!.snippet) + .toBe("codex mcp add diskhound --url http://127.0.0.1:51735/mcp --oauth-client-registration dcr"); + }); + + it("adds Claude Desktop with its own install dialog, where Claude Desktop exists", () => { + // Its chat can't run commands, so there's no prompt to paste, and + // nothing to merge into Claude's config by hand. + for (const platform of ["darwin", "win32"]) { + const desktop = guide("claude-desktop", AGENT_ACCESS_PORT, platform); + expect(desktop.steps.map((step) => step.action ?? null)).toEqual(["add-to-claude", null]); + expect(desktop.steps.some((step) => step.prompt || step.manual)).toBe(false); + expect(desktop.note).toBe("The extension works in the Claude app's chats and its Code sessions."); + // Both would give the app's Code sessions two DiskHounds. + expect(guide("claude-code", AGENT_ACCESS_PORT, platform).note).toContain("use the Claude Desktop extension instead"); + } + expect(guide("claude-code", AGENT_ACCESS_PORT, "linux").note).toBeUndefined(); + expect(agentClientGuides(AGENT_ACCESS_PORT, helper, "linux").map((candidate) => candidate.id)) + .toEqual(["claude-code", "codex", "other"]); + }); + + it("passes a non-default port everywhere", () => { + expect(guide("claude-code", 51999).steps[0]!.prompt).toContain("with the arguments --port 51999"); + expect(guide("claude-code", 51999).steps[0]!.manual!.items[0]!.snippet).toMatch(/ --port 51999$/); + expect(guide("codex", 51999).steps[0]!.prompt).toContain("http://127.0.0.1:51999/mcp"); + expect(agentSetupPrompt(51999, helper)).toContain("with the arguments --port 51999"); + }); +}); diff --git a/src/shared/agentAccess.ts b/src/shared/agentAccess.ts new file mode 100644 index 00000000..4caedccd --- /dev/null +++ b/src/shared/agentAccess.ts @@ -0,0 +1,416 @@ +// โ”€โ”€ Local agent access (MCP) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ +// +// Shared between the main process (src/mcp/*) and the renderer +// (Settings โ†’ AI Agents, the approval window, the header activity +// pill). Keep this module free of Node imports โ€” Vite bundles it into +// the renderer. + +/** + * The endpoint is a fixed loopback port, not a discovery file: Claude + * Code and Codex store the URL once (`claude mcp add โ€ฆ <url>`), so it + * has to survive restarts. PwrSnap uses 51729, PwrGit 51731 and + * PwrSuiteLab Control 51733; 51735 keeps DiskHound out of their way + * when they run side by side. + */ +export const AGENT_ACCESS_PORT = 51735; +export const AGENT_ACCESS_HOST = "127.0.0.1"; +export const AGENT_ACCESS_MCP_PATH = "/mcp"; + +/** Name agents see in `initialize`; Claude Code prefixes tools with it. */ +export const MCP_SERVER_NAME = "diskhound"; + +/** SEP-2640 extension identifier (Skills over MCP). */ +export const SKILLS_EXTENSION_ID = "io.modelcontextprotocol/skills"; + +export function agentAccessMcpUrl(port: number = AGENT_ACCESS_PORT): string { + return `http://${AGENT_ACCESS_HOST}:${port}${AGENT_ACCESS_MCP_PATH}`; +} + +export type AgentClientId = "claude-code" | "claude-desktop" | "codex" | "other"; + +/** One numbered step in Settings โ†’ AI Agents โ†’ Connect. */ +export interface AgentSetupStep { + text: string; + /** Setup instructions to paste into the agent, with a Copy button. */ + prompt?: string; + /** Doing it by hand instead, behind "Show <toggle>": notes, each with a snippet to copy. */ + manual?: { toggle: string; items: { text: string; snippet: string }[] }; + /** A button that does the step: open DiskHound's extension in Claude. */ + action?: "add-to-claude"; +} + +/** What "Add to Claude" did. `file` is the extension, to show when Claude didn't open it. */ +export type AddToClaudeResult = { ok: true; file: string } | { ok: false; error: string; file?: string }; + +export interface AgentClientGuide { + id: AgentClientId; + name: string; + /** How the client reaches DiskHound, shown next to its name. */ + via: string; + steps: AgentSetupStep[]; + /** A first thing to ask once connected. */ + firstPrompt: string; + /** A line under the steps. */ + note?: string; +} + +/** Quote a path for PowerShell or a POSIX shell. Never interpolate a raw app path. */ +function shellQuote(value: string, platform: string): string { + return platform === "win32" + ? "'" + value.replaceAll("'", "''") + "'" + : "'" + value.replaceAll("'", "'\\''") + "'"; +} + +const helperArgs = (port: number) => (port === AGENT_ACCESS_PORT ? "no arguments" : `the arguments --port ${port}`); +const promptTail = "Preserve my other MCP servers, then help me connect and approve access in DiskHound."; + +/** + * One prompt for whichever agent the user has, the connect guide's main + * button. Like the per-client prompts, it asks the agent to set itself + * up: DiskHound never writes another app's configuration. + */ +export function agentSetupPrompt(port: number = AGENT_ACCESS_PORT, stdioPath = "diskhound-mcp"): string { + return `Set up ${MCP_SERVER_NAME} as a user-level MCP server for this agent. For Claude, use the stdio executable "${stdioPath}" with ${helperArgs(port)}. For other clients, use the HTTP MCP endpoint ${agentAccessMcpUrl(port)} with OAuth. ${promptTail}`; +} + +/** + * Setup steps per client, shown in Settings โ†’ AI Agents. + * + * - DiskHound never writes another app's configuration. Agents that + * can run commands get a prompt to paste, and add DiskHound to their + * own configuration; the command to do it by hand sits behind a Show + * button. + * - Claude Desktop's chat can't run commands, so DiskHound opens its + * extension (an MCP Bundle) in Claude, and Claude asks the user to + * install it. It serves the app's chats and Code sessions alike. + * Claude Desktop isn't made for Linux. + * - Claude Code and Claude Desktop use the bundled stdio helper, which + * handles OAuth itself (Claude Desktop can't reach a loopback URL: + * its custom connectors connect from Anthropic's servers). + * - Codex speaks HTTP + OAuth natively, and its CLI and app share + * ~/.codex/config.toml. + * - `--scope user` matters for Claude Code: the default `local` scope + * only registers the server for the directory the terminal is in. + */ +export function agentClientGuides( + port: number = AGENT_ACCESS_PORT, + stdioPath = "diskhound-mcp", + platform = "linux", +): AgentClientGuide[] { + const url = agentAccessMcpUrl(port); + const portArgs = port === AGENT_ACCESS_PORT ? "" : ` --port ${port}`; + const executable = shellQuote(stdioPath, platform); + const stdioPrompt = (client: string) => + `Add ${MCP_SERVER_NAME} to my ${client} user configuration using the stdio executable "${stdioPath}", with ${helperArgs(port)}. ${promptTail}`; + const httpPrompt = (whose: string) => + `Add ${MCP_SERVER_NAME} to ${whose} user configuration using the HTTP MCP endpoint ${url} with OAuth. ${promptTail}`; + const firstPrompt = "What's using the most space on my disk?"; + return [ + { + id: "claude-code", + name: "Claude Code", + via: "stdio helper", + firstPrompt, + steps: [ + { + text: "Paste this into Claude Code in your terminal or IDE.", + prompt: stdioPrompt("Claude Code"), + manual: { + toggle: "command", + items: [{ + text: "Or run this yourself in a terminal. It adds DiskHound for every project.", + snippet: `claude mcp add --scope user --transport stdio ${MCP_SERVER_NAME} -- ${executable}${portArgs}`, + }], + }, + }, + { text: "Start a new Claude Code session (or run /mcp and reconnect diskhound). DiskHound asks you to approve it here." }, + ], + // Its config reaches the Claude app's Code sessions too, where the extension already is. + ...(platform === "linux" ? {} : { note: "In the Claude app, chats and Code sessions use the Claude Desktop extension instead." }), + }, + ...(platform === "linux" ? [] : [{ + id: "claude-desktop" as const, + name: "Claude Desktop", + via: "Claude extension", + firstPrompt, + steps: [ + { + text: "Add DiskHound's extension to Claude. Claude shows what it installs and asks you to confirm.", + action: "add-to-claude" as const, + }, + { text: "Click Install in Claude. DiskHound asks you to approve it here." }, + ], + note: "The extension works in the Claude app's chats and its Code sessions.", + }]), + { + id: "codex", + name: "Codex", + via: "HTTP + OAuth", + firstPrompt, + steps: [ + { + text: "Paste this into Codex. The Codex CLI and the Codex app share their settings.", + prompt: httpPrompt("my Codex"), + manual: { + toggle: "command", + items: [{ + text: "Or run this yourself in a terminal:", + snippet: `codex mcp add ${MCP_SERVER_NAME} --url ${url} --oauth-client-registration dcr`, + }], + }, + }, + { text: "Codex opens a browser tab that says Continue in DiskHound. Approve the request here." }, + ], + }, + { + id: "other", + name: "Other MCP clients", + via: "HTTP + OAuth or stdio", + firstPrompt, + steps: [ + { + text: "Paste this into your agent.", + prompt: httpPrompt("this agent's"), + manual: { + toggle: "details", + items: [ + { text: "Clients that support OAuth over loopback HTTP connect to this URL:", snippet: url }, + { text: "Clients that launch local servers run this command, which handles sign-in for them:", snippet: `${executable}${portArgs}` }, + ], + }, + }, + ], + }, + ]; +} + +/** + * What an agent Session may do. These double as OAuth scopes: a + * Session's effective permissions are its role's permissions + * intersected with the scopes the user approved, so editing a role + * later can never exceed the original consent. + */ +export const MCP_AGENT_CAPABILITIES = [ + "disk.read", + "scan.run", + "app.navigate", + "files.trash", + "files.delete", +] as const; + +export type McpAgentCapability = (typeof MCP_AGENT_CAPABILITIES)[number]; +/** + * - standard: can't expose or change anything the user hasn't seen. + * - sensitive: exposes private data (every file name on the disk). + * - destructive: removes files (after the user confirms each request). + */ +export type McpAgentPermissionDanger = "standard" | "sensitive" | "destructive"; + +export const MCP_AGENT_CAPABILITY_DETAILS: Record< + McpAgentCapability, + { + label: string; + /** For chips on the approval sheet's role cards. */ + short: string; + /** Completes "this session can ask to โ€ฆ". */ + verb: string; + detail: string; + danger: McpAgentPermissionDanger; + } +> = { + "disk.read": { + label: "Read drives and scan results", + short: "Read scans", + verb: "read drives and scan results", + detail: "Drive capacity, scan summaries, folder sizes, file names and paths, search, history, duplicates, and cleanup suggestions.", + danger: "sensitive", + }, + "scan.run": { + label: "Run scans", + short: "Run scans", + verb: "run scans", + detail: "Start or cancel drive scans and duplicate searches. Scans read metadata only and never change files.", + danger: "standard", + }, + "app.navigate": { + label: "Drive the DiskHound window", + short: "Steer window", + verb: "steer the DiskHound window", + detail: "Switch tabs, open folders, and reveal items in Finder or Explorer so you can follow along.", + danger: "standard", + }, + "files.trash": { + label: "Ask to move items to the Trash", + short: "Trash ยท asks you", + verb: "move items to the Trash", + detail: "Request that files or folders go to the Trash / Recycle Bin. DiskHound asks you to confirm every request, and you can restore items until the Trash is emptied.", + danger: "destructive", + }, + "files.delete": { + label: "Ask to delete items permanently", + short: "Delete ยท asks you", + verb: "delete items permanently", + detail: "Request that files or folders be deleted without going to the Trash. DiskHound asks you to confirm every request. Deleted items can't be restored.", + danger: "destructive", + }, +}; + +export interface McpAgentRole { + id: string; + name: string; + description: string; + permissions: McpAgentCapability[]; +} + +/** + * Roles are fixed in code โ€” there is no role editor. The policy file + * only stores Sessions, which point at one of these ids. + */ +export const BUILT_IN_MCP_ROLES: readonly McpAgentRole[] = [ + { + id: "builtin.reader", + name: "Disk Explorer", + description: "Read drive usage and scan results. Cannot start scans, move the app, or touch files.", + permissions: ["disk.read"], + }, + { + id: "builtin.guide", + name: "Cleanup Guide", + description: "Read scan results, run scans, and steer the DiskHound window. Cannot touch files.", + permissions: ["disk.read", "scan.run", "app.navigate"], + }, + { + id: "builtin.operator", + name: "Cleanup Operator", + description: "Everything the Cleanup Guide can do, plus ask to move items to the Trash. You confirm every request in DiskHound.", + permissions: ["disk.read", "scan.run", "app.navigate", "files.trash"], + }, + { + id: "builtin.admin", + name: "Cleanup Admin", + description: "Everything the Cleanup Operator can do, plus ask to delete items permanently. You confirm every request in DiskHound.", + permissions: ["disk.read", "scan.run", "app.navigate", "files.trash", "files.delete"], + }, +]; + +export const DEFAULT_CONSENT_ROLE_ID = "builtin.guide"; + +export interface McpAgentSession { + id: string; + name: string; + roleId: string; + createdAt: string; + updatedAt: string; + revokedAt: string | null; + oauth?: { clientId: string; scopes: McpAgentCapability[] }; + /** What the client called itself at sign-in, and how it connects. */ + client?: { name: string; via: AgentClientVia }; +} + +/** `stdio` is DiskHound's bundled diskhound-mcp helper. */ +export type AgentClientVia = "stdio" | "http"; + +/** A session's effective permissions: its role, capped by what the agent asked for. */ +export function sessionPermissions(session: McpAgentSession, roles: readonly McpAgentRole[] = BUILT_IN_MCP_ROLES): McpAgentCapability[] { + const role = roles.find((candidate) => candidate.id === session.roleId); + const approved = session.oauth?.scopes; + return (role?.permissions ?? []).filter((permission) => !approved || approved.includes(permission)); +} + +export interface AgentAccessStatus { + /** User setting โ€” whether DiskHound should listen. */ + enabled: boolean; + /** Whether the loopback listener is actually bound right now. */ + listening: boolean; + mcpUrl: string; + port: number; + error?: string; +} + +/** An agent login waiting for the user in DiskHound's approval sheet. */ +export interface AgentPendingApproval { + requestId: string; + clientName: string; + via: AgentClientVia; + requestedAt: number; + /** The agent stopped checking back (it likely timed out or quit). */ + stale: boolean; +} + +/** + * Something an agent tried that its session doesn't allow. Kept in + * agent-security.log so the user can see it after a restart. + */ +export interface AgentSecurityEvent { + id: string; + at: number; + sessionId: string; + sessionName: string; + roleName: string; + /** + * - tool_not_allowed: the session's role doesn't grant the tool. + * - protected_path: a Trash or delete request named a folder agents + * may never remove. + */ + kind: "tool_not_allowed" | "protected_path"; + tool: string; + /** One line for the user: what was asked and why it was refused. */ + detail: string; + /** Identical events within a minute are counted here, not repeated. */ + count: number; +} + +export interface AgentAccessSnapshot { + status: AgentAccessStatus; + roles: McpAgentRole[]; + sessions: McpAgentSession[]; + activity: AgentActivityEntry[]; + pending: AgentPendingApproval[]; + security: AgentSecurityEvent[]; + policyFile: string; + securityLogFile: string; + stdioPath: string; + platform: string; +} + +/** + * One line in the "Recent agent actions" feed and the header pill. + * Written by the MCP tool layer after every call, success or failure. + */ +export interface AgentActivityEntry { + id: string; + at: number; + sessionId: string; + sessionName: string; + tool: string; + summary: string; + ok: boolean; +} + +export interface AgentConsentPrompt { + requestId: string; + clientName: string; + via: AgentClientVia; + sessionName: string; + requestedScopes: McpAgentCapability[]; + roles: McpAgentRole[]; + defaultRoleId: string; +} + +/** + * Pushed to the approval sheet when the waiting agent goes quiet or + * comes back, and when the queue behind it changes. + */ +export interface AgentConsentState { + requestId: string; + stale: boolean; + /** The client whose request is shown after this one, if any. */ + next: string | null; +} + +export interface AgentConsentDecision { + requestId: string; + decision: "allow" | "deny"; + sessionName: string; + roleId: string; +} diff --git a/src/shared/contracts.ts b/src/shared/contracts.ts index cbf5fd44..63fb8f9d 100644 --- a/src/shared/contracts.ts +++ b/src/shared/contracts.ts @@ -9,6 +9,15 @@ import { isPowerEfficiency, type PowerEfficiency, } from "./powerEfficiency"; +import type { + AddToClaudeResult, + AgentAccessSnapshot, + AgentActivityEntry, + AgentConsentDecision, + AgentConsentPrompt, + AgentConsentState, + AgentSecurityEvent, +} from "./agentAccess"; export type ScanStatus = "idle" | "running" | "done" | "cancelled" | "error"; export type ScanEngine = "js-worker" | "native-sidecar" | "usn-journal"; @@ -363,6 +372,18 @@ export interface AppSettings { * overridden by another tool). Matches Process Lasso's "CPU * Affinity Rules" tab semantics. */ affinityRules: AffinityRule[]; + /** Local AI agent access over MCP (Settings โ†’ AI Agents). */ + agents: AgentSettings; +} + +export interface AgentSettings { + /** + * Listen for MCP connections from local agents (Claude Code, Codex) + * on the loopback port. Off by default: nothing listens until the + * user opts in, and every agent still needs OAuth approval in the + * app. Sessions and their roles live in mcp-policy.json, not here. + */ + enabled: boolean; } export interface AffinityRule { @@ -1349,6 +1370,23 @@ export interface NavigateViewPayload { * rows in the widget so clicking C: jumps to its overview. */ scanRoot?: string; + /** + * With `view: "folders"`, the folder to open. Sent by the MCP + * `diskhound_show` / `diskhound_list_folder` tools so the window + * follows an agent's drill-down. + */ + folderPath?: string; + /** + * With `view: "settings"`, the section to scroll to. The app menu's + * Connect an AI Agentโ€ฆ and the tray use "ai-agents". + */ + section?: "ai-agents"; +} + +/** What the main window is showing; reported to main for agents. */ +export interface WindowViewState { + view: AppView; + rootPath: string | null; } // โ”€โ”€ IPC API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @@ -1725,6 +1763,34 @@ export interface DiskhoundNativeApi { * navigation request โ€” only the main window's renderer does. */ onNavigateView: (listener: (payload: NavigateViewPayload) => void) => () => void; + /** Tell main which tab and root the main window shows (for agents). */ + reportViewState: (state: WindowViewState) => void; + /** Paths an agent moved to the Trash (after the user confirmed). */ + onPathsTrashed: (listener: (paths: string[]) => void) => () => void; + /** Paths an agent deleted permanently (after the user confirmed). */ + onPathsDeleted: (listener: (paths: string[]) => void) => () => void; + + // Local AI agent access (MCP) + getAgentAccess: () => Promise<AgentAccessSnapshot>; + setAgentAccessEnabled: (enabled: boolean) => Promise<AgentAccessSnapshot>; + revokeAgentSession: (sessionId: string) => Promise<AgentAccessSnapshot>; + assignAgentSessionRole: (sessionId: string, roleId: string) => Promise<AgentAccessSnapshot>; + forgetRevokedAgentSessions: () => Promise<AgentAccessSnapshot>; + onAgentAccessChanged: (listener: (snapshot: AgentAccessSnapshot) => void) => () => void; + onAgentActivity: (listener: (entry: AgentActivityEntry) => void) => () => void; + /** Something an agent tried and wasn't allowed to do (new or repeated). */ + onAgentSecurityEvent: (listener: (event: AgentSecurityEvent) => void) => () => void; + /** Bring the approval sheet that's waiting to the front. */ + focusAgentApproval: () => Promise<boolean>; + /** Deny a waiting approval from Settings. */ + dismissAgentApproval: (requestId: string) => Promise<AgentAccessSnapshot>; + /** Build DiskHound's Claude extension and open it in Claude, which asks to install it. */ + addAgentToClaude: () => Promise<AddToClaudeResult>; + /** Approval window only: the pending request this window was opened for. */ + agentConsentRead: () => Promise<(AgentConsentPrompt & Omit<AgentConsentState, "requestId">) | null>; + agentConsentDecide: (decision: AgentConsentDecision) => Promise<{ ok: boolean; message?: string }>; + /** Approval window only: the waiting agent went quiet, or came back. */ + onAgentConsentState: (listener: (state: AgentConsentState) => void) => () => void; } // โ”€โ”€ Defaults โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @@ -1786,6 +1852,9 @@ export function defaultSettings(): AppSettings { }, recentScans: [], affinityRules: [], + agents: { + enabled: false, + }, }; } @@ -1839,6 +1908,7 @@ export function normalizeAppSettings(input?: Partial<AppSettings> | null): AppSe cleanup: { ...defaults.cleanup, ...(input?.cleanup ?? {}) }, storage: { ...defaults.storage, ...(input?.storage ?? {}) }, recentScans: Array.isArray(input?.recentScans) ? input!.recentScans : defaults.recentScans, + agents: { ...defaults.agents, ...(input?.agents ?? {}) }, affinityRules: Array.isArray(input?.affinityRules) ? input!.affinityRules .map((r) => normalizeAffinityRule(r)) @@ -1974,6 +2044,9 @@ export function normalizeAppSettings(input?: Partial<AppSettings> | null): AppSe bytesFound: Math.max(0, Math.round(scan.bytesFound)), })), affinityRules: merged.affinityRules, + agents: { + enabled: Boolean(merged.agents.enabled), + }, }; } diff --git a/src/shared/settingsStore.ts b/src/shared/settingsStore.ts index 3124855f..973c44c0 100644 --- a/src/shared/settingsStore.ts +++ b/src/shared/settingsStore.ts @@ -113,5 +113,6 @@ function mergeSettings(defaults: AppSettings, partial: Partial<AppSettings>): Ap storage: { ...defaults.storage, ...partial.storage }, recentScans: partial.recentScans ?? defaults.recentScans, affinityRules: partial.affinityRules ?? defaults.affinityRules, + agents: { ...defaults.agents, ...partial.agents }, }; } diff --git a/src/test/io-budgets.json b/src/test/io-budgets.json index 3d4e928c..a2aa4762 100644 --- a/src/test/io-budgets.json +++ b/src/test/io-budgets.json @@ -75,6 +75,86 @@ "open": 0, "observedBytesWritten": 0 }, + "agent-security-log-burst": { + "note": "20 refusals in one request become one append of 20 lines. Only an agent's refused request writes, so the monitoring interval doesn't change it: the same at the default and at the 1-minute interval. Appends are at least 5 minutes apart after the first and capped at 60 lines an hour, so an agent refused nonstop for a day costs at most 288 appends and 1,440 lines (about 0.5 MB/day); the file rotates at 256 KB.", + "writeFile": 0, + "appendFile": 1, + "rename": 0, + "copyFile": 0, + "link": 0, + "mkdir": 0, + "createWriteStream": 0, + "unlink": 0, + "readFile": 0, + "readdir": 0, + "stat": 1, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "observedBytesWritten": 6601 + }, + "agent-security-log-load": { + "note": "Opening Settings โ†’ AI Agents reads the log once per run; 20 more opens read nothing. No writes. Only an agent's refused request writes, so the monitoring interval doesn't change it: the same at the default and at the 1-minute interval. Appends are at least 5 minutes apart after the first and capped at 60 lines an hour, so an agent refused nonstop for a day costs at most 288 appends and 1,440 lines (about 0.5 MB/day); the file rotates at 256 KB.", + "writeFile": 0, + "appendFile": 0, + "rename": 0, + "copyFile": 0, + "link": 0, + "mkdir": 0, + "createWriteStream": 0, + "unlink": 0, + "readFile": 1, + "readdir": 0, + "stat": 0, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "observedBytesWritten": 0 + }, + "agent-security-log-looping-agent": { + "note": "360 distinct refusals and 720 repeats in an hour: the 60-line cap fills within minutes, so 60 lines reach disk in 3 appends (2 s after the first refusal, 5 minutes later, and at quit). Later refusals stay in memory for Settings. Only an agent's refused request writes, so the monitoring interval doesn't change it: the same at the default and at the 1-minute interval. Appends are at least 5 minutes apart after the first and capped at 60 lines an hour, so an agent refused nonstop for a day costs at most 288 appends and 1,440 lines (about 0.5 MB/day); the file rotates at 256 KB.", + "writeFile": 0, + "appendFile": 3, + "rename": 0, + "copyFile": 0, + "link": 0, + "mkdir": 0, + "createWriteStream": 0, + "unlink": 0, + "readFile": 0, + "readdir": 0, + "stat": 1, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "observedBytesWritten": 19703 + }, + "agent-security-log-one-refusal": { + "note": "One refusal: one stat for the file's size, then one append of one line. A few refusals a day is a few appends and under 1 KB/day. Only an agent's refused request writes, so the monitoring interval doesn't change it: the same at the default and at the 1-minute interval. Appends are at least 5 minutes apart after the first and capped at 60 lines an hour, so an agent refused nonstop for a day costs at most 288 appends and 1,440 lines (about 0.5 MB/day); the file rotates at 256 KB.", + "writeFile": 0, + "appendFile": 1, + "rename": 0, + "copyFile": 0, + "link": 0, + "mkdir": 0, + "createWriteStream": 0, + "unlink": 0, + "readFile": 0, + "readdir": 0, + "stat": 1, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "observedBytesWritten": 322 + }, "crash-log-idle-hour": { "note": "an hour in the tray with memory flat: 12 samples 5 minutes apart log only the hourly heartbeat, 1 append, ~250 bytes. 24/day and ~6 KB/day; no setting changes the idle cadence. Was 12 lines, each a sync append, mkdir and stat: 288 of each a day", "writeFile": 0, @@ -1342,6 +1422,126 @@ "worker": 0, "observedBytesWritten": 0 }, + "mcp-client-registration": { + "note": "Registration with 32 saved clients; one complete client-store replacement. Not tied to monitoring: at default or aggressive 1-minute monitoring, assuming 1 event/day: 1 file writes/day, 0.010 MB/day; 24 events/day: 24 file writes/day, 0.228 MB/day. Each changed file is atomically replaced with a rename; polling adds no writes.", + "writeFile": 1, + "appendFile": 0, + "rename": 1, + "copyFile": 0, + "link": 0, + "mkdir": 1, + "createWriteStream": 0, + "unlink": 0, + "readFile": 0, + "readdir": 0, + "stat": 0, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "observedBytesWritten": 9505 + }, + "mcp-client-registration-at-cap": { + "note": "256 saved clients; evicts one unapproved client and replaces the bounded store once. Not tied to monitoring: at default or aggressive 1-minute monitoring, assuming 1 event/day: 1 file writes/day, 0.074 MB/day; 24 events/day: 24 file writes/day, 1.769 MB/day. Each changed file is atomically replaced with a rename; polling adds no writes.", + "writeFile": 1, + "appendFile": 0, + "rename": 1, + "copyFile": 0, + "link": 0, + "mkdir": 1, + "createWriteStream": 0, + "unlink": 0, + "readFile": 1, + "readdir": 0, + "stat": 0, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "observedBytesWritten": 73729 + }, + "mcp-policy-idempotent-updates": { + "note": "Repeated role/revoke/forget requests; only the first forget changes the policy (one replacement). Not tied to monitoring: at default or aggressive 1-minute monitoring, assuming 1 event/day: 1 file writes/day, 0.018 MB/day; 24 events/day: 24 file writes/day, 0.441 MB/day. Each changed file is atomically replaced with a rename; polling adds no writes.", + "writeFile": 1, + "appendFile": 0, + "rename": 1, + "copyFile": 0, + "link": 0, + "mkdir": 1, + "createWriteStream": 0, + "unlink": 0, + "readFile": 4, + "readdir": 0, + "stat": 0, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "observedBytesWritten": 18370 + }, + "mcp-read-poll-activity": { + "note": "60 token/read/poll/activity cycles with 32 sessions; 0 writes/day and 0 MB/day even at one cycle/second (86,400/day). Not tied to monitoring: at default or aggressive 1-minute monitoring, assuming 1 event/day: 0 file writes/day, 0.000 MB/day; 24 events/day: 0 file writes/day, 0.000 MB/day. Each changed file is atomically replaced with a rename; polling adds no writes.", + "writeFile": 0, + "appendFile": 0, + "rename": 0, + "copyFile": 0, + "link": 0, + "mkdir": 0, + "createWriteStream": 0, + "unlink": 0, + "readFile": 120, + "readdir": 0, + "stat": 0, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "observedBytesWritten": 0 + }, + "mcp-session-lifecycle": { + "note": "32 existing sessions; approval, role change and revocation replace the policy three times per lifecycle. Not tied to monitoring: at default or aggressive 1-minute monitoring, assuming 1 event/day: 3 file writes/day, 0.059 MB/day; 24 events/day: 72 file writes/day, 1.416 MB/day. Each changed file is atomically replaced with a rename; polling adds no writes.", + "writeFile": 3, + "appendFile": 0, + "rename": 3, + "copyFile": 0, + "link": 0, + "mkdir": 3, + "createWriteStream": 0, + "unlink": 0, + "readFile": 6, + "readdir": 0, + "stat": 0, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "observedBytesWritten": 58984 + }, + "mcp-stdio-approval-and-reuse": { + "note": "One stdio registration and approval with 32 saved clients/sessions, then 24 reconnects and 1,440 requests. The helper's separate OS-store budget is in native/diskhound-mcp/io-budgets.json; no token is written to a file. Not tied to monitoring: at default or aggressive 1-minute monitoring, assuming 1 event/day: 2 file writes/day, 0.029 MB/day; 24 events/day: 48 file writes/day, 0.699 MB/day. Each changed file is atomically replaced with a rename; polling adds no writes.", + "writeFile": 2, + "appendFile": 0, + "rename": 2, + "copyFile": 0, + "link": 0, + "mkdir": 2, + "createWriteStream": 0, + "unlink": 0, + "readFile": 1441, + "readdir": 0, + "stat": 0, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "observedBytesWritten": 29133 + }, "permanent-delete-tree": { "note": "User-requested 4 MiB build tree: 256 file unlinks, 9 streamed directory opens, no content writes or persisted progress. rmdir metadata operations are outside this harness's counters. No automatic deletion: 0 writes/day and 0 MB/day at default and 1-minute monitoring. One manual delete performs these 256 metadata unlinks; OS metadata bytes are not measured.", "writeFile": 0, @@ -1362,6 +1562,94 @@ "open": 9, "observedBytesWritten": 0 }, + "renderer-agents-add-to-claude": { + "note": "Add to Claude: reads the helper (1.4 MB), the icon and, unpackaged, package.json, then writes the ~0.7 MB bundle to temp once and hands it to Claude. A user click, about once per setup, so 0 writes/day and 0 MB/day from monitoring at the default or the 1-minute interval.", + "writeFile": 1, + "appendFile": 0, + "rename": 0, + "copyFile": 0, + "link": 0, + "mkdir": 1, + "createWriteStream": 0, + "unlink": 0, + "readFile": 3, + "readdir": 0, + "stat": 0, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "spawn": 0, + "worker": 0, + "observedBytesWritten": 715570 + }, + "renderer-agents-blocked-delete": { + "note": "A Cleanup Guide agent calls diskhound_delete_permanently over HTTP: refused before any tool runs, one append to agent-security.log and the crash.log line, pushed to the UI with 0 IPC. Writes happen only when an agent is refused (not per monitoring tick), and the log caps them at 288 appends and ~0.5 MB/day even for an agent refused nonstop.", + "writeFile": 0, + "appendFile": 2, + "rename": 0, + "copyFile": 0, + "link": 0, + "mkdir": 0, + "createWriteStream": 0, + "unlink": 0, + "readFile": 1, + "readdir": 0, + "stat": 0, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "spawn": 0, + "worker": 0, + "observedBytesWritten": 531 + }, + "renderer-agents-browse": { + "note": "Header popover opened 4 times, 3-5 client tabs, a command disclosure and a link into Settings with 3 sessions and 40 logged refusals: local state, 0 IPC, 0 reads and 0 writes/day at any monitoring interval.", + "writeFile": 0, + "appendFile": 0, + "rename": 0, + "copyFile": 0, + "link": 0, + "mkdir": 0, + "createWriteStream": 0, + "unlink": 0, + "readFile": 0, + "readdir": 0, + "stat": 0, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "spawn": 0, + "worker": 0, + "observedBytesWritten": 0 + }, + "renderer-agents-role-change-revoke": { + "note": "One role change and one revoke from Settings: each replaces mcp-policy.json once (atomic write + rename). User clicks only, so a few writes/day and well under 0.1 MB/day at any monitoring interval.", + "writeFile": 2, + "appendFile": 0, + "rename": 2, + "copyFile": 0, + "link": 0, + "mkdir": 2, + "createWriteStream": 0, + "unlink": 0, + "readFile": 6, + "readdir": 0, + "stat": 0, + "lstat": 0, + "access": 0, + "existsSync": 0, + "createReadStream": 0, + "open": 0, + "spawn": 0, + "worker": 0, + "observedBytesWritten": 5030 + }, "renderer-changes-browse-again": { "note": "the same Changes visit again: 16 IPC calls, all answered from main's snapshot, diff and full-diff caches, 0 reads", "writeFile": 0, diff --git a/src/test/mainProcessHarness.ts b/src/test/mainProcessHarness.ts index b7498db5..7bd1ad17 100644 --- a/src/test/mainProcessHarness.ts +++ b/src/test/mainProcessHarness.ts @@ -112,8 +112,10 @@ function current(): HarnessState { } /** What a handler sees as `event`: sent from the main window. */ -function ipcEvent(harness: HarnessState): { sender: unknown } { - return { sender: harness.windows[0]?.webContents ?? null }; +/** An event from the main window's top frame, as Electron sends it. */ +function ipcEvent(harness: HarnessState): { sender: unknown; senderFrame: unknown } { + const sender = harness.windows[0]?.webContents ?? null; + return { sender, senderFrame: sender?.mainFrame ?? null }; } async function callHandler<T>(harness: HarnessState, channel: string, args: unknown[]): Promise<T> { @@ -141,6 +143,8 @@ function lenient<T extends object>(target: T): T { } class FakeWebContents extends EventEmitter { + readonly mainFrame = { routingId: 1 }; + constructor(readonly id: number) { super(); } diff --git a/src/test/zipReader.ts b/src/test/zipReader.ts new file mode 100644 index 00000000..bbeca5e8 --- /dev/null +++ b/src/test/zipReader.ts @@ -0,0 +1,37 @@ +import * as Zlib from "node:zlib"; + +export interface UnzippedEntry { + name: string; + data: Buffer; + /** Unix mode bits from the central directory. */ + mode: number; +} + +/** Read a zip through its central directory, inflating each entry and checking its CRC. */ +export function unzip(archive: Buffer): UnzippedEntry[] { + const end = archive.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06])); + if (end < 0) throw new Error("No end of central directory"); + const count = archive.readUInt16LE(end + 10); + let at = archive.readUInt32LE(end + 16); + const entries: UnzippedEntry[] = []; + for (let i = 0; i < count; i++) { + if (archive.readUInt32LE(at) !== 0x02014b50) throw new Error(`Bad central directory entry at ${at}`); + const method = archive.readUInt16LE(at + 10); + const crc = archive.readUInt32LE(at + 16); + const compressed = archive.readUInt32LE(at + 20); + const nameLength = archive.readUInt16LE(at + 28); + const extraLength = archive.readUInt16LE(at + 30); + const commentLength = archive.readUInt16LE(at + 32); + const external = archive.readUInt32LE(at + 38); + const local = archive.readUInt32LE(at + 42); + const name = archive.toString("utf8", at + 46, at + 46 + nameLength); + if (archive.readUInt32LE(local) !== 0x04034b50) throw new Error(`Bad local header for ${name}`); + const start = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28); + const raw = archive.subarray(start, start + compressed); + const data = method === 8 ? Zlib.inflateRawSync(raw) : Buffer.from(raw); + if (Zlib.crc32(data) !== crc) throw new Error(`CRC mismatch for ${name}`); + entries.push({ name, data, mode: (external >>> 16) & 0o7777 }); + at += 46 + nameLength + extraLength + commentLength; + } + return entries; +} diff --git a/tsdown.config.ts b/tsdown.config.ts index 6dc7d232..07bfe353 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -46,6 +46,16 @@ export default defineConfig([ ...shared, entry: ["src/preload.ts"], }, + { + // Local-agent (MCP) runtime. Separate so main.cjs doesn't require + // the MCP SDK and Express at startup; electronHost.ts loads it by + // path the first time AI Agents is turned on. + ...shared, + ...noCodeSplitting, + entry: { + "mcp/agentRuntime": "src/mcp/agentRuntime.ts", + }, + }, ...scanWorkers.map((name) => ({ ...shared, ...noCodeSplitting,