From aa978d61d31b59b5d8b81e9fb827292190acccec Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:30:57 -0300 Subject: [PATCH 01/18] Scaffold, core contracts and run pipeline Add the project skeleton (package, TypeScript strict ESM, vitest, CI on Linux, macOS and Windows, Apache-2.0 LICENSE and NOTICE, CLAUDE.md and AGENTS.md) and the frozen contracts the sandbox, host adapter, tool and benchmark parts build against. The run path is executable end to end with test fakes: MCP tools/call -> FakeSandbox -> Dispatcher (prepare, static rules, hooks, re-prepare on updated args, commit) -> StaticHostAdapter -> MemoryToolRuntime, with mutation ordering, cancellation, transactions with rollback, output caps with overflow files, and a command hook runner that kills the process group on timeout. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 39 + .gitignore | 6 + AGENTS.md | 27 + CLAUDE.md | 27 + LICENSE | 202 ++ NOTICE | 9 + README.md | 2 + package-lock.json | 2865 ++++++++++++++++++++++++++++ package.json | 38 + src/cli.ts | 78 + src/core/command-hook.test.ts | 72 + src/core/command-hook.ts | 179 ++ src/core/dispatcher.test.ts | 287 +++ src/core/dispatcher.ts | 481 +++++ src/core/errors.ts | 30 + src/core/freeze.ts | 10 + src/core/output.test.ts | 96 + src/core/output.ts | 125 ++ src/core/paths.test.ts | 25 + src/core/paths.ts | 68 + src/core/run.test.ts | 170 ++ src/core/run.ts | 251 +++ src/core/schemas.test.ts | 43 + src/core/schemas.ts | 181 ++ src/core/state-dir.ts | 20 + src/core/types.ts | 644 +++++++ src/server/context.test.ts | 59 + src/server/context.ts | 152 ++ src/server/mcp.test.ts | 161 ++ src/server/mcp.ts | 120 ++ src/server/runtime.ts | 45 + src/testing/context.ts | 6 + src/testing/fake-sandbox.ts | 108 ++ src/testing/index.ts | 4 + src/testing/memory-tool-runtime.ts | 343 ++++ src/testing/static-host-adapter.ts | 104 + tsconfig.build.json | 4 + tsconfig.json | 23 + vitest.config.ts | 8 + 39 files changed, 7112 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100644 LICENSE create mode 100644 NOTICE create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 src/cli.ts create mode 100644 src/core/command-hook.test.ts create mode 100644 src/core/command-hook.ts create mode 100644 src/core/dispatcher.test.ts create mode 100644 src/core/dispatcher.ts create mode 100644 src/core/errors.ts create mode 100644 src/core/freeze.ts create mode 100644 src/core/output.test.ts create mode 100644 src/core/output.ts create mode 100644 src/core/paths.test.ts create mode 100644 src/core/paths.ts create mode 100644 src/core/run.test.ts create mode 100644 src/core/run.ts create mode 100644 src/core/schemas.test.ts create mode 100644 src/core/schemas.ts create mode 100644 src/core/state-dir.ts create mode 100644 src/core/types.ts create mode 100644 src/server/context.test.ts create mode 100644 src/server/context.ts create mode 100644 src/server/mcp.test.ts create mode 100644 src/server/mcp.ts create mode 100644 src/server/runtime.ts create mode 100644 src/testing/context.ts create mode 100644 src/testing/fake-sandbox.ts create mode 100644 src/testing/index.ts create mode 100644 src/testing/memory-tool-runtime.ts create mode 100644 src/testing/static-host-adapter.ts create mode 100644 tsconfig.build.json create mode 100644 tsconfig.json create mode 100644 vitest.config.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3f03ff8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,39 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + verify: + name: verify (${{ matrix.os }}, Node ${{ matrix.node }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + node: [22, 24] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + cache: npm + - run: npm ci + - run: npm run verify + + windows: + name: typecheck and test (windows-latest, Node 22) + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npm run typecheck + - run: npm test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c278402 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +dist/ +coverage/ +*.log +.DS_Store +TASKS.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..ab7de15 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,27 @@ +# agent-code-mode + +An MCP stdio server that exposes one tool, `run`: the model writes a JavaScript script that runs in an isolated QuickJS-ng WASM sandbox and calls async bindings (`bash`, `read`, `write`, `edit`, `grep`, `glob`). +Every binding call is prepared, authorized against the host's permission rules and PreToolUse hooks (Claude Code or Codex CLI, fail-closed), and only then committed exactly as authorized. + +## Verification + +`npm run verify` (typecheck, tests, build). It must pass before any change is considered done. + +## Repo rules + +- English only: code, comments, tests, commit messages, PRs, README. +- The repo is public: nothing private (personal names, emails, home-directory paths, machine names, personal hook or config names). Test fixtures use generic example hooks. +- No `docs/` folder and no extra markdown files; the only markdown files are README.md, CLAUDE.md and AGENTS.md. +- Validate outside data at the boundary with zod (MCP requests, sandbox IPC, hook stdout, config files, `_meta`); never use `as` on unvalidated data. Internal code trusts validated types. +- TypeScript strict, ESM, Node >= 22. Keep dependencies small and justified. + +## Module map + +- `src/core`: frozen contracts (`types.ts`), boundary schemas, dispatcher (prepare, authorize, commit), run orchestration, output shaping, command hooks. +- `src/server`: MCP stdio server, host detection, runtime factory. +- `src/sandbox`: QuickJS-ng WASM sandbox in a child process. +- `src/hosts/claude`: Claude Code host adapter (settings, permission rules, hooks). +- `src/hosts/codex`: Codex CLI host adapter (config, exec policy, hooks). +- `src/tools`: tool runtime (`bash`, `read`, `write`, `edit`, `grep`, `glob`), journal and rollback. +- `src/testing`: fakes for tests (sandbox, host adapter, in-memory tool runtime). +- `bench`: benchmark. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..ab7de15 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,27 @@ +# agent-code-mode + +An MCP stdio server that exposes one tool, `run`: the model writes a JavaScript script that runs in an isolated QuickJS-ng WASM sandbox and calls async bindings (`bash`, `read`, `write`, `edit`, `grep`, `glob`). +Every binding call is prepared, authorized against the host's permission rules and PreToolUse hooks (Claude Code or Codex CLI, fail-closed), and only then committed exactly as authorized. + +## Verification + +`npm run verify` (typecheck, tests, build). It must pass before any change is considered done. + +## Repo rules + +- English only: code, comments, tests, commit messages, PRs, README. +- The repo is public: nothing private (personal names, emails, home-directory paths, machine names, personal hook or config names). Test fixtures use generic example hooks. +- No `docs/` folder and no extra markdown files; the only markdown files are README.md, CLAUDE.md and AGENTS.md. +- Validate outside data at the boundary with zod (MCP requests, sandbox IPC, hook stdout, config files, `_meta`); never use `as` on unvalidated data. Internal code trusts validated types. +- TypeScript strict, ESM, Node >= 22. Keep dependencies small and justified. + +## Module map + +- `src/core`: frozen contracts (`types.ts`), boundary schemas, dispatcher (prepare, authorize, commit), run orchestration, output shaping, command hooks. +- `src/server`: MCP stdio server, host detection, runtime factory. +- `src/sandbox`: QuickJS-ng WASM sandbox in a child process. +- `src/hosts/claude`: Claude Code host adapter (settings, permission rules, hooks). +- `src/hosts/codex`: Codex CLI host adapter (config, exec policy, hooks). +- `src/tools`: tool runtime (`bash`, `read`, `write`, `edit`, `grep`, `glob`), journal and rollback. +- `src/testing`: fakes for tests (sandbox, host adapter, in-memory tool runtime). +- `bench`: benchmark. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..03af142 --- /dev/null +++ b/NOTICE @@ -0,0 +1,9 @@ +agent-code-mode +Copyright 2026 The agent-code-mode authors + +This product is licensed under the Apache License, Version 2.0 (see LICENSE). + +Third-party code +---------------- +Portions of this product that are derived from third-party projects are +listed below together with their copyright notices and licenses. diff --git a/README.md b/README.md index 9524fde..4779128 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,4 @@ # agent-code-mode A generic Code Mode for coding agents: the model writes one sandboxed script that makes many tool calls, with your existing hooks still enforced. Works with Claude Code and Codex. + +Status: under construction. diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..596f70d --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2865 @@ +{ + "name": "agent-code-mode", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "agent-code-mode", + "version": "0.0.0", + "license": "Apache-2.0", + "dependencies": { + "@modelcontextprotocol/sdk": "^1.32.2", + "zod": "^4.6.7" + }, + "bin": { + "agent-code-mode": "dist/cli.js" + }, + "devDependencies": { + "@types/node": "^22.20.5", + "typescript": "^7.0.2", + "vitest": "^5.1.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@hono/node-server": { + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.8.tgz", + "integrity": "sha512-jdf7FHh6A1lzjpHHQUgxsg2GeER2vMetnAOfeActzcoli6jamlK+NAwL6Dsr5Fl3BS3tYUQzCdtZjU8Qxv7bEA==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "hono": "^4 || ^5.0.0-0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.32.2", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.2.tgz", + "integrity": "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==", + "license": "MIT", + "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" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitest/mocker": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", + "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.1.0", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", + "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/body-parser": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.1.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.3", + "on-finished": "^2.4.1", + "qs": "^6.16.1", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/content-disposition": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", + "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", + "integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/express": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", + "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.3.0", + "content-disposition": "^2.0.1", + "content-type": "^2.0.0", + "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.8", + "qs": "^6.16.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.1.0", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.7.4", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.4.tgz", + "integrity": "sha512-LKBXzX700wz3zAGNNmVnjRI5mEbYkLv7UbMI4+9Xa+JPcg2UZh6AgY/2CZh9RrJjFM5ttC/N1lD+KzyFoZITCw==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/express/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "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" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.13.18", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.18.tgz", + "integrity": "sha512-H9q/E1XizaWstJxUW881dmLxEj+t/TrGGnyxINkm4+sK0qUwsMtFdo2BWI9Vs3cIS19MU6b6iCijoUoEf4f3DA==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ip-address": { + "version": "10.7.6", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", + "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.2.17", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.17.tgz", + "integrity": "sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "peer": true, + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/negotiator/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/on-finished": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", + "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC", + "peer": true + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/postcss": { + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/qs": { + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rolldown": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "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" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "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" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "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" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true, + "peer": true + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vite": { + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.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" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", + "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.1.0", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser-preview": "5.1.0", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.1.0", + "@vitest/coverage-v8": "5.1.0", + "@vitest/ui": "5.1.0", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..1d1997d --- /dev/null +++ b/package.json @@ -0,0 +1,38 @@ +{ + "name": "agent-code-mode", + "version": "0.0.0", + "description": "A generic Code Mode for coding agents: one sandboxed script makes many tool calls, with the host's hooks and permission rules still enforced.", + "license": "Apache-2.0", + "type": "module", + "bin": { + "agent-code-mode": "dist/cli.js" + }, + "files": [ + "dist", + "LICENSE", + "NOTICE" + ], + "engines": { + "node": ">=22" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/mths-mcfs/agent-code-mode.git" + }, + "scripts": { + "build": "tsc -p tsconfig.build.json", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run", + "verify": "npm run typecheck && npm test && npm run build", + "bench": "node -e \"console.log('bench: not implemented yet')\"" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "^1.32.2", + "zod": "^4.6.7" + }, + "devDependencies": { + "@types/node": "^22.20.5", + "typescript": "^7.0.2", + "vitest": "^5.1.0" + } +} diff --git a/src/cli.ts b/src/cli.ts new file mode 100644 index 0000000..d02c6dd --- /dev/null +++ b/src/cli.ts @@ -0,0 +1,78 @@ +#!/usr/bin/env node +import { readFileSync } from 'node:fs'; +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import { z } from 'zod'; +import type { HostKind } from './core/types.js'; +import { createMcpServer } from './server/mcp.js'; + +const USAGE = `Usage: agent-code-mode + +Commands: + serve [--host claude|codex|generic] Run the MCP stdio server + hook Companion hook entry point (not implemented yet) + install Register the server with a host (not implemented yet) + +Options: + --version Print the version + --help Print this help`; + +function readVersion(): string { + try { + const pkg = z.object({ version: z.string() }).parse(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))); + return pkg.version; + } catch { + return '0.0.0'; + } +} + +const HostSchema = z.enum(['claude', 'codex', 'generic']); + +function parseHost(args: readonly string[]): HostKind | undefined | Error { + const i = args.findIndex((a) => a === '--host' || a.startsWith('--host=')); + if (i === -1) return undefined; + const arg = args[i] ?? ''; + const value = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[i + 1]; + const parsed = HostSchema.safeParse(value); + return parsed.success ? parsed.data : new Error(`--host must be one of claude, codex, generic`); +} + +export async function main(argv: readonly string[]): Promise { + const [command, ...rest] = argv; + if (command === '--version' || command === '-v') { + process.stdout.write(`${readVersion()}\n`); + return 0; + } + if (command === undefined || command === '--help' || command === '-h') { + process.stdout.write(`${USAGE}\n`); + return command === undefined ? 1 : 0; + } + switch (command) { + case 'serve': { + const host = parseHost(rest); + if (host instanceof Error) { + process.stderr.write(`${host.message}\n`); + return 2; + } + const server = createMcpServer({ version: readVersion(), ...(host ? { host } : {}) }); + await server.connect(new StdioServerTransport()); + return -1; // keep running until stdin closes + } + case 'hook': + case 'install': + process.stderr.write(`agent-code-mode ${command}: not implemented yet\n`); + return 1; + default: + process.stderr.write(`unknown command ${JSON.stringify(command)}\n${USAGE}\n`); + return 2; + } +} + +main(process.argv.slice(2)).then( + (code) => { + if (code >= 0) process.exitCode = code; + }, + (err: unknown) => { + process.stderr.write(`agent-code-mode: ${err instanceof Error ? err.message : String(err)}\n`); + process.exitCode = 1; + }, +); diff --git a/src/core/command-hook.test.ts b/src/core/command-hook.test.ts new file mode 100644 index 0000000..9419b54 --- /dev/null +++ b/src/core/command-hook.test.ts @@ -0,0 +1,72 @@ +import os from 'node:os'; +import { describe, expect, it } from 'vitest'; +import { runCommandHook } from './command-hook.js'; + +const posix = process.platform !== 'win32'; +const base = { cwd: os.tmpdir(), timeoutMs: 5_000 }; + +function alive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +describe.skipIf(!posix)('runCommandHook (POSIX)', () => { + it('passes JSON on stdin and env additions, exit 0', async () => { + const r = await runCommandHook({ ...base, command: 'cat; printf " %s" "$HOOK_EXTRA"', stdin: '{"a":1}', env: { HOOK_EXTRA: 'yes' } }); + expect(r).toMatchObject({ exitCode: 0, stdout: '{"a":1} yes', timedOut: false, spawnError: null }); + }); + + it('reports exit 2 with stderr and other exit codes', async () => { + const two = await runCommandHook({ ...base, command: 'echo blocked >&2; exit 2', stdin: '' }); + expect(two).toMatchObject({ exitCode: 2, stderr: 'blocked\n' }); + const other = await runCommandHook({ ...base, command: 'exit 7', stdin: '' }); + expect(other.exitCode).toBe(7); + }); + + it('kills the child and its grandchild on timeout', async () => { + const started = Date.now(); + const r = await runCommandHook({ ...base, timeoutMs: 300, command: 'sleep 30 & echo $!; wait', stdin: '' }); + expect(r.timedOut).toBe(true); + expect(Date.now() - started).toBeLessThan(5_000); + const grandchild = Number(r.stdout.trim()); + expect(grandchild).toBeGreaterThan(0); + await new Promise((res) => setTimeout(res, 100)); + expect(alive(grandchild)).toBe(false); + }); + + it('caps huge stdout', async () => { + const r = await runCommandHook({ ...base, command: 'head -c 5000000 /dev/zero', stdin: '', maxOutputBytes: 1000 }); + expect(r.stdout.length).toBe(1000); + expect(r.stdoutTruncated).toBe(true); + }); + + it('reports a non-existent command as exit 127', async () => { + const r = await runCommandHook({ ...base, command: 'definitely-not-a-command-xyz', stdin: '' }); + expect(r.exitCode).toBe(127); + expect(r.spawnError).toBeNull(); + }); + + it('kills the hook when aborted', async () => { + const controller = new AbortController(); + setTimeout(() => controller.abort(), 100); + const r = await runCommandHook({ ...base, command: 'sleep 30', stdin: '', signal: controller.signal }); + expect(r).toMatchObject({ aborted: true, timedOut: false }); + }); + + it('survives a hook that does not read stdin', async () => { + const r = await runCommandHook({ ...base, command: 'exit 0', stdin: 'x'.repeat(2_000_000) }); + expect(r.exitCode).toBe(0); + }); +}); + +describe('runCommandHook', () => { + it('reports a spawn error for a missing cwd and never throws', async () => { + const r = await runCommandHook({ ...base, cwd: '/definitely/missing/dir', command: 'echo hi', stdin: '' }); + expect(r.exitCode).toBeNull(); + expect(r.spawnError).toBeTruthy(); + }); +}); diff --git a/src/core/command-hook.ts b/src/core/command-hook.ts new file mode 100644 index 0000000..ead5d94 --- /dev/null +++ b/src/core/command-hook.ts @@ -0,0 +1,179 @@ +import { spawn, type ChildProcess } from 'node:child_process'; + +/** Default cap of captured stdout and stderr, each. */ +export const DEFAULT_HOOK_MAX_OUTPUT_BYTES = 1024 * 1024; + +export interface CommandHookOptions { + /** Shell command line, run with `/bin/sh -c` on POSIX and the default shell on Windows. */ + readonly command: string; + /** Written to stdin, then stdin is closed. */ + readonly stdin: string; + /** Added to the server's environment. */ + readonly env?: Readonly>; + readonly cwd: string; + readonly timeoutMs: number; + /** Cap of captured bytes, for stdout and stderr each. */ + readonly maxOutputBytes?: number; + /** Aborting kills the hook like a timeout (but `timedOut` stays false). */ + readonly signal?: AbortSignal; +} + +export interface CommandHookResult { + /** Exit code, or null when killed by a signal or not started. */ + readonly exitCode: number | null; + readonly signal: string | null; + readonly stdout: string; + readonly stderr: string; + readonly stdoutTruncated: boolean; + readonly stderrTruncated: boolean; + readonly timedOut: boolean; + /** True when `signal` aborted the hook. */ + readonly aborted: boolean; + /** Set when the process could not be started (e.g. missing cwd). */ + readonly spawnError: string | null; +} + +/** After the process exits, how long to wait for its pipes to close (a detached grandchild may hold them). */ +const PIPE_GRACE_MS = 200; + +class Capture { + readonly #chunks: Buffer[] = []; + #bytes = 0; + truncated = false; + + constructor(readonly max: number) {} + + push(chunk: Buffer): void { + const room = this.max - this.#bytes; + if (room <= 0) { + this.truncated = true; + return; + } + const kept = chunk.length > room ? chunk.subarray(0, room) : chunk; + if (kept.length < chunk.length) this.truncated = true; + this.#chunks.push(kept); + this.#bytes += kept.length; + } + + text(): string { + return Buffer.concat(this.#chunks).toString('utf8'); + } +} + +function killTree(child: ChildProcess): void { + if (child.pid === undefined) return; + try { + if (process.platform === 'win32') { + spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }).on('error', () => undefined); + } else { + // Negative pid: the whole process group (the child is a group leader). + process.kill(-child.pid, 'SIGKILL'); + } + } catch { + try { + child.kill('SIGKILL'); + } catch { + // Already gone. + } + } +} + +/** + * Runs a command hook: JSON on stdin, output captured up to a cap, killed + * with its whole process group on timeout or abort. Never rejects. + */ +export function runCommandHook(opts: CommandHookOptions): Promise { + const max = opts.maxOutputBytes ?? DEFAULT_HOOK_MAX_OUTPUT_BYTES; + const stdout = new Capture(max); + const stderr = new Capture(max); + + return new Promise((resolve) => { + let settled = false; + let timedOut = false; + let aborted = false; + let timer: NodeJS.Timeout | undefined; + let graceTimer: NodeJS.Timeout | undefined; + let child: ChildProcess; + let exit: { code: number | null; signal: NodeJS.Signals | null } | undefined; + + const finish = (spawnError: string | null): void => { + if (settled) return; + settled = true; + if (timer) clearTimeout(timer); + if (graceTimer) clearTimeout(graceTimer); + opts.signal?.removeEventListener('abort', onAbort); + child.stdout?.destroy(); + child.stderr?.destroy(); + child.stdin?.destroy(); + resolve({ + exitCode: exit?.code ?? null, + signal: exit?.signal ?? null, + stdout: stdout.text(), + stderr: stderr.text(), + stdoutTruncated: stdout.truncated, + stderrTruncated: stderr.truncated, + timedOut, + aborted, + spawnError, + }); + }; + + const onAbort = (): void => { + aborted = true; + killTree(child); + }; + + try { + child = spawn(opts.command, { + cwd: opts.cwd, + env: { ...process.env, ...opts.env }, + shell: process.platform === 'win32' ? true : '/bin/sh', + detached: process.platform !== 'win32', + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true, + }); + } catch (err) { + resolve({ + exitCode: null, + signal: null, + stdout: '', + stderr: '', + stdoutTruncated: false, + stderrTruncated: false, + timedOut: false, + aborted: false, + spawnError: err instanceof Error ? err.message : String(err), + }); + return; + } + + child.stdout?.on('data', (chunk: Buffer) => stdout.push(chunk)); + child.stderr?.on('data', (chunk: Buffer) => stderr.push(chunk)); + child.on('error', (err) => { + // 'error' without a pid means the process never started. + if (child.pid === undefined) finish(err.message); + }); + child.on('exit', (code, signal) => { + exit = { code, signal }; + // Give the pipes a moment to flush; a grandchild that escaped the group may keep them open. + graceTimer = setTimeout(() => finish(null), PIPE_GRACE_MS); + }); + child.on('close', (code, signal) => { + exit ??= { code, signal }; + finish(null); + }); + + timer = setTimeout(() => { + timedOut = true; + killTree(child); + }, Math.max(1, opts.timeoutMs)); + + if (opts.signal) { + if (opts.signal.aborted) onAbort(); + else opts.signal.addEventListener('abort', onAbort, { once: true }); + } + + child.stdin?.on('error', () => undefined); // EPIPE when the hook does not read stdin. + child.stdin?.end(opts.stdin); + }); +} diff --git a/src/core/dispatcher.test.ts b/src/core/dispatcher.test.ts new file mode 100644 index 0000000..7af3a36 --- /dev/null +++ b/src/core/dispatcher.test.ts @@ -0,0 +1,287 @@ +import { describe, expect, it } from 'vitest'; +import { makeContext } from '../testing/context.js'; +import { MemoryToolRuntime } from '../testing/memory-tool-runtime.js'; +import { StaticHostAdapter, type StaticHostAdapterOptions } from '../testing/static-host-adapter.js'; +import { Dispatcher } from './dispatcher.js'; +import type { CallReply, PolicyLoadError, PolicySnapshot, Transaction } from './types.js'; + +async function setup( + adapterOpts: StaticHostAdapterOptions = {}, + toolOpts: Partial[0]> = {}, + extra: { transaction?: boolean } = {}, +) { + const ctx = makeContext('/ws'); + const adapter = new StaticHostAdapter(adapterOpts); + const tools = new MemoryToolRuntime({ root: '/ws', ...toolOpts }); + const policy: PolicySnapshot | PolicyLoadError = await adapter.loadPolicy(ctx); + const tx: Transaction | undefined = extra.transaction ? tools.beginTransaction() : undefined; + const denies: string[] = []; + const dispatcher = new Dispatcher({ + adapter, + tools, + ctx, + policy, + ...(tx ? { transaction: tx } : {}), + onDeny: (entry) => denies.push(entry.id), + }); + return { ctx, adapter, tools, dispatcher, tx, denies }; +} + +function errorOf(reply: CallReply) { + if (reply.ok) throw new Error(`expected failure, got ${JSON.stringify(reply.value)}`); + return reply.error; +} + +describe('Dispatcher', () => { + it('assigns ids in call order and logs each call', async () => { + const { dispatcher } = await setup({}, { files: { 'a.txt': 'hello' } }); + await Promise.all([ + dispatcher.dispatch('read', { path: 'a.txt' }), + dispatcher.dispatch('glob', { pattern: '*' }), + dispatcher.dispatch('write', { path: 'b.txt', content: 'x' }), + ]); + expect(dispatcher.calls.map((c) => c.id)).toEqual(['c1', 'c2', 'c3']); + expect(dispatcher.calls.map((c) => c.summary)).toEqual(['read a.txt', 'glob *', 'write b.txt']); + expect(dispatcher.calls.every((c) => c.decision === 'allowed')).toBe(true); + }); + + it('rejects invalid args and unknown tools without preparing', async () => { + const { dispatcher, adapter } = await setup(); + const bad = errorOf(await dispatcher.dispatch('write', { file_path: 'a', content: 'x' })); + expect(bad).toMatchObject({ name: 'ToolError', code: 'invalid-args' }); + const unknown = errorOf(await dispatcher.dispatch('rm', {})); + expect(unknown).toMatchObject({ name: 'ToolError', code: 'invalid-args' }); + const notObject = errorOf(await dispatcher.dispatch('read', 'a.txt')); + expect(notObject.code).toBe('invalid-args'); + expect(adapter.staticChecked).toHaveLength(0); + expect(dispatcher.calls.map((c) => c.decision)).toEqual(['error', 'error', 'error']); + }); + + it('keeps mutation order under concurrent Promise.all of 20 reads and 5 writes', async () => { + const { dispatcher, tools } = await setup({}, { files: { 'r.txt': 'r' }, jitterMs: 5 }); + const calls: Promise[] = []; + for (let i = 0; i < 25; i++) { + if (i % 5 === 4) calls.push(dispatcher.dispatch('write', { path: 'out.txt', content: `w${(i + 1) / 5}` })); + else calls.push(dispatcher.dispatch('read', { path: 'r.txt' })); + } + const replies = await Promise.all(calls); + expect(replies.every((r) => r.ok)).toBe(true); + const writes = tools.commits.filter((c) => c.tool === 'write').map((c) => c.id); + expect(writes).toEqual(['c5', 'c10', 'c15', 'c20', 'c25']); + expect(tools.read('out.txt')).toBe('w5'); + expect(tools.maxConcurrentReads).toBeGreaterThan(1); + }); + + it('denies by static rule without running hooks', async () => { + const { dispatcher, adapter, tools, denies } = await setup({ + rules: [(p) => (p.tool === 'bash' && p.effect.command.startsWith('rm ') ? { kind: 'deny', reason: 'no rm' } : undefined)], + }); + const err = errorOf(await dispatcher.dispatch('bash', { command: 'rm -rf /' })); + expect(err).toEqual({ name: 'PermissionDenied', code: 'denied', source: 'rule', message: 'no rm' }); + expect(adapter.authorized).toHaveLength(0); + expect(tools.commits).toHaveLength(0); + expect(denies).toEqual(['c1']); + expect(dispatcher.calls[0]).toMatchObject({ decision: 'denied', reason: 'rule: no rm' }); + }); + + it('turns ask (static or hook) into deny ask-unavailable', async () => { + const a = await setup({ rules: [() => ({ kind: 'ask', reason: 'confirm' })] }); + expect(errorOf(await a.dispatcher.dispatch('write', { path: 'x', content: '' }))).toMatchObject({ source: 'ask-unavailable' }); + const b = await setup({ hook: { kind: 'ask', reason: 'confirm' } }); + expect(errorOf(await b.dispatcher.dispatch('write', { path: 'x', content: '' }))).toMatchObject({ source: 'ask-unavailable' }); + expect(b.tools.commits).toHaveLength(0); + }); + + it('denies with hook source when a hook denies', async () => { + const { dispatcher, tools } = await setup({ hook: { kind: 'deny', reason: 'blocked by hook' } }); + expect(errorOf(await dispatcher.dispatch('write', { path: 'x', content: '' }))).toMatchObject({ source: 'hook', message: 'blocked by hook' }); + expect(tools.commits).toHaveLength(0); + }); + + it('turns a throwing or malformed hook adapter into deny hook-error', async () => { + const thrower = await setup({ hook: { kind: 'throw', message: 'boom' } }); + expect(errorOf(await thrower.dispatcher.dispatch('write', { path: 'x', content: '' }))).toMatchObject({ + source: 'hook-error', + message: 'hook failed: boom', + }); + const malformed = await setup({ hook: { kind: 'malformed' } }); + expect(errorOf(await malformed.dispatcher.dispatch('write', { path: 'x', content: '' }))).toMatchObject({ source: 'hook-error' }); + expect(thrower.tools.commits).toHaveLength(0); + expect(malformed.tools.commits).toHaveLength(0); + }); + + it('denies every call with unsupported-config when the policy failed to load', async () => { + const { dispatcher, tools } = await setup({ policyError: 'unknown hook type "agent"' }, { files: { 'a.txt': 'x' } }); + expect(errorOf(await dispatcher.dispatch('read', { path: 'a.txt' }))).toMatchObject({ source: 'unsupported-config' }); + expect(tools.commits).toHaveLength(0); + }); + + it('re-prepares updatedArgs and commits the updated effect', async () => { + const { dispatcher, tools, adapter } = await setup({ + hook: (p) => (p.tool === 'write' && p.effect.afterContent === 'secret' ? { kind: 'updatedArgs', args: { path: 'a.txt', content: 'redacted' } } : { kind: 'allow' }), + }); + const reply = await dispatcher.dispatch('write', { path: 'a.txt', content: 'secret' }); + expect(reply.ok).toBe(true); + expect(tools.read('a.txt')).toBe('redacted'); + // Hooks ran once; static rules ran on both the original and the updated call. + expect(adapter.authorized).toHaveLength(1); + expect(adapter.staticChecked).toHaveLength(2); + }); + + it('refuses updatedArgs that point outside the workspace', async () => { + const { dispatcher, tools } = await setup({ hook: { kind: 'updatedArgs', args: { path: '../etc/passwd', content: 'x' } } }); + const err = errorOf(await dispatcher.dispatch('write', { path: 'a.txt', content: 'x' })); + expect(err).toMatchObject({ name: 'PermissionDenied', source: 'hook' }); + expect(err.message).toContain('outside the workspace'); + expect(tools.commits).toHaveLength(0); + expect(tools.files.size).toBe(0); + }); + + it('refuses malformed updatedArgs and lets deny rules win over updated args', async () => { + const malformed = await setup({ hook: { kind: 'updatedArgs', args: { path: 1 } } }); + expect(errorOf(await malformed.dispatcher.dispatch('write', { path: 'a', content: '' }))).toMatchObject({ source: 'hook' }); + + const ruled = await setup({ + rules: [(p) => (p.tool === 'bash' && p.effect.command.includes('curl') ? { kind: 'deny', reason: 'no network' } : undefined)], + hook: { kind: 'updatedArgs', args: { command: 'curl example.com' } }, + }); + expect(errorOf(await ruled.dispatcher.dispatch('bash', { command: 'echo hi' }))).toMatchObject({ source: 'rule', message: 'no network' }); + expect(ruled.tools.commits).toHaveLength(0); + }); + + it('refuses writes to protected paths even through updatedArgs', async () => { + const { dispatcher, tools } = await setup({ + protectedPaths: ['/ws/.claude/**'], + hook: { kind: 'updatedArgs', args: { path: '.claude/settings.json', content: '{}' } }, + }); + const direct = await setup({ protectedPaths: ['/ws/.claude/**'] }); + expect(errorOf(await direct.dispatcher.dispatch('write', { path: '.claude/hooks/x.sh', content: '' }))).toMatchObject({ code: 'protected-path' }); + expect(errorOf(await dispatcher.dispatch('write', { path: 'ok.txt', content: '' }))).toMatchObject({ name: 'PermissionDenied' }); + expect(tools.files.size).toBe(0); + }); + + it('denies bash when prepared containment differs from the policy', async () => { + const adapterOpts: StaticHostAdapterOptions = { bashContainment: { mode: 'sandbox', readOnly: true, writableRoots: [], network: false } }; + const { ctx, adapter } = await setup(adapterOpts); + const tools = new MemoryToolRuntime({ root: '/ws' }); + const weakened: typeof tools = Object.assign(Object.create(tools) as typeof tools, { + prepare: async (...args: Parameters) => { + const p = await tools.prepare(...args); + return p.tool === 'bash' ? { ...p, effect: { ...p.effect, containment: { mode: 'none' as const } } } : p; + }, + }); + const policy = await adapter.loadPolicy(ctx); + const dispatcher = new Dispatcher({ adapter, tools: weakened, ctx, policy }); + expect(errorOf(await dispatcher.dispatch('bash', { command: 'ls' }))).toMatchObject({ source: 'containment-unavailable' }); + expect(tools.commits).toHaveLength(0); + }); + + it('refuses calls and commits after stop', async () => { + const { dispatcher, tools } = await setup({ hook: { kind: 'hang' } }); + const pending = dispatcher.dispatch('write', { path: 'a.txt', content: 'x' }); + await new Promise((r) => setTimeout(r, 10)); + await dispatcher.stop('cancelled'); + expect(errorOf(await pending)).toMatchObject({ code: 'cancelled' }); + expect(errorOf(await dispatcher.dispatch('read', { path: 'a.txt' }))).toMatchObject({ code: 'cancelled' }); + expect(tools.commits).toHaveLength(0); + }); + + it('refuses a queued commit once the run stops', async () => { + const { dispatcher, tools } = await setup({}, { commitDelayMs: 50 }); + const first = dispatcher.dispatch('write', { path: 'a.txt', content: '1' }); + const second = dispatcher.dispatch('write', { path: 'b.txt', content: '2' }); + await new Promise((r) => setTimeout(r, 10)); + await dispatcher.stop('timeout'); + expect(errorOf(await first)).toMatchObject({ code: 'cancelled' }); + expect(errorOf(await second)).toMatchObject({ code: 'cancelled' }); + expect(tools.files.size).toBe(0); + }); + + it('reports a commit that was mid-flight when the run stopped', async () => { + const { dispatcher, tools } = await setup({}, { commitDelayMs: 40, honorAbortInCommit: false }); + const pending = dispatcher.dispatch('write', { path: 'a.txt', content: 'x' }); + await new Promise((r) => setTimeout(r, 10)); + await dispatcher.stop('cancelled'); + expect((await pending).ok).toBe(true); + expect(tools.read('a.txt')).toBe('x'); + expect(dispatcher.warnings.join('\n')).toMatch(/c1 \(write a\.txt\) was committing when the run stopped \(cancelled\)/); + expect(dispatcher.changedFiles).toEqual(['a.txt']); + }); + + it('fails a write whose file changed between prepare and commit (stale)', async () => { + const { dispatcher, tools } = await setup({ hook: (p) => { + if (p.tool === 'edit') tools.externalWrite('a.txt', 'changed by someone else'); + return { kind: 'allow' }; + } }, { files: { 'a.txt': 'old text' } }); + const err = errorOf(await dispatcher.dispatch('edit', { path: 'a.txt', oldString: 'old', newString: 'new' })); + expect(err).toMatchObject({ name: 'ToolError', code: 'stale' }); + expect(tools.read('a.txt')).toBe('changed by someone else'); + }); + + it('collects changed files and the combined diff in commit order', async () => { + const { dispatcher } = await setup({}, { files: { 'a.txt': 'one\n' } }); + await dispatcher.dispatch('edit', { path: 'a.txt', oldString: 'one', newString: 'two' }); + await dispatcher.dispatch('write', { path: 'sub/b.txt', content: 'b\n' }); + await dispatcher.dispatch('write', { path: 'a.txt', content: 'three\n' }); + expect(dispatcher.changedFiles).toEqual(['a.txt', 'sub/b.txt']); + const diff = dispatcher.diff; + expect(diff.indexOf('+two')).toBeLessThan(diff.indexOf('+b')); + expect(diff.indexOf('+b')).toBeLessThan(diff.indexOf('+three')); + }); + + it('deep-freezes prepared calls before adapters see them', async () => { + const { dispatcher, adapter } = await setup(); + await dispatcher.dispatch('write', { path: 'a.txt', content: 'x' }); + const seen = adapter.authorized[0]; + expect(seen && Object.isFrozen(seen) && Object.isFrozen(seen.effect) && Object.isFrozen(seen.args)).toBe(true); + }); + + it('a deny mid-script in a transaction lets the transaction roll back earlier writes', async () => { + const { dispatcher, tools, tx, denies } = await setup( + { rules: [(p) => (p.tool === 'write' && p.effect.absPath.endsWith('forbidden.txt') ? { kind: 'deny', reason: 'nope' } : undefined)] }, + { files: { 'a.txt': 'original' } }, + { transaction: true }, + ); + expect((await dispatcher.dispatch('write', { path: 'a.txt', content: 'changed' })).ok).toBe(true); + expect((await dispatcher.dispatch('write', { path: 'new.txt', content: 'n' })).ok).toBe(true); + expect((await dispatcher.dispatch('write', { path: 'forbidden.txt', content: 'x' })).ok).toBe(false); + expect(denies).toEqual(['c3']); + const report = await tx?.rollback(); + expect([...(report?.restored ?? [])].sort()).toEqual(['/ws/a.txt', '/ws/new.txt']); + expect(tools.read('a.txt')).toBe('original'); + expect(tools.read('new.txt')).toBeUndefined(); + }); + + it('a hook that tries to mutate the prepared call is denied hook-error and nothing is committed', async () => { + const { dispatcher, tools } = await setup({ + hook: (p) => { + if (p.tool === 'write') Object.assign(p.effect, { absPath: '/etc/passwd' }); + return { kind: 'allow' }; + }, + }); + expect(errorOf(await dispatcher.dispatch('write', { path: 'a.txt', content: 'x' }))).toMatchObject({ source: 'hook-error' }); + expect(tools.commits).toHaveLength(0); + }); + + it('refuses a prepared call that does not belong to the call', async () => { + const { ctx, adapter } = await setup(); + const tools = new MemoryToolRuntime({ root: '/ws' }); + const wrong: typeof tools = Object.assign(Object.create(tools) as typeof tools, { + prepare: async (...args: Parameters) => ({ ...(await tools.prepare(...args)), id: 'c999' }), + }); + const dispatcher = new Dispatcher({ adapter, tools: wrong, ctx, policy: await adapter.loadPolicy(ctx) }); + expect(errorOf(await dispatcher.dispatch('write', { path: 'a.txt', content: 'x' }))).toMatchObject({ code: 'tool-error' }); + expect(tools.commits).toHaveLength(0); + }); + + it('runs postToolUse after commit and turns its failure into a warning', async () => { + const { ctx, tools } = await setup(); + const adapter = new StaticHostAdapter(); + adapter.postToolUse = async () => { + throw new Error('post failed'); + }; + const dispatcher = new Dispatcher({ adapter, tools, ctx, policy: await adapter.loadPolicy(ctx) }); + expect((await dispatcher.dispatch('write', { path: 'a.txt', content: 'x' })).ok).toBe(true); + expect(dispatcher.warnings[0]).toContain('post failed'); + }); +}); diff --git a/src/core/dispatcher.ts b/src/core/dispatcher.ts new file mode 100644 index 0000000..e1e1a11 --- /dev/null +++ b/src/core/dispatcher.ts @@ -0,0 +1,481 @@ +import path from 'node:path'; +import { ToolError, errorMessage } from './errors.js'; +import { deepFreeze } from './freeze.js'; +import { findMatchingPattern } from './paths.js'; +import { isMutating, parseToolCall } from './schemas.js'; +import type { + BashContainment, + BindingError, + CallLogEntry, + CallReply, + Decision, + DenySource, + HostAdapter, + PolicyLoadError, + PolicySnapshot, + PreparedCall, + SessionContext, + ToolCall, + ToolResult, + ToolRuntime, + Transaction, +} from './types.js'; + +/** Why the dispatcher stopped accepting calls. */ +export type StopReason = 'finished' | 'cancelled' | 'timeout' | 'denied'; + +export interface DispatcherOptions

{ + readonly adapter: HostAdapter

; + readonly tools: ToolRuntime

; + readonly ctx: SessionContext; + readonly policy: PolicySnapshot

| PolicyLoadError; + /** Journal of a transactional run; passed to every commit. */ + readonly transaction?: Transaction; + /** Called once, on the first denied call. A transactional run aborts there. */ + readonly onDeny?: (entry: CallLogEntry) => void; + /** Clock, for tests. */ + readonly now?: () => number; +} + +type Failure = + | { readonly kind: 'deny'; readonly source: DenySource; readonly reason: string } + | { readonly kind: 'error'; readonly error: ToolError }; + +const ABORTED: unique symbol = Symbol('aborted'); + +const MAX_SUMMARY_CHARS = 160; + +function isPolicyError

(policy: PolicySnapshot

| PolicyLoadError): policy is PolicyLoadError { + return 'error' in policy; +} + +function clip(s: string, max: number): string { + return s.length <= max ? s : `${s.slice(0, max - 1)}…`; +} + +function oneLine(s: string): string { + return s.replace(/\s*\n\s*/g, ' ⏎ '); +} + +function containmentEquals(a: BashContainment, b: BashContainment): boolean { + if (a.mode === 'none' || b.mode === 'none') return a.mode === b.mode; + return ( + a.readOnly === b.readOnly && + a.network === b.network && + a.writableRoots.length === b.writableRoots.length && + a.writableRoots.every((root, i) => root === b.writableRoots[i]) + ); +} + +/** Fail-closed shape check of a decision coming from an adapter. */ +function isDecision(value: unknown): value is Decision { + if (value === null || typeof value !== 'object' || !('kind' in value)) return false; + const kind: unknown = value.kind; + if (kind === 'allow') return true; + if (kind === 'ask') return 'reason' in value && typeof value.reason === 'string'; + if (kind === 'deny') { + return 'reason' in value && typeof value.reason === 'string' && 'source' in value && typeof value.source === 'string'; + } + return false; +} + +function raceAbort(promise: Promise, signal: AbortSignal): Promise { + if (signal.aborted) { + promise.catch(() => undefined); + return Promise.resolve(ABORTED); + } + return new Promise((resolve, reject) => { + const onAbort = (): void => resolve(ABORTED); + signal.addEventListener('abort', onAbort, { once: true }); + promise.then( + (value) => { + signal.removeEventListener('abort', onAbort); + resolve(value); + }, + (err: unknown) => { + signal.removeEventListener('abort', onAbort); + reject(err); + }, + ); + }); +} + +/** + * Runs every binding call of one script through prepare → authorize → commit. + * + * Rules it enforces: + * - ids `c1`, `c2`, ... in call order; args validated with `parseToolCall`. + * - a policy load error denies every call with `unsupported-config`. + * - `checkStatic` first (deny/ask short-circuit; hooks are not run), then + * `authorize`. `ask` becomes deny `ask-unavailable`. A throwing or malformed + * adapter becomes deny `hook-error`. + * - `updatedArgs` are re-parsed, re-prepared and re-checked statically; a + * failure there is a deny (source `hook`). + * - write/edit on a protected path is refused even if the tool runtime missed + * it; a bash call whose containment differs from the policy is denied + * `containment-unavailable`. + * - mutations (`bash`, `write`, `edit`) run one at a time, in call order; + * reads run concurrently. + * - after `stop()` no call starts and no commit starts; a commit that was + * running when the run stopped is reported in `warnings`. + */ +export class Dispatcher

{ + readonly #opts: DispatcherOptions

; + readonly #now: () => number; + readonly #abort = new AbortController(); + #stopReason: StopReason | undefined; + #nextId = 1; + #mutationTail: Promise = Promise.resolve(); + readonly #inflight = new Set>(); + readonly #calls: (CallLogEntry | undefined)[] = []; + readonly #changed: string[] = []; + readonly #diffs: string[] = []; + readonly #warnings: string[] = []; + #deniedCount = 0; + #bashCommits = 0; + + constructor(opts: DispatcherOptions

) { + this.#opts = opts; + this.#now = opts.now ?? (() => performance.now()); + } + + /** Signal aborted when the dispatcher stops. */ + get signal(): AbortSignal { + return this.#abort.signal; + } + + /** Call log, in call order. */ + get calls(): readonly CallLogEntry[] { + return this.#calls.filter((entry): entry is CallLogEntry => entry !== undefined); + } + + /** Files written or edited by committed calls, in first-commit order. */ + get changedFiles(): readonly string[] { + return [...this.#changed]; + } + + /** Combined diff of committed writes and edits, in commit order. */ + get diff(): string { + return this.#diffs.join(''); + } + + get warnings(): readonly string[] { + return [...this.#warnings]; + } + + get deniedCount(): number { + return this.#deniedCount; + } + + /** Number of `bash` calls that committed (their effects are never rolled back). */ + get bashCommits(): number { + return this.#bashCommits; + } + + get stopReason(): StopReason | undefined { + return this.#stopReason; + } + + /** + * Handles one binding call from the script. Never rejects. `tool` and + * `args` are untrusted. + */ + dispatch(tool: unknown, args: unknown): Promise { + const id = `c${this.#nextId++}`; + const slot = this.#calls.length; + this.#calls.push(undefined); + const started = this.#now(); + const toolLabel = clip(typeof tool === 'string' ? tool : String(tool), 40); + + let handled: Promise; + try { + handled = this.#handle(id, slot, toolLabel, tool, args, started); + } catch (err) { + handled = Promise.reject(err); + } + const reply = handled.catch((err: unknown) => + // Defensive: #handle catches everything it expects. + this.#fail(slot, id, toolLabel, toolLabel, started, { + kind: 'error', + error: new ToolError('tool-error', `internal error: ${errorMessage(err)}`), + }), + ); + this.#inflight.add(reply); + void reply.finally(() => this.#inflight.delete(reply)); + return reply; + } + + /** + * Stops accepting calls, aborts in-flight ones and waits for them to + * settle. Idempotent; the first reason wins. + */ + async stop(reason: StopReason): Promise { + if (this.#stopReason === undefined) { + this.#stopReason = reason; + this.#abort.abort(reason); + } + while (this.#inflight.size > 0) { + await Promise.allSettled([...this.#inflight]); + } + } + + #handle(id: string, slot: number, toolLabel: string, tool: unknown, args: unknown, started: number): Promise { + // Everything up to the mutation queue is synchronous so the queue keeps call order. + if (this.#stopReason !== undefined) { + return Promise.resolve(this.#fail(slot, id, toolLabel, toolLabel, started, this.#stoppedFailure())); + } + const parsed = parseToolCall(typeof tool === 'string' ? tool : String(tool), args, id); + if (parsed instanceof ToolError) { + return Promise.resolve(this.#fail(slot, id, toolLabel, toolLabel, started, { kind: 'error', error: parsed })); + } + const call = parsed; + const summary = summarize(call, this.#opts.ctx.cwd); + const policy = this.#opts.policy; + if (isPolicyError(policy)) { + return Promise.resolve( + this.#fail(slot, id, call.tool, summary, started, { + kind: 'deny', + source: 'unsupported-config', + reason: `host configuration could not be loaded: ${policy.error}`, + }), + ); + } + const run = (): Promise => this.#pipeline(slot, call, summary, policy, started); + if (!isMutating(call.tool)) return run(); + const queued = this.#mutationTail.then(run); + this.#mutationTail = queued.catch(() => undefined); + return queued; + } + + async #pipeline( + slot: number, + call: ToolCall, + summary: string, + policy: PolicySnapshot

, + started: number, + ): Promise { + const fail = (failure: Failure): CallReply => this.#fail(slot, call.id, call.tool, summary, started, failure); + if (this.#stopReason !== undefined) return fail(this.#stoppedFailure()); + + const first = await this.#prepareChecked(call, policy); + if ('kind' in first) return fail(first); + let prepared = first.prepared; + if (this.#stopReason !== undefined) return fail(this.#stoppedFailure()); + + const staticFailure = this.#checkStatic(prepared, policy); + if (staticFailure) return fail(staticFailure); + + const decision = await this.#authorize(prepared, policy); + if (decision === ABORTED || this.#stopReason !== undefined) return fail(this.#stoppedFailure()); + if (decision.kind === 'deny') return fail({ kind: 'deny', source: decision.source, reason: decision.reason }); + if (decision.kind === 'ask') { + return fail({ kind: 'deny', source: 'ask-unavailable', reason: `host would ask the user and no interactive channel exists: ${decision.reason}` }); + } + + if (decision.updatedArgs !== undefined) { + const reparsed = parseToolCall(call.tool, decision.updatedArgs, call.id); + if (reparsed instanceof ToolError) { + return fail({ kind: 'deny', source: 'hook', reason: `hook returned invalid updated input: ${reparsed.message}` }); + } + const second = await this.#prepareChecked(reparsed, policy); + if ('kind' in second) { + const reason = second.kind === 'deny' ? second.reason : second.error.message; + return fail({ kind: 'deny', source: second.kind === 'deny' ? second.source : 'hook', reason: `hook updated input was refused: ${reason}` }); + } + const recheck = this.#checkStatic(second.prepared, policy); + if (recheck) return fail(recheck); + prepared = second.prepared; + if (this.#stopReason !== undefined) return fail(this.#stoppedFailure()); + } + + return this.#commit(slot, prepared, summary, policy, started); + } + + async #prepareChecked(call: ToolCall, policy: PolicySnapshot

): Promise<{ prepared: PreparedCall } | Failure> { + let prepared: PreparedCall; + try { + prepared = deepFreeze(await this.#opts.tools.prepare(call, this.#opts.ctx, policy)); + } catch (err) { + return this.#toolFailure(err); + } + if (prepared.id !== call.id || prepared.tool !== call.tool) { + return { kind: 'error', error: new ToolError('tool-error', 'tool runtime returned a prepared call for another call') }; + } + if (prepared.tool === 'write' || prepared.tool === 'edit') { + const hit = findMatchingPattern(prepared.effect.absPath, policy.protectedPaths); + if (hit !== undefined) { + return { kind: 'error', error: new ToolError('protected-path', `${prepared.effect.absPath} is a protected host policy path`) }; + } + } + if (prepared.tool === 'bash' && !containmentEquals(prepared.effect.containment, policy.bashContainment)) { + return { kind: 'deny', source: 'containment-unavailable', reason: 'bash containment does not match the host policy' }; + } + return { prepared }; + } + + #checkStatic(prepared: PreparedCall, policy: PolicySnapshot

): Failure | undefined { + let decision: unknown; + try { + decision = this.#opts.adapter.checkStatic(prepared, this.#opts.ctx, policy); + } catch (err) { + return { kind: 'deny', source: 'rule', reason: `permission rule check failed: ${errorMessage(err)}` }; + } + if (!isDecision(decision)) return { kind: 'deny', source: 'rule', reason: 'permission rule check returned an invalid decision' }; + if (decision.kind === 'deny') return { kind: 'deny', source: decision.source, reason: decision.reason }; + if (decision.kind === 'ask') { + return { kind: 'deny', source: 'ask-unavailable', reason: `host would ask the user and no interactive channel exists: ${decision.reason}` }; + } + // A static allow never carries updated args; ignore any. + return undefined; + } + + async #authorize(prepared: PreparedCall, policy: PolicySnapshot

): Promise { + const signal = this.#abort.signal; + let pending: Promise; + try { + pending = Promise.resolve(this.#opts.adapter.authorize(prepared, this.#opts.ctx, policy, signal)); + } catch (err) { + pending = Promise.reject(err); + } + try { + const decision = await raceAbort(pending, signal); + if (decision === ABORTED) return ABORTED; + if (!isDecision(decision)) return { kind: 'deny', source: 'hook-error', reason: 'hook adapter returned an invalid decision' }; + return decision; + } catch (err) { + if (signal.aborted) return ABORTED; + return { kind: 'deny', source: 'hook-error', reason: `hook failed: ${errorMessage(err)}` }; + } + } + + async #commit( + slot: number, + prepared: PreparedCall, + summary: string, + policy: PolicySnapshot

, + started: number, + ): Promise { + const signal = this.#abort.signal; + let result: ToolResult; + try { + result = await this.#opts.tools.commit(prepared, signal, this.#opts.transaction); + } catch (err) { + if (signal.aborted) { + this.#warnings.push( + `${prepared.id} (${summary}) was committing when the run stopped (${this.#stopReason ?? 'stopped'}) and then failed: ${errorMessage(err)}. Its effect may be partial.`, + ); + if (prepared.tool === 'write' || prepared.tool === 'edit') this.#addChanged(prepared.effect.absPath); + } + return this.#fail(slot, prepared.id, prepared.tool, summary, started, this.#toolFailure(err)); + } + + if (signal.aborted) { + this.#warnings.push( + `${prepared.id} (${summary}) was committing when the run stopped (${this.#stopReason ?? 'stopped'}); its effect was applied.`, + ); + } + if (prepared.tool === 'write' || prepared.tool === 'edit') { + this.#addChanged(prepared.effect.absPath); + const diff = 'diff' in result && typeof result.diff === 'string' ? result.diff : prepared.effect.diff; + this.#diffs.push(diff.endsWith('\n') || diff === '' ? diff : `${diff}\n`); + } else if (prepared.tool === 'bash') { + this.#bashCommits++; + } + + const post = this.#opts.adapter.postToolUse; + if (post) { + try { + await post.call(this.#opts.adapter, prepared, result, this.#opts.ctx, policy); + } catch (err) { + this.#warnings.push(`PostToolUse hooks failed for ${prepared.id} (${summary}): ${errorMessage(err)}`); + } + } + + this.#calls[slot] = { id: prepared.id, tool: prepared.tool, summary, decision: 'allowed', durationMs: this.#elapsed(started) }; + return { ok: true, value: result }; + } + + #toolFailure(err: unknown): Failure { + if (err instanceof ToolError) { + if (err.code === 'containment-unavailable') { + return { kind: 'deny', source: 'containment-unavailable', reason: err.message }; + } + return { kind: 'error', error: err }; + } + if (this.#abort.signal.aborted) return this.#stoppedFailure(); + return { kind: 'error', error: new ToolError('tool-error', errorMessage(err)) }; + } + + #stoppedFailure(): Failure { + const reason = this.#stopReason ?? 'finished'; + const message = + reason === 'finished' + ? 'the script already finished; calls made after it returned are refused' + : `the run was stopped (${reason}); the call was not executed`; + return { kind: 'error', error: new ToolError('cancelled', message) }; + } + + #fail(slot: number, id: string, tool: string, summary: string, started: number, failure: Failure): CallReply { + let error: BindingError; + let entry: CallLogEntry; + const durationMs = this.#elapsed(started); + if (failure.kind === 'deny') { + error = { name: 'PermissionDenied', code: 'denied', source: failure.source, message: failure.reason }; + entry = { id, tool, summary, decision: 'denied', reason: `${failure.source}: ${failure.reason}`, durationMs }; + } else { + const code = failure.error.code === 'containment-unavailable' ? 'tool-error' : failure.error.code; + error = { name: 'ToolError', code, message: failure.error.message }; + entry = { id, tool, summary, decision: 'error', reason: failure.error.message, durationMs }; + } + this.#calls[slot] = entry; + if (failure.kind === 'deny') { + this.#deniedCount++; + if (this.#deniedCount === 1 && this.#opts.onDeny) { + try { + this.#opts.onDeny(entry); + } catch { + // The callback is internal; a failure must not change the reply. + } + } + } + return { ok: false, error }; + } + + #addChanged(absPath: string): void { + const shown = displayPath(absPath, this.#opts.ctx.cwd); + if (!this.#changed.includes(shown)) this.#changed.push(shown); + } + + #elapsed(started: number): number { + return Math.max(0, Math.round(this.#now() - started)); + } +} + +/** Path relative to `cwd` when inside it, else the absolute path. */ +export function displayPath(absPath: string, cwd: string): string { + const rel = path.relative(cwd, absPath); + return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel.split(path.sep).join('/') : absPath; +} + +/** Short description of a call for the call log. */ +export function summarize(call: ToolCall, cwd: string): string { + const p = (value: string): string => displayPath(path.resolve(cwd, value), cwd); + let s: string; + switch (call.tool) { + case 'bash': + s = `bash ${oneLine(call.args.command)}`; + break; + case 'read': + case 'write': + case 'edit': + s = `${call.tool} ${p(call.args.path)}`; + break; + case 'grep': + s = `grep ${JSON.stringify(call.args.pattern)}${call.args.path ? ` in ${p(call.args.path)}` : ''}`; + break; + case 'glob': + s = `glob ${call.args.pattern}${call.args.path ? ` in ${p(call.args.path)}` : ''}`; + break; + } + return clip(s, MAX_SUMMARY_CHARS); +} diff --git a/src/core/errors.ts b/src/core/errors.ts new file mode 100644 index 0000000..0fa9c1c --- /dev/null +++ b/src/core/errors.ts @@ -0,0 +1,30 @@ +import type { BindingErrorCode } from './types.js'; + +/** Codes a `ToolError` can carry. */ +export type ToolErrorCode = Exclude | 'containment-unavailable'; + +/** + * Error thrown by the tool runtime (`prepare`/`commit`) and returned by + * `parseToolCall`. The dispatcher converts it into a `BindingError`; + * `containment-unavailable` becomes a deny instead. + */ +export class ToolError extends Error { + override readonly name = 'ToolError'; + readonly code: ToolErrorCode; + + constructor(code: ToolErrorCode, message: string) { + super(message); + this.code = code; + } +} + +/** Message of any thrown value, without trusting its shape. */ +export function errorMessage(err: unknown): string { + if (err instanceof Error) return err.message; + if (typeof err === 'string') return err; + try { + return String(err); + } catch { + return 'unknown error'; + } +} diff --git a/src/core/freeze.ts b/src/core/freeze.ts new file mode 100644 index 0000000..3e0f327 --- /dev/null +++ b/src/core/freeze.ts @@ -0,0 +1,10 @@ +/** Recursively freezes plain objects and arrays in place and returns the value. */ +export function deepFreeze(value: T): T { + if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) { + Object.freeze(value); + for (const key of Reflect.ownKeys(value)) { + deepFreeze((value as Record)[key]); + } + } + return value; +} diff --git a/src/core/output.test.ts b/src/core/output.test.ts new file mode 100644 index 0000000..409c2af --- /dev/null +++ b/src/core/output.test.ts @@ -0,0 +1,96 @@ +import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { ERROR_CAP_CHARS, SUCCESS_CAP_CHARS, formatRunResult, truncateStructurally } from './output.js'; +import { stateDirPath } from './state-dir.js'; +import type { RunResult } from './types.js'; + +const base: RunResult = { ok: true, result: null, logs: [], calls: [], changedFiles: [], diff: '', warnings: [] }; +const dirs: string[] = []; +async function tmp(): Promise { + const d = await mkdtemp(path.join(os.tmpdir(), 'acm-out-')); + dirs.push(d); + return path.join(d, 'state'); +} +afterEach(async () => { + await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true }))); +}); + +describe('formatRunResult', () => { + it('returns compact JSON and isError', async () => { + const ok = await formatRunResult({ ...base, result: { a: 1 } }, { stateDir: await tmp() }); + expect(ok.isError).toBe(false); + expect(JSON.parse(ok.content[0]?.text ?? '')).toMatchObject({ ok: true, result: { a: 1 } }); + const err = await formatRunResult({ ...base, ok: false, error: { kind: 'error', name: 'Error', message: 'x' } }, { stateDir: await tmp() }); + expect(err.isError).toBe(true); + }); + + it('writes oversized success results to an overflow file and returns a valid preview', async () => { + const stateDir = await tmp(); + const big: RunResult = { ...base, result: { text: 'x'.repeat(100_000), list: Array.from({ length: 5_000 }, (_, i) => i) }, diff: 'd'.repeat(50_000) }; + const out = await formatRunResult(big, { stateDir }); + const text = out.content[0]?.text ?? ''; + expect(text.length).toBeLessThanOrEqual(SUCCESS_CAP_CHARS); + const preview = JSON.parse(text) as { overflowPath: string; truncated: boolean; ok: boolean }; + expect(preview.truncated).toBe(true); + expect(preview.ok).toBe(true); + const full: unknown = JSON.parse(await readFile(preview.overflowPath, 'utf8')); + expect(full).toEqual(JSON.parse(JSON.stringify(big))); + if (process.platform !== 'win32') { + expect((await stat(preview.overflowPath)).mode & 0o777).toBe(0o600); + expect((await stat(stateDir)).mode & 0o777).toBe(0o700); + } + }); + + it('caps error results lower', async () => { + const big: RunResult = { ...base, ok: false, error: { kind: 'error', name: 'Error', message: 'm'.repeat(20_000) }, logs: ['l'.repeat(20_000)] }; + const out = await formatRunResult(big, { stateDir: await tmp() }); + const text = out.content[0]?.text ?? ''; + expect(text.length).toBeLessThanOrEqual(ERROR_CAP_CHARS); + expect(JSON.parse(text)).toMatchObject({ ok: false, truncated: true, error: { name: 'Error' } }); + }); + + it('still returns a preview when the overflow file cannot be written', async () => { + const big: RunResult = { ...base, result: 'x'.repeat(60_000) }; + const out = await formatRunResult(big, { stateDir: '\0invalid' }); + const preview = JSON.parse(out.content[0]?.text ?? '') as Record; + expect(preview['overflowPath']).toBeUndefined(); + expect(String(preview['note'])).toContain('could not be saved'); + }); +}); + +describe('truncateStructurally', () => { + it('always returns valid JSON within the cap', () => { + const deep: Record = {}; + let cur = deep; + for (let i = 0; i < 50; i++) { + const next: Record = { s: 'y'.repeat(1_000) }; + cur['n'] = next; + cur = next; + } + for (const cap of [40, 200, 1_000, 5_000]) { + const text = truncateStructurally({ ok: true, deep, arr: new Array(1000).fill('z'.repeat(100)) }, cap, { overflowPath: '/state/x.json' }); + expect(text.length).toBeLessThanOrEqual(cap); + expect(() => JSON.parse(text)).not.toThrow(); + } + }); +}); + +describe('truncateStructurally with wide objects', () => { + it('cuts objects with many keys instead of dropping everything', () => { + const wide = Object.fromEntries(Array.from({ length: 50_000 }, (_, i) => [`k${i}`, i])); + const text = truncateStructurally({ ok: true, result: wide }, 30_000); + const parsed = JSON.parse(text) as { result: Record }; + expect(text.length).toBeLessThanOrEqual(30_000); + expect(parsed.result['k0']).toBe(0); + }); +}); + +describe('stateDirPath', () => { + it('uses an absolute XDG_STATE_HOME, else ~/.local/state', () => { + expect(stateDirPath({ XDG_STATE_HOME: '/x/state' }, '/home/u')).toBe(path.join('/x/state', 'agent-code-mode')); + expect(stateDirPath({ XDG_STATE_HOME: 'relative' }, '/home/u')).toBe(path.join('/home/u', '.local', 'state', 'agent-code-mode')); + expect(stateDirPath({}, '/home/u')).toBe(path.join('/home/u', '.local', 'state', 'agent-code-mode')); + }); +}); diff --git a/src/core/output.ts b/src/core/output.ts new file mode 100644 index 0000000..cc8a69d --- /dev/null +++ b/src/core/output.ts @@ -0,0 +1,125 @@ +import { randomBytes } from 'node:crypto'; +import { writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { errorMessage } from './errors.js'; +import { ensureStateDir } from './state-dir.js'; +import type { RunResult } from './types.js'; + +/** Largest text of a successful result. */ +export const SUCCESS_CAP_CHARS = 30_000; +/** Largest text of an error result (Claude cuts the middle of long errors). */ +export const ERROR_CAP_CHARS = 9_500; + +export interface McpToolResponse { + [key: string]: unknown; + content: { type: 'text'; text: string }[]; + isError: boolean; +} + +export interface FormatOptions { + /** Directory for overflow files. Created 0700 when needed. */ + readonly stateDir: string; + readonly successCap?: number; + readonly errorCap?: number; +} + +interface Limits { + readonly str: number; + readonly arr: number; + readonly depth: number; +} + +const LEVELS: readonly Limits[] = [ + { str: 8_000, arr: 500, depth: 12 }, + { str: 2_000, arr: 100, depth: 10 }, + { str: 600, arr: 40, depth: 8 }, + { str: 200, arr: 15, depth: 6 }, + { str: 80, arr: 6, depth: 4 }, + { str: 30, arr: 3, depth: 3 }, +]; + +function shrink(value: unknown, limits: Limits, depth: number): unknown { + if (typeof value === 'string') { + return value.length <= limits.str ? value : `${value.slice(0, limits.str)}…[${value.length - limits.str} more chars]`; + } + if (value === null || typeof value !== 'object') return value; + if (depth >= limits.depth) return Array.isArray(value) ? `[array of ${value.length} items]` : '[object]'; + if (Array.isArray(value)) { + const kept = value.slice(0, limits.arr).map((item) => shrink(item, limits, depth + 1)); + if (value.length > limits.arr) kept.push(`…[${value.length - limits.arr} more items]`); + return kept; + } + const out: Record = {}; + const entries = Object.entries(value); + for (const [key, item] of entries.slice(0, limits.arr)) out[key] = shrink(item, limits, depth + 1); + if (entries.length > limits.arr) out['…'] = `[${entries.length - limits.arr} more keys]`; + return out; +} + +/** JSON text of `value`; values JSON cannot represent become strings instead of throwing. */ +export function safeStringify(value: unknown): string { + const seen = new WeakSet(); + try { + return JSON.stringify(value, (_key, v: unknown) => { + if (typeof v === 'bigint') return v.toString(); + if (v !== null && typeof v === 'object') { + if (seen.has(v)) return '[circular]'; + seen.add(v); + } + return v; + }) ?? 'null'; + } catch (err) { + return JSON.stringify({ unserializable: errorMessage(err) }); + } +} + +/** + * Shrinks a JSON-compatible value until its JSON text fits `cap`, keeping the + * structure valid: long strings and arrays are cut with explicit markers. + * `extra` fields are added at the top level untouched. + */ +export function truncateStructurally(value: unknown, cap: number, extra: Record = {}): string { + const plain: unknown = JSON.parse(safeStringify(value)); + const base = plain !== null && typeof plain === 'object' && !Array.isArray(plain) ? plain : { value: plain }; + for (const limits of LEVELS) { + const shrunk = shrink(base, limits, 0); + const text = safeStringify({ ...(shrunk !== null && typeof shrunk === 'object' ? shrunk : { value: shrunk }), ...extra, truncated: true }); + if (text.length <= cap) return text; + } + // Last resort: only the essentials, clipped to fit. + const essentials: Record = { ...extra, truncated: true }; + if ('ok' in base) essentials['ok'] = base.ok; + if ('error' in base) essentials['error'] = shrink(base.error, { str: 200, arr: 3, depth: 2 }, 0); + let text = safeStringify(essentials); + if (text.length > cap) text = safeStringify({ truncated: true, ...('ok' in base ? { ok: base.ok } : {}) }); + return text.length <= cap ? text : '{"truncated":true}'; +} + +async function writeOverflow(stateDir: string, text: string): Promise { + const dir = await ensureStateDir(stateDir); + const file = path.join(dir, `run-${Date.now()}-${randomBytes(6).toString('hex')}.json`); + await writeFile(file, text, { mode: 0o600, flag: 'wx' }); + return file; +} + +/** + * Formats a `RunResult` as an MCP tool response: compact JSON text, `isError` + * when the run failed. Results above the cap are written whole to an + * overflow file (mode 0600) and replaced by a structurally truncated preview + * carrying `overflowPath`. + */ +export async function formatRunResult(result: RunResult, opts: FormatOptions): Promise { + const isError = !result.ok; + const cap = isError ? (opts.errorCap ?? ERROR_CAP_CHARS) : (opts.successCap ?? SUCCESS_CAP_CHARS); + const full = safeStringify(result); + if (full.length <= cap) return { content: [{ type: 'text', text: full }], isError }; + + let extra: Record; + try { + const overflowPath = await writeOverflow(opts.stateDir, full); + extra = { overflowPath, note: `Result was ${full.length} chars; the full JSON is in the file at overflowPath (open it with the host's file reading tool).` }; + } catch (err) { + extra = { note: `Result was ${full.length} chars and could not be saved: ${errorMessage(err)}` }; + } + return { content: [{ type: 'text', text: truncateStructurally(result, cap, extra) }], isError }; +} diff --git a/src/core/paths.test.ts b/src/core/paths.test.ts new file mode 100644 index 0000000..3f6c479 --- /dev/null +++ b/src/core/paths.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from 'vitest'; +import { matchesPathPattern } from './paths.js'; + +describe('matchesPathPattern', () => { + it.each([ + ['/ws/.claude/settings.json', '/ws/.claude/settings*.json', true], + ['/ws/.claude/settings.local.json', '/ws/.claude/settings*.json', true], + ['/ws/.claude/sub/settings.json', '/ws/.claude/settings*.json', false], + ['/ws/.claude/hooks', '/ws/.claude/hooks/**', true], + ['/ws/.claude/hooks/a/b.sh', '/ws/.claude/hooks/**', true], + ['/ws/.claude/hooksx', '/ws/.claude/hooks/**', false], + ['/ws/src/a/b/c.ts', '/ws/src/**/*.ts', true], + ['/ws/src/c.ts', '/ws/src/**/*.ts', true], + ['C:\\ws\\.codex\\config.toml', 'C:/ws/.codex/**', true], + ['/ws/a+b.txt', '/ws/a+b.txt', true], + ['/ws/aab.txt', '/ws/a+b.txt', false], + ])('%s vs %s → %s', (p, pattern, expected) => { + expect(matchesPathPattern(p, pattern, false)).toBe(expected); + }); + + it('can match case-insensitively', () => { + expect(matchesPathPattern('/ws/.Claude/Settings.json', '/ws/.claude/settings*.json', true)).toBe(true); + expect(matchesPathPattern('/ws/.Claude/Settings.json', '/ws/.claude/settings*.json', false)).toBe(false); + }); +}); diff --git a/src/core/paths.ts b/src/core/paths.ts new file mode 100644 index 0000000..1195022 --- /dev/null +++ b/src/core/paths.ts @@ -0,0 +1,68 @@ +/** + * Path pattern matching shared by the tool runtimes (protected paths, glob). + * + * Patterns use `/` as separator. `**` matches any number of characters + * including `/`; a trailing `/**` also matches the directory itself. `*` + * matches inside one segment, `?` one character inside a segment. Everything + * else is literal. Backslashes in both the path and the pattern are treated as + * separators so Windows paths match too. + */ + +const cache = new Map(); + +function toRegExp(pattern: string, caseInsensitive: boolean): RegExp { + const key = `${caseInsensitive ? 'i' : 's'}:${pattern}`; + const hit = cache.get(key); + if (hit) return hit; + const p = normalizeSeparators(pattern); + let src = ''; + for (let i = 0; i < p.length; i++) { + const ch = p[i] ?? ''; + if (ch === '*') { + if (p[i + 1] === '*') { + // `/**` at the end matches the directory itself and anything below. + if (src.endsWith('/') && i + 2 === p.length) { + src = `${src.slice(0, -1)}(?:/.*)?`; + } else if (p[i + 2] === '/') { + // `**/` matches zero or more whole segments. + src += '(?:.*/)?'; + i++; + } else { + src += '.*'; + } + i++; + } else { + src += '[^/]*'; + } + } else if (ch === '?') { + src += '[^/]'; + } else { + src += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&'); + } + } + const re = new RegExp(`^${src}$`, caseInsensitive ? 'i' : ''); + cache.set(key, re); + return re; +} + +/** Replaces `\` with `/`. */ +export function normalizeSeparators(p: string): string { + return p.replace(/\\/g, '/'); +} + +/** Whether file names on this platform are usually case-insensitive. */ +export const DEFAULT_CASE_INSENSITIVE = process.platform === 'darwin' || process.platform === 'win32'; + +/** Whether `path` matches `pattern`. Case-insensitive by default on macOS and Windows. */ +export function matchesPathPattern(path: string, pattern: string, caseInsensitive = DEFAULT_CASE_INSENSITIVE): boolean { + return toRegExp(pattern, caseInsensitive).test(normalizeSeparators(path)); +} + +/** The first pattern `path` matches, or undefined. */ +export function findMatchingPattern( + path: string, + patterns: readonly string[], + caseInsensitive = DEFAULT_CASE_INSENSITIVE, +): string | undefined { + return patterns.find((pattern) => matchesPathPattern(path, pattern, caseInsensitive)); +} diff --git a/src/core/run.test.ts b/src/core/run.test.ts new file mode 100644 index 0000000..e574d14 --- /dev/null +++ b/src/core/run.test.ts @@ -0,0 +1,170 @@ +import { describe, expect, it } from 'vitest'; +import { makeContext } from '../testing/context.js'; +import { FakeSandbox, type FakeStep } from '../testing/fake-sandbox.js'; +import { MemoryToolRuntime } from '../testing/memory-tool-runtime.js'; +import { StaticHostAdapter, type StaticHostAdapterOptions } from '../testing/static-host-adapter.js'; +import { resolveTimeoutMs, runScript, toRunRequest } from './run.js'; +import type { Sandbox } from './types.js'; + +function deps(adapterOpts: StaticHostAdapterOptions = {}, files: Record = {}, sandbox: Sandbox = new FakeSandbox()) { + return { + sandbox, + adapter: new StaticHostAdapter(adapterOpts), + tools: new MemoryToolRuntime({ root: '/ws', files }), + ctx: makeContext('/ws'), + stopGraceMs: 100, + }; +} + +const script = (steps: FakeStep[]): string => JSON.stringify(steps); +const denyForbidden: StaticHostAdapterOptions = { + rules: [(p) => (p.tool === 'write' && p.effect.absPath.endsWith('forbidden.txt') ? { kind: 'deny', reason: 'nope' } : undefined)], +}; + +describe('resolveTimeoutMs', () => { + it('defaults to 120 s and clamps to the server cap and to 600 s', () => { + expect(resolveTimeoutMs(undefined)).toBe(120_000); + expect(resolveTimeoutMs(10_000_000)).toBe(600_000); + expect(resolveTimeoutMs(90_000, 55_000)).toBe(55_000); + expect(resolveTimeoutMs(undefined, 55_000)).toBe(55_000); + expect(resolveTimeoutMs(0)).toBe(1); + expect(toRunRequest({ code: 'x' })).toEqual({ code: 'x', transaction: false, timeoutMs: 120_000 }); + }); +}); + +describe('runScript', () => { + it('returns the script value, logs, calls, changed files and diff', async () => { + const d = deps({}, { 'a.txt': 'hi\n' }); + const result = await runScript( + { code: script([{ log: 'start' }, { log: 'careful', level: 'warn' }, { tool: 'read', args: { path: 'a.txt' } }, { tool: 'write', args: { path: 'b.txt', content: 'b\n' } }]), transaction: false, timeoutMs: 5_000 }, + d, + ); + expect(result.ok).toBe(true); + expect(result.logs).toEqual(['start', 'warn: careful']); + expect(result.calls.map((c) => c.decision)).toEqual(['allowed', 'allowed']); + expect(result.changedFiles).toEqual(['b.txt']); + expect(result.diff).toContain('+b'); + expect(Array.isArray(result.result)).toBe(true); + }); + + it('keeps going after a denied call outside a transaction', async () => { + const d = deps(denyForbidden); + const result = await runScript( + { code: script([{ tool: 'write', args: { path: 'forbidden.txt', content: 'x' } }, { tool: 'write', args: { path: 'ok.txt', content: 'y' } }]), transaction: false, timeoutMs: 5_000 }, + d, + ); + expect(result.ok).toBe(true); + expect(result.calls.map((c) => c.decision)).toEqual(['denied', 'allowed']); + expect(d.tools.read('ok.txt')).toBe('y'); + }); + + it('aborts and rolls back a transaction on the first denied call', async () => { + const d = deps(denyForbidden, { 'a.txt': 'original' }); + const result = await runScript( + { + code: script([ + { tool: 'write', args: { path: 'a.txt', content: 'changed' } }, + { tool: 'bash', args: { command: 'echo hi' } }, + { tool: 'write', args: { path: 'forbidden.txt', content: 'x' } }, + { tool: 'write', args: { path: 'after.txt', content: 'never' } }, + ]), + transaction: true, + timeoutMs: 5_000, + }, + d, + ); + expect(result.ok).toBe(false); + expect(result.error).toMatchObject({ kind: 'denied', name: 'PermissionDenied' }); + expect(result.error?.message).toContain('c3'); + expect(result.rolledBack?.restored).toEqual(['/ws/a.txt']); + expect(d.tools.read('a.txt')).toBe('original'); + expect(d.tools.read('after.txt')).toBeUndefined(); + expect(result.warnings.join('\n')).toContain('bash effects are never rolled back'); + }); + + it('rolls back on script error and reports files changed externally', async () => { + const d = deps({}, { 'a.txt': 'original', 'b.txt': 'original b' }); + const sandbox: Sandbox = { + run: async (code, opts) => { + await opts.onCall('write', { path: 'a.txt', content: 'mine' }); + await opts.onCall('write', { path: 'b.txt', content: 'mine b' }); + d.tools.externalWrite('b.txt', 'theirs'); + return { ok: false, kind: 'error', error: { name: 'TypeError', message: 'x is undefined', stack: 'at line 3' } }; + }, + }; + const result = await runScript({ code: 'ignored', transaction: true, timeoutMs: 5_000 }, { ...d, sandbox }); + expect(result.error).toMatchObject({ kind: 'error', name: 'TypeError', stack: 'at line 3' }); + expect(result.rolledBack).toEqual({ restored: ['/ws/a.txt'], skipped: [{ path: '/ws/b.txt', reason: 'changed-externally' }] }); + expect(d.tools.read('a.txt')).toBe('original'); + expect(d.tools.read('b.txt')).toBe('theirs'); + }); + + it('times out, refuses later calls and rolls back', async () => { + const d = deps({}, {}); + const result = await runScript( + { code: script([{ tool: 'write', args: { path: 'a.txt', content: 'x' } }, { sleep: 2_000 }, { tool: 'write', args: { path: 'b.txt', content: 'y' } }]), transaction: true, timeoutMs: 50 }, + d, + ); + expect(result.error?.kind).toBe('timeout'); + expect(d.tools.files.size).toBe(0); + expect(result.rolledBack?.restored).toEqual(['/ws/a.txt']); + }); + + it('treats a sandbox that ignores stop as killed after the grace period', async () => { + const hanging: Sandbox = { run: () => new Promise(() => undefined) }; + const controller = new AbortController(); + const pending = runScript({ code: 'x', transaction: false, timeoutMs: 5_000 }, { ...deps(), sandbox: hanging, signal: controller.signal }); + setTimeout(() => controller.abort(), 10); + const result = await pending; + expect(result.error?.kind).toBe('cancelled'); + }); + + it('cancels when the client aborts and refuses calls made afterwards', async () => { + const d = deps(); + const controller = new AbortController(); + let late: unknown; + const sandbox: Sandbox = { + run: async (_code, opts) => { + controller.abort(); + late = await opts.onCall('write', { path: 'a.txt', content: 'x' }); + return { ok: false, kind: 'killed', error: { name: 'Killed', message: 'stopped' } }; + }, + }; + const result = await runScript({ code: 'x', transaction: false, timeoutMs: 5_000 }, { ...d, sandbox, signal: controller.signal }); + expect(result.error?.kind).toBe('cancelled'); + expect(late).toMatchObject({ ok: false, error: { code: 'cancelled' } }); + expect(d.tools.files.size).toBe(0); + }); + + it('refuses calls that arrive after the script returned', async () => { + const d = deps(); + let call: ((tool: string, args: unknown) => Promise) | undefined; + const sandbox: Sandbox = { + run: async (_code, opts) => { + call = opts.onCall; + return { ok: true, value: 1 }; + }, + }; + const result = await runScript({ code: 'x', transaction: false, timeoutMs: 5_000 }, { ...d, sandbox }); + expect(result).toMatchObject({ ok: true, result: 1 }); + expect(await call?.('write', { path: 'a.txt', content: 'x' })).toMatchObject({ ok: false, error: { code: 'cancelled' } }); + expect(d.tools.files.size).toBe(0); + }); + + it('denies every call when the policy fails to load', async () => { + const d = deps({ policyError: 'bad settings' }, { 'a.txt': 'x' }); + const result = await runScript({ code: script([{ tool: 'read', args: { path: 'a.txt' } }]), transaction: false, timeoutMs: 5_000 }, d); + expect(result.calls[0]).toMatchObject({ decision: 'denied' }); + expect(result.calls[0]?.reason).toContain('unsupported-config'); + }); + + it('never rejects when the sandbox throws', async () => { + const sandbox: Sandbox = { + run: () => { + throw new Error('spawn failed'); + }, + }; + const result = await runScript({ code: 'x', transaction: false, timeoutMs: 5_000 }, { ...deps(), sandbox }); + expect(result.error).toMatchObject({ kind: 'error', message: 'spawn failed' }); + }); +}); diff --git a/src/core/run.ts b/src/core/run.ts new file mode 100644 index 0000000..a9a70bd --- /dev/null +++ b/src/core/run.ts @@ -0,0 +1,251 @@ +import { Dispatcher, type StopReason } from './dispatcher.js'; +import { errorMessage } from './errors.js'; +import { DEFAULT_RUN_TIMEOUT_MS, MAX_RUN_TIMEOUT_MS, type RunArgs } from './schemas.js'; +import type { + CallLogEntry, + HostAdapter, + LogLevel, + PolicyLoadError, + PolicySnapshot, + RollbackReport, + RunError, + RunRequest, + RunResult, + Sandbox, + SandboxOutcome, + SessionContext, + ToolRuntime, + Transaction, +} from './types.js'; + +/** Default heap limit of a script. */ +export const DEFAULT_MEMORY_BYTES = 256 * 1024 * 1024; +/** How long to wait for the sandbox to return after it was told to stop. */ +export const DEFAULT_STOP_GRACE_MS = 2_000; +const MAX_LOG_LINES = 5_000; +const MAX_LOG_CHARS = 1_000_000; + +export interface RunDeps

{ + readonly sandbox: Sandbox; + readonly adapter: HostAdapter

; + readonly tools: ToolRuntime

; + readonly ctx: SessionContext; + /** Aborted when the client cancels the `run` request. */ + readonly signal?: AbortSignal; + /** Server cap of the timeout (lower for hosts with short tool timeouts). Never above `MAX_RUN_TIMEOUT_MS`. */ + readonly maxTimeoutMs?: number; + readonly memoryBytes?: number; + /** Grace after a stop before the sandbox is considered killed. */ + readonly stopGraceMs?: number; +} + +/** Applies defaults and clamps the timeout to `[1, min(maxTimeoutMs, MAX_RUN_TIMEOUT_MS)]`. */ +export function resolveTimeoutMs(requested: number | undefined, maxTimeoutMs: number = MAX_RUN_TIMEOUT_MS): number { + const cap = Math.max(1, Math.min(MAX_RUN_TIMEOUT_MS, Math.floor(maxTimeoutMs))); + const wanted = requested === undefined || !Number.isFinite(requested) ? DEFAULT_RUN_TIMEOUT_MS : Math.floor(requested); + return Math.min(cap, Math.max(1, wanted)); +} + +/** Builds a `RunRequest` from validated `run` arguments. */ +export function toRunRequest(args: RunArgs, maxTimeoutMs?: number): RunRequest { + return { code: args.code, transaction: args.transaction ?? false, timeoutMs: resolveTimeoutMs(args.timeoutMs, maxTimeoutMs) }; +} + +class LogCollector { + readonly lines: string[] = []; + #chars = 0; + #dropped = 0; + + add(level: LogLevel, text: string): void { + const line = level === 'log' ? text : `${level}: ${text}`; + if (this.lines.length >= MAX_LOG_LINES || this.#chars + line.length > MAX_LOG_CHARS) { + this.#dropped++; + return; + } + this.#chars += line.length; + this.lines.push(line); + } + + finish(): string[] { + if (this.#dropped > 0) this.lines.push(`[${this.#dropped} more log lines dropped]`); + return this.lines; + } +} + +function waitOrGrace(promise: Promise, signal: AbortSignal, graceMs: number): Promise { + return new Promise((resolve) => { + let timer: NodeJS.Timeout | undefined; + const onAbort = (): void => { + timer = setTimeout( + () => + resolve({ + ok: false, + kind: 'killed', + error: { name: 'Killed', message: 'the sandbox did not stop in time after the run was stopped' }, + }), + graceMs, + ); + }; + if (signal.aborted) onAbort(); + else signal.addEventListener('abort', onAbort, { once: true }); + promise.then( + (outcome) => { + if (timer) clearTimeout(timer); + signal.removeEventListener('abort', onAbort); + resolve(outcome); + }, + (err: unknown) => { + if (timer) clearTimeout(timer); + signal.removeEventListener('abort', onAbort); + resolve({ ok: false, kind: 'error', error: { name: 'SandboxError', message: errorMessage(err) } }); + }, + ); + }); +} + +function runError(stopReason: StopReason | undefined, outcome: SandboxOutcome, denied: CallLogEntry | undefined, timeoutMs: number): RunError | undefined { + if (stopReason === 'denied') { + const what = denied ? `${denied.id} (${denied.summary}) was denied: ${denied.reason ?? ''}` : 'a call was denied'; + return { kind: 'denied', name: 'PermissionDenied', message: `transaction aborted: ${what}` }; + } + if (stopReason === 'cancelled') return { kind: 'cancelled', name: 'Cancelled', message: 'the run was cancelled by the client' }; + if (stopReason === 'timeout' || (!outcome.ok && outcome.kind === 'timeout')) { + return { kind: 'timeout', name: 'Timeout', message: `the script did not finish within ${timeoutMs} ms` }; + } + if (!outcome.ok) { + const { name, message, stack } = outcome.error; + return stack === undefined ? { kind: outcome.kind, name, message } : { kind: outcome.kind, name, message, stack }; + } + return undefined; +} + +/** + * Runs one script end to end: loads the policy, starts the transaction, + * runs the sandbox with the dispatcher behind its bindings, enforces the + * timeout and cancellation, rolls back on failure and builds the `RunResult`. + * Never rejects. + */ +export async function runScript

(req: RunRequest, deps: RunDeps

): Promise { + const timeoutMs = resolveTimeoutMs(req.timeoutMs, deps.maxTimeoutMs); + const graceMs = deps.stopGraceMs ?? DEFAULT_STOP_GRACE_MS; + const logs = new LogCollector(); + const controller = new AbortController(); + let stopReason: StopReason | undefined; + let dispatcher: Dispatcher

| undefined; + let denied: CallLogEntry | undefined; + let tx: Transaction | undefined; + + const stop = (reason: StopReason): void => { + if (stopReason !== undefined) return; + stopReason = reason; + controller.abort(reason); + void dispatcher?.stop(reason); + }; + const onExternalAbort = (): void => stop('cancelled'); + deps.signal?.addEventListener('abort', onExternalAbort, { once: true }); + if (deps.signal?.aborted) stop('cancelled'); + + let timer: NodeJS.Timeout | undefined; + try { + let policy: PolicySnapshot

| PolicyLoadError; + try { + policy = await deps.adapter.loadPolicy(deps.ctx); + } catch (err) { + policy = { error: errorMessage(err) }; + } + + if (req.transaction) tx = deps.tools.beginTransaction(); + dispatcher = new Dispatcher

({ + adapter: deps.adapter, + tools: deps.tools, + ctx: deps.ctx, + policy, + ...(tx ? { transaction: tx, onDeny: (entry: CallLogEntry) => ((denied = entry), stop('denied')) } : {}), + }); + const active = dispatcher; + if (stopReason !== undefined) void active.stop(stopReason); + + // Backup timer: the sandbox enforces `timeoutMs` itself; this fires only if it does not. + timer = setTimeout(() => stop('timeout'), timeoutMs + graceMs); + + let outcome: SandboxOutcome; + if (stopReason !== undefined) { + outcome = { ok: false, kind: 'killed', error: { name: 'Killed', message: 'the run was stopped before the script started' } }; + } else { + let started: Promise; + try { + started = deps.sandbox.run(req.code, { + timeoutMs, + memoryBytes: deps.memoryBytes ?? DEFAULT_MEMORY_BYTES, + signal: controller.signal, + onCall: (tool, args) => active.dispatch(tool, args), + onLog: (level, text) => logs.add(level, text), + }); + } catch (err) { + started = Promise.reject(err); + } + outcome = await waitOrGrace(started, controller.signal, graceMs); + } + clearTimeout(timer); + timer = undefined; + + // No call may start after the script ended; wait for in-flight ones. + await active.stop(stopReason ?? 'finished'); + + const error = runError(stopReason, outcome, denied, timeoutMs); + const warnings = [...active.warnings]; + let rolledBack: RollbackReport | undefined; + if (tx && error) { + try { + rolledBack = await tx.rollback(); + } catch (err) { + warnings.push(`rollback failed: ${errorMessage(err)}`); + } + if (active.bashCommits > 0) { + warnings.push(`${active.bashCommits} bash call(s) ran in this transaction; bash effects are never rolled back.`); + } + } + + const base = { + logs: logs.finish(), + calls: active.calls, + changedFiles: active.changedFiles, + diff: active.diff, + warnings, + ...(rolledBack ? { rolledBack } : {}), + }; + if (error) return { ok: false, error, ...base }; + return { ok: true, result: outcome.ok ? (outcome.value ?? null) : null, ...base }; + } catch (err) { + if (dispatcher) await dispatcher.stop(stopReason ?? 'finished'); + const warnings = dispatcher ? [...dispatcher.warnings] : []; + let rolledBack: RollbackReport | undefined; + if (tx) { + try { + rolledBack = await tx.rollback(); + } catch (rollbackErr) { + warnings.push(`rollback failed: ${errorMessage(rollbackErr)}`); + } + } + return { + ok: false, + error: { kind: 'internal', name: 'InternalError', message: errorMessage(err) }, + logs: logs.finish(), + calls: dispatcher?.calls ?? [], + changedFiles: dispatcher?.changedFiles ?? [], + diff: dispatcher?.diff ?? '', + warnings, + ...(rolledBack ? { rolledBack } : {}), + }; + } finally { + if (timer) clearTimeout(timer); + deps.signal?.removeEventListener('abort', onExternalAbort); + if (tx) { + try { + await tx.dispose(); + } catch { + // Disposing only releases the journal. + } + } + } +} diff --git a/src/core/schemas.test.ts b/src/core/schemas.test.ts new file mode 100644 index 0000000..cef9a3b --- /dev/null +++ b/src/core/schemas.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest'; +import { ToolError } from './errors.js'; +import { parseRunArgs, parseToolCall } from './schemas.js'; + +describe('parseToolCall', () => { + it('returns a typed call for valid args', () => { + expect(parseToolCall('edit', { path: 'a', oldString: 'x', newString: 'y' }, 'c1')).toEqual({ + id: 'c1', + tool: 'edit', + args: { path: 'a', oldString: 'x', newString: 'y' }, + }); + }); + + it.each([ + ['bash', { command: '' }], + ['bash', { command: 'ls', extra: 1 }], + ['read', { path: 'a', offset: 0 }], + ['read', { path: 'a\0b' }], + ['write', { path: 'a' }], + ['edit', { path: 'a', oldString: '', newString: 'x' }], + ['grep', { pattern: 'x', maxResults: 1.5 }], + ['glob', null], + ['read', ['a']], + ['__proto__', {}], + ])('rejects %s %j', (tool, args) => { + const r = parseToolCall(tool, args, 'c1'); + expect(r).toBeInstanceOf(ToolError); + expect(r instanceof ToolError && r.code).toBe('invalid-args'); + }); +}); + +describe('parseRunArgs', () => { + it('strips unknown fields including _ctx', () => { + const r = parseRunArgs({ code: 'return 1', _ctx: { permission_mode: 'bypassPermissions' }, transaction: true }); + expect(r).toEqual({ ok: true, value: { code: 'return 1', transaction: true } }); + }); + + it('rejects missing code and bad types', () => { + expect(parseRunArgs(undefined).ok).toBe(false); + expect(parseRunArgs({ code: 1 }).ok).toBe(false); + expect(parseRunArgs({ code: 'x', timeoutMs: -1 }).ok).toBe(false); + }); +}); diff --git a/src/core/schemas.ts b/src/core/schemas.ts new file mode 100644 index 0000000..248d5cf --- /dev/null +++ b/src/core/schemas.ts @@ -0,0 +1,181 @@ +import { z } from 'zod'; +import { ToolError } from './errors.js'; +import type { ToolArgsMap, ToolCall, ToolName } from './types.js'; + +/** + * Boundary schemas. Everything that crosses into the server (MCP request + * arguments, binding calls from the sandbox child, `updatedArgs` from hooks) + * is parsed here before internal code sees it. + */ + +/** Default `run` timeout. */ +export const DEFAULT_RUN_TIMEOUT_MS = 120_000; +/** Hard upper bound of the `run` timeout. */ +export const MAX_RUN_TIMEOUT_MS = 600_000; +/** Largest script accepted. */ +export const MAX_CODE_CHARS = 1_000_000; +/** Largest string accepted in a binding argument (file content, command). */ +export const MAX_ARG_CHARS = 20_000_000; + +export const TOOL_NAMES = ['bash', 'read', 'write', 'edit', 'grep', 'glob'] as const satisfies readonly ToolName[]; + +const MUTATING: ReadonlySet = new Set(['bash', 'write', 'edit']); + +/** Whether `tool` changes state (serialized per run). */ +export function isMutating(tool: ToolName): boolean { + return MUTATING.has(tool); +} + +/** Narrows an untrusted string to a `ToolName`. */ +export function isToolName(tool: string): tool is ToolName { + return (TOOL_NAMES as readonly string[]).includes(tool); +} + +const pathString = z + .string() + .min(1, 'must not be empty') + .max(4096) + .refine((s) => !s.includes('\0'), 'must not contain NUL characters'); + +const text = z.string().max(MAX_ARG_CHARS); +const positiveInt = (max: number) => z.number().int().min(1).max(max); + +// Tool args are strict: an unknown key (e.g. `file_path` instead of `path`) +// is an error the script author should see, not something silently dropped. + +export const BashArgsSchema = z.strictObject({ + command: text.min(1, 'must not be empty').refine((s) => !s.includes('\0'), 'must not contain NUL characters'), + cwd: pathString.optional(), + timeoutMs: positiveInt(MAX_RUN_TIMEOUT_MS).optional(), +}) satisfies z.ZodType; + +export const ReadArgsSchema = z.strictObject({ + path: pathString, + offset: positiveInt(Number.MAX_SAFE_INTEGER).optional(), + limit: positiveInt(1_000_000).optional(), +}) satisfies z.ZodType; + +export const WriteArgsSchema = z.strictObject({ + path: pathString, + content: text, +}) satisfies z.ZodType; + +export const EditArgsSchema = z.strictObject({ + path: pathString, + oldString: text.min(1, 'must not be empty'), + newString: text, + replaceAll: z.boolean().optional(), +}) satisfies z.ZodType; + +export const GrepArgsSchema = z.strictObject({ + pattern: z.string().min(1, 'must not be empty').max(10_000), + path: pathString.optional(), + glob: z.string().min(1).max(4096).optional(), + ignoreCase: z.boolean().optional(), + maxResults: positiveInt(100_000).optional(), +}) satisfies z.ZodType; + +export const GlobArgsSchema = z.strictObject({ + pattern: z.string().min(1, 'must not be empty').max(4096), + path: pathString.optional(), + maxResults: positiveInt(100_000).optional(), +}) satisfies z.ZodType; + +/** Args schema of each tool. */ +export const ToolArgsSchemas = { + bash: BashArgsSchema, + read: ReadArgsSchema, + write: WriteArgsSchema, + edit: EditArgsSchema, + grep: GrepArgsSchema, + glob: GlobArgsSchema, +} as const; + +function formatIssues(error: z.ZodError): string { + return error.issues + .map((issue) => { + const where = issue.path.length > 0 ? issue.path.join('.') : 'args'; + return `${where}: ${issue.message}`; + }) + .join('; '); +} + +/** + * Validates an untrusted binding call. Returns a typed `ToolCall` with the + * given id, or a `ToolError` (`invalid-args`) describing what is wrong. + */ +export function parseToolCall(tool: string, args: unknown, id: string): ToolCall | ToolError { + if (typeof tool !== 'string' || !isToolName(tool)) { + return new ToolError('invalid-args', `unknown tool ${JSON.stringify(String(tool)).slice(0, 80)}; expected one of ${TOOL_NAMES.join(', ')}`); + } + switch (tool) { + case 'bash': { + const r = BashArgsSchema.safeParse(args); + return r.success ? { id, tool, args: r.data } : new ToolError('invalid-args', `bash: ${formatIssues(r.error)}`); + } + case 'read': { + const r = ReadArgsSchema.safeParse(args); + return r.success ? { id, tool, args: r.data } : new ToolError('invalid-args', `read: ${formatIssues(r.error)}`); + } + case 'write': { + const r = WriteArgsSchema.safeParse(args); + return r.success ? { id, tool, args: r.data } : new ToolError('invalid-args', `write: ${formatIssues(r.error)}`); + } + case 'edit': { + const r = EditArgsSchema.safeParse(args); + return r.success ? { id, tool, args: r.data } : new ToolError('invalid-args', `edit: ${formatIssues(r.error)}`); + } + case 'grep': { + const r = GrepArgsSchema.safeParse(args); + return r.success ? { id, tool, args: r.data } : new ToolError('invalid-args', `grep: ${formatIssues(r.error)}`); + } + case 'glob': { + const r = GlobArgsSchema.safeParse(args); + return r.success ? { id, tool, args: r.data } : new ToolError('invalid-args', `glob: ${formatIssues(r.error)}`); + } + } +} + +/** + * Raw `run` tool arguments. Unknown keys (including any model-supplied + * `_ctx`) are stripped and never trusted. + */ +export const RunArgsSchema = z.object({ + code: z.string().min(1, 'must not be empty').max(MAX_CODE_CHARS), + transaction: z.boolean().optional(), + timeoutMs: z.number().int().min(1).optional(), +}); + +export type RunArgs = z.infer; + +/** JSON Schema of the `run` input, as announced in `tools/list`. */ +export const RUN_INPUT_JSON_SCHEMA: { + type: 'object'; + properties: Record; + required: string[]; +} = { + type: 'object', + properties: { + code: { + type: 'string', + description: + 'Body of an async JavaScript function. Use await with the bindings bash, read, write, edit, grep, glob; the return value is the result.', + }, + transaction: { + type: 'boolean', + description: 'Roll back file writes and edits if the script fails, times out or any call is denied. bash effects are never rolled back.', + }, + timeoutMs: { + type: 'integer', + minimum: 1, + description: `Script timeout in milliseconds (default ${DEFAULT_RUN_TIMEOUT_MS}, capped by the server).`, + }, + }, + required: ['code'], +}; + +/** Validates raw `run` arguments. */ +export function parseRunArgs(args: unknown): { ok: true; value: RunArgs } | { ok: false; message: string } { + const r = RunArgsSchema.safeParse(args ?? {}); + return r.success ? { ok: true, value: r.data } : { ok: false, message: formatIssues(r.error) }; +} diff --git a/src/core/state-dir.ts b/src/core/state-dir.ts new file mode 100644 index 0000000..f59c304 --- /dev/null +++ b/src/core/state-dir.ts @@ -0,0 +1,20 @@ +import { chmod, mkdir } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; + +/** + * Server state directory: `$XDG_STATE_HOME/agent-code-mode` when + * `XDG_STATE_HOME` is an absolute path, else `~/.local/state/agent-code-mode`. + */ +export function stateDirPath(env: Readonly> = process.env, home: string = os.homedir()): string { + const xdg = env['XDG_STATE_HOME']; + if (xdg !== undefined && xdg !== '' && path.isAbsolute(xdg)) return path.join(xdg, 'agent-code-mode'); + return path.join(home, '.local', 'state', 'agent-code-mode'); +} + +/** Creates the state directory with mode 0700 (and tightens it if it already existed). Returns its path. */ +export async function ensureStateDir(dir: string = stateDirPath()): Promise { + await mkdir(dir, { recursive: true, mode: 0o700 }); + if (process.platform !== 'win32') await chmod(dir, 0o700); + return dir; +} diff --git a/src/core/types.ts b/src/core/types.ts new file mode 100644 index 0000000..bc83bc6 --- /dev/null +++ b/src/core/types.ts @@ -0,0 +1,644 @@ +/** + * Frozen contracts shared by every part of agent-code-mode. + * + * The sandbox (src/sandbox), the host adapters (src/hosts/*), the tool runtime + * (src/tools) and the benchmark are built against these types without seeing + * each other. Changing a type here is a cross-part change: do it in its own PR. + * + * Pipeline for every binding call made by a script: + * sandbox → Dispatcher.dispatch(tool, args) + * 1. parse : `parseToolCall` validates the raw args (schemas.ts). + * 2. prepare : `ToolRuntime.prepare` resolves paths and computes the exact + * effect, with no side effect. Result is a deep-frozen + * `PreparedCall`. + * 3. authorize: `HostAdapter.checkStatic` (permission rules), then + * `HostAdapter.authorize` (the host's PreToolUse hooks). + * If a hook returns `updatedArgs`, the call is re-parsed, + * re-prepared and re-checked statically (hooks are not re-run). + * 4. commit : `ToolRuntime.commit` executes exactly the prepared effect, + * re-checking content hashes first. + */ + +/** Names of the bindings a script can call. */ +export type ToolName = 'bash' | 'read' | 'write' | 'edit' | 'grep' | 'glob'; + +/** Tools that change state. They are serialized per run, in call order. */ +export type MutatingToolName = 'bash' | 'write' | 'edit'; + +/** Tools that only read. They may run concurrently. */ +export type ReadOnlyToolName = 'read' | 'grep' | 'glob'; + +// --------------------------------------------------------------------------- +// Arguments, as the script passes them (camelCase). +// --------------------------------------------------------------------------- + +/** `bash(args)`: run a shell command. */ +export interface BashArgs { + /** Shell command line, run with the platform shell. */ + readonly command: string; + /** Working directory; relative paths resolve against the session cwd. Defaults to the session cwd. */ + readonly cwd?: string; + /** Per-command timeout in milliseconds. The tool runtime applies its default when absent. */ + readonly timeoutMs?: number; +} + +/** `read(args)`: read a text file. */ +export interface ReadArgs { + /** File path; relative paths resolve against the session cwd. */ + readonly path: string; + /** 1-based line number of the first line to return. Defaults to 1. */ + readonly offset?: number; + /** Maximum number of lines to return. The tool runtime applies its default when absent. */ + readonly limit?: number; +} + +/** `write(args)`: create or overwrite a file with the given content. */ +export interface WriteArgs { + /** File path; relative paths resolve against the session cwd. */ + readonly path: string; + /** Full new content of the file. */ + readonly content: string; +} + +/** `edit(args)`: replace text in an existing file. */ +export interface EditArgs { + /** File path; relative paths resolve against the session cwd. */ + readonly path: string; + /** Text to find. Must be non-empty. */ + readonly oldString: string; + /** Replacement text. */ + readonly newString: string; + /** Replace every occurrence instead of requiring exactly one. Defaults to false. */ + readonly replaceAll?: boolean; +} + +/** `grep(args)`: search file contents with a regular expression. */ +export interface GrepArgs { + /** Regular expression (the tool runtime documents the dialect). */ + readonly pattern: string; + /** File or directory to search. Defaults to the session cwd. */ + readonly path?: string; + /** Glob that filters which files are searched, e.g. `*.ts`. */ + readonly glob?: string; + /** Case-insensitive match. Defaults to false. */ + readonly ignoreCase?: boolean; + /** Maximum number of matches returned. The tool runtime applies its default when absent. */ + readonly maxResults?: number; +} + +/** `glob(args)`: list files matching a glob pattern. */ +export interface GlobArgs { + /** Glob pattern, e.g. `src/**\/*.ts`. */ + readonly pattern: string; + /** Directory to search from. Defaults to the session cwd. */ + readonly path?: string; + /** Maximum number of files returned. The tool runtime applies its default when absent. */ + readonly maxResults?: number; +} + +/** Maps each tool to its argument type. */ +export interface ToolArgsMap { + readonly bash: BashArgs; + readonly read: ReadArgs; + readonly write: WriteArgs; + readonly edit: EditArgs; + readonly grep: GrepArgs; + readonly glob: GlobArgs; +} + +/** + * A validated binding call. `id` is assigned by the dispatcher in call order: + * `c1`, `c2`, ... It is unique within one run. + */ +export type ToolCall = { + [K in ToolName]: { readonly id: string; readonly tool: K; readonly args: ToolArgsMap[K] }; +}[ToolName]; + +// --------------------------------------------------------------------------- +// Results, as the script receives them. +// --------------------------------------------------------------------------- + +/** Result of `bash`. A non-zero exit code is a result, not an error. */ +export interface BashResult { + /** Exit code, or null when the process was killed by a signal. */ + readonly exitCode: number | null; + /** Signal name that killed the process, or null. */ + readonly signal: string | null; + readonly stdout: string; + readonly stderr: string; + /** True when stdout or stderr was cut to the tool runtime's cap. */ + readonly truncated: boolean; + /** True when the command hit its timeout and was killed. */ + readonly timedOut: boolean; +} + +/** Result of `read`. */ +export interface ReadResult { + /** Absolute real path that was read. */ + readonly path: string; + /** The returned lines, joined with `\n`. */ + readonly content: string; + /** 1-based line number of the first returned line. */ + readonly startLine: number; + /** Number of lines in the whole file. */ + readonly totalLines: number; + /** True when lines after the returned window exist or long lines were cut. */ + readonly truncated: boolean; +} + +/** Result of `write`. */ +export interface WriteResult { + /** Absolute real path that was written. */ + readonly path: string; + /** True when the file did not exist before. */ + readonly created: boolean; + /** Unified diff of the change. */ + readonly diff: string; +} + +/** + * How `edit` located `oldString`. `exact` is a byte-for-byte match; the other + * strategies are tolerant fallbacks the tool runtime may implement. + */ +export type MatchStrategy = 'exact' | 'line-trimmed' | 'whitespace-normalized' | 'indentation-flexible'; + +/** Result of `edit`. */ +export interface EditResult { + /** Absolute real path that was edited. */ + readonly path: string; + /** Number of occurrences replaced. */ + readonly replacements: number; + readonly matchStrategy: MatchStrategy; + /** Unified diff of the change. */ + readonly diff: string; +} + +/** One `grep` match. */ +export interface GrepMatch { + /** Absolute real path of the file. */ + readonly file: string; + /** 1-based line number. */ + readonly line: number; + /** The matching line (may be cut by the tool runtime). */ + readonly text: string; +} + +/** Result of `grep`. */ +export interface GrepResult { + readonly matches: readonly GrepMatch[]; + /** True when more matches existed than were returned. */ + readonly truncated: boolean; +} + +/** Result of `glob`. */ +export interface GlobResult { + /** Absolute real paths. */ + readonly files: readonly string[]; + /** True when more files existed than were returned. */ + readonly truncated: boolean; +} + +/** Maps each tool to its result type. */ +export interface ToolResultMap { + readonly bash: BashResult; + readonly read: ReadResult; + readonly write: WriteResult; + readonly edit: EditResult; + readonly grep: GrepResult; + readonly glob: GlobResult; +} + +/** Any tool result. */ +export type ToolResult = ToolResultMap[ToolName]; + +// --------------------------------------------------------------------------- +// Prepared calls: the exact effect that is authorized and then committed. +// --------------------------------------------------------------------------- + +/** + * How `bash` is contained. `none` runs the command directly. `sandbox` runs it + * inside an OS sandbox that the tool runtime must enforce: if it cannot, + * `prepare` must throw `ToolError('containment-unavailable')`. + */ +export type BashContainment = + | { readonly mode: 'none' } + | { + readonly mode: 'sandbox'; + /** No writes at all when true; `writableRoots` is then ignored. */ + readonly readOnly: boolean; + /** Absolute directories the command may write to. */ + readonly writableRoots: readonly string[]; + /** Whether network access is allowed. */ + readonly network: boolean; + }; + +/** Effect of a `bash` call. */ +export interface BashEffect { + readonly command: string; + /** Absolute real working directory. */ + readonly cwd: string; + /** Effective timeout in milliseconds. */ + readonly timeoutMs: number; + /** Containment the tool runtime will enforce; must equal the policy's `bashContainment`. */ + readonly containment: BashContainment; +} + +/** Effect of a `read` call. */ +export interface ReadEffect { + readonly absPath: string; + /** Effective 1-based offset. */ + readonly offset: number; + /** Effective line limit. */ + readonly limit: number; +} + +/** Effect of a `write` call. */ +export interface WriteEffect { + readonly absPath: string; + /** SHA-256 hex of the current content, or null when the file does not exist. */ + readonly beforeHash: string | null; + readonly afterContent: string; + /** Unified diff between the current and the new content. */ + readonly diff: string; +} + +/** Effect of an `edit` call, computed against the current file content. */ +export interface EditEffect { + readonly absPath: string; + /** SHA-256 hex of the content the edit was computed against. */ + readonly beforeHash: string; + readonly afterContent: string; + readonly diff: string; + /** The exact text that was matched in the file (may differ from `oldString` with tolerant strategies). */ + readonly matchedOldString: string; + readonly matchStrategy: MatchStrategy; + readonly replacements: number; +} + +/** Effect of a `grep` call. */ +export interface GrepEffect { + /** Absolute real file or directory searched. */ + readonly absRoot: string; + readonly pattern: string; + readonly glob: string | null; + readonly ignoreCase: boolean; + readonly maxResults: number; +} + +/** Effect of a `glob` call. */ +export interface GlobEffect { + /** Absolute real directory searched from. */ + readonly absRoot: string; + readonly pattern: string; + readonly maxResults: number; +} + +/** Maps each tool to its effect type. */ +export interface ToolEffectMap { + readonly bash: BashEffect; + readonly read: ReadEffect; + readonly write: WriteEffect; + readonly edit: EditEffect; + readonly grep: GrepEffect; + readonly glob: GlobEffect; +} + +/** + * A call after `ToolRuntime.prepare`: validated, normalized args (paths are + * absolute real paths inside the workspace) plus the exact effect. The + * dispatcher deep-freezes it; nobody may mutate it. + * + * What a host adapter shows to the host's hooks (the native-shaped payload, + * e.g. Claude `Write {file_path, content}` or Codex `apply_patch {command}`) + * is NOT part of this type: each adapter derives it from the `PreparedCall`, + * so the adapter owns that mapping. The payload shown must describe exactly + * the effect here. + */ +export type PreparedCall = { + [K in ToolName]: { + readonly id: string; + readonly tool: K; + readonly args: ToolArgsMap[K]; + readonly effect: ToolEffectMap[K]; + }; +}[ToolName]; + +/** A `PreparedCall` narrowed to one tool. */ +export type PreparedCallOf = Extract; + +// --------------------------------------------------------------------------- +// Session context and policy. +// --------------------------------------------------------------------------- + +/** Which host started the server. */ +export type HostKind = 'claude' | 'codex' | 'generic'; + +/** Where a `SessionContext` field came from. `default` means it was unknown and a conservative default was used. */ +export type ContextSource = 'env' | 'meta' | 'roots' | 'ctx-file' | 'default'; + +/** + * Who is calling and from where. Built only from host-controlled channels: + * env, request `_meta`, MCP roots and the companion-hook context file. Fields + * the model controls (tool arguments, including any `_ctx`) never reach it. + */ +export interface SessionContext { + readonly host: HostKind; + /** Absolute workspace directory; relative paths resolve against it. */ + readonly cwd: string; + /** Absolute workspace roots announced by the client. */ + readonly roots: readonly string[]; + readonly sessionId?: string; + readonly transcriptPath?: string; + /** Host permission mode, e.g. Claude `default`, `acceptEdits`, `plan`. Unknown → `default`. */ + readonly permissionMode: string; + /** Subagent id when called from a subagent (Claude). */ + readonly agentId?: string; + /** Subagent type when called from a subagent (Claude). */ + readonly agentType?: string; + /** Host tool-use id of the `run` call (Claude `claudecode/toolUseId`). */ + readonly toolUseId?: string; + /** Host turn id (Codex). */ + readonly turnId?: string; + readonly model?: string; + /** Host sandbox mode (Codex `sandbox_mode`, e.g. `read-only`). */ + readonly sandboxMode?: string; + /** Source of each field that was set, keyed by field name. */ + readonly sources: Readonly>; +} + +/** Why a call was denied. */ +export type DenySource = + | 'rule' + | 'hook' + | 'hook-error' + | 'hook-timeout' + | 'unsupported-config' + | 'ask-unavailable' + | 'containment-unavailable'; + +/** + * An authorization decision. + * - `allow` with `updatedArgs`: a hook rewrote the call. `updatedArgs` is in + * this project's camelCase args shape for the same tool (the adapter maps + * from the host's native shape). It is untrusted: the dispatcher re-validates, + * re-prepares and re-checks it statically. + * - `ask`: the host would prompt the user. Without an interactive channel the + * dispatcher turns it into `deny` with source `ask-unavailable`. + */ +export type Decision = + | { readonly kind: 'allow'; readonly updatedArgs?: unknown; readonly reason?: string } + | { readonly kind: 'deny'; readonly reason: string; readonly source: DenySource } + | { readonly kind: 'ask'; readonly reason: string }; + +/** + * The host policy loaded once per run. `payload` is adapter-specific and + * opaque to the dispatcher. + */ +export interface PolicySnapshot

{ + readonly host: HostKind; + /** Containment the tool runtime must enforce on every `bash` call. */ + readonly bashContainment: BashContainment; + /** + * Absolute path patterns the script must never write or edit: host policy + * and hook files (e.g. `/.claude/settings*.json`, `/.claude/hooks/**`, + * `/.claude/**`, `/.codex/**`, `/.codex/**`, `/.mcp.json`) + * and the server state dir. `*` matches inside one path segment, `**` any + * depth (see `matchesPathPattern`). The adapter returns its host's list; the + * tool runtime refuses writes and edits there with `ToolError('protected-path')`. + */ + readonly protectedPaths: readonly string[]; + readonly payload: P; +} + +/** Returned by `HostAdapter.loadPolicy` when the host config cannot be understood. Every call is then denied with `unsupported-config`. */ +export interface PolicyLoadError { + readonly error: string; +} + +/** Input of `ContextProvider.resolve`. `meta` is the raw, unvalidated request `_meta`. */ +export interface ContextInput { + readonly env: Readonly>; + readonly meta: unknown; + readonly roots: readonly string[]; + readonly serverCwd: string; +} + +/** Builds the `SessionContext` of one `run` call from host channels. */ +export interface ContextProvider { + resolve(input: ContextInput): Promise; +} + +/** + * A record written by the companion PreToolUse hook (Claude) for one `run` + * call, keyed by the host's tool-use id. Fields mirror the hook input. + */ +export interface HookContextRecord { + readonly sessionId: string; + readonly toolUseId: string; + readonly cwd?: string; + readonly transcriptPath?: string; + readonly permissionMode?: string; + readonly agentId?: string; + readonly agentType?: string; +} + +/** + * Reads companion-hook context records. The implementation (P2) validates the + * file at the boundary and returns undefined when there is no valid record. + */ +export interface HookContextStore { + lookup(toolUseId: string): Promise; +} + +/** + * Host adapter: reproduces how the host authorizes a native tool call. + * Implementations must be fail-closed: an error in a hook is a deny. + */ +export interface HostAdapter

{ + readonly host: HostKind; + /** Loads the host's permission rules and hooks for this context. */ + loadPolicy(ctx: SessionContext): Promise | PolicyLoadError>; + /** + * The host's static permission rules (deny → ask → allow) applied to the + * prepared call. `allow` means "no rule denies or asks". Must not do I/O. + */ + checkStatic(prepared: PreparedCall, ctx: SessionContext, policy: PolicySnapshot

): Decision; + /** + * Runs the host's PreToolUse hooks on the prepared call. Must honor + * `signal` (kill running hooks). Only called after `checkStatic` allowed. + */ + authorize( + prepared: PreparedCall, + ctx: SessionContext, + policy: PolicySnapshot

, + signal: AbortSignal, + ): Promise; + /** Optional PostToolUse hooks. Errors are reported as warnings, never change the result. */ + postToolUse?( + prepared: PreparedCall, + result: ToolResult, + ctx: SessionContext, + policy: PolicySnapshot

, + ): Promise; +} + +/** Outcome of rolling back a transaction. */ +export interface RollbackReport { + /** Absolute paths restored to their content before the run (or deleted when they did not exist). */ + readonly restored: readonly string[]; + /** Files not restored, with the reason. `changed-externally`: the file no longer holds what this run wrote. */ + readonly skipped: readonly { readonly path: string; readonly reason: 'changed-externally' | 'error'; readonly detail?: string }[]; +} + +/** A per-run journal of file writes and edits. */ +export interface Transaction { + /** Restores every journaled file whose content is still what this run wrote. */ + rollback(): Promise; + /** Releases the journal (keeps the changes). Idempotent. */ + dispose(): Promise; +} + +/** Executes tool calls. Implemented by src/tools (P4) and `MemoryToolRuntime` (tests). */ +export interface ToolRuntime

{ + /** + * Validates semantics, resolves paths to absolute real paths inside the + * workspace, refuses protected paths, and computes the exact effect against + * the current file content. No side effect. Throws `ToolError` on refusal. + * The returned call keeps `call.id` and `call.tool`. + */ + prepare(call: ToolCall, ctx: SessionContext, policy: PolicySnapshot

): Promise; + /** + * Executes exactly `prepared.effect`. For write/edit it first re-checks + * `beforeHash` and throws `ToolError('stale')` if the file changed. When + * `tx` is given, file changes are journaled in it. Must honor `signal`: + * not start when already aborted, and stop a running `bash`. + */ + commit(prepared: PreparedCall, signal: AbortSignal, tx?: Transaction): Promise; + /** Starts a journal for one transactional run. */ + beginTransaction(): Transaction; +} + +// --------------------------------------------------------------------------- +// Sandbox. +// --------------------------------------------------------------------------- + +/** Console level of a script log line. */ +export type LogLevel = 'log' | 'info' | 'warn' | 'error'; + +/** Code of a `BindingError`. */ +export type BindingErrorCode = + | 'denied' + | 'invalid-args' + | 'outside-workspace' + | 'protected-path' + | 'not-found' + | 'stale' + | 'cancelled' + | 'tool-error'; + +/** + * Serialized error of a failed binding call. The sandbox (P1) rehydrates it as + * a rejected Promise with an `Error` whose `name` is `PermissionDenied` + * (carrying `source` and `reason` = `message`) or `ToolError` (carrying `code`). + */ +export type BindingError = + | { readonly name: 'PermissionDenied'; readonly message: string; readonly code: 'denied'; readonly source: DenySource } + | { readonly name: 'ToolError'; readonly message: string; readonly code: Exclude }; + +/** Reply to one binding call. Never thrown: the dispatcher always resolves. */ +export type CallReply = + | { readonly ok: true; readonly value: ToolResult } + | { readonly ok: false; readonly error: BindingError }; + +/** Options of `Sandbox.run`. */ +export interface SandboxRunOptions { + /** Wall-clock limit; the sandbox kills the script when it is reached. */ + readonly timeoutMs: number; + /** Memory limit of the script heap. */ + readonly memoryBytes: number; + /** Aborting it kills the script (cancel, timeout, transaction abort). */ + readonly signal: AbortSignal; + /** + * Called for every binding call. `tool` and `args` come from the script and + * are untrusted. Always resolves. + */ + onCall(tool: string, args: unknown): Promise; + /** Called for every console line of the script. */ + onLog(level: LogLevel, text: string): void; +} + +/** Serialized script error. */ +export interface ScriptError { + readonly name: string; + readonly message: string; + readonly stack?: string; +} + +/** + * What a script run ended with. `value` is the script's `return` value as + * plain JSON data (the sandbox converts it). + */ +export type SandboxOutcome = + | { readonly ok: true; readonly value: unknown } + | { readonly ok: false; readonly kind: 'error' | 'timeout' | 'oom' | 'killed'; readonly error: ScriptError }; + +/** Runs a script body as an async function with the bindings as globals. */ +export interface Sandbox { + run(code: string, opts: SandboxRunOptions): Promise; +} + +// --------------------------------------------------------------------------- +// Run request and result. +// --------------------------------------------------------------------------- + +/** A validated `run` request with defaults applied. */ +export interface RunRequest { + /** Script body (JavaScript). */ + readonly code: string; + /** Roll back file changes on error, timeout, cancel or any denied call. */ + readonly transaction: boolean; + /** Effective timeout in milliseconds, already clamped. */ + readonly timeoutMs: number; +} + +/** One entry of the call log returned to the model. */ +export interface CallLogEntry { + readonly id: string; + /** The tool name as the script passed it (may be unknown). */ + readonly tool: string; + /** Short human-readable description, e.g. `write src/a.ts`. */ + readonly summary: string; + readonly decision: 'allowed' | 'denied' | 'error'; + readonly reason?: string; + readonly durationMs: number; +} + +/** Error part of a failed `RunResult`. */ +export interface RunError { + readonly name: string; + readonly message: string; + readonly stack?: string; + /** What ended the run. */ + readonly kind: 'error' | 'timeout' | 'oom' | 'killed' | 'cancelled' | 'denied' | 'internal'; +} + +/** The result of one `run`. */ +export interface RunResult { + readonly ok: boolean; + /** The script's return value when `ok`. */ + readonly result?: unknown; + readonly error?: RunError; + /** Console output, one entry per line, prefixed with the level when not `log`. */ + readonly logs: readonly string[]; + readonly calls: readonly CallLogEntry[]; + /** Files written or edited by committed calls (paths relative to the session cwd when inside it). */ + readonly changedFiles: readonly string[]; + /** Combined unified diff of committed writes and edits, in commit order. */ + readonly diff: string; + /** Present when a transaction was rolled back. */ + readonly rolledBack?: RollbackReport; + /** Notes the model must know, e.g. bash effects that were not rolled back. */ + readonly warnings: readonly string[]; + /** Set by output shaping when the full result was written to a file. */ + readonly overflowPath?: string; +} diff --git a/src/server/context.test.ts b/src/server/context.test.ts new file mode 100644 index 0000000..8696655 --- /dev/null +++ b/src/server/context.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest'; +import type { HookContextRecord, HookContextStore } from '../core/types.js'; +import { ClaudeContextProvider, CodexContextProvider, GenericContextProvider, detectHost } from './context.js'; + +const store = (record: HookContextRecord | undefined): HookContextStore => ({ lookup: async () => record }); + +describe('context providers', () => { + it('Claude: falls back to conservative defaults', async () => { + const ctx = await new ClaudeContextProvider().resolve({ env: {}, meta: 'garbage', roots: [], serverCwd: '/srv' }); + expect(ctx).toMatchObject({ host: 'claude', cwd: '/srv', permissionMode: 'default', sources: { cwd: 'default', permissionMode: 'default' } }); + expect(ctx.sessionId).toBeUndefined(); + }); + + it('Claude: ignores invalid meta values', async () => { + const ctx = await new ClaudeContextProvider().resolve({ env: {}, meta: { 'claudecode/toolUseId': 123 }, roots: ['/ws'], serverCwd: '/srv' }); + expect(ctx.toolUseId).toBeUndefined(); + expect(ctx.cwd).toBe('/ws'); + }); + + it('Claude: uses a companion-hook record only for the same call and session', async () => { + const record: HookContextRecord = { sessionId: 's1', toolUseId: 't1', permissionMode: 'acceptEdits', agentId: 'a1', agentType: 'helper', cwd: '/ws/sub' }; + const input = { env: { CLAUDE_CODE_SESSION_ID: 's1' }, meta: { 'claudecode/toolUseId': 't1' }, roots: ['/ws'], serverCwd: '/srv' }; + const good = await new ClaudeContextProvider(store(record)).resolve(input); + expect(good).toMatchObject({ permissionMode: 'acceptEdits', agentId: 'a1', cwd: '/ws/sub', sources: { permissionMode: 'ctx-file' } }); + + const otherSession = await new ClaudeContextProvider(store({ ...record, sessionId: 's2' })).resolve(input); + expect(otherSession.permissionMode).toBe('default'); + const otherCall = await new ClaudeContextProvider(store({ ...record, toolUseId: 't2' })).resolve(input); + expect(otherCall.permissionMode).toBe('default'); + const outsideRoots = await new ClaudeContextProvider(store({ ...record, cwd: '/elsewhere' })).resolve(input); + expect(outsideRoots.cwd).toBe('/ws'); + const throwing = await new ClaudeContextProvider({ lookup: () => Promise.reject(new Error('io')) }).resolve(input); + expect(throwing.permissionMode).toBe('default'); + }); + + it('Codex: reads turn metadata and drops malformed fields', async () => { + const ctx = await new CodexContextProvider().resolve({ + env: {}, + meta: { sessionId: 's', 'x-codex-turn-metadata': { turn_id: 't', model: 7, sandbox_mode: 'workspace-write' } }, + roots: [], + serverCwd: '/srv', + }); + expect(ctx).toMatchObject({ host: 'codex', sessionId: 's', turnId: 't', sandboxMode: 'workspace-write', cwd: '/srv' }); + expect(ctx.model).toBeUndefined(); + }); + + it('Generic: ignores relative roots', async () => { + const ctx = await new GenericContextProvider().resolve({ env: {}, meta: undefined, roots: ['relative', '/ws'], serverCwd: '/srv' }); + expect(ctx.cwd).toBe('/ws'); + }); + + it('detectHost: flag, then Claude env, then Codex meta, then generic', () => { + expect(detectHost({ flag: 'codex', env: { CLAUDE_CODE_SESSION_ID: 'x' }, meta: {} })).toBe('codex'); + expect(detectHost({ env: { CLAUDE_CODE_SESSION_ID: 'x' }, meta: {} })).toBe('claude'); + expect(detectHost({ env: {}, meta: { 'x-codex-turn-metadata': {} } })).toBe('codex'); + expect(detectHost({ env: {}, meta: { 'x-codex-turn-metadata': 'str' } })).toBe('generic'); + expect(detectHost({ env: {}, meta: null })).toBe('generic'); + }); +}); diff --git a/src/server/context.ts b/src/server/context.ts new file mode 100644 index 0000000..b3376f1 --- /dev/null +++ b/src/server/context.ts @@ -0,0 +1,152 @@ +import path from 'node:path'; +import { z } from 'zod'; +import type { ContextInput, ContextProvider, ContextSource, HookContextStore, HostKind, SessionContext } from '../core/types.js'; + +/** + * Context providers. They read only host-controlled channels (env, request + * `_meta`, MCP roots, the companion-hook context file) and validate each one + * here, at the boundary. Unknown fields fall back to conservative defaults. + */ + +const id = z.string().min(1).max(512); + +/** `_meta` fields Claude Code sends on `tools/call`. */ +export const ClaudeMetaSchema = z.object({ + 'claudecode/toolUseId': id.optional().catch(undefined), +}); + +/** `_meta["x-codex-turn-metadata"]` as Codex CLI sends it. */ +export const CodexTurnMetadataSchema = z.object({ + session_id: id.optional().catch(undefined), + turn_id: id.optional().catch(undefined), + model: id.optional().catch(undefined), + sandbox_mode: id.optional().catch(undefined), +}); + +/** `_meta` fields Codex CLI sends on `tools/call`. */ +export const CodexMetaSchema = z.object({ + sessionId: id.optional().catch(undefined), + 'x-codex-turn-metadata': CodexTurnMetadataSchema.optional().catch(undefined), +}); + +const DEFAULT_PERMISSION_MODE = 'default'; + +function metaObject(meta: unknown): Record { + return meta !== null && typeof meta === 'object' && !Array.isArray(meta) ? Object.fromEntries(Object.entries(meta)) : {}; +} + +function isInside(child: string, parent: string): boolean { + const rel = path.relative(parent, child); + return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel)); +} + +class Builder { + readonly fields: Record = {}; + readonly sources: Record = {}; + + set(field: string, value: string | undefined, source: ContextSource): void { + if (value === undefined || this.fields[field] !== undefined) return; + this.fields[field] = value; + this.sources[field] = source; + } + + build(host: HostKind, roots: readonly string[], fallbackCwd: string): SessionContext { + this.set('cwd', fallbackCwd, 'default'); + this.set('permissionMode', DEFAULT_PERMISSION_MODE, 'default'); + const f = this.fields; + const optional = (key: string): Record => (f[key] === undefined ? {} : { [key]: f[key] }); + return { + host, + cwd: f['cwd'] ?? fallbackCwd, + roots: [...roots], + permissionMode: f['permissionMode'] ?? DEFAULT_PERMISSION_MODE, + ...optional('sessionId'), + ...optional('transcriptPath'), + ...optional('agentId'), + ...optional('agentType'), + ...optional('toolUseId'), + ...optional('turnId'), + ...optional('model'), + ...optional('sandboxMode'), + sources: { ...this.sources }, + }; + } +} + +function absoluteRoots(roots: readonly string[]): string[] { + return roots.filter((r) => path.isAbsolute(r)); +} + +/** Claude Code: session id from env, tool-use id from `_meta`, the rest from the companion-hook record when present. */ +export class ClaudeContextProvider implements ContextProvider { + constructor(private readonly store?: HookContextStore) {} + + async resolve(input: ContextInput): Promise { + const b = new Builder(); + const roots = absoluteRoots(input.roots); + const envSession = input.env['CLAUDE_CODE_SESSION_ID']; + const sessionId = envSession !== undefined && id.safeParse(envSession).success ? envSession : undefined; + b.set('sessionId', sessionId, 'env'); + const meta = ClaudeMetaSchema.parse(metaObject(input.meta)); + const toolUseId = meta['claudecode/toolUseId']; + b.set('toolUseId', toolUseId, 'meta'); + + if (toolUseId !== undefined && this.store) { + let record; + try { + record = await this.store.lookup(toolUseId); + } catch { + record = undefined; + } + // Only a record for this exact call and session is trusted. + if (record && record.toolUseId === toolUseId && (sessionId === undefined || record.sessionId === sessionId)) { + b.set('sessionId', record.sessionId, 'ctx-file'); + if (record.cwd !== undefined && path.isAbsolute(record.cwd) && (roots.length === 0 || roots.some((r) => isInside(record.cwd ?? '', r)))) { + b.set('cwd', record.cwd, 'ctx-file'); + } + b.set('transcriptPath', record.transcriptPath, 'ctx-file'); + b.set('permissionMode', record.permissionMode, 'ctx-file'); + b.set('agentId', record.agentId, 'ctx-file'); + b.set('agentType', record.agentType, 'ctx-file'); + } + } + b.set('cwd', roots[0], 'roots'); + return b.build('claude', roots, input.serverCwd); + } +} + +/** Codex CLI: session, turn, model and sandbox mode from `_meta`. */ +export class CodexContextProvider implements ContextProvider { + async resolve(input: ContextInput): Promise { + const b = new Builder(); + const roots = absoluteRoots(input.roots); + const meta = CodexMetaSchema.parse(metaObject(input.meta)); + const turn = meta['x-codex-turn-metadata']; + b.set('sessionId', turn?.session_id ?? meta.sessionId, 'meta'); + b.set('turnId', turn?.turn_id, 'meta'); + b.set('model', turn?.model, 'meta'); + b.set('sandboxMode', turn?.sandbox_mode, 'meta'); + b.set('cwd', roots[0], 'roots'); + return b.build('codex', roots, input.serverCwd); + } +} + +/** Any other client: cwd from roots, everything else default. */ +export class GenericContextProvider implements ContextProvider { + async resolve(input: ContextInput): Promise { + const b = new Builder(); + const roots = absoluteRoots(input.roots); + b.set('cwd', roots[0], 'roots'); + return b.build('generic', roots, input.serverCwd); + } +} + +/** Picks the host: explicit flag, else Claude env, else Codex `_meta`, else generic. */ +export function detectHost(input: { flag?: HostKind | undefined; env: Readonly>; meta: unknown }): HostKind { + if (input.flag) return input.flag; + const session = input.env['CLAUDE_CODE_SESSION_ID']; + if (session !== undefined && session !== '') return 'claude'; + const turn = metaObject(input.meta)['x-codex-turn-metadata']; + if (turn !== null && typeof turn === 'object' && !Array.isArray(turn)) return 'codex'; + return 'generic'; +} diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts new file mode 100644 index 0000000..0c0644f --- /dev/null +++ b/src/server/mcp.test.ts @@ -0,0 +1,161 @@ +import os from 'node:os'; +import { pathToFileURL } from 'node:url'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { CallToolResultSchema, ListRootsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; +import { afterEach, describe, expect, it } from 'vitest'; +import type { SessionContext } from '../core/types.js'; +import { FakeSandbox } from '../testing/fake-sandbox.js'; +import { MemoryToolRuntime } from '../testing/memory-tool-runtime.js'; +import { StaticHostAdapter } from '../testing/static-host-adapter.js'; +import { ClaudeContextProvider, CodexContextProvider, GenericContextProvider } from './context.js'; +import { createMcpServer } from './mcp.js'; +import type { Runtime } from './runtime.js'; + +const root = os.tmpdir(); +const closers: (() => Promise)[] = []; +afterEach(async () => { + await Promise.all(closers.splice(0).map((c) => c())); +}); + +async function connect(opts: { env?: Record; host?: 'claude' | 'codex' | 'generic' } = {}) { + const seen: SessionContext[] = []; + const tools = new MemoryToolRuntime({ root, files: { 'notes.txt': 'hello\n' } }); + const adapter = new StaticHostAdapter({ + rules: [ + (p, ctx) => { + seen.push(ctx); + return p.tool === 'bash' && p.effect.command.startsWith('rm ') ? { kind: 'deny', reason: 'rm is not allowed' } : undefined; + }, + ], + }); + const runtime = (host: 'claude' | 'codex' | 'generic'): Runtime => ({ + host, + contextProvider: host === 'claude' ? new ClaudeContextProvider() : host === 'codex' ? new CodexContextProvider() : new GenericContextProvider(), + adapter, + tools, + sandbox: new FakeSandbox(), + maxTimeoutMs: 10_000, + }); + const server = createMcpServer({ + version: '0.0.0-test', + env: opts.env ?? {}, + serverCwd: root, + stateDir: `${root}/acm-test-state`, + createRuntime: runtime, + ...(opts.host ? { host: opts.host } : {}), + }); + const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { roots: {} } }); + client.setRequestHandler(ListRootsRequestSchema, () => ({ roots: [{ uri: pathToFileURL(root).href }] })); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + closers.push(async () => { + await client.close(); + await server.close(); + }); + return { client, tools, seen }; +} + +function textOf(result: unknown): string { + const parsed = CallToolResultSchema.parse(result); + const first = parsed.content[0]; + if (first?.type !== 'text') throw new Error('expected text content'); + return first.text; +} + +describe('MCP server', () => { + it('lists the run tool with annotations, _meta and instructions', async () => { + const { client } = await connect(); + const { tools } = await client.listTools(); + expect(tools).toHaveLength(1); + expect(tools[0]).toMatchObject({ + name: 'run', + annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, + _meta: { 'anthropic/alwaysLoad': true }, + inputSchema: { type: 'object', required: ['code'] }, + }); + expect(client.getInstructions()).toContain('bash({command'); + }); + + it('runs a script end to end: FakeSandbox → Dispatcher → StaticHostAdapter → MemoryToolRuntime, with one denied call', async () => { + const { client, tools } = await connect(); + const code = JSON.stringify([ + { tool: 'write', args: { path: 'out.txt', content: 'written\n' } }, + { tool: 'bash', args: { command: 'rm -rf /' } }, + { tool: 'read', args: { path: 'notes.txt' } }, + ]); + const result = await client.callTool({ name: 'run', arguments: { code } }); + expect(result.isError).toBe(false); + const body = JSON.parse(textOf(result)) as { + ok: boolean; + result: unknown[]; + calls: { id: string; decision: string; reason?: string }[]; + changedFiles: string[]; + diff: string; + }; + expect(body.ok).toBe(true); + expect(body.calls.map((c) => [c.id, c.decision])).toEqual([ + ['c1', 'allowed'], + ['c2', 'denied'], + ['c3', 'allowed'], + ]); + expect(body.calls[1]?.reason).toBe('rule: rm is not allowed'); + expect(body.result[1]).toMatchObject({ error: { name: 'PermissionDenied', source: 'rule' } }); + expect(body.result[2]).toMatchObject({ content: 'hello\n' }); + expect(body.changedFiles).toHaveLength(1); + expect(body.changedFiles[0]).toMatch(/out\.txt$/); + expect(body.diff).toContain('+written'); + expect(tools.read('out.txt')).toBe('written\n'); + expect(tools.commits.some((c) => c.tool === 'bash')).toBe(false); + }); + + it('rolls back a transaction when a call is denied and reports isError', async () => { + const { client, tools } = await connect(); + const code = JSON.stringify([ + { tool: 'write', args: { path: 'out.txt', content: 'x' } }, + { tool: 'bash', args: { command: 'rm -rf /' } }, + ]); + const result = await client.callTool({ name: 'run', arguments: { code, transaction: true } }); + expect(result.isError).toBe(true); + expect(JSON.parse(textOf(result))).toMatchObject({ ok: false, error: { kind: 'denied' }, rolledBack: { restored: [expect.stringContaining('out.txt')] } }); + expect(tools.read('out.txt')).toBeUndefined(); + }); + + it('ignores a model-supplied _ctx and builds the context from host channels only', async () => { + const { client, seen } = await connect({ env: { CLAUDE_CODE_SESSION_ID: 'session-from-env' } }); + const code = JSON.stringify([{ tool: 'write', args: { path: 'a.txt', content: '' } }]); + await client.callTool({ + name: 'run', + arguments: { code, _ctx: { permission_mode: 'bypassPermissions', session_id: 'forged' } }, + _meta: { 'claudecode/toolUseId': 'toolu_test_1' }, + }); + expect(seen[0]).toMatchObject({ + host: 'claude', + sessionId: 'session-from-env', + toolUseId: 'toolu_test_1', + permissionMode: 'default', + cwd: root, + sources: { sessionId: 'env', toolUseId: 'meta', permissionMode: 'default', cwd: 'roots' }, + }); + }); + + it('detects Codex from _meta', async () => { + const { client, seen } = await connect(); + await client.callTool({ + name: 'run', + arguments: { code: JSON.stringify([{ tool: 'write', args: { path: 'a.txt', content: '' } }]) }, + _meta: { sessionId: 's1', 'x-codex-turn-metadata': { session_id: 's1', turn_id: 't1', model: 'm', sandbox_mode: 'read-only' } }, + }); + expect(seen[0]).toMatchObject({ host: 'codex', sessionId: 's1', turnId: 't1', model: 'm', sandboxMode: 'read-only' }); + }); + + it('returns isError for invalid arguments and unknown tools', async () => { + const { client } = await connect(); + const bad = await client.callTool({ name: 'run', arguments: { code: 42 } }); + expect(bad.isError).toBe(true); + expect(textOf(bad)).toContain('invalid run arguments'); + const unknown = await client.callTool({ name: 'nope', arguments: {} }); + expect(unknown.isError).toBe(true); + }); +}); diff --git a/src/server/mcp.ts b/src/server/mcp.ts new file mode 100644 index 0000000..0f50e41 --- /dev/null +++ b/src/server/mcp.ts @@ -0,0 +1,120 @@ +import { fileURLToPath } from 'node:url'; +import { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { CallToolRequestSchema, ListToolsRequestSchema, type Tool } from '@modelcontextprotocol/sdk/types.js'; +import { errorMessage } from '../core/errors.js'; +import { formatRunResult, type McpToolResponse } from '../core/output.js'; +import { runScript, toRunRequest } from '../core/run.js'; +import { RUN_INPUT_JSON_SCHEMA, parseRunArgs } from '../core/schemas.js'; +import { stateDirPath } from '../core/state-dir.js'; +import type { HostKind } from '../core/types.js'; +import { detectHost } from './context.js'; +import { createRuntime, type Runtime, type RuntimeFactory } from './runtime.js'; + +export const SERVER_NAME = 'agent-code-mode'; + +export const SERVER_INSTRUCTIONS = `Prefer the run tool when a step needs several tool calls: batch many reads, searches, edits and commands into one script instead of calling tools one by one. +The script is the body of an async JavaScript function; return a value to get it back. Globals (all async, all subject to your normal permission rules and hooks): + bash({command, cwd?, timeoutMs?}) -> {exitCode, signal, stdout, stderr, truncated, timedOut} + read({path, offset?, limit?}) -> {path, content, startLine, totalLines, truncated} + write({path, content}) -> {path, created, diff} + edit({path, oldString, newString, replaceAll?}) -> {path, replacements, matchStrategy, diff} + grep({pattern, path?, glob?, ignoreCase?, maxResults?}) -> {matches: [{file, line, text}], truncated} + glob({pattern, path?, maxResults?}) -> {files, truncated} + console.log/info/warn/error +A denied call rejects with an Error named PermissionDenied; other failures reject with ToolError. Pass transaction: true to roll back file changes if the script fails or a call is denied (bash effects are never rolled back).`; + +export const RUN_TOOL: Tool = { + name: 'run', + title: 'Run a code-mode script', + description: + 'Run a JavaScript script that calls bash, read, write, edit, grep and glob. Every call goes through the host permission rules and hooks. Returns the script result, logs, a call log, changed files and the diff.', + inputSchema: RUN_INPUT_JSON_SCHEMA, + annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, + _meta: { 'anthropic/alwaysLoad': true }, +}; + +export interface McpServerOptions { + readonly version: string; + /** `--host` flag; skips detection. */ + readonly host?: HostKind; + readonly env?: Readonly>; + readonly serverCwd?: string; + readonly stateDir?: string; + readonly createRuntime?: RuntimeFactory; + /** How long to wait for `roots/list`. */ + readonly rootsTimeoutMs?: number; +} + +function errorResponse(message: string): McpToolResponse { + return { content: [{ type: 'text', text: JSON.stringify({ ok: false, error: { kind: 'internal', name: 'Error', message } }) }], isError: true }; +} + +function rootPaths(roots: readonly { uri: string }[]): string[] { + const out: string[] = []; + for (const root of roots) { + if (!root.uri.startsWith('file:')) continue; + try { + out.push(fileURLToPath(root.uri)); + } catch { + // Not a local file URL. + } + } + return out; +} + +/** Creates the MCP server exposing the `run` tool. Connect it to a transport to serve. */ +export function createMcpServer(opts: McpServerOptions): Server { + const env = opts.env ?? process.env; + const serverCwd = opts.serverCwd ?? process.cwd(); + const stateDir = opts.stateDir ?? stateDirPath(env); + const factory = opts.createRuntime ?? createRuntime; + const runtimes = new Map(); + const runtimeFor = (host: HostKind): Runtime => { + let runtime = runtimes.get(host); + if (!runtime) { + runtime = factory(host); + runtimes.set(host, runtime); + } + return runtime; + }; + + const server = new Server({ name: SERVER_NAME, version: opts.version }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS }); + + const listRoots = async (): Promise => { + if (!server.getClientCapabilities()?.roots) return []; + try { + const result = await server.listRoots(undefined, { timeout: opts.rootsTimeoutMs ?? 5_000 }); + return rootPaths(result.roots); + } catch { + return []; + } + }; + + server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [RUN_TOOL] })); + + server.setRequestHandler(CallToolRequestSchema, async (request, extra): Promise => { + if (request.params.name !== RUN_TOOL.name) return errorResponse(`unknown tool ${JSON.stringify(request.params.name)}`); + const args = parseRunArgs(request.params.arguments); + if (!args.ok) return errorResponse(`invalid run arguments: ${args.message}`); + try { + const meta: unknown = request.params._meta; + const host = detectHost({ flag: opts.host, env, meta }); + const runtime = runtimeFor(host); + const roots = await listRoots(); + const ctx = await runtime.contextProvider.resolve({ env, meta, roots, serverCwd }); + const result = await runScript(toRunRequest(args.value, runtime.maxTimeoutMs), { + sandbox: runtime.sandbox, + adapter: runtime.adapter, + tools: runtime.tools, + ctx, + signal: extra.signal, + maxTimeoutMs: runtime.maxTimeoutMs, + }); + return await formatRunResult(result, { stateDir }); + } catch (err) { + return errorResponse(`internal error: ${errorMessage(err)}`); + } + }); + + return server; +} diff --git a/src/server/runtime.ts b/src/server/runtime.ts new file mode 100644 index 0000000..5b85da1 --- /dev/null +++ b/src/server/runtime.ts @@ -0,0 +1,45 @@ +import type { ContextProvider, HostAdapter, HostKind, Sandbox, ToolRuntime } from '../core/types.js'; +import { MAX_RUN_TIMEOUT_MS } from '../core/schemas.js'; +import { FakeSandbox } from '../testing/fake-sandbox.js'; +import { MemoryToolRuntime } from '../testing/memory-tool-runtime.js'; +import { StaticHostAdapter } from '../testing/static-host-adapter.js'; +import { ClaudeContextProvider, CodexContextProvider, GenericContextProvider } from './context.js'; + +/** The components that serve `run` for one host. */ +export interface Runtime { + readonly host: HostKind; + readonly contextProvider: ContextProvider; + readonly adapter: HostAdapter; + readonly tools: ToolRuntime; + readonly sandbox: Sandbox; + /** Timeout cap for this host. */ + readonly maxTimeoutMs: number; +} + +export type RuntimeFactory = (host: HostKind) => Runtime; + +/** + * Codex's documented MCP tool timeout is 60 s and progress notifications do + * not extend it, so runs are capped below it. + */ +export const CODEX_MAX_TIMEOUT_MS = 55_000; + +/** + * Builds the runtime for a host. Today it returns the test fakes (the + * sandbox, host adapters and tool runtime are built in separate parts); + * the integration part switches each piece to the real implementation. + */ +export function createRuntime(host: HostKind): Runtime { + const contextProvider = host === 'claude' ? new ClaudeContextProvider() : host === 'codex' ? new CodexContextProvider() : new GenericContextProvider(); + return { + host, + contextProvider, + adapter: new StaticHostAdapter({ + host, + rules: [(p) => (p.tool === 'bash' && /^\s*rm\s/.test(p.effect.command) ? { kind: 'deny', reason: 'rm is denied by the placeholder policy' } : undefined)], + }), + tools: new MemoryToolRuntime({ root: '/workspace' }), + sandbox: new FakeSandbox(), + maxTimeoutMs: host === 'codex' ? CODEX_MAX_TIMEOUT_MS : MAX_RUN_TIMEOUT_MS, + }; +} diff --git a/src/testing/context.ts b/src/testing/context.ts new file mode 100644 index 0000000..4c445a3 --- /dev/null +++ b/src/testing/context.ts @@ -0,0 +1,6 @@ +import type { SessionContext } from '../core/types.js'; + +/** A `SessionContext` for tests rooted at `cwd`. */ +export function makeContext(cwd = '/ws', overrides: Partial = {}): SessionContext { + return { host: 'generic', cwd, roots: [cwd], permissionMode: 'default', sources: { cwd: 'default' }, ...overrides }; +} diff --git a/src/testing/fake-sandbox.ts b/src/testing/fake-sandbox.ts new file mode 100644 index 0000000..f3c9e9e --- /dev/null +++ b/src/testing/fake-sandbox.ts @@ -0,0 +1,108 @@ +import { z } from 'zod'; +import type { CallReply, Sandbox, SandboxOutcome, SandboxRunOptions } from '../core/types.js'; + +/** + * A step of a FakeSandbox script: + * - `{tool, args}` makes one binding call; its slot holds the value, or `{error}` if it failed. + * - `{parallel: [...]}` runs the inner steps concurrently (`Promise.all`). + * - `{log: text, level?}` writes a console line. + * - `{throw: message}` fails the script. + * - `{sleep: ms}` waits. + * - `{throwOnError: true}` makes later failed calls fail the script, like an uncaught rejection. + */ +export type FakeStep = + | { readonly tool: string; readonly args?: unknown } + | { readonly parallel: readonly FakeStep[] } + | { readonly log: string; readonly level?: 'log' | 'info' | 'warn' | 'error' } + | { readonly throw: string } + | { readonly sleep: number } + | { readonly throwOnError: boolean }; + +const StepSchema: z.ZodType = z.lazy(() => + z.union([ + z.strictObject({ tool: z.string(), args: z.unknown().optional() }), + z.strictObject({ parallel: z.array(StepSchema) }), + z.strictObject({ log: z.string(), level: z.enum(['log', 'info', 'warn', 'error']).optional() }), + z.strictObject({ throw: z.string() }), + z.strictObject({ sleep: z.number().int().min(0) }), + z.strictObject({ throwOnError: z.boolean() }), + ]), +); + +const ScriptSchema = z.array(StepSchema); + +class ScriptFailure extends Error { + override readonly name: string; + constructor(name: string, message: string) { + super(message); + this.name = name; + } +} + +class Stopped extends Error {} + +/** + * Test sandbox. `code` is a JSON array of `FakeStep`s run in sequence; the + * outcome value is the array of step results. Honors `timeoutMs` and `signal`. + */ +export class FakeSandbox implements Sandbox { + readonly runs: string[] = []; + + async run(code: string, opts: SandboxRunOptions): Promise { + this.runs.push(code); + let steps: FakeStep[]; + try { + steps = ScriptSchema.parse(JSON.parse(code)); + } catch (err) { + return { ok: false, kind: 'error', error: { name: 'SyntaxError', message: err instanceof Error ? err.message : String(err) } }; + } + + let timedOut = false; + const stopped = new Promise((_resolve, reject) => { + const onAbort = (): void => reject(new Stopped()); + if (opts.signal.aborted) onAbort(); + else opts.signal.addEventListener('abort', onAbort, { once: true }); + setTimeout(() => { + timedOut = true; + reject(new Stopped()); + }, opts.timeoutMs).unref(); + }); + stopped.catch(() => undefined); + + const state = { throwOnError: false }; + const exec = async (step: FakeStep): Promise => { + if ('tool' in step) { + const reply: CallReply = await opts.onCall(step.tool, step.args); + if (reply.ok) return reply.value; + if (state.throwOnError) throw new ScriptFailure(reply.error.name, reply.error.message); + return { error: reply.error }; + } + if ('parallel' in step) return Promise.all(step.parallel.map(exec)); + if ('log' in step) { + opts.onLog(step.level ?? 'log', step.log); + return null; + } + if ('throw' in step) throw new ScriptFailure('Error', step.throw); + if ('sleep' in step) { + await new Promise((resolve) => setTimeout(resolve, step.sleep)); + return null; + } + state.throwOnError = step.throwOnError; + return null; + }; + + try { + const results: unknown[] = []; + for (const step of steps) results.push(await Promise.race([exec(step), stopped])); + return { ok: true, value: results }; + } catch (err) { + if (err instanceof Stopped) { + return timedOut + ? { ok: false, kind: 'timeout', error: { name: 'Timeout', message: `script exceeded ${opts.timeoutMs} ms` } } + : { ok: false, kind: 'killed', error: { name: 'Killed', message: 'script was stopped' } }; + } + const e = err instanceof Error ? err : new Error(String(err)); + return { ok: false, kind: 'error', error: { name: e.name, message: e.message } }; + } + } +} diff --git a/src/testing/index.ts b/src/testing/index.ts new file mode 100644 index 0000000..b7726d4 --- /dev/null +++ b/src/testing/index.ts @@ -0,0 +1,4 @@ +export { FakeSandbox, type FakeStep } from './fake-sandbox.js'; +export { MemoryToolRuntime, sha256, simpleDiff, type CommitRecord, type MemoryToolRuntimeOptions } from './memory-tool-runtime.js'; +export { StaticHostAdapter, type HookBehavior, type RuleVerdict, type StaticHostAdapterOptions, type StaticRule } from './static-host-adapter.js'; +export { makeContext } from './context.js'; diff --git a/src/testing/memory-tool-runtime.ts b/src/testing/memory-tool-runtime.ts new file mode 100644 index 0000000..740212e --- /dev/null +++ b/src/testing/memory-tool-runtime.ts @@ -0,0 +1,343 @@ +import { createHash } from 'node:crypto'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; +import { findMatchingPattern, matchesPathPattern } from '../core/paths.js'; +import type { + PolicySnapshot, + PreparedCall, + RollbackReport, + SessionContext, + ToolCall, + ToolResult, + ToolRuntime, + Transaction, +} from '../core/types.js'; + +const posix = path.posix; + +/** SHA-256 hex of a string. */ +export function sha256(text: string): string { + return createHash('sha256').update(text, 'utf8').digest('hex'); +} + +/** Minimal whole-file unified diff, good enough for tests. */ +export function simpleDiff(file: string, before: string | null, after: string): string { + const lines = (s: string): string[] => (s === '' ? [] : s.replace(/\n$/, '').split('\n')); + const a = before === null ? [] : lines(before); + const b = lines(after); + const head = `--- ${before === null ? '/dev/null' : `a${file}`}\n+++ b${file}\n@@ -${a.length > 0 ? 1 : 0},${a.length} +${b.length > 0 ? 1 : 0},${b.length} @@\n`; + return head + a.map((l) => `-${l}\n`).join('') + b.map((l) => `+${l}\n`).join(''); +} + +export interface MemoryToolRuntimeOptions { + /** Absolute POSIX workspace root of the virtual file system, e.g. `/ws`. */ + readonly root: string; + /** Initial files, keyed by path relative to `root` or absolute. */ + readonly files?: Readonly>; + /** Random delay up to this many ms inside prepare and commit, to shake out ordering bugs. */ + readonly jitterMs?: number; + /** Fixed delay inside every mutating commit. */ + readonly commitDelayMs?: number; + /** When false, a mutating commit ignores abort during `commitDelayMs` and applies its effect anyway. Default true. */ + readonly honorAbortInCommit?: boolean; +} + +/** One committed call, for assertions. */ +export interface CommitRecord { + readonly id: string; + readonly tool: ToolCall['tool']; + readonly target: string; +} + +interface JournalEntry { + readonly original: string | null; + lastWritten: string; +} + +function sleep(ms: number, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (ms <= 0) return resolve(); + const timer = setTimeout(() => { + signal?.removeEventListener('abort', onAbort); + resolve(); + }, ms); + const onAbort = (): void => { + clearTimeout(timer); + reject(new ToolError('cancelled', 'aborted')); + }; + signal?.addEventListener('abort', onAbort, { once: true }); + }); +} + +class MemoryTransaction implements Transaction { + readonly journal = new Map(); + disposed = false; + + constructor(private readonly runtime: MemoryToolRuntime) {} + + record(absPath: string, before: string | null, after: string): void { + if (this.disposed) return; + const entry = this.journal.get(absPath); + if (entry) entry.lastWritten = after; + else this.journal.set(absPath, { original: before, lastWritten: after }); + } + + async rollback(): Promise { + const restored: string[] = []; + const skipped: { path: string; reason: 'changed-externally' }[] = []; + for (const [absPath, entry] of [...this.journal.entries()].reverse()) { + const current = this.runtime.files.get(absPath); + if (current !== entry.lastWritten) { + skipped.push({ path: absPath, reason: 'changed-externally' }); + continue; + } + if (entry.original === null) this.runtime.files.delete(absPath); + else this.runtime.files.set(absPath, entry.original); + restored.push(absPath); + } + this.journal.clear(); + return { restored, skipped }; + } + + async dispose(): Promise { + this.disposed = true; + this.journal.clear(); + } +} + +/** + * In-memory `ToolRuntime` for tests: a virtual POSIX file system under + * `root`, real hashing and stale checks, transactions with a journal, and + * `bash` that only echoes the command. + */ +export class MemoryToolRuntime implements ToolRuntime { + readonly root: string; + readonly files = new Map(); + readonly commits: CommitRecord[] = []; + /** Highest number of concurrent prepare/commit calls of read-only tools seen. */ + maxConcurrentReads = 0; + #reading = 0; + readonly #opts: MemoryToolRuntimeOptions; + + constructor(opts: MemoryToolRuntimeOptions) { + this.#opts = opts; + this.root = posix.resolve(opts.root); + for (const [p, content] of Object.entries(opts.files ?? {})) this.files.set(posix.resolve(this.root, p), content); + } + + /** Simulates a change made outside the run. */ + externalWrite(p: string, content: string): void { + this.files.set(posix.resolve(this.root, p), content); + } + + read(p: string): string | undefined { + return this.files.get(posix.resolve(this.root, p)); + } + + #resolve(p: string): string { + const abs = posix.resolve(this.root, p); + const rel = posix.relative(this.root, abs); + if (rel.startsWith('..') || posix.isAbsolute(rel)) { + throw new ToolError('outside-workspace', `${p} is outside the workspace ${this.root}`); + } + return abs; + } + + async #jitter(signal?: AbortSignal): Promise { + const max = this.#opts.jitterMs ?? 0; + if (max > 0) await sleep(Math.random() * max, signal); + } + + async prepare(call: ToolCall, _ctx: SessionContext, policy: PolicySnapshot): Promise { + const readOnly = call.tool === 'read' || call.tool === 'grep' || call.tool === 'glob'; + if (readOnly) this.#enterRead(); + try { + await this.#jitter(); + return this.#prepareNow(call, policy); + } finally { + if (readOnly) this.#reading--; + } + } + + #enterRead(): void { + this.#reading++; + this.maxConcurrentReads = Math.max(this.maxConcurrentReads, this.#reading); + } + + #protect(absPath: string, policy: PolicySnapshot): void { + if (findMatchingPattern(absPath, policy.protectedPaths) !== undefined) { + throw new ToolError('protected-path', `${absPath} is a protected host policy path`); + } + } + + #prepareNow(call: ToolCall, policy: PolicySnapshot): PreparedCall { + switch (call.tool) { + case 'bash': { + const cwd = this.#resolve(call.args.cwd ?? '.'); + const args = { command: call.args.command, cwd, timeoutMs: call.args.timeoutMs ?? 120_000 }; + return { id: call.id, tool: 'bash', args, effect: { ...args, containment: policy.bashContainment } }; + } + case 'read': { + const absPath = this.#resolve(call.args.path); + if (!this.files.has(absPath)) throw new ToolError('not-found', `${absPath} does not exist`); + const offset = call.args.offset ?? 1; + const limit = call.args.limit ?? 2000; + return { id: call.id, tool: 'read', args: { path: absPath, offset, limit }, effect: { absPath, offset, limit } }; + } + case 'write': { + const absPath = this.#resolve(call.args.path); + this.#protect(absPath, policy); + const before = this.files.get(absPath) ?? null; + return { + id: call.id, + tool: 'write', + args: { path: absPath, content: call.args.content }, + effect: { + absPath, + beforeHash: before === null ? null : sha256(before), + afterContent: call.args.content, + diff: simpleDiff(absPath, before, call.args.content), + }, + }; + } + case 'edit': { + const absPath = this.#resolve(call.args.path); + this.#protect(absPath, policy); + const before = this.files.get(absPath); + if (before === undefined) throw new ToolError('not-found', `${absPath} does not exist`); + const count = before.split(call.args.oldString).length - 1; + if (count === 0) throw new ToolError('not-found', `oldString not found in ${absPath}`); + if (count > 1 && call.args.replaceAll !== true) { + throw new ToolError('invalid-args', `oldString matches ${count} times in ${absPath}; pass replaceAll or a longer oldString`); + } + const afterContent = call.args.replaceAll === true + ? before.split(call.args.oldString).join(call.args.newString) + : before.replace(call.args.oldString, () => call.args.newString); + return { + id: call.id, + tool: 'edit', + args: { ...call.args, path: absPath }, + effect: { + absPath, + beforeHash: sha256(before), + afterContent, + diff: simpleDiff(absPath, before, afterContent), + matchedOldString: call.args.oldString, + matchStrategy: 'exact', + replacements: call.args.replaceAll === true ? count : 1, + }, + }; + } + case 'grep': { + const absRoot = this.#resolve(call.args.path ?? '.'); + const effect = { + absRoot, + pattern: call.args.pattern, + glob: call.args.glob ?? null, + ignoreCase: call.args.ignoreCase ?? false, + maxResults: call.args.maxResults ?? 200, + }; + try { + new RegExp(effect.pattern); + } catch { + throw new ToolError('invalid-args', `invalid regular expression ${effect.pattern}`); + } + return { id: call.id, tool: 'grep', args: { ...call.args, path: absRoot }, effect }; + } + case 'glob': { + const absRoot = this.#resolve(call.args.path ?? '.'); + const effect = { absRoot, pattern: call.args.pattern, maxResults: call.args.maxResults ?? 200 }; + return { id: call.id, tool: 'glob', args: { ...call.args, path: absRoot }, effect }; + } + } + } + + async commit(prepared: PreparedCall, signal: AbortSignal, tx?: Transaction): Promise { + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before commit'); + switch (prepared.tool) { + case 'read': + case 'grep': + case 'glob': { + this.#enterRead(); + try { + await this.#jitter(signal); + return this.#commitRead(prepared); + } finally { + this.#reading--; + } + } + case 'bash': + case 'write': + case 'edit': { + const delay = this.#opts.commitDelayMs ?? 0; + await sleep(delay, this.#opts.honorAbortInCommit === false ? undefined : signal); + await this.#jitter(this.#opts.honorAbortInCommit === false ? undefined : signal); + return this.#commitMutation(prepared, tx); + } + } + } + + #commitRead(prepared: Extract): ToolResult { + switch (prepared.tool) { + case 'read': { + const { absPath, offset, limit } = prepared.effect; + const content = this.files.get(absPath); + if (content === undefined) throw new ToolError('not-found', `${absPath} does not exist`); + const lines = content.split('\n'); + const window = lines.slice(offset - 1, offset - 1 + limit); + this.commits.push({ id: prepared.id, tool: 'read', target: absPath }); + return { path: absPath, content: window.join('\n'), startLine: offset, totalLines: lines.length, truncated: offset - 1 + limit < lines.length }; + } + case 'grep': { + const { absRoot, pattern, ignoreCase, maxResults, glob } = prepared.effect; + const re = new RegExp(pattern, ignoreCase ? 'i' : ''); + const matches: { file: string; line: number; text: string }[] = []; + let truncated = false; + for (const [file, content] of [...this.files.entries()].sort(([a], [b]) => a.localeCompare(b))) { + if (file !== absRoot && !file.startsWith(`${absRoot}/`)) continue; + if (glob !== null && !matchesPathPattern(posix.basename(file), glob, false) && !matchesPathPattern(posix.relative(absRoot, file), glob, false)) continue; + content.split('\n').forEach((text, i) => { + if (!re.test(text)) return; + if (matches.length >= maxResults) truncated = true; + else matches.push({ file, line: i + 1, text }); + }); + } + this.commits.push({ id: prepared.id, tool: 'grep', target: absRoot }); + return { matches, truncated }; + } + case 'glob': { + const { absRoot, pattern, maxResults } = prepared.effect; + const all = [...this.files.keys()] + .filter((file) => file.startsWith(`${absRoot}/`) && matchesPathPattern(posix.relative(absRoot, file), pattern, false)) + .sort(); + this.commits.push({ id: prepared.id, tool: 'glob', target: absRoot }); + return { files: all.slice(0, maxResults), truncated: all.length > maxResults }; + } + } + } + + #commitMutation(prepared: Extract, tx: Transaction | undefined): ToolResult { + switch (prepared.tool) { + case 'bash': { + this.commits.push({ id: prepared.id, tool: 'bash', target: prepared.effect.command }); + return { exitCode: 0, signal: null, stdout: `fake: ${prepared.effect.command}\n`, stderr: '', truncated: false, timedOut: false }; + } + case 'write': + case 'edit': { + const { absPath, beforeHash, afterContent, diff } = prepared.effect; + const current = this.files.get(absPath) ?? null; + const currentHash = current === null ? null : sha256(current); + if (currentHash !== beforeHash) throw new ToolError('stale', `${absPath} changed after the call was prepared`); + this.files.set(absPath, afterContent); + if (tx instanceof MemoryTransaction) tx.record(absPath, current, afterContent); + this.commits.push({ id: prepared.id, tool: prepared.tool, target: absPath }); + if (prepared.tool === 'write') return { path: absPath, created: current === null, diff }; + return { path: absPath, replacements: prepared.effect.replacements, matchStrategy: prepared.effect.matchStrategy, diff }; + } + } + } + + beginTransaction(): Transaction { + return new MemoryTransaction(this); + } +} diff --git a/src/testing/static-host-adapter.ts b/src/testing/static-host-adapter.ts new file mode 100644 index 0000000..5b1b2f0 --- /dev/null +++ b/src/testing/static-host-adapter.ts @@ -0,0 +1,104 @@ +import type { + BashContainment, + Decision, + HostAdapter, + HostKind, + PolicyLoadError, + PolicySnapshot, + PreparedCall, + SessionContext, + ToolResult, +} from '../core/types.js'; + +/** Verdict of one static rule; undefined means the rule does not apply. */ +export type RuleVerdict = { readonly kind: 'deny' | 'ask' | 'allow'; readonly reason: string } | undefined; + +/** A static rule as a predicate over the prepared call. Rules are checked deny → ask → allow, like the hosts. */ +export type StaticRule = (prepared: PreparedCall, ctx: SessionContext) => RuleVerdict; + +/** What the fake PreToolUse hook does. */ +export type HookBehavior = + | { readonly kind: 'allow' } + | { readonly kind: 'deny'; readonly reason: string } + | { readonly kind: 'ask'; readonly reason: string } + | { readonly kind: 'updatedArgs'; readonly args: unknown } + | { readonly kind: 'throw'; readonly message: string } + | { readonly kind: 'hang' } + | { readonly kind: 'malformed' }; + +export interface StaticHostAdapterOptions { + readonly host?: HostKind; + readonly rules?: readonly StaticRule[]; + /** Fixed behavior, or one chosen per call. Default allow. */ + readonly hook?: HookBehavior | ((prepared: PreparedCall) => HookBehavior); + /** When set, `loadPolicy` returns this error. */ + readonly policyError?: string; + readonly bashContainment?: BashContainment; + readonly protectedPaths?: readonly string[]; +} + +/** + * Host adapter for tests: static rules as predicates and a scripted fake + * hook. Records every call it sees. + */ +export class StaticHostAdapter implements HostAdapter { + readonly host: HostKind; + readonly authorized: PreparedCall[] = []; + readonly staticChecked: PreparedCall[] = []; + readonly postToolUses: { prepared: PreparedCall; result: ToolResult }[] = []; + readonly #opts: StaticHostAdapterOptions; + + constructor(opts: StaticHostAdapterOptions = {}) { + this.#opts = opts; + this.host = opts.host ?? 'generic'; + } + + async loadPolicy(_ctx: SessionContext): Promise | PolicyLoadError> { + if (this.#opts.policyError !== undefined) return { error: this.#opts.policyError }; + return { + host: this.host, + bashContainment: this.#opts.bashContainment ?? { mode: 'none' }, + protectedPaths: this.#opts.protectedPaths ?? [], + payload: null, + }; + } + + checkStatic(prepared: PreparedCall, ctx: SessionContext): Decision { + this.staticChecked.push(prepared); + const verdicts = (this.#opts.rules ?? []).map((rule) => rule(prepared, ctx)); + const deny = verdicts.find((v) => v?.kind === 'deny'); + if (deny) return { kind: 'deny', source: 'rule', reason: deny.reason }; + const ask = verdicts.find((v) => v?.kind === 'ask'); + if (ask) return { kind: 'ask', reason: ask.reason }; + return { kind: 'allow' }; + } + + authorize(prepared: PreparedCall, _ctx: SessionContext, _policy: PolicySnapshot, signal: AbortSignal): Promise { + this.authorized.push(prepared); + const hook = this.#opts.hook; + const behavior: HookBehavior = typeof hook === 'function' ? hook(prepared) : (hook ?? { kind: 'allow' }); + switch (behavior.kind) { + case 'allow': + return Promise.resolve({ kind: 'allow' }); + case 'deny': + return Promise.resolve({ kind: 'deny', source: 'hook', reason: behavior.reason }); + case 'ask': + return Promise.resolve({ kind: 'ask', reason: behavior.reason }); + case 'updatedArgs': + return Promise.resolve({ kind: 'allow', updatedArgs: behavior.args }); + case 'throw': + throw new Error(behavior.message); + case 'malformed': + // Simulates a buggy adapter that resolves something that is not a Decision. + return Promise.resolve(JSON.parse('{"kind":"maybe"}')); + case 'hang': + // Never settles on its own; ignores the signal on purpose. + void signal; + return new Promise(() => undefined); + } + } + + async postToolUse(prepared: PreparedCall, result: ToolResult): Promise { + this.postToolUses.push({ prepared, result }); + } +} diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 0000000..0a11719 --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["src/**/*.test.ts"] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..2ced264 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "target": "ES2023", + "lib": ["ES2023"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "types": ["node"], + "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": false, + "noImplicitOverride": true, + "noFallthroughCasesInSwitch": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true, + "declaration": true, + "sourceMap": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src/**/*.ts"] +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..37ed53d --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['src/**/*.test.ts'], + testTimeout: 20_000, + }, +}); From b230183ce959e256ed1d31c948b217d46fcc3b7c Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:18:56 -0300 Subject: [PATCH 02/18] Fix four seam defects found in adversarial review - Commit a dispatcher-owned deep-frozen copy of each prepared call; deep freeze now descends into objects that are already frozen. - Bound every await on adapter and runtime code by the run's abort signal or a grace: prepare, PostToolUse (which now receives the signal), loadPolicy (the run deadline starts before it), in-flight calls on stop, rollback and dispose. - Kill the command hook's whole process group on every completion path, so a backgrounded descendant cannot outlive the hook. - Send protocol and validation errors through the capped result formatter. Co-Authored-By: Claude Opus 5.5 --- src/core/command-hook.test.ts | 28 ++++++++++ src/core/command-hook.ts | 18 ++++++ src/core/dispatcher.test.ts | 67 ++++++++++++++++++++++ src/core/dispatcher.ts | 50 ++++++++++++++--- src/core/freeze.ts | 28 +++++++--- src/core/run.test.ts | 54 ++++++++++++++++++ src/core/run.ts | 102 +++++++++++++++++++++++++--------- src/core/types.ts | 7 ++- src/server/mcp.test.ts | 15 +++++ src/server/mcp.ts | 16 +++--- 10 files changed, 336 insertions(+), 49 deletions(-) diff --git a/src/core/command-hook.test.ts b/src/core/command-hook.test.ts index 9419b54..c73798e 100644 --- a/src/core/command-hook.test.ts +++ b/src/core/command-hook.test.ts @@ -1,4 +1,6 @@ +import { existsSync, mkdtempSync, rmSync } from 'node:fs'; import os from 'node:os'; +import path from 'node:path'; import { describe, expect, it } from 'vitest'; import { runCommandHook } from './command-hook.js'; @@ -38,6 +40,32 @@ describe.skipIf(!posix)('runCommandHook (POSIX)', () => { expect(alive(grandchild)).toBe(false); }); + it('kills a backgrounded descendant when the hook exits normally', async () => { + const dir = mkdtempSync(path.join(os.tmpdir(), 'acm-hook-')); + const marker = path.join(dir, 'late'); + try { + const r = await runCommandHook({ ...base, command: `(sleep 0.5; touch '${marker}') & echo started`, stdin: '' }); + expect(r).toMatchObject({ exitCode: 0, timedOut: false, stdout: 'started\n' }); + await new Promise((res) => setTimeout(res, 1_000)); + expect(existsSync(marker)).toBe(false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it('kills a backgrounded descendant when the hook exits with an error', async () => { + const dir = mkdtempSync(path.join(os.tmpdir(), 'acm-hook-')); + const marker = path.join(dir, 'late'); + try { + const r = await runCommandHook({ ...base, command: `(sleep 0.5; touch '${marker}') & exit 2`, stdin: '' }); + expect(r.exitCode).toBe(2); + await new Promise((res) => setTimeout(res, 1_000)); + expect(existsSync(marker)).toBe(false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + it('caps huge stdout', async () => { const r = await runCommandHook({ ...base, command: 'head -c 5000000 /dev/zero', stdin: '', maxOutputBytes: 1000 }); expect(r.stdout.length).toBe(1000); diff --git a/src/core/command-hook.ts b/src/core/command-hook.ts index ead5d94..916e1e1 100644 --- a/src/core/command-hook.ts +++ b/src/core/command-hook.ts @@ -60,6 +60,21 @@ class Capture { } } +/** + * POSIX: kills whatever is left of the hook's process group (the hook is the + * group leader). Called on every completion path, so a backgrounded + * descendant cannot keep running after the hook returned. ESRCH (nothing + * left) is ignored. + */ +function killGroup(child: ChildProcess): void { + if (process.platform === 'win32' || child.pid === undefined) return; + try { + process.kill(-child.pid, 'SIGKILL'); + } catch { + // The group is already empty. + } +} + function killTree(child: ChildProcess): void { if (child.pid === undefined) return; try { @@ -102,6 +117,7 @@ export function runCommandHook(opts: CommandHookOptions): Promise { exit = { code, signal }; + // The hook is done: nothing it started may outlive it. + killGroup(child); // Give the pipes a moment to flush; a grandchild that escaped the group may keep them open. graceTimer = setTimeout(() => finish(null), PIPE_GRACE_MS); }); diff --git a/src/core/dispatcher.test.ts b/src/core/dispatcher.test.ts index 7af3a36..985a84f 100644 --- a/src/core/dispatcher.test.ts +++ b/src/core/dispatcher.test.ts @@ -274,6 +274,73 @@ describe('Dispatcher', () => { expect(tools.commits).toHaveLength(0); }); + it('commits the authorized effect even when the runtime returns a shallow-frozen call it can still mutate', async () => { + const { ctx, adapter } = await setup(); + const tools = new MemoryToolRuntime({ root: '/ws' }); + let returned: { effect: { afterContent: string } } | undefined; + const sneaky: typeof tools = Object.assign(Object.create(tools) as typeof tools, { + commit: tools.commit.bind(tools), + prepare: async (...args: Parameters) => { + const p = Object.freeze(await tools.prepare(...args)); + returned = p as unknown as { effect: { afterContent: string } }; + return p; + }, + }); + let authorized: string | undefined; + const spy = new StaticHostAdapter({ + hook: (p) => { + if (p.tool === 'write') { + authorized = p.effect.afterContent; + // Both the runtime's own object and the one the hook sees are tampered with. + if (returned && !Object.isFrozen(returned.effect)) returned.effect.afterContent = 'EVIL'; + try { + Object.assign(p.effect, { afterContent: 'EVIL' }); + } catch { + // Frozen, as it must be. + } + } + return { kind: 'allow' }; + }, + }); + void adapter; + const dispatcher = new Dispatcher({ adapter: spy, tools: sneaky, ctx, policy: await spy.loadPolicy(ctx) }); + const reply = await dispatcher.dispatch('write', { path: 'a.txt', content: 'SAFE' }); + expect(reply.ok).toBe(true); + expect(authorized).toBe('SAFE'); + expect(tools.read('a.txt')).toBe('SAFE'); + const seen = spy.authorized[0]; + expect(seen && Object.isFrozen(seen.effect)).toBe(true); + }); + + it('stop gives up on a commit that ignores the signal after the grace and reports it', async () => { + const { ctx, adapter } = await setup(); + const tools = new MemoryToolRuntime({ root: '/ws' }); + const stuck: typeof tools = Object.assign(Object.create(tools) as typeof tools, { + prepare: tools.prepare.bind(tools), + commit: () => new Promise(() => undefined), + }); + const dispatcher = new Dispatcher({ adapter, tools: stuck, ctx, policy: await adapter.loadPolicy(ctx) }); + void dispatcher.dispatch('write', { path: 'a.txt', content: 'x' }); + await new Promise((r) => setTimeout(r, 10)); + const started = Date.now(); + await dispatcher.stop('cancelled', 50); + expect(Date.now() - started).toBeLessThan(1_000); + expect(dispatcher.warnings.join('\n')).toMatch(/c1 \(write a\.txt\) did not settle within 50 ms/); + expect(dispatcher.calls[0]).toMatchObject({ id: 'c1', decision: 'error' }); + }); + + it('stops waiting for a PostToolUse hook that never returns once the run stops', async () => { + const { ctx, tools } = await setup(); + const adapter = new StaticHostAdapter(); + adapter.postToolUse = () => new Promise(() => undefined); + const dispatcher = new Dispatcher({ adapter, tools, ctx, policy: await adapter.loadPolicy(ctx) }); + const pending = dispatcher.dispatch('write', { path: 'a.txt', content: 'x' }); + await new Promise((r) => setTimeout(r, 10)); + await dispatcher.stop('cancelled', 60_000); + expect((await pending).ok).toBe(true); + expect(dispatcher.warnings.join('\n')).toContain('PostToolUse hooks for c1 (write a.txt) were abandoned'); + }); + it('runs postToolUse after commit and turns its failure into a warning', async () => { const { ctx, tools } = await setup(); const adapter = new StaticHostAdapter(); diff --git a/src/core/dispatcher.ts b/src/core/dispatcher.ts index e1e1a11..400fcce 100644 --- a/src/core/dispatcher.ts +++ b/src/core/dispatcher.ts @@ -1,6 +1,6 @@ import path from 'node:path'; import { ToolError, errorMessage } from './errors.js'; -import { deepFreeze } from './freeze.js'; +import { frozenCopy } from './freeze.js'; import { findMatchingPattern } from './paths.js'; import { isMutating, parseToolCall } from './schemas.js'; import type { @@ -45,6 +45,9 @@ const ABORTED: unique symbol = Symbol('aborted'); const MAX_SUMMARY_CHARS = 160; +/** How long `stop` waits for in-flight calls before giving up on them. */ +export const DEFAULT_SETTLE_GRACE_MS = 2_000; + function isPolicyError

(policy: PolicySnapshot

| PolicyLoadError): policy is PolicyLoadError { return 'error' in policy; } @@ -126,7 +129,10 @@ export class Dispatcher

{ #stopReason: StopReason | undefined; #nextId = 1; #mutationTail: Promise = Promise.resolve(); - readonly #inflight = new Set>(); + readonly #inflight = new Map, number>(); + /** id, tool and summary of each call by slot, for reporting calls that never settle. */ + readonly #labels: { id: string; tool: string; summary: string }[] = []; + readonly #abandoned = new WeakSet>(); readonly #calls: (CallLogEntry | undefined)[] = []; readonly #changed: string[] = []; readonly #diffs: string[] = []; @@ -184,6 +190,7 @@ export class Dispatcher

{ const id = `c${this.#nextId++}`; const slot = this.#calls.length; this.#calls.push(undefined); + this.#labels.push({ id, tool: typeof tool === 'string' ? clip(tool, 40) : 'unknown', summary: typeof tool === 'string' ? clip(tool, 40) : 'unknown' }); const started = this.#now(); const toolLabel = clip(typeof tool === 'string' ? tool : String(tool), 40); @@ -200,7 +207,7 @@ export class Dispatcher

{ error: new ToolError('tool-error', `internal error: ${errorMessage(err)}`), }), ); - this.#inflight.add(reply); + this.#inflight.set(reply, slot); void reply.finally(() => this.#inflight.delete(reply)); return reply; } @@ -209,13 +216,35 @@ export class Dispatcher

{ * Stops accepting calls, aborts in-flight ones and waits for them to * settle. Idempotent; the first reason wins. */ - async stop(reason: StopReason): Promise { + async stop(reason: StopReason, graceMs: number = DEFAULT_SETTLE_GRACE_MS): Promise { if (this.#stopReason === undefined) { this.#stopReason = reason; this.#abort.abort(reason); } + const deadline = this.#now() + Math.max(0, graceMs); while (this.#inflight.size > 0) { - await Promise.allSettled([...this.#inflight]); + const left = deadline - this.#now(); + let timer: NodeJS.Timeout | undefined; + const expired = left <= 0 + ? Promise.resolve(true) + : new Promise((resolve) => { + timer = setTimeout(() => resolve(true), left); + }); + const settled = Promise.allSettled([...this.#inflight.keys()]).then(() => false); + const timedOut = await Promise.race([settled, expired]); + if (timer) clearTimeout(timer); + if (timedOut) { + for (const [pending, slot] of this.#inflight) { + const label = this.#labels[slot]; + if (!label || this.#abandoned.has(pending)) continue; + this.#abandoned.add(pending); + this.#warnings.push( + `${label.id} (${label.summary}) did not settle within ${graceMs} ms after the run stopped (${this.#stopReason ?? reason}); its effect is unknown.`, + ); + this.#calls[slot] ??= { id: label.id, tool: label.tool, summary: label.summary, decision: 'error', reason: 'did not settle after the run stopped', durationMs: 0 }; + } + return; + } } } @@ -230,6 +259,7 @@ export class Dispatcher

{ } const call = parsed; const summary = summarize(call, this.#opts.ctx.cwd); + this.#labels[slot] = { id, tool: call.tool, summary }; const policy = this.#opts.policy; if (isPolicyError(policy)) { return Promise.resolve( @@ -294,7 +324,12 @@ export class Dispatcher

{ async #prepareChecked(call: ToolCall, policy: PolicySnapshot

): Promise<{ prepared: PreparedCall } | Failure> { let prepared: PreparedCall; try { - prepared = deepFreeze(await this.#opts.tools.prepare(call, this.#opts.ctx, policy)); + const pending = this.#opts.tools.prepare(call, this.#opts.ctx, policy); + const returned = await raceAbort(pending, this.#abort.signal); + if (returned === ABORTED) return this.#stoppedFailure(); + // A dispatcher-owned deep-frozen copy: what is authorized and then + // committed cannot be changed by the runtime or anyone holding its object. + prepared = frozenCopy(returned); } catch (err) { return this.#toolFailure(err); } @@ -385,7 +420,8 @@ export class Dispatcher

{ const post = this.#opts.adapter.postToolUse; if (post) { try { - await post.call(this.#opts.adapter, prepared, result, this.#opts.ctx, policy); + const done = await raceAbort(Promise.resolve(post.call(this.#opts.adapter, prepared, result, this.#opts.ctx, policy, this.#abort.signal)), this.#abort.signal); + if (done === ABORTED) this.#warnings.push(`PostToolUse hooks for ${prepared.id} (${summary}) were abandoned when the run stopped.`); } catch (err) { this.#warnings.push(`PostToolUse hooks failed for ${prepared.id} (${summary}): ${errorMessage(err)}`); } diff --git a/src/core/freeze.ts b/src/core/freeze.ts index 3e0f327..0e532f0 100644 --- a/src/core/freeze.ts +++ b/src/core/freeze.ts @@ -1,10 +1,24 @@ -/** Recursively freezes plain objects and arrays in place and returns the value. */ -export function deepFreeze(value: T): T { - if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) { - Object.freeze(value); - for (const key of Reflect.ownKeys(value)) { - deepFreeze((value as Record)[key]); - } +/** + * Recursively freezes objects and arrays in place and returns the value. + * It descends into objects that are already frozen too: a shallow + * `Object.freeze` on the outside says nothing about what is inside. + */ +export function deepFreeze(value: T, seen: WeakSet = new WeakSet()): T { + if (value === null || typeof value !== 'object' || seen.has(value)) return value; + seen.add(value); + Object.freeze(value); + for (const key of Reflect.ownKeys(value)) { + const descriptor = Reflect.getOwnPropertyDescriptor(value, key); + if (descriptor && 'value' in descriptor) deepFreeze(descriptor.value, seen); } return value; } + +/** + * A deep-frozen structured clone of `value`, owned by the caller: whoever + * produced `value` keeps no reference into the copy. Throws on values that + * cannot be cloned (functions, symbols). + */ +export function frozenCopy(value: T): T { + return deepFreeze(structuredClone(value)); +} diff --git a/src/core/run.test.ts b/src/core/run.test.ts index e574d14..f147f27 100644 --- a/src/core/run.test.ts +++ b/src/core/run.test.ts @@ -158,6 +158,60 @@ describe('runScript', () => { expect(result.calls[0]?.reason).toContain('unsupported-config'); }); + it('rolls back within the grace after cancel even if a PostToolUse hook never returns', async () => { + const d = deps(); + let entered!: () => void; + const inside = new Promise((r) => (entered = r)); + d.adapter.postToolUse = () => { + entered(); + return new Promise(() => undefined); + }; + const controller = new AbortController(); + let settled = false; + const pending = runScript( + { code: script([{ tool: 'write', args: { path: 'a.txt', content: 'SAFE' } }]), transaction: true, timeoutMs: 5_000 }, + { ...d, signal: controller.signal, stopGraceMs: 20 }, + ).then((r) => ((settled = true), r)); + await inside; + controller.abort(); + await new Promise((r) => setTimeout(r, 300)); + expect(settled).toBe(true); + const result = await pending; + expect(result.error?.kind).toBe('cancelled'); + expect(result.rolledBack?.restored).toEqual(['/ws/a.txt']); + expect(d.tools.read('a.txt')).toBeUndefined(); + }); + + it('settles on cancel and on timeout while loadPolicy never returns', async () => { + const d = deps(); + d.adapter.loadPolicy = () => new Promise(() => undefined); + const controller = new AbortController(); + let settled = false; + const cancelled = runScript({ code: script([]), transaction: true, timeoutMs: 5_000 }, { ...d, signal: controller.signal, stopGraceMs: 5 }).then( + (r) => ((settled = true), r), + ); + controller.abort(); + await new Promise((r) => setTimeout(r, 150)); + expect(settled).toBe(true); + expect((await cancelled).error?.kind).toBe('cancelled'); + + const timedOut = await runScript({ code: script([]), transaction: false, timeoutMs: 20 }, { ...d, stopGraceMs: 5 }); + expect(timedOut.error?.kind).toBe('timeout'); + }); + + it('reports a rollback that does not finish within its bound', async () => { + const d = deps(denyForbidden); + const tx = d.tools.beginTransaction(); + d.tools.beginTransaction = () => ({ rollback: () => new Promise(() => undefined), dispose: () => tx.dispose() }); + const result = await runScript( + { code: script([{ tool: 'write', args: { path: 'forbidden.txt', content: 'x' } }]), transaction: true, timeoutMs: 5_000 }, + { ...d, rollbackTimeoutMs: 30 }, + ); + expect(result.error?.kind).toBe('denied'); + expect(result.rolledBack).toBeUndefined(); + expect(result.warnings.join('\n')).toContain('rollback did not finish within 30 ms'); + }); + it('never rejects when the sandbox throws', async () => { const sandbox: Sandbox = { run: () => { diff --git a/src/core/run.ts b/src/core/run.ts index a9a70bd..eb9a44e 100644 --- a/src/core/run.ts +++ b/src/core/run.ts @@ -22,6 +22,8 @@ import type { export const DEFAULT_MEMORY_BYTES = 256 * 1024 * 1024; /** How long to wait for the sandbox to return after it was told to stop. */ export const DEFAULT_STOP_GRACE_MS = 2_000; +/** Upper bound of a transaction rollback. */ +export const DEFAULT_ROLLBACK_TIMEOUT_MS = 30_000; const MAX_LOG_LINES = 5_000; const MAX_LOG_CHARS = 1_000_000; @@ -35,8 +37,66 @@ export interface RunDeps

{ /** Server cap of the timeout (lower for hosts with short tool timeouts). Never above `MAX_RUN_TIMEOUT_MS`. */ readonly maxTimeoutMs?: number; readonly memoryBytes?: number; - /** Grace after a stop before the sandbox is considered killed. */ + /** Grace after a stop before the sandbox, in-flight calls and hooks are abandoned. */ readonly stopGraceMs?: number; + /** Upper bound of a transaction rollback. */ + readonly rollbackTimeoutMs?: number; +} + +type Bounded = { readonly done: true; readonly value: T } | { readonly done: false; readonly why: 'aborted' | 'timeout' }; + +/** + * Awaits adapter or runtime code without letting it hold the run hostage: + * resolves when `work` settles, when `signal` aborts, or after `ms`. + * A rejection of `work` is rethrown. + */ +function bounded(work: () => Promise, opts: { signal?: AbortSignal; ms?: number }): Promise> { + return new Promise((resolve, reject) => { + let timer: NodeJS.Timeout | undefined; + const cleanup = (): void => { + if (timer) clearTimeout(timer); + opts.signal?.removeEventListener('abort', onAbort); + }; + const onAbort = (): void => { + cleanup(); + resolve({ done: false, why: 'aborted' }); + }; + if (opts.signal?.aborted) return resolve({ done: false, why: 'aborted' }); + opts.signal?.addEventListener('abort', onAbort, { once: true }); + if (opts.ms !== undefined) { + timer = setTimeout(() => { + cleanup(); + resolve({ done: false, why: 'timeout' }); + }, Math.max(0, opts.ms)); + } + let pending: Promise; + try { + pending = Promise.resolve(work()); + } catch (err) { + pending = Promise.reject(err); + } + pending.then( + (value) => { + cleanup(); + resolve({ done: true, value }); + }, + (err: unknown) => { + cleanup(); + reject(err); + }, + ); + }); +} + +async function rollbackBounded(tx: Transaction, ms: number, warnings: string[]): Promise { + try { + const r = await bounded(() => tx.rollback(), { ms }); + if (r.done) return r.value; + warnings.push(`rollback did not finish within ${ms} ms; some files may not be restored.`); + } catch (err) { + warnings.push(`rollback failed: ${errorMessage(err)}`); + } + return undefined; } /** Applies defaults and clamps the timeout to `[1, min(maxTimeoutMs, MAX_RUN_TIMEOUT_MS)]`. */ @@ -145,11 +205,15 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise stop('timeout'), timeoutMs + graceMs); try { let policy: PolicySnapshot

| PolicyLoadError; try { - policy = await deps.adapter.loadPolicy(deps.ctx); + const loaded = await bounded(() => deps.adapter.loadPolicy(deps.ctx), { signal: controller.signal }); + policy = loaded.done ? loaded.value : { error: 'the run stopped while the host policy was loading' }; } catch (err) { policy = { error: errorMessage(err) }; } @@ -165,9 +229,6 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise stop('timeout'), timeoutMs + graceMs); - let outcome: SandboxOutcome; if (stopReason !== undefined) { outcome = { ok: false, kind: 'killed', error: { name: 'Killed', message: 'the run was stopped before the script started' } }; @@ -189,18 +250,14 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise 0) { warnings.push(`${active.bashCommits} bash call(s) ran in this transaction; bash effects are never rolled back.`); } @@ -217,16 +274,9 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise(req: RunRequest, deps: RunDeps

): Promise journal.dispose(), { ms: graceMs }).catch(() => undefined); } } } diff --git a/src/core/types.ts b/src/core/types.ts index bc83bc6..34193eb 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -473,12 +473,17 @@ export interface HostAdapter

{ policy: PolicySnapshot

, signal: AbortSignal, ): Promise; - /** Optional PostToolUse hooks. Errors are reported as warnings, never change the result. */ + /** + * Optional PostToolUse hooks. Errors are reported as warnings, never change + * the result. Must honor `signal` (kill running hooks); the dispatcher stops + * waiting when it aborts. + */ postToolUse?( prepared: PreparedCall, result: ToolResult, ctx: SessionContext, policy: PolicySnapshot

, + signal: AbortSignal, ): Promise; } diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 0c0644f..6863a74 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -150,6 +150,21 @@ describe('MCP server', () => { expect(seen[0]).toMatchObject({ host: 'codex', sessionId: 's1', turnId: 't1', model: 'm', sandboxMode: 'read-only' }); }); + it('caps protocol and validation errors like any other result', async () => { + const { client } = await connect(); + const unknown = await client.callTool({ name: 'x'.repeat(100_000), arguments: {} }); + expect(unknown.isError).toBe(true); + const text = textOf(unknown); + expect(text.length).toBeLessThanOrEqual(9_500); + const body = JSON.parse(text) as { overflowPath?: string; truncated?: boolean }; + expect(body.truncated).toBe(true); + expect(typeof body.overflowPath).toBe('string'); + + const invalid = await client.callTool({ name: 'run', arguments: { code: 'x', transaction: 'y'.repeat(100_000) } }); + expect(invalid.isError).toBe(true); + expect(textOf(invalid).length).toBeLessThanOrEqual(9_500); + }); + it('returns isError for invalid arguments and unknown tools', async () => { const { client } = await connect(); const bad = await client.callTool({ name: 'run', arguments: { code: 42 } }); diff --git a/src/server/mcp.ts b/src/server/mcp.ts index 0f50e41..9f3961c 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -6,7 +6,7 @@ import { formatRunResult, type McpToolResponse } from '../core/output.js'; import { runScript, toRunRequest } from '../core/run.js'; import { RUN_INPUT_JSON_SCHEMA, parseRunArgs } from '../core/schemas.js'; import { stateDirPath } from '../core/state-dir.js'; -import type { HostKind } from '../core/types.js'; +import type { HostKind, RunResult } from '../core/types.js'; import { detectHost } from './context.js'; import { createRuntime, type Runtime, type RuntimeFactory } from './runtime.js'; @@ -45,8 +45,9 @@ export interface McpServerOptions { readonly rootsTimeoutMs?: number; } -function errorResponse(message: string): McpToolResponse { - return { content: [{ type: 'text', text: JSON.stringify({ ok: false, error: { kind: 'internal', name: 'Error', message } }) }], isError: true }; +/** A failed `RunResult` for protocol and validation errors, so they go through the same capped formatter. */ +function errorResult(message: string): RunResult { + return { ok: false, error: { kind: 'internal', name: 'Error', message }, logs: [], calls: [], changedFiles: [], diff: '', warnings: [] }; } function rootPaths(roots: readonly { uri: string }[]): string[] { @@ -93,9 +94,10 @@ export function createMcpServer(opts: McpServerOptions): Server { server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [RUN_TOOL] })); server.setRequestHandler(CallToolRequestSchema, async (request, extra): Promise => { - if (request.params.name !== RUN_TOOL.name) return errorResponse(`unknown tool ${JSON.stringify(request.params.name)}`); + const respond = (result: RunResult): Promise => formatRunResult(result, { stateDir }); + if (request.params.name !== RUN_TOOL.name) return respond(errorResult(`unknown tool ${JSON.stringify(request.params.name)}`)); const args = parseRunArgs(request.params.arguments); - if (!args.ok) return errorResponse(`invalid run arguments: ${args.message}`); + if (!args.ok) return respond(errorResult(`invalid run arguments: ${args.message}`)); try { const meta: unknown = request.params._meta; const host = detectHost({ flag: opts.host, env, meta }); @@ -110,9 +112,9 @@ export function createMcpServer(opts: McpServerOptions): Server { signal: extra.signal, maxTimeoutMs: runtime.maxTimeoutMs, }); - return await formatRunResult(result, { stateDir }); + return await respond(result); } catch (err) { - return errorResponse(`internal error: ${errorMessage(err)}`); + return respond(errorResult(`internal error: ${errorMessage(err)}`)); } }); From 6ba5f52f564f8434d38c93ca269da008c27bde68 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:41:24 -0300 Subject: [PATCH 03/18] Claude Code host adapter: permissions, hooks, session context Implements HostAdapter and the context store for Claude Code in src/hosts/claude: settings from every source with Claude's precedence, deny/ask/allow permission rules (Bash with a real shell parser, Read/Edit gitignore-style paths), permission modes, PreToolUse/PostToolUse command and http hooks with the native payload (fail-closed), sandbox containment, protected paths, and the companion hook that records trusted session context keyed by the tool-use id. Adds sh-syntax (mvdan/sh compiled to WASM, synchronous, no dependencies) to parse Bash commands. Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 13 + package.json | 1 + src/hosts/claude/adapter.test.ts | 612 +++++++++++++++++++++ src/hosts/claude/adapter.ts | 568 +++++++++++++++++++ src/hosts/claude/bash.ts | 475 ++++++++++++++++ src/hosts/claude/context-hook.ts | 92 ++++ src/hosts/claude/context.test.ts | 133 +++++ src/hosts/claude/context.ts | 101 ++++ src/hosts/claude/fixtures/deny-rm.sh | 7 + src/hosts/claude/fixtures/example-hook.mjs | 72 +++ src/hosts/claude/hooks.ts | 418 ++++++++++++++ src/hosts/claude/index.ts | 4 + src/hosts/claude/parent-args.ts | 170 ++++++ src/hosts/claude/rules.test.ts | 140 +++++ src/hosts/claude/rules.ts | 304 ++++++++++ src/hosts/claude/settings.test.ts | 163 ++++++ src/hosts/claude/settings.ts | 380 +++++++++++++ 17 files changed, 3653 insertions(+) create mode 100644 src/hosts/claude/adapter.test.ts create mode 100644 src/hosts/claude/adapter.ts create mode 100644 src/hosts/claude/bash.ts create mode 100644 src/hosts/claude/context-hook.ts create mode 100644 src/hosts/claude/context.test.ts create mode 100644 src/hosts/claude/context.ts create mode 100755 src/hosts/claude/fixtures/deny-rm.sh create mode 100644 src/hosts/claude/fixtures/example-hook.mjs create mode 100644 src/hosts/claude/hooks.ts create mode 100644 src/hosts/claude/index.ts create mode 100644 src/hosts/claude/parent-args.ts create mode 100644 src/hosts/claude/rules.test.ts create mode 100644 src/hosts/claude/rules.ts create mode 100644 src/hosts/claude/settings.test.ts create mode 100644 src/hosts/claude/settings.ts diff --git a/package-lock.json b/package-lock.json index 596f70d..13cc300 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "license": "Apache-2.0", "dependencies": { "@modelcontextprotocol/sdk": "^1.32.2", + "sh-syntax": "^0.8.7", "zod": "^4.6.7" }, "bin": { @@ -2381,6 +2382,18 @@ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", "license": "ISC" }, + "node_modules/sh-syntax": { + "version": "0.8.7", + "resolved": "https://registry.npmjs.org/sh-syntax/-/sh-syntax-0.8.7.tgz", + "integrity": "sha512-zaJUdXFCbDFgtREm3KiqvX3dBlngGY0tumPzHvC5RqX67UuaBLIIZqb16MCbYLGyk5rPYrM+5FlghF+w6WdVUw==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "funding": { + "url": "https://opencollective.com/sh-syntax" + } + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", diff --git a/package.json b/package.json index 1d1997d..817729f 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ }, "dependencies": { "@modelcontextprotocol/sdk": "^1.32.2", + "sh-syntax": "^0.8.7", "zod": "^4.6.7" }, "devDependencies": { diff --git a/src/hosts/claude/adapter.test.ts b/src/hosts/claude/adapter.test.ts new file mode 100644 index 0000000..d62af93 --- /dev/null +++ b/src/hosts/claude/adapter.test.ts @@ -0,0 +1,612 @@ +import { mkdir, mkdtemp, readFile, realpath, symlink, writeFile } from 'node:fs/promises'; +import { createServer, type Server } from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterAll, describe, expect, it } from 'vitest'; +import { Dispatcher } from '../../core/dispatcher.js'; +import type { Decision, PolicySnapshot, PreparedCall, SessionContext } from '../../core/types.js'; +import { MemoryToolRuntime, makeContext } from '../../testing/index.js'; +import { ClaudeHostAdapter, type ClaudePolicy } from './adapter.js'; + +const posix = process.platform !== 'win32'; +const FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), 'fixtures'); +const HOOK = path.join(FIXTURES, 'example-hook.mjs'); + +/** A command hook handler running the example hook in `mode`. */ +function exampleHook(mode: string, arg?: string, extra: Record = {}): Record { + return { type: 'command', command: process.execPath, args: [HOOK, mode, ...(arg === undefined ? [] : [arg])], ...extra }; +} + +function preHooks(matcher: string, ...hooks: Record[]): Record { + return { hooks: { PreToolUse: [{ matcher, hooks }] } }; +} + +interface Setup { + readonly adapter: ClaudeHostAdapter; + readonly ctx: SessionContext; + readonly policy: PolicySnapshot; + readonly project: string; + readonly home: string; + readonly base: string; +} + +interface SetupOptions { + readonly project?: Record; + readonly local?: Record; + readonly user?: Record; + /** Extra Claude CLI args seen on the parent process. */ + readonly argv?: readonly string[]; + readonly trusted?: boolean; + /** Live permission mode from the companion hook. */ + readonly mode?: string; + readonly env?: Record; + readonly files?: Record; +} + +async function setup(o: SetupOptions = {}): Promise { + const base = await realpath(await mkdtemp(path.join(os.tmpdir(), 'acm-claude-'))); + const home = path.join(base, 'home'); + const project = path.join(base, 'project'); + await mkdir(path.join(home, '.claude'), { recursive: true }); + await mkdir(path.join(project, '.claude'), { recursive: true }); + if (o.project) await writeFile(path.join(project, '.claude', 'settings.json'), JSON.stringify(o.project)); + if (o.local) await writeFile(path.join(project, '.claude', 'settings.local.json'), JSON.stringify(o.local)); + if (o.user) await writeFile(path.join(home, '.claude', 'settings.json'), JSON.stringify(o.user)); + if (o.trusted !== false) await writeFile(path.join(home, '.claude.json'), JSON.stringify({ projects: { [project]: { hasTrustDialogAccepted: true } } })); + for (const [rel, content] of Object.entries(o.files ?? {})) { + await mkdir(path.dirname(path.join(project, rel)), { recursive: true }); + await writeFile(path.join(project, rel), content); + } + const adapter = new ClaudeHostAdapter({ + env: o.env ?? {}, + home, + managedDir: null, + stateDir: path.join(base, 'state'), + readParent: async () => (o.argv ? { argv: ['claude', ...o.argv], cwd: project } : undefined), + }); + const ctx = makeContext(project, { + host: 'claude', + sessionId: 'session-1', + toolUseId: 'toolu_1', + transcriptPath: path.join(base, 't.jsonl'), + permissionMode: o.mode ?? 'default', + sources: o.mode === undefined ? { cwd: 'roots' } : { cwd: 'roots', permissionMode: 'ctx-file' }, + }); + const policy = await adapter.loadPolicy(ctx); + if ('error' in policy) throw new Error(policy.error); + return { adapter, ctx, policy, project, home, base }; +} + +const containment = { mode: 'none' } as const; + +function bash(command: string, cwd: string): PreparedCall { + return { id: 'c1', tool: 'bash', args: { command, cwd, timeoutMs: 120_000 }, effect: { command, cwd, timeoutMs: 120_000, containment } }; +} +function read(p: string, real = p): PreparedCall { + return { id: 'c1', tool: 'read', args: { path: p, offset: 1, limit: 2000 }, effect: { absPath: real, offset: 1, limit: 2000 } }; +} +function write(p: string, content = 'x'): PreparedCall { + return { id: 'c1', tool: 'write', args: { path: p, content }, effect: { absPath: p, beforeHash: null, afterContent: content, diff: '' } }; +} +function edit(p: string, matched: string, newString: string): PreparedCall { + return { + id: 'c1', + tool: 'edit', + args: { path: p, oldString: matched.trim(), newString }, + effect: { absPath: p, beforeHash: 'h', afterContent: newString, diff: '', matchedOldString: matched, matchStrategy: 'line-trimmed', replacements: 1 }, + }; +} +function grep(root: string): PreparedCall { + return { id: 'c1', tool: 'grep', args: { pattern: 'x', path: root }, effect: { absRoot: root, pattern: 'x', glob: '*.ts', ignoreCase: true, maxResults: 50 } }; +} +function glob(root: string): PreparedCall { + return { id: 'c1', tool: 'glob', args: { pattern: '**/*.ts', path: root }, effect: { absRoot: root, pattern: '**/*.ts', maxResults: 50 } }; +} + +function check(s: Setup, prepared: PreparedCall): Decision['kind'] { + return s.adapter.checkStatic(prepared, s.ctx, s.policy).kind; +} + +function authorize(s: Setup, prepared: PreparedCall, signal = new AbortController().signal): Promise { + return s.adapter.authorize(prepared, s.ctx, s.policy, signal); +} + +describe('Bash rules', () => { + it.each([ + ['echo ok && rm -rf x', 'deny'], + ['echo $(rm -rf x)', 'deny'], + ['echo `rm x`', 'deny'], + ['FOO=1 rm x', 'deny'], + ['timeout 5 rm x', 'deny'], + ['sudo rm x', 'deny'], + ['sudo -u root rm x', 'deny'], + ["bash -c 'rm x'", 'deny'], + ['sh -ec "echo a; rm x"', 'deny'], + ['nice -n 5 nohup rm x', 'deny'], + ['env A=1 rm x', 'deny'], + ['/bin/rm -rf build', 'deny'], + ['ls | xargs rm', 'deny'], + ['ls | xargs -n1 rm', 'deny'], + ['find . -name a -exec rm {} \\;', 'deny'], + ['cat <(rm z)', 'deny'], + ['(cd sub && rm x)', 'deny'], + ['for f in a b; do rm "$f"; done', 'deny'], + ['rm', 'deny'], + ['rm $TARGET', 'deny'], + ['echo ok', 'allow'], + ['rmdir x', 'allow'], + ['echo rm', 'allow'], + ['echo "unbalanced', 'ask'], + ['eval "$X"', 'ask'], + ['cat < { + const s = await setup({ user: { permissions: { deny: ['Bash(rm:*)'] } }, mode: 'bypassPermissions' }); + expect(check(s, bash(command, s.project))).toBe(expected); + }); + + it('applies ask rules after deny rules, in every mode', async () => { + const s = await setup({ user: { permissions: { deny: ['Bash(git push --force *)'], ask: ['Bash(git push *)'] } }, mode: 'bypassPermissions' }); + expect(check(s, bash('git push --force origin', s.project))).toBe('deny'); + expect(check(s, bash('git push origin main', s.project))).toBe('ask'); + expect(check(s, bash('cd x && echo "$(git push)"', s.project))).toBe('ask'); + expect(check(s, bash('git status', s.project))).toBe('allow'); + }); + + it('matches a parameter rule and the ambiguous timeout command', async () => { + const s = await setup({ user: { permissions: { deny: ['Bash(timeout:*)'] } }, mode: 'bypassPermissions' }); + // `timeout:*` is both a parameter rule (any timeout) and a `timeout` prefix rule: strict reading denies. + expect(check(s, bash('echo hi', s.project))).toBe('deny'); + }); + + it('allow rules approve only when every subcommand is approved', async () => { + const s = await setup({ user: { permissions: { allow: ['Bash(npm run *)', 'Bash(git status)'] } } }); + expect(check(s, bash('npm run build', s.project))).toBe('allow'); + expect(check(s, bash('npm run build && git status', s.project))).toBe('allow'); + expect(check(s, bash('timeout 30 npm run test', s.project))).toBe('allow'); + expect(check(s, bash('npm run build && rm -rf x', s.project))).toBe('ask'); + expect(check(s, bash('NODE_ENV=x npm run build', s.project))).toBe('ask'); + expect(check(s, bash('sudo npm run build', s.project))).toBe('ask'); + expect(check(s, bash('npm install', s.project))).toBe('ask'); + expect(check(s, bash('npm run build > /tmp/out.log', s.project))).toBe('ask'); + expect(check(s, bash('npm run build > out.log', s.project))).toBe('allow'); + }); + + it('checks redirect and file-reader targets against Read/Edit rules', async () => { + const s = await setup({ user: { permissions: { deny: ['Read(./.env)', 'Edit(./locked/**)'] } }, mode: 'bypassPermissions' }); + expect(check(s, bash('cat .env', s.project))).toBe('deny'); + expect(check(s, bash('wc -l < .env', s.project))).toBe('deny'); + expect(check(s, bash('echo x > .env', s.project))).toBe('deny'); // a Read deny also blocks writes + expect(check(s, bash('echo x > locked/a.txt', s.project))).toBe('deny'); + expect(check(s, bash('echo x | tee locked/a.txt', s.project))).toBe('deny'); + expect(check(s, bash('echo x > "$OUT"', s.project))).toBe('ask'); + expect(check(s, bash('cd sub && cat .env', s.project))).toBe('ask'); + expect(check(s, bash('echo x > notes.txt', s.project))).toBe('allow'); + expect(check(s, bash('cat README.md 2>/dev/null', s.project))).toBe('allow'); + }); +}); + +describe('path rules', () => { + it('anchors //, ~/, /, ./ and bare patterns like gitignore', async () => { + const s = await setup({ + project: { permissions: { deny: ['Read(./.env)', 'Edit(/src/generated/**)', 'Read(secrets/**)', 'Read(*.pem)'] } }, + user: { permissions: { deny: ['Read(~/notes/secret.txt)', 'Read(//etc/example-shadow)', 'Read(/private/**)'] } }, + mode: 'bypassPermissions', + }); + const p = (rel: string): string => path.join(s.project, rel); + expect(check(s, read(p('.env')))).toBe('deny'); + expect(check(s, read(p('sub/.env')))).toBe('allow'); // ./ is anchored + expect(check(s, read(path.join(s.home, 'notes', 'secret.txt')))).toBe('deny'); + expect(check(s, read('/etc/example-shadow'))).toBe('deny'); + expect(check(s, write(p('src/generated/a.ts')))).toBe('deny'); + expect(check(s, edit(p('src/generated/deep/b.ts'), 'a', 'b'))).toBe('deny'); + expect(check(s, write(p('src/a.ts')))).toBe('allow'); + expect(check(s, write(p('vendor/src/generated/a.ts')))).toBe('allow'); + expect(check(s, read(p('a/b/secrets/key')))).toBe('deny'); // single-dir deny matches at any depth + expect(check(s, read(p('certs/x.pem')))).toBe('deny'); // bare name: any depth + expect(check(s, read(path.join(s.home, '.claude', 'private', 'x')))).toBe('deny'); // `/` in user settings → config dir + expect(check(s, read(p('private/x')))).toBe('allow'); + expect(check(s, write(p('.env')))).toBe('deny'); // Read deny blocks Write + expect(check(s, grep(p('a/secrets')))).toBe('deny'); // Read rules govern Grep + expect(check(s, glob(p('secrets')))).toBe('deny'); // and Glob + expect(check(s, grep(p('src')))).toBe('allow'); + }); + + it.skipIf(!posix)('checks the real path, so a symlink cannot dodge a deny', async () => { + const s = await setup({ project: { permissions: { deny: ['Read(./.env)'] } }, mode: 'bypassPermissions', files: { '.env': 'SECRET=1' } }); + await symlink(path.join(s.project, '.env'), path.join(s.project, 'innocent.txt')); + const real = await realpath(path.join(s.project, 'innocent.txt')); + expect(check(s, read(path.join(s.project, 'innocent.txt'), real))).toBe('deny'); + }); + + it.skipIf(!posix)('applies a rule written through a symlinked directory to the real location', async () => { + const s0 = await setup(); + const realDir = path.join(s0.base, 'real-secrets'); + await mkdir(realDir); + await symlink(realDir, path.join(s0.base, 'alias')); + const s = await setup({ user: { permissions: { deny: [`Read(/${path.join(s0.base, 'alias')}/**)`] } }, mode: 'bypassPermissions' }); + expect(check(s, read(path.join(realDir, 'k')))).toBe('deny'); + }); + + it('allow rules need both the requested and the real path to match', async () => { + const s = await setup({ user: { permissions: { allow: ['Read(//opt/shared/**)'] } } }); + expect(check(s, read('/opt/shared/a'))).toBe('allow'); + expect(check(s, read('/opt/shared/link', '/etc/passwd'))).toBe('ask'); + }); +}); + +describe('permission modes (no rule matches)', () => { + const cases: Record> = { + default: { readIn: 'allow', readOut: 'ask', writeIn: 'ask', writeOut: 'ask', editIn: 'ask', bash: 'ask', grepIn: 'allow', globIn: 'allow' }, + acceptEdits: { readIn: 'allow', readOut: 'ask', writeIn: 'allow', writeOut: 'ask', editIn: 'allow', bash: 'ask', grepIn: 'allow', globIn: 'allow' }, + plan: { readIn: 'allow', readOut: 'ask', writeIn: 'deny', writeOut: 'deny', editIn: 'deny', bash: 'deny', grepIn: 'allow', globIn: 'allow' }, + dontAsk: { readIn: 'allow', readOut: 'deny', writeIn: 'deny', writeOut: 'deny', editIn: 'deny', bash: 'deny', grepIn: 'allow', globIn: 'allow' }, + auto: { readIn: 'allow', readOut: 'allow', writeIn: 'allow', writeOut: 'allow', editIn: 'allow', bash: 'allow', grepIn: 'allow', globIn: 'allow' }, + bypassPermissions: { readIn: 'allow', readOut: 'allow', writeIn: 'allow', writeOut: 'allow', editIn: 'allow', bash: 'allow', grepIn: 'allow', globIn: 'allow' }, + 'not-a-mode': { readIn: 'allow', readOut: 'ask', writeIn: 'ask', writeOut: 'ask', editIn: 'ask', bash: 'ask', grepIn: 'allow', globIn: 'allow' }, + }; + for (const [mode, expected] of Object.entries(cases)) { + it(`${mode}`, async () => { + const s = await setup({ mode }); + const inside = path.join(s.project, 'a.ts'); + const outside = path.join(s.base, 'elsewhere', 'b.ts'); + const got = { + readIn: check(s, read(inside)), + readOut: check(s, read(outside)), + writeIn: check(s, write(inside)), + writeOut: check(s, write(outside)), + editIn: check(s, edit(inside, 'a', 'b')), + bash: check(s, bash('ls', s.project)), + grepIn: check(s, grep(s.project)), + globIn: check(s, glob(s.project)), + }; + expect(got).toEqual(expected); + }); + } + + it('ask rules still ask in bypassPermissions and deny in dontAsk', async () => { + const ask = { user: { permissions: { ask: ['Read(./a.ts)'] } } }; + const bypass = await setup({ ...ask, mode: 'bypassPermissions' }); + expect(check(bypass, read(path.join(bypass.project, 'a.ts')))).toBe('ask'); + const dontAsk = await setup({ ...ask, mode: 'dontAsk' }); + expect(check(dontAsk, read(path.join(dontAsk.project, 'a.ts')))).toBe('deny'); + }); + + it('takes the mode from the companion hook, else the CLI flag, else settings defaultMode', async () => { + const fromFlag = await setup({ argv: ['--permission-mode', 'acceptEdits'], user: { permissions: { defaultMode: 'plan' } } }); + expect(check(fromFlag, write(path.join(fromFlag.project, 'a.ts')))).toBe('allow'); + const fromSettings = await setup({ user: { permissions: { defaultMode: 'plan' } } }); + expect(check(fromSettings, write(path.join(fromSettings.project, 'a.ts')))).toBe('deny'); + const fromCtx = await setup({ mode: 'bypassPermissions', argv: ['--permission-mode', 'plan'] }); + expect(check(fromCtx, bash('ls', fromCtx.project))).toBe('allow'); + const locked = await setup({ mode: 'bypassPermissions', user: { permissions: { disableBypassPermissionsMode: 'disable' } } }); + expect(check(locked, bash('ls', locked.project))).toBe('ask'); + }); + + it('additionalDirectories count as working directories', async () => { + const s = await setup({ user: { permissions: { additionalDirectories: ['~/shared'] } } }); + expect(check(s, read(path.join(s.home, 'shared', 'x')))).toBe('allow'); + }); +}); + +describe.skipIf(!posix)('PreToolUse hooks', () => { + const anyBash = (s: Setup): PreparedCall => bash('ls -la', s.project); + + it('exit 2 denies with stderr as the reason', async () => { + const s = await setup({ user: preHooks('Bash', exampleHook('exit2')) }); + expect(await authorize(s, anyBash(s))).toEqual({ kind: 'deny', source: 'hook', reason: 'blocked by example hook' }); + }); + + it('a shell-form hook script denies', async () => { + const s = await setup({ user: preHooks('Bash', { type: 'command', command: `"${path.join(FIXTURES, 'deny-rm.sh')}"` }) }); + expect(await authorize(s, bash('rm -rf build', s.project))).toMatchObject({ kind: 'deny', source: 'hook', reason: 'rm is not allowed' }); + expect(await authorize(s, bash('ls', s.project))).toEqual({ kind: 'allow' }); + }); + + it.each([ + ['deny', { kind: 'deny', source: 'hook' }], + ['legacy-block', { kind: 'deny', source: 'hook', reason: 'legacy block' }], + ['stop', { kind: 'deny', source: 'hook', reason: 'stop requested' }], + ['ask', { kind: 'ask' }], + ['defer', { kind: 'ask' }], + ['allow', { kind: 'allow' }], + ['empty', { kind: 'allow' }], + ['exit1', { kind: 'deny', source: 'hook-error' }], + ['crash', { kind: 'deny', source: 'hook-error' }], + ['invalid', { kind: 'deny', source: 'hook-error' }], + ['bad-decision', { kind: 'deny', source: 'hook-error' }], + ])('JSON/exit behavior %s', async (mode, expected) => { + const s = await setup({ user: preHooks('Bash', exampleHook(mode)) }); + expect(await authorize(s, anyBash(s))).toMatchObject(expected); + }); + + it('a hook that cannot start denies', async () => { + const s = await setup({ user: preHooks('Bash', { type: 'command', command: path.join(s0Dir(), 'missing-hook.sh') }) }); + expect(await authorize(s, anyBash(s))).toMatchObject({ kind: 'deny', source: 'hook-error' }); + }); + + it('honors onFailure: continue', async () => { + const s = await setup({ user: preHooks('Bash', exampleHook('crash', undefined, { onFailure: 'continue' })) }); + expect(await authorize(s, anyBash(s))).toEqual({ kind: 'allow' }); + }); + + it('times out, kills the hook and denies with hook-timeout', async () => { + const pidFile = path.join(os.tmpdir(), `acm-hook-pid-${process.pid}-${Date.now()}`); + const s = await setup({ user: preHooks('Bash', { type: 'command', command: `echo $$ > "${pidFile}"; exec sleep 30`, timeout: 0.5 }) }); + const started = Date.now(); + const decision = await authorize(s, anyBash(s)); + expect(decision).toMatchObject({ kind: 'deny', source: 'hook-timeout' }); + expect(Date.now() - started).toBeLessThan(5_000); + const pid = Number((await readFile(pidFile, 'utf8')).trim()); + await new Promise((r) => setTimeout(r, 100)); + expect(() => process.kill(pid, 0)).toThrow(); + }); + + it('rewrites the call with updatedInput (mapped back to binding args)', async () => { + const s = await setup({ user: preHooks('Bash', exampleHook('update', JSON.stringify({ command: 'echo safe', timeout: 5000 }))) }); + expect(await authorize(s, anyBash(s))).toEqual({ + kind: 'allow', + reason: 'example allow', + updatedArgs: { command: 'echo safe', cwd: s.project, timeoutMs: 5000 }, + }); + const w = await setup({ user: preHooks('Write', exampleHook('update-only', JSON.stringify({ file_path: '/x/y', content: 'clean' }))) }); + expect(await authorize(w, write(path.join(w.project, 'a')))).toMatchObject({ kind: 'allow', updatedArgs: { path: '/x/y', content: 'clean' } }); + const bad = await setup({ user: preHooks('Bash', exampleHook('update', JSON.stringify({ command: 'ls', run_in_background: true }))) }); + expect(await authorize(bad, anyBash(bad))).toMatchObject({ kind: 'deny', source: 'hook' }); + }); + + it('matches tool names exactly or by regex', async () => { + const exact = await setup({ user: preHooks('Edit|Write', exampleHook('deny')) }); + expect((await authorize(exact, write(path.join(exact.project, 'a')))).kind).toBe('deny'); + expect((await authorize(exact, read(path.join(exact.project, 'a')))).kind).toBe('allow'); + const partial = await setup({ user: preHooks('Bas', exampleHook('deny')) }); + expect((await authorize(partial, anyBash(partial))).kind).toBe('allow'); + const regex = await setup({ user: preHooks('^(Bash|Read)$', exampleHook('deny')) }); + expect((await authorize(regex, read(path.join(regex.project, 'a')))).kind).toBe('deny'); + expect((await authorize(regex, glob(regex.project))).kind).toBe('allow'); + const all = await setup({ user: preHooks('*', exampleHook('deny')) }); + expect((await authorize(all, grep(all.project))).kind).toBe('deny'); + }); + + it('combines parallel hooks: deny > ask > allow; two updatedInputs are refused', async () => { + const denyWins = await setup({ user: preHooks('Bash', exampleHook('allow'), exampleHook('deny'), exampleHook('ask')) }); + expect((await authorize(denyWins, anyBash(denyWins))).kind).toBe('deny'); + const askWins = await setup({ user: preHooks('Bash', exampleHook('allow'), exampleHook('ask')) }); + expect((await authorize(askWins, anyBash(askWins))).kind).toBe('ask'); + const twoUpdates = await setup({ + user: preHooks('Bash', exampleHook('update', JSON.stringify({ command: 'a' })), exampleHook('update', JSON.stringify({ command: 'b' }))), + }); + expect(await authorize(twoUpdates, anyBash(twoUpdates))).toMatchObject({ kind: 'deny', source: 'unsupported-config' }); + const started = Date.now(); + const slow = await setup({ user: preHooks('Bash', exampleHook('sleep', '600'), exampleHook('sleep', '600'), exampleHook('sleep', '600')) }); + expect((await authorize(slow, anyBash(slow))).kind).toBe('allow'); + expect(Date.now() - started).toBeLessThan(1_700); // ran in parallel, not 1.8 s in sequence + }); + + it('merges hooks from every source and runs a duplicate once', async () => { + const record = path.join(os.tmpdir(), `acm-dup-${process.pid}-${Date.now()}`); + const hook = { type: 'command', command: `echo run >> "${record}"` }; + const s = await setup({ user: preHooks('Bash', hook), project: preHooks('Bash', hook) }); + await authorize(s, anyBash(s)); + expect((await readFile(record, 'utf8')).trim().split('\n')).toEqual(['run']); + }); + + it('disableAllHooks turns hooks off', async () => { + const s = await setup({ user: preHooks('Bash', exampleHook('deny')), project: { disableAllHooks: true } }); + expect((await authorize(s, anyBash(s))).kind).toBe('allow'); + }); + + it('a hook type it cannot evaluate denies matching calls with unsupported-config', async () => { + const s = await setup({ user: preHooks('Bash', { type: 'prompt', prompt: 'Is this safe? $ARGUMENTS' }) }); + expect(await authorize(s, anyBash(s))).toMatchObject({ kind: 'deny', source: 'unsupported-config' }); + expect((await authorize(s, read(path.join(s.project, 'a')))).kind).toBe('allow'); // matcher does not match + const weird = await setup({ user: preHooks('Bash', { type: 'teleport' }) }); + expect(await authorize(weird, anyBash(weird))).toMatchObject({ kind: 'deny', source: 'unsupported-config' }); + }); + + it('honors the `if` filter', async () => { + const s = await setup({ user: preHooks('Bash', exampleHook('deny', undefined, { if: 'Bash(git push *)' })) }); + expect((await authorize(s, bash('git status', s.project))).kind).toBe('allow'); + expect((await authorize(s, bash('npm test && git push origin', s.project))).kind).toBe('deny'); + expect((await authorize(s, bash('echo $(date)', s.project))).kind).toBe('deny'); // dynamic: runs anyway + }); + + it('exec form substitutes ${CLAUDE_PROJECT_DIR} and exports it', async () => { + const s = await setup({ files: { '.claude/hooks/check.mjs': "process.stderr.write(process.env.CLAUDE_PROJECT_DIR + '|' + process.argv[2]); process.exit(2);" } }); + const s2 = await setup({ user: preHooks('Bash', { type: 'command', command: process.execPath, args: [`${s.project}/.claude/hooks/check.mjs`, '${CLAUDE_PROJECT_DIR}'] }) }); + const d = await authorize(s2, anyBash(s2)); + expect(d).toEqual({ kind: 'deny', source: 'hook', reason: `${s2.project}|${s2.project}` }); + }); + + it('runs hooks of enabled plugins', async () => { + const s0 = await setup(); + const pluginRoot = path.join(s0.base, 'plugin'); + await mkdir(path.join(pluginRoot, 'hooks'), { recursive: true }); + await writeFile(path.join(pluginRoot, 'hooks', 'hooks.json'), JSON.stringify(preHooks('Bash', exampleHook('deny')))); + const configDir = path.join(s0.base, 'config'); + await mkdir(path.join(configDir, 'plugins'), { recursive: true }); + await writeFile(path.join(configDir, 'plugins', 'installed_plugins.json'), JSON.stringify({ plugins: { 'guard@example': [{ installPath: pluginRoot }] } })); + await writeFile(path.join(configDir, 'settings.json'), JSON.stringify({ enabledPlugins: { 'guard@example': true } })); + const s = await setup({ env: { CLAUDE_CONFIG_DIR: configDir } }); + expect(await authorize(s, anyBash(s))).toMatchObject({ kind: 'deny', source: 'hook' }); + }); + + it('sends the exact native payload (byte-identical command)', async () => { + const out = path.join(os.tmpdir(), `acm-payload-${process.pid}-${Date.now()}.json`); + const s = await setup({ user: preHooks('*', exampleHook('record', out)) }); + const command = 'printf "%s" \'héllo "wörld"\' && echo ✓\nline two\t$HOME \\n'; + expect((await authorize(s, bash(command, path.join(s.project, 'sub')))).kind).toBe('allow'); + const payload: unknown = JSON.parse(await readFile(out, 'utf8')); + expect(payload).toEqual({ + session_id: 'session-1', + transcript_path: path.join(s.base, 't.jsonl'), + cwd: path.join(s.project, 'sub'), + permission_mode: 'default', + hook_event_name: 'PreToolUse', + tool_name: 'Bash', + tool_input: { command, timeout: 120_000, description: 'agent-code-mode script call c1', run_in_background: false }, + tool_use_id: 'toolu_1/c1', + }); + + await authorize(s, edit(path.join(s.project, 'a.ts'), ' const a = 1;', 'const a = 2;')); + expect(JSON.parse(await readFile(out, 'utf8'))).toMatchObject({ + tool_name: 'Edit', + tool_input: { file_path: path.join(s.project, 'a.ts'), old_string: ' const a = 1;', new_string: 'const a = 2;', replace_all: false }, + }); + await authorize(s, grep(s.project)); + expect(JSON.parse(await readFile(out, 'utf8'))).toMatchObject({ + tool_name: 'Grep', + tool_input: { pattern: 'x', path: s.project, glob: '*.ts', '-i': true, output_mode: 'content', '-n': true, head_limit: 50 }, + }); + }); + + it('kills running hooks when the signal aborts', async () => { + const s = await setup({ user: preHooks('Bash', exampleHook('sleep', '30000')) }); + const controller = new AbortController(); + const started = Date.now(); + const pending = authorize(s, anyBash(s), controller.signal); + setTimeout(() => controller.abort(), 200); + expect((await pending).kind).toBe('deny'); + expect(Date.now() - started).toBeLessThan(5_000); + }); +}); + +function s0Dir(): string { + return os.tmpdir(); +} + +describe('HTTP hooks', () => { + let server: Server | undefined; + let url = ''; + let reply: { status: number; body: string } = { status: 200, body: '' }; + let lastBody = ''; + let lastAuth: string | undefined; + + async function start(): Promise { + if (server) return; + server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + lastBody = Buffer.concat(chunks).toString('utf8'); + lastAuth = req.headers['authorization']; + res.writeHead(reply.status, { 'content-type': 'application/json' }); + res.end(reply.body); + }); + }); + await new Promise((resolve) => server?.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (address === null || typeof address === 'string') throw new Error('no address'); + url = `http://127.0.0.1:${address.port}/hook`; + } + + afterAll(async () => { + await new Promise((r) => server?.close(r)); + }); + + it('POSTs the input and applies the JSON decision', async () => { + await start(); + reply = { status: 200, body: JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: 'http says no' } }) }; + const s = await setup({ + user: preHooks('Bash', { type: 'http', url, headers: { Authorization: 'Bearer $HOOK_TOKEN', 'X-Other': '$NOT_ALLOWED' }, allowedEnvVars: ['HOOK_TOKEN'] }), + }); + process.env['HOOK_TOKEN'] = 'tok'; + try { + expect(await authorize(s, bash('ls', s.project))).toEqual({ kind: 'deny', source: 'hook', reason: 'http says no' }); + } finally { + delete process.env['HOOK_TOKEN']; + } + expect(JSON.parse(lastBody)).toMatchObject({ tool_name: 'Bash', tool_input: { command: 'ls' } }); + expect(lastAuth).toBe('Bearer tok'); + }); + + it('treats a non-2xx status or a non-JSON body as a failure (deny) unless onFailure is continue', async () => { + await start(); + reply = { status: 500, body: 'oops' }; + const s = await setup({ user: preHooks('Bash', { type: 'http', url }) }); + expect(await authorize(s, bash('ls', s.project))).toMatchObject({ kind: 'deny', source: 'hook-error' }); + reply = { status: 200, body: 'plain text' }; + expect(await authorize(s, bash('ls', s.project))).toMatchObject({ kind: 'deny', source: 'hook-error' }); + reply = { status: 200, body: '' }; + expect(await authorize(s, bash('ls', s.project))).toEqual({ kind: 'allow' }); + reply = { status: 503, body: '' }; + const lenient = await setup({ user: preHooks('Bash', { type: 'http', url, onFailure: 'continue' }) }); + expect(await authorize(lenient, bash('ls', lenient.project))).toEqual({ kind: 'allow' }); + }); + + it('times out', async () => { + const hang = createServer(() => undefined); + await new Promise((resolve) => hang.listen(0, '127.0.0.1', resolve)); + const address = hang.address(); + if (address === null || typeof address === 'string') throw new Error('no address'); + const s = await setup({ user: preHooks('Bash', { type: 'http', url: `http://127.0.0.1:${address.port}/`, timeout: 0.3 }) }); + expect(await authorize(s, bash('ls', s.project))).toMatchObject({ kind: 'deny', source: 'hook-timeout' }); + hang.closeAllConnections(); + await new Promise((r) => hang.close(r)); + }); +}); + +describe.skipIf(!posix)('PostToolUse hooks', () => { + it('reports a block as an error the dispatcher turns into a warning', async () => { + const s = await setup({ user: { hooks: { PostToolUse: [{ matcher: 'Bash', hooks: [exampleHook('exit2')] }] } } }); + const result = { exitCode: 0, signal: null, stdout: 'ok', stderr: '', truncated: false, timedOut: false }; + await expect(s.adapter.postToolUse(bash('ls', s.project), result, s.ctx, s.policy)).rejects.toThrow(/blocked after the call ran.*blocked by example hook/); + const quiet = await setup({ user: { hooks: { PostToolUse: [{ matcher: 'Bash', hooks: [exampleHook('empty')] }] } } }); + await expect(quiet.adapter.postToolUse(bash('ls', quiet.project), result, quiet.ctx, quiet.policy)).resolves.toBeUndefined(); + }); +}); + +describe('policy snapshot', () => { + it('lists protected paths and no containment without the sandbox', async () => { + const s = await setup(); + expect(s.policy.bashContainment).toEqual({ mode: 'none' }); + expect(s.policy.protectedPaths).toEqual( + expect.arrayContaining([ + path.join(s.project, '.claude', 'settings*.json'), + path.join(s.project, '.claude', 'hooks', '**'), + path.join(s.project, '.claude', 'agents', '**'), + path.join(s.project, '.mcp.json'), + path.join(s.home, '.claude', '**'), + path.join(s.base, 'state', '**'), + ]), + ); + }); + + it('returns a sandbox containment when Claude sandboxing is enabled', async () => { + const s = await setup({ user: { sandbox: { enabled: true, filesystem: { allowWrite: ['~/.cache/tool', '/opt/build'] } }, permissions: { additionalDirectories: ['/opt/extra'] } } }); + expect(s.policy.bashContainment).toEqual({ + mode: 'sandbox', + readOnly: false, + writableRoots: [s.project, path.resolve('/opt/extra'), path.join(s.home, '.cache', 'tool'), path.resolve('/opt/build')], + network: false, + }); + }); +}); + +describe.skipIf(!posix)('with the dispatcher', () => { + it('re-prepares and re-checks a hook rewrite; a rewrite into a denied command is refused', async () => { + const s = await setup({ + user: { + permissions: { deny: ['Bash(rm:*)'] }, + hooks: { + PreToolUse: [ + { matcher: 'Write', hooks: [exampleHook('update', JSON.stringify({ file_path: '/workspace/a.txt', content: 'sanitized' }))] }, + { matcher: 'Bash', hooks: [exampleHook('update', JSON.stringify({ command: 'rm -rf /workspace' }))] }, + ], + }, + }, + mode: 'bypassPermissions', + }); + const tools = new MemoryToolRuntime({ root: '/workspace' }); + const ctx: SessionContext = { ...s.ctx, cwd: '/workspace', roots: ['/workspace'] }; + const dispatcher = new Dispatcher({ adapter: s.adapter, tools, ctx, policy: s.policy }); + const wrote = await dispatcher.dispatch('write', { path: 'a.txt', content: 'secret' }); + expect(wrote.ok).toBe(true); + expect(tools.read('a.txt')).toBe('sanitized'); + const ran = await dispatcher.dispatch('bash', { command: 'echo hi' }); + expect(ran).toMatchObject({ ok: false, error: { name: 'PermissionDenied', source: 'rule' } }); + }); +}); diff --git a/src/hosts/claude/adapter.ts b/src/hosts/claude/adapter.ts new file mode 100644 index 0000000..7266fb9 --- /dev/null +++ b/src/hosts/claude/adapter.ts @@ -0,0 +1,568 @@ +import { realpath } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { errorMessage } from '../../core/errors.js'; +import { stateDirPath } from '../../core/state-dir.js'; +import type { + BashContainment, + Decision, + HostAdapter, + PolicyLoadError, + PolicySnapshot, + PreparedCall, + SessionContext, + ToolResult, +} from '../../core/types.js'; +import { BashAnalyzer, type BashAnalysis } from './bash.js'; +import { + NATIVE_TOOL, + combineOutcomes, + mapUpdatedInput, + matcherMatches, + nativeCall, + nativeResponse, + runHook, + unsupportedReason, + type CompiledHook, + type HookOutcome, + type NativeCall, +} from './hooks.js'; +import { parseClaudeFlags, readParentClaudeProcess, type ClaudeCliFlags, type ParentArgsReader } from './parent-args.js'; +import { + bashSpecMayMatchDynamic, + isInsidePath, + matchesBashSpec, + matchesParamValue, + matchesPath, + matchesToolName, + parseRule, + resolveCommandPath, + toPosixPath, + type NativeToolName, + type PathPattern, + type Rule, + type RuleKind, +} from './rules.js'; +import { claudeConfigDir, firstSetting, loadSettings, managedSettingsDir, type LoadedSettings, type SettingsDoc } from './settings.js'; +import type { HookMatcherEntry } from './settings.js'; + +/** + * Claude Code host adapter. + * + * Static check (`checkStatic`, no I/O): permission rules from every settings + * source, deny → ask → allow, first match wins, then the permission mode for + * calls no rule decides. Hooks (`authorize`): the PreToolUse hooks that match + * the native tool name, run in parallel with the JSON Claude Code would send. + */ + +/** Claude permission modes. Unknown values are treated as `default`. */ +export type PermissionMode = 'default' | 'acceptEdits' | 'plan' | 'dontAsk' | 'auto' | 'bypassPermissions'; + +const MODES: readonly PermissionMode[] = ['default', 'acceptEdits', 'plan', 'dontAsk', 'auto', 'bypassPermissions']; + +function toMode(value: string | undefined): PermissionMode | undefined { + if (value === 'manual') return 'default'; + return MODES.find((m) => m === value); +} + +export interface ClaudePolicy { + readonly projectRoot: string; + readonly cwd: string; + readonly home: string; + readonly configDir: string; + readonly mode: PermissionMode; + readonly rules: { readonly deny: readonly Rule[]; readonly ask: readonly Rule[]; readonly allow: readonly Rule[] }; + /** Project root, MCP roots and additional directories: reads there need no approval. */ + readonly workingDirs: readonly string[]; + readonly preHooks: readonly CompiledHook[]; + readonly postHooks: readonly CompiledHook[]; + /** Env added for every hook. */ + readonly hookEnv: Readonly>; +} + +export interface ClaudeHostAdapterOptions { + readonly env?: Readonly>; + readonly home?: string; + /** Managed settings directory; `null` disables managed settings (tests). Defaults to the platform path. */ + readonly managedDir?: string | null; + /** Server state directory (protected). Defaults to `stateDirPath()`. */ + readonly stateDir?: string; + /** Reads the parent Claude process argv. Defaults to the platform reader. */ + readonly readParent?: ParentArgsReader; + readonly platform?: NodeJS.Platform; +} + +const NO_FLAGS: ClaudeCliFlags = { settings: [], allowedTools: [], disallowedTools: [], addDirs: [] }; + +/** Which native tools a rule's tool name governs. */ +function governs(rule: Rule, tool: NativeToolName): boolean { + if (matchesToolName(rule.tool, tool)) return true; + if (rule.tool === 'Read') return tool === 'Grep' || tool === 'Glob' || (rule.kind === 'deny' && (tool === 'Write' || tool === 'Edit')); + if (rule.tool === 'Edit') return tool === 'Write'; + return false; +} + +/** Paths a file call touches: the path as given in args (may be the requested path) and the real path of the effect. */ +function callPaths(prepared: PreparedCall): string[] { + switch (prepared.tool) { + case 'read': + case 'write': + case 'edit': + return [...new Set([prepared.args.path, prepared.effect.absPath])]; + case 'grep': + case 'glob': + return [...new Set([...(prepared.args.path === undefined ? [] : [prepared.args.path]), prepared.effect.absRoot])]; + case 'bash': + return []; + } +} + +type Verdict = 'match' | 'maybe' | 'no'; + +interface CallView { + readonly prepared: PreparedCall; + readonly native: NativeCall; + readonly analysis: BashAnalysis | undefined; + /** Resolved file targets of a bash command; undefined path = only known at run time. */ + readonly bashFiles: readonly { readonly access: 'read' | 'write'; readonly path: string | undefined }[]; +} + +function pathRuleVerdict(patterns: readonly PathPattern[], paths: readonly string[], kind: RuleKind): Verdict { + if (paths.length === 0) return 'no'; + const hits = paths.map((p) => matchesPath(p, patterns)); + // Deny/ask: either the requested or the real path. Allow: both. + return (kind === 'allow' ? hits.every(Boolean) : hits.some(Boolean)) ? 'match' : 'no'; +} + +/** Evaluates one deny/ask rule against a call. */ +function restrictVerdict(rule: Rule, view: CallView): Verdict { + const { prepared, native } = view; + const m = rule.matcher; + if (m.type === 'never') return 'no'; + if (prepared.tool === 'bash' && view.analysis) { + // File targets of the command (redirects, tee, cat ...) against Read/Edit rules. + let fileVerdict: Verdict = 'no'; + const targetTool = (access: 'read' | 'write'): NativeToolName => (access === 'read' ? 'Read' : 'Edit'); + for (const target of view.bashFiles) { + const asTool = targetTool(target.access); + if (!(matchesToolName(rule.tool, asTool) || (rule.tool === 'Read' && rule.kind === 'deny' && asTool === 'Edit'))) continue; + if (m.type === 'all') return 'match'; + if (m.type !== 'path') continue; + if (target.path === undefined) fileVerdict = 'maybe'; + else if (matchesPath(target.path, m.patterns)) return 'match'; + } + if (!governs(rule, 'Bash')) return fileVerdict; + if (m.type === 'all') return 'match'; + if (m.type === 'param') { + if (matchesParamValue(m.value, native.toolInput[m.name])) return 'match'; + if (m.bashSpec === undefined) return fileVerdict; + } + const spec = m.type === 'bash' ? m.spec : m.type === 'param' ? m.bashSpec : undefined; + if (spec === undefined) return fileVerdict; + let verdict: Verdict = fileVerdict; + for (const cmd of view.analysis.commands) { + if (cmd.denyForms.some((form) => matchesBashSpec(spec, form))) return 'match'; + if (cmd.dynamic && bashSpecMayMatchDynamic(spec, cmd.staticPrefix)) verdict = 'maybe'; + } + return verdict; + } + if (!governs(rule, native.toolName)) return 'no'; + switch (m.type) { + case 'all': + return 'match'; + case 'param': + return matchesParamValue(m.value, native.toolInput[m.name]) ? 'match' : 'no'; + case 'path': + return pathRuleVerdict(m.patterns, callPaths(prepared), rule.kind); + case 'bash': + return 'no'; + } +} + +function insideWorkingDirs(paths: readonly string[], dirs: readonly string[]): boolean { + return paths.length > 0 && paths.every((p) => dirs.some((d) => isInsidePath(p, d))); +} + +/** Whether allow rules approve the call. */ +function allowedByRule(view: CallView, rules: readonly Rule[], policy: ClaudePolicy): boolean { + const { prepared, native } = view; + const applicable = rules.filter((r) => r.matcher.type !== 'never'); + if (prepared.tool === 'bash') { + const analysis = view.analysis; + if (!analysis || analysis.uncertain.length > 0 || analysis.commands.length === 0) { + return applicable.some((r) => governs(r, 'Bash') && r.matcher.type === 'all'); + } + if (applicable.some((r) => governs(r, 'Bash') && r.matcher.type === 'all') && view.bashFiles.length === 0) return true; + // Every subcommand must be approved; files it names must be inside the working directories. + const everyCommand = analysis.commands.every((cmd) => { + const form = cmd.allowForm; + if (form === undefined) return false; + return applicable.some((r) => governs(r, 'Bash') && (r.matcher.type === 'all' || (r.matcher.type === 'bash' && matchesBashSpec(r.matcher.spec, form)))); + }); + const filesInside = view.bashFiles.every((f) => f.path !== undefined && policy.workingDirs.some((d) => isInsidePath(f.path ?? '', d))); + return everyCommand && filesInside; + } + const paths = callPaths(prepared); + return applicable.some((r) => { + if (!governs(r, native.toolName) || r.kind !== 'allow') return false; + if (r.matcher.type === 'all') return true; + if (r.matcher.type === 'path') return pathRuleVerdict(r.matcher.patterns, paths, 'allow') === 'match'; + return false; + }); +} + +/** What the permission mode does with a call that no rule decided. */ +function modeDecision(view: CallView, policy: ClaudePolicy): Decision { + const { prepared } = view; + const mode = policy.mode; + const tool = NATIVE_TOOL[prepared.tool]; + const isRead = prepared.tool === 'read' || prepared.tool === 'grep' || prepared.tool === 'glob'; + const isEdit = prepared.tool === 'write' || prepared.tool === 'edit'; + const inside = isRead || isEdit ? insideWorkingDirs(callPaths(prepared), policy.workingDirs) : false; + if (mode === 'auto' || mode === 'bypassPermissions') return { kind: 'allow' }; + if (isRead) { + if (inside) return { kind: 'allow' }; + if (mode === 'dontAsk') return { kind: 'deny', source: 'rule', reason: `dontAsk mode: ${tool} outside the working directories is not pre-approved by an allow rule` }; + return { kind: 'ask', reason: `${tool} outside the working directories needs approval in ${mode} mode` }; + } + if (mode === 'plan') return { kind: 'deny', source: 'rule', reason: `plan mode does not allow ${tool}` }; + if (mode === 'dontAsk') return { kind: 'deny', source: 'rule', reason: `dontAsk mode: ${tool} is not pre-approved by an allow rule` }; + if (isEdit && mode === 'acceptEdits' && inside) return { kind: 'allow' }; + return { kind: 'ask', reason: `${tool} needs approval in ${mode} mode` }; +} + +function describe(rule: Rule): string { + return `${rule.kind} rule ${JSON.stringify(rule.raw)} from ${rule.source} settings`; +} + +function compileHooks(entries: readonly HookMatcherEntry[] | undefined, origin: string, env: Readonly>, platform: NodeJS.Platform, seen: Set): CompiledHook[] { + const out: CompiledHook[] = []; + for (const entry of entries ?? []) { + for (const handler of entry.hooks) { + // The same handler defined in several settings files runs once. + const key = JSON.stringify([entry.matcher ?? '', handler, env]); + if (seen.has(key)) continue; + seen.add(key); + out.push({ handler, matcher: entry.matcher, origin, env, unsupported: unsupportedReason(handler, platform) }); + } + } + return out; +} + +/** Literal leading directory of a glob pattern (before the first segment with a glob character). */ +function literalHead(pattern: string): { head: string; rest: string } { + const segments = pattern.split('/'); + const i = segments.findIndex((s) => /[*?[]/.test(s)); + const cut = i === -1 ? Math.max(0, segments.length - 1) : i; + return { head: segments.slice(0, cut).join('/'), rest: segments.slice(cut).join('/') }; +} + +/** Adds the real location of rules written through a symlinked directory (`//etc/**` → `/private/etc/**`). */ +async function withRealAnchors(rule: Rule): Promise { + if (rule.matcher.type !== 'path' || rule.kind === 'allow') return rule; + const extra: PathPattern[] = []; + for (const p of rule.matcher.patterns) { + if (p.pattern.startsWith('**')) continue; + const { head, rest } = literalHead(p.pattern); + const dir = path.posix.join(p.anchor, head); + try { + const real = toPosixPath(await realpath(dir)); + if (real !== dir && rest !== '') extra.push({ anchor: real, pattern: rest }); + else if (real !== dir) extra.push({ anchor: path.posix.dirname(real), pattern: path.posix.basename(real) }); + } catch { + // Missing directory: nothing to alias. + } + } + return extra.length === 0 ? rule : { ...rule, matcher: { type: 'path', patterns: [...rule.matcher.patterns, ...extra] } }; +} + +function resolveDir(p: string, base: string, home: string): string { + if (p === '~') return home; + if (p.startsWith('~/')) return path.join(home, p.slice(2)); + return path.resolve(base, p); +} + +export class ClaudeHostAdapter implements HostAdapter { + readonly host = 'claude' as const; + readonly #opts: ClaudeHostAdapterOptions; + + constructor(opts: ClaudeHostAdapterOptions = {}) { + this.#opts = opts; + } + + async loadPolicy(ctx: SessionContext): Promise | PolicyLoadError> { + try { + return await this.#load(ctx); + } catch (err) { + return { error: errorMessage(err) }; + } + } + + async #load(ctx: SessionContext): Promise> { + const env = this.#opts.env ?? process.env; + const home = this.#opts.home ?? os.homedir(); + const platform = this.#opts.platform ?? process.platform; + const configDir = claudeConfigDir(env, home); + const projectRoot = ctx.roots[0] ?? ctx.cwd; + const stateDir = this.#opts.stateDir ?? stateDirPath(env, home); + const managedDir = this.#opts.managedDir === null ? undefined : (this.#opts.managedDir ?? managedSettingsDir(platform)); + const parent = await (this.#opts.readParent ?? readParentClaudeProcess)(); + const flags = parent ? parseClaudeFlags(parent.argv) : NO_FLAGS; + const settings: LoadedSettings = await loadSettings({ projectRoot, home, configDir, managedDir, env, flags, parentCwd: parent?.cwd }); + const docs = settings.docs; + + // Permission rules. + const managedOnly = firstSetting(docs.filter((d) => d.source === 'managed'), (s) => s.allowManagedPermissionRulesOnly) === true; + const ruleDocs = managedOnly ? docs.filter((d) => d.source === 'managed') : docs; + const holdsCapability = (doc: SettingsDoc): boolean => (doc.source === 'project' || doc.source === 'local') && !settings.projectTrusted; + const rules: { deny: Rule[]; ask: Rule[]; allow: Rule[] } = { deny: [], ask: [], allow: [] }; + for (const doc of ruleDocs) { + const anchors = { cwd: ctx.cwd, sourceDir: doc.anchorDir, home }; + for (const kind of ['deny', 'ask', 'allow'] as const) { + if (kind === 'allow' && holdsCapability(doc)) continue; + for (const raw of doc.data.permissions?.[kind] ?? []) { + const rule = parseRule(raw, kind, doc.source, anchors); + if (rule) rules[kind].push(await withRealAnchors(rule)); + else if (kind !== 'allow') throw new Error(`${kind} rule ${JSON.stringify(raw)} in ${doc.file ?? doc.source} cannot be parsed`); + } + } + } + + // Working directories. + const workingDirs = new Set([projectRoot, ctx.cwd, ...ctx.roots]); + for (const doc of docs) { + if (holdsCapability(doc)) continue; + for (const dir of doc.data.permissions?.additionalDirectories ?? []) workingDirs.add(resolveDir(dir, projectRoot, home)); + } + + // Permission mode: the live mode from the companion hook, else the CLI flag, else settings, else default. + const fromCtx = ctx.sources['permissionMode'] !== undefined && ctx.sources['permissionMode'] !== 'default' ? toMode(ctx.permissionMode) : undefined; + let mode: PermissionMode = fromCtx ?? toMode(flags.permissionMode) ?? toMode(firstSetting(docs, (s) => s.permissions?.defaultMode)) ?? 'default'; + if (mode === 'bypassPermissions' && firstSetting(docs, (s) => s.permissions?.disableBypassPermissionsMode) === 'disable') mode = 'default'; + + // Hooks. + const managedDocs = docs.filter((d) => d.source === 'managed'); + const managedDisable = firstSetting(managedDocs, (s) => s.disableAllHooks) === true; + const otherDisable = firstSetting(docs.filter((d) => d.source !== 'managed'), (s) => s.disableAllHooks) === true; + const managedOnlyHooks = firstSetting(managedDocs, (s) => s.allowManagedHooksOnly) === true; + const seen = new Set(); + const pre: CompiledHook[] = []; + const post: CompiledHook[] = []; + for (const doc of docs) { + const isManaged = doc.source === 'managed'; + if (managedDisable) break; + if (!isManaged && (otherDisable || managedOnlyHooks)) continue; + const origin = `${doc.source} settings`; + pre.push(...compileHooks(doc.data.hooks?.PreToolUse, origin, {}, platform, seen)); + post.push(...compileHooks(doc.data.hooks?.PostToolUse, origin, {}, platform, seen)); + } + if (!managedDisable && !otherDisable && !managedOnlyHooks) { + for (const plugin of settings.plugins) { + const env = { CLAUDE_PLUGIN_ROOT: plugin.root }; + pre.push(...compileHooks(plugin.hooks.PreToolUse, `plugin ${plugin.plugin}`, env, platform, seen)); + post.push(...compileHooks(plugin.hooks.PostToolUse, `plugin ${plugin.plugin}`, env, platform, seen)); + } + } + + // Bash containment: Claude's sandbox when enabled. + let bashContainment: BashContainment = { mode: 'none' }; + if (firstSetting(docs, (s) => s.sandbox?.enabled) === true) { + const roots = new Set([projectRoot, ...workingDirs]); + const fsDisabled = firstSetting( + docs.filter((d) => d.source === 'managed' || d.source === 'user' || d.source === 'flag-settings'), + (s) => s.sandbox?.filesystem?.disabled, + ); + for (const doc of docs) { + for (const entry of doc.data.sandbox?.filesystem?.allowWrite ?? []) roots.add(resolveDir(entry, projectRoot, home)); + } + bashContainment = { + mode: 'sandbox', + readOnly: false, + writableRoots: fsDisabled === true ? [path.parse(projectRoot).root] : [...roots], + // Claude's sandbox filters network by domain through a proxy; a boolean + // cannot express an allowlist, so network stays off (strict). + network: false, + }; + } + + const protectedPaths = [ + ...new Set([ + ...[projectRoot, ctx.cwd].flatMap((root) => [ + path.join(root, '.claude', 'settings*.json'), + path.join(root, '.claude', 'hooks', '**'), + path.join(root, '.claude', 'agents', '**'), + path.join(root, '.mcp.json'), + ]), + path.join(configDir, '**'), + path.join(home, '.claude', '**'), + path.join(home, '.claude.json'), + ...(managedDir === undefined ? [] : [path.join(managedDir, '**')]), + path.join(stateDir, '**'), + ...docs.flatMap((d) => (d.source === 'flag-settings' && d.file !== undefined ? [d.file] : [])), + ]), + ]; + + return { + host: 'claude', + bashContainment, + protectedPaths, + payload: { + projectRoot, + cwd: ctx.cwd, + home, + configDir, + mode, + rules, + workingDirs: [...workingDirs], + preHooks: pre, + postHooks: post, + hookEnv: { CLAUDE_PROJECT_DIR: projectRoot }, + }, + }; + } + + #view(prepared: PreparedCall, policy: ClaudePolicy): CallView { + const native = nativeCall(prepared); + if (prepared.tool !== 'bash') return { prepared, native, analysis: undefined, bashFiles: [] }; + const analysis = BashAnalyzer.analyze(prepared.effect.command); + const bashFiles = analysis.files.map((f) => { + if (f.path === undefined) return { access: f.access, path: undefined }; + const relative = !(f.path.startsWith('/') || f.path.startsWith('~') || path.isAbsolute(f.path)); + // After a `cd`, a relative target cannot be resolved statically. + if (relative && analysis.changesDirectory) return { access: f.access, path: undefined }; + return { access: f.access, path: resolveCommandPath(f.path, prepared.effect.cwd, policy.home) }; + }); + return { prepared, native, analysis, bashFiles }; + } + + checkStatic(prepared: PreparedCall, _ctx: SessionContext, snapshot: PolicySnapshot): Decision { + const policy = snapshot.payload; + const view = this.#view(prepared, policy); + const askOrDeny = (reason: string): Decision => + policy.mode === 'dontAsk' ? { kind: 'deny', source: 'rule', reason: `dontAsk mode denies what would ask: ${reason}` } : { kind: 'ask', reason }; + + for (const rule of policy.rules.deny) { + const v = restrictVerdict(rule, view); + if (v === 'match') return { kind: 'deny', source: 'rule', reason: `denied by ${describe(rule)}` }; + } + // A deny rule that may match once run-time values are known: cannot be settled statically. + for (const rule of policy.rules.deny) { + if (restrictVerdict(rule, view) === 'maybe') return askOrDeny(`${describe(rule)} may match parts of the command that are only known at run time`); + } + for (const rule of policy.rules.ask) { + const v = restrictVerdict(rule, view); + if (v !== 'no') return askOrDeny(`${describe(rule)} matches`); + } + if (view.analysis && view.analysis.uncertain.length > 0) { + return askOrDeny(`the command cannot be checked statically (${view.analysis.uncertain.join('; ')})`); + } + if (allowedByRule(view, policy.rules.allow, policy)) return { kind: 'allow' }; + return modeDecision(view, policy); + } + + #select(hooks: readonly CompiledHook[], view: CallView, policy: ClaudePolicy): CompiledHook[] { + return hooks.filter((hook) => matcherMatches(hook.matcher, view.native.toolName) && this.#ifMatches(hook, view, policy)); + } + + /** The `if` filter: a hook is skipped only when the call certainly does not match its rule. */ + #ifMatches(hook: CompiledHook, view: CallView, policy: ClaudePolicy): boolean { + const condition = hook.handler.if; + if (condition === undefined) return true; + const rule = parseRule(condition, 'allow', 'project', { cwd: policy.cwd, sourceDir: policy.projectRoot, home: policy.home }); + if (!rule || rule.matcher.type === 'never') return true; + if (!matchesToolName(rule.tool, view.native.toolName) && !governs(rule, view.native.toolName)) return false; + const m = rule.matcher; + if (m.type === 'all') return true; + if (m.type === 'bash') { + const a = view.analysis; + if (!a || a.uncertain.length > 0) return true; + // Documented: a pattern naming more than the command (`Bash(git push *)`) runs the hook on any `$()`, backticks or `$VAR`. + const specific = (m.spec.split('*')[0] ?? '').trim().split(/\s+/).length > 1; + return a.commands.some( + (cmd) => cmd.denyForms.some((f) => matchesBashSpec(m.spec, f)) || (cmd.dynamic && (specific || bashSpecMayMatchDynamic(m.spec, cmd.staticPrefix))), + ); + } + if (m.type === 'path') return pathRuleVerdict(m.patterns, callPaths(view.prepared), 'deny') === 'match'; + if (m.type === 'param') return matchesParamValue(m.value, view.native.toolInput[m.name]); + return true; + } + + #input(view: CallView, ctx: SessionContext, policy: ClaudePolicy, event: 'PreToolUse' | 'PostToolUse'): Record { + const { prepared, native } = view; + return { + session_id: ctx.sessionId ?? null, + transcript_path: ctx.transcriptPath ?? null, + // For bash the command runs in the effect's cwd, so that is what the hook is told. + cwd: prepared.tool === 'bash' ? prepared.effect.cwd : ctx.cwd, + permission_mode: policy.mode, + hook_event_name: event, + tool_name: native.toolName, + tool_input: native.toolInput, + tool_use_id: `${ctx.toolUseId ?? 'unknown'}/${prepared.id}`, + ...(ctx.agentId === undefined ? {} : { agent_id: ctx.agentId }), + ...(ctx.agentType === undefined ? {} : { agent_type: ctx.agentType }), + }; + } + + async authorize(prepared: PreparedCall, ctx: SessionContext, snapshot: PolicySnapshot, signal: AbortSignal): Promise { + const policy = snapshot.payload; + const view = this.#view(prepared, policy); + const hooks = this.#select(policy.preHooks, view, policy); + const unsupported = hooks.find((h) => h.unsupported !== undefined); + if (unsupported) { + return { kind: 'deny', source: 'unsupported-config', reason: `${unsupported.origin}: ${unsupported.unsupported ?? 'unsupported hook'}` }; + } + if (hooks.length === 0) return { kind: 'allow' }; + const input = this.#input(view, ctx, policy, 'PreToolUse'); + const opts = { event: 'PreToolUse' as const, input, cwd: policy.projectRoot, env: policy.hookEnv, signal }; + const blocking: Promise[] = []; + for (const hook of hooks) { + if (hook.handler.async === true || hook.handler.asyncRewake === true) { + // Background hooks cannot block natively either; run them and ignore the result. + void runHook(hook, opts); + continue; + } + blocking.push(runHook(hook, opts)); + } + const combined = combineOutcomes(await Promise.all(blocking)); + switch (combined.kind) { + case 'deny': + return combined; + case 'ask': + return { kind: 'ask', reason: combined.reason }; + case 'none': + case 'allow': { + if (combined.updatedInput === undefined) return { kind: 'allow', ...(combined.reason === undefined ? {} : { reason: combined.reason }) }; + const mapped = mapUpdatedInput(prepared, combined.updatedInput); + if ('error' in mapped) return { kind: 'deny', source: 'hook', reason: mapped.error }; + return { kind: 'allow', updatedArgs: mapped.args, ...(combined.reason === undefined ? {} : { reason: combined.reason }) }; + } + } + } + + async postToolUse(prepared: PreparedCall, result: ToolResult, ctx: SessionContext, snapshot: PolicySnapshot): Promise { + const policy = snapshot.payload; + const view = this.#view(prepared, policy); + const hooks = this.#select(policy.postHooks, view, policy); + if (hooks.length === 0) return; + const input = { ...this.#input(view, ctx, policy, 'PostToolUse'), tool_response: nativeResponse(prepared, result) }; + const controller = new AbortController(); + const opts = { event: 'PostToolUse' as const, input, cwd: policy.projectRoot, env: policy.hookEnv, signal: controller.signal }; + const notes: string[] = []; + const outcomes = await Promise.all( + hooks.map(async (hook) => { + if (hook.unsupported !== undefined) return { hook, outcome: { kind: 'failure', source: 'hook-error', reason: hook.unsupported } satisfies HookOutcome }; + if (hook.handler.async === true || hook.handler.asyncRewake === true) { + void runHook(hook, opts); + return { hook, outcome: { kind: 'none' } satisfies HookOutcome }; + } + return { hook, outcome: await runHook(hook, opts) }; + }), + ); + for (const { hook, outcome } of outcomes) { + if (outcome.kind === 'deny') notes.push(`${hook.origin} PostToolUse hook blocked after the call ran (it was not undone): ${outcome.reason}`); + else if (outcome.kind === 'failure') notes.push(`${hook.origin} PostToolUse hook failed: ${outcome.reason}`); + } + if (notes.length > 0) throw new Error(notes.join('; ')); + } +} diff --git a/src/hosts/claude/bash.ts b/src/hosts/claude/bash.ts new file mode 100644 index 0000000..eb05ecc --- /dev/null +++ b/src/hosts/claude/bash.ts @@ -0,0 +1,475 @@ +import { parse, walk } from 'sh-syntax/sync'; +import type { CallExpr, DeclClause, File, Node, Redirect, Word, WordPart } from 'sh-syntax/sync'; + +/** + * Splits a Bash command line into the simple commands it would run, the way + * Claude Code does before it matches Bash permission rules, but stricter. + * + * Parser: `sh-syntax` (mvdan/sh, the parser behind shfmt, compiled to WASM + * with a synchronous Node entry). It understands the full bash grammar, so + * commands nested in `&&`, `||`, `;`, `|`, `&`, subshells, blocks, control + * flow, `$(...)`, backticks, process substitution and here-documents are all + * found. On top of the parse tree this module: + * - strips leading `VAR=value` assignments and process wrappers (`timeout`, + * `time`, `nice`, `nohup`, `stdbuf`, `command`, `builtin`, `noglob`, `exec`, + * `env`, `sudo`, `xargs`, `find -exec`) and offers every stripped form to + * deny/ask matching; + * - parses the inner string of `bash -c`/`sh -c` (and other shells) and adds + * its commands; + * - collects redirection targets (`> f`, `< f`, `tee f`) so file rules can + * check them; + * - reports constructs it cannot evaluate statically (`eval`, `source`, a + * dynamic command name, a shell reading commands from stdin, a here-document + * with substitutions, a parse error) as `uncertain`, which callers treat as + * `ask`. + */ + +/** One simple command, as matching sees it. */ +export interface SimpleCommand { + /** Source text of the command as written (assignments included). */ + readonly raw: string; + /** Every text deny/ask rules are matched against: normalized forms with and without wrappers. */ + readonly denyForms: readonly string[]; + /** + * Text allow rules are matched against: the command after stripping only + * the wrappers Claude Code documents (`timeout`, `time`, `nice`, `nohup`, + * `stdbuf`, `command`, `builtin`, `noglob`, bare `xargs`). Undefined when the + * command cannot be approved by an allow rule (dynamic words, leading + * assignments, unknown command name). + */ + readonly allowForm: string | undefined; + /** Words before the first word whose value is only known at run time. */ + readonly staticPrefix: string; + /** True when some word's value is only known at run time. */ + readonly dynamic: boolean; +} + +/** A file a command reads or writes by name (redirection or `tee`). */ +export interface FileTarget { + readonly access: 'read' | 'write'; + /** The path as written, or undefined when it is only known at run time. */ + readonly path: string | undefined; +} + +export interface BashAnalysis { + readonly commands: readonly SimpleCommand[]; + readonly files: readonly FileTarget[]; + /** Reasons the command cannot be evaluated statically. Non-empty means `ask`. */ + readonly uncertain: readonly string[]; + /** True when a `cd` appears, so relative file targets may not resolve against the call's cwd. */ + readonly changesDirectory: boolean; +} + +/** Commands longer than this are not analyzed (treated as uncertain). */ +export const MAX_ANALYZED_COMMAND_CHARS = 100_000; + +/** How deep `bash -c '...'` strings are followed. */ +const MAX_SHELL_NESTING = 4; + +const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'mksh', 'ash', 'fish', 'busybox']); + +/** Builtins whose arguments become shell code: always uncertain. */ +const CODE_EVALUATORS = new Set(['eval', 'source', '.', 'trap', 'fc']); + +/** Commands whose operands are files they read, for Read rules. */ +const FILE_READERS = new Set(['cat', 'head', 'tail', 'less', 'more', 'nl', 'tac', 'strings', 'xxd', 'od', 'base64']); + +/** Options of those readers that take a separate value (`head -n 5 file`). */ +const READER_OPTIONS_WITH_VALUE = new Set(['-n', '-c', '--lines', '--bytes', '-s', '-w', '-b', '-t', '-j', '-N']); + +// Redirect operators (sh-syntax RedirOperator values). +const REDIR_OUT = new Set([63, 64, 69, 70, 74, 75, 76, 77]); // > >> >| >>| &> &>| &>> &>>| +const REDIR_IN = new Set([65]); // < +const REDIR_INOUT = new Set([66]); // <> +const REDIR_HDOC = new Set([71, 72]); // << <<- +const REDIR_DUP = new Set([67, 68]); // <& >& + +interface WordValue { + /** Shell value when fully static, else undefined. */ + readonly value: string | undefined; + /** Source text. */ + readonly raw: string; + /** True when an unquoted glob character appears (the shell may expand it). */ + readonly glob: boolean; +} + +function decodeUnquoted(lit: string): string { + let out = ''; + for (let i = 0; i < lit.length; i++) { + const ch = lit[i]; + if (ch === '\\' && i + 1 < lit.length) { + const next = lit[i + 1]; + i++; + if (next !== '\n') out += next; + } else { + out += ch; + } + } + return out; +} + +function decodeDoubleQuoted(lit: string): string { + let out = ''; + for (let i = 0; i < lit.length; i++) { + const ch = lit[i]; + const next = lit[i + 1]; + if (ch === '\\' && next !== undefined && '$`"\\\n'.includes(next)) { + i++; + if (next !== '\n') out += next; + } else { + out += ch; + } + } + return out; +} + +const ANSI_ESCAPES: Record = { n: '\n', t: '\t', r: '\r', '\\': '\\', "'": "'", '"': '"', a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', v: '\v' }; + +/** Decodes `$'...'`; undefined when an escape is not a simple one. */ +function decodeAnsi(lit: string): string | undefined { + let out = ''; + for (let i = 0; i < lit.length; i++) { + const ch = lit[i]; + if (ch !== '\\') { + out += ch; + continue; + } + const next = lit[i + 1]; + const mapped = next === undefined ? undefined : ANSI_ESCAPES[next]; + if (mapped === undefined) return undefined; + out += mapped; + i++; + } + return out; +} + +const UNQUOTED_GLOB = /(^|[^\\])[*?[]/; + +function partsValue(parts: readonly WordPart[], quoted: boolean): { value: string | undefined; glob: boolean } { + let value: string | undefined = ''; + let glob = false; + for (const part of parts) { + let piece: string | undefined; + switch (part.type) { + case 'Lit': + if (!quoted && UNQUOTED_GLOB.test(part.value)) glob = true; + piece = quoted ? decodeDoubleQuoted(part.value) : decodeUnquoted(part.value); + break; + case 'SglQuoted': + piece = part.dollar ? decodeAnsi(part.value) : part.value; + break; + case 'DblQuoted': { + if (part.dollar) { + piece = undefined; // $"..." is locale translation + break; + } + const inner = partsValue(part.parts, true); + piece = inner.value; + break; + } + default: + piece = undefined; + } + if (piece === undefined || value === undefined) value = undefined; + else value += piece; + } + return { value, glob }; +} + +export class BashAnalyzer { + readonly #commands: SimpleCommand[] = []; + readonly #files: FileTarget[] = []; + readonly #uncertain: string[] = []; + #changesDirectory = false; + + static analyze(command: string): BashAnalysis { + const analyzer = new BashAnalyzer(); + analyzer.#analyzeSource(command, 0); + return { + commands: analyzer.#commands, + files: analyzer.#files, + uncertain: [...new Set(analyzer.#uncertain)], + changesDirectory: analyzer.#changesDirectory, + }; + } + + #analyzeSource(source: string, depth: number): void { + if (source.includes('\0')) { + this.#uncertain.push('command contains a NUL byte'); + return; + } + if (source.length > MAX_ANALYZED_COMMAND_CHARS) { + this.#uncertain.push(`command is longer than ${MAX_ANALYZED_COMMAND_CHARS} characters`); + return; + } + let file: File; + try { + file = parse(source); + } catch (err) { + this.#uncertain.push(`command could not be parsed: ${err instanceof Error ? err.message : String(err)}`); + return; + } + const ctx = { source, depth }; + walk(file, (node) => { + switch (node.type) { + case 'CallExpr': + this.#callExpr(node, ctx); + break; + case 'DeclClause': + this.#declClause(node, ctx); + break; + case 'Redirect': + this.#redirect(node, ctx); + break; + case 'Stmt': + if (node.coprocess) this.#uncertain.push('coprocesses are not analyzed'); + break; + case 'CoprocClause': + this.#uncertain.push('coprocesses are not analyzed'); + break; + default: + break; + } + }); + } + + #text(node: Node, ctx: { source: string }): string { + return ctx.source.slice(node.start, node.end); + } + + #word(word: Word, ctx: { source: string }): WordValue { + const { value, glob } = partsValue(word.parts, false); + return { value, raw: this.#text(word, ctx), glob }; + } + + #declClause(decl: DeclClause, ctx: { source: string; depth: number }): void { + // `export`, `declare`, `local`, `readonly`, `typeset`, `nameref`: their own + // words are assignments; nested substitutions are walked generically. + const name = decl.variant?.value ?? 'declare'; + const raw = this.#text(decl, ctx); + this.#commands.push({ raw, denyForms: [raw, name], allowForm: undefined, staticPrefix: name, dynamic: true }); + } + + #redirect(redir: Redirect, ctx: { source: string; depth: number }): void { + if (REDIR_HDOC.has(redir.op)) { + const body = redir.hdoc; + if (body && body.parts.some((p) => p.type !== 'Lit')) { + this.#uncertain.push('here-document with substitutions'); + } + return; + } + if (REDIR_DUP.has(redir.op) || redir.word === null) return; + const target = this.#word(redir.word, ctx); + const path = target.value !== undefined && !target.glob ? target.value : undefined; + if (path === '/dev/null' || path === '/dev/stdout' || path === '/dev/stderr') return; + if (REDIR_OUT.has(redir.op)) this.#files.push({ access: 'write', path }); + else if (REDIR_IN.has(redir.op)) this.#files.push({ access: 'read', path }); + else if (REDIR_INOUT.has(redir.op)) { + this.#files.push({ access: 'read', path }); + this.#files.push({ access: 'write', path }); + } + // Here-strings (`<<<`) carry no file. + } + + #callExpr(call: CallExpr, ctx: { source: string; depth: number }): void { + const raw = this.#text(call, ctx); + const words = call.args.map((w) => this.#word(w, ctx)); + if (words.length === 0) return; // pure assignment, e.g. `A=$(rm x)`: nested commands are walked + this.#addCommand(raw, words, call.assigns.length > 0, ctx); + } + + #addCommand(raw: string, words: readonly WordValue[], hasAssigns: boolean, ctx: { source: string; depth: number }): void { + const denyForms = new Set([raw]); + const dynamic = words.some((w) => w.value === undefined); + const firstDynamic = words.findIndex((w) => w.value === undefined); + const staticWords = (firstDynamic === -1 ? words : words.slice(0, firstDynamic)).map((w) => w.value ?? ''); + const staticPrefix = staticWords.join(' '); + const text = (ws: readonly WordValue[]): string => ws.map((w) => w.value ?? w.raw).join(' '); + + denyForms.add(text(words)); + + // Strip wrappers one level at a time; every level is a deny/ask candidate. + let current = words; + let allowStripped: readonly WordValue[] | undefined = hasAssigns ? undefined : words; + let allowChainIntact = !hasAssigns; + for (let guard = 0; guard < 16; guard++) { + const head = current[0]; + if (!head) break; + if (head.value === undefined || head.glob) { + this.#uncertain.push(`command name ${JSON.stringify(head.raw)} is only known at run time`); + allowStripped = undefined; + break; + } + const name = head.value; + const base = basename(name); + if (base !== name) { + // `/bin/rm x` is matched as `rm x` too. + denyForms.add(text([{ ...head, value: base, raw: base }, ...current.slice(1)])); + } + if (base === 'cd' || base === 'pushd' || base === 'popd') this.#changesDirectory = true; + if (CODE_EVALUATORS.has(base)) this.#uncertain.push(`\`${base}\` runs code that is only known at run time`); + if (FILE_READERS.has(base)) { + const operands = current.slice(1); + for (let k = 0; k < operands.length; k++) { + const operand = operands[k]; + if (!operand) continue; + if (operand.raw.startsWith('<(') || operand.raw.startsWith('>(')) continue; + if (operand.value !== undefined && operand.value.startsWith('-')) { + if (READER_OPTIONS_WITH_VALUE.has(operand.value)) k++; + continue; + } + this.#files.push({ access: 'read', path: operand.value !== undefined && !operand.glob ? operand.value : undefined }); + } + } + if (base === 'tee') { + for (const operand of current.slice(1)) { + if (operand.value !== undefined && operand.value.startsWith('-')) continue; + this.#files.push({ access: 'write', path: operand.value !== undefined && !operand.glob ? operand.value : undefined }); + } + } + if (SHELLS.has(base)) this.#shell(current, ctx); + if (base === 'find') this.#findExec(current, ctx); + + const unwrapped = unwrap(base, current); + if (unwrapped === undefined) break; + if (unwrapped.inner.length === 0) break; + current = unwrapped.inner; + denyForms.add(text(current)); + if (allowChainIntact && unwrapped.documented) allowStripped = current; + else allowChainIntact = false; + } + + const allowForm = allowStripped !== undefined && !dynamic ? text(allowStripped) : undefined; + this.#commands.push({ raw, denyForms: [...denyForms], allowForm, staticPrefix, dynamic }); + } + + #shell(words: readonly WordValue[], ctx: { source: string; depth: number }): void { + // Find `-c