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/17] 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/17] 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 c7a6e20b44a7e680fd9086754ad637dad2131987 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:28:35 -0300 Subject: [PATCH 03/17] Tools runtime: jail, tolerant edit, transactional rollback, contained bash Implements the ToolRuntime contract for bash, read, write, edit, grep and glob in src/tools: - Workspace jail: paths resolve to real paths under the session cwd, MCP roots and configured extra roots; traversal, links leaving the roots, Windows alias spellings and NUL bytes are refused. Writes and edits to protected host paths and .git are refused. - Commits re-check what prepare saw: no link at the final component (O_NOFOLLOW plus an fd path check), parent directories unchanged, content hash equal to the prepared before-hash. Writes are atomic (temp file in the same directory, mode kept; creates never replace a file that appeared meanwhile). - Edit uses Turnpack's tolerant matcher (exact, line endings, copied line numbers, trailing whitespace, indentation, punctuation), refusing ambiguous and missing matches with the nearest text. - Transactions journal originals in memory and durably under the state dir (64 MiB cap), roll back without clobbering external changes, and recoverStaleJournals restores journals left by a dead server. - bash runs in its own process group with output caps, kills the group on timeout, abort and exit, and runs under @anthropic-ai/sandbox-runtime (bubblewrap or Seatbelt) when the policy asks for containment. - grep and glob are pure JS with .git, node_modules and .gitignore ignores, and never follow links. Co-Authored-By: Claude Opus 5.5 --- NOTICE | 17 ++ package-lock.json | 52 ++++ package.json | 1 + src/tools/bash.test.ts | 155 +++++++++++ src/tools/bash.ts | 190 +++++++++++++ src/tools/diff.test.ts | 62 +++++ src/tools/diff.ts | 178 ++++++++++++ src/tools/edit-match.test.ts | 113 ++++++++ src/tools/edit-match.ts | 495 ++++++++++++++++++++++++++++++++++ src/tools/fs-ops.ts | 249 +++++++++++++++++ src/tools/index.ts | 5 + src/tools/integration.test.ts | 62 +++++ src/tools/jail.ts | 224 +++++++++++++++ src/tools/journal.test.ts | 185 +++++++++++++ src/tools/journal.ts | 386 ++++++++++++++++++++++++++ src/tools/runtime.test.ts | 370 +++++++++++++++++++++++++ src/tools/runtime.ts | 372 +++++++++++++++++++++++++ src/tools/sandbox.ts | 133 +++++++++ src/tools/search.ts | 338 +++++++++++++++++++++++ 19 files changed, 3587 insertions(+) create mode 100644 src/tools/bash.test.ts create mode 100644 src/tools/bash.ts create mode 100644 src/tools/diff.test.ts create mode 100644 src/tools/diff.ts create mode 100644 src/tools/edit-match.test.ts create mode 100644 src/tools/edit-match.ts create mode 100644 src/tools/fs-ops.ts create mode 100644 src/tools/index.ts create mode 100644 src/tools/integration.test.ts create mode 100644 src/tools/jail.ts create mode 100644 src/tools/journal.test.ts create mode 100644 src/tools/journal.ts create mode 100644 src/tools/runtime.test.ts create mode 100644 src/tools/runtime.ts create mode 100644 src/tools/sandbox.ts create mode 100644 src/tools/search.ts diff --git a/NOTICE b/NOTICE index 03af142..63d495a 100644 --- a/NOTICE +++ b/NOTICE @@ -7,3 +7,20 @@ Third-party code ---------------- Portions of this product that are derived from third-party projects are listed below together with their copyright notices and licenses. + +Turnpack + Files: src/tools/edit-match.ts, src/tools/edit-match.test.ts (ported), + src/tools/journal.ts and src/tools/jail.ts (design and parts adapted) + Source: https://github.com/OnlyTerp/turnpack (commit b14330d) + License: Apache License, Version 2.0 + Modified by the agent-code-mode authors (see the header of each file). + Turnpack's NOTICE: + + Turnpack + Copyright 2026 OnlyTerp (https://github.com/OnlyTerp) + + This product is licensed under the Apache License, Version 2.0. + You may obtain a copy of the License in the LICENSE file, or at + http://www.apache.org/licenses/LICENSE-2.0 + + Project home: https://github.com/OnlyTerp/turnpack diff --git a/package-lock.json b/package-lock.json index 596f70d..321bc15 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.0.0", "license": "Apache-2.0", "dependencies": { + "@anthropic-ai/sandbox-runtime": "^0.0.81", "@modelcontextprotocol/sdk": "^1.32.2", "zod": "^4.6.7" }, @@ -24,6 +25,33 @@ "node": ">=22" } }, + "node_modules/@anthropic-ai/sandbox-runtime": { + "version": "0.0.81", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sandbox-runtime/-/sandbox-runtime-0.0.81.tgz", + "integrity": "sha512-bjHDu87gjIR7+Oxy9jPiK3v8CvSELCzfpXa3fjqfSKdvlZET2iF51xcXILWPayTpowB3xtZeQVf2JR916nVW/w==", + "license": "Apache-2.0", + "dependencies": { + "@pondwader/socks5-server": "^1.0.10", + "commander": "^12.1.0", + "node-forge": "^1.4.0", + "zod": "^3.25.0" + }, + "bin": { + "srt": "dist/cli.js" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/@anthropic-ai/sandbox-runtime/node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, "node_modules/@emnapi/core": { "version": "2.0.0-beta.2", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", @@ -175,6 +203,12 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@pondwader/socks5-server": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@pondwader/socks5-server/-/socks5-server-1.0.10.tgz", + "integrity": "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg==", + "license": "MIT" + }, "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", @@ -1057,6 +1091,15 @@ "node": ">=18" } }, + "node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "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", @@ -2054,6 +2097,15 @@ "url": "https://opencollective.com/express" } }, + "node_modules/node-forge": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.3.tgz", + "integrity": "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g==", + "license": "(BSD-3-Clause OR GPL-2.0)", + "engines": { + "node": ">= 6.13.0" + } + }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", diff --git a/package.json b/package.json index 1d1997d..0f8d93a 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "bench": "node -e \"console.log('bench: not implemented yet')\"" }, "dependencies": { + "@anthropic-ai/sandbox-runtime": "^0.0.81", "@modelcontextprotocol/sdk": "^1.32.2", "zod": "^4.6.7" }, diff --git a/src/tools/bash.test.ts b/src/tools/bash.test.ts new file mode 100644 index 0000000..0806edf --- /dev/null +++ b/src/tools/bash.test.ts @@ -0,0 +1,155 @@ +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ToolError } from '../core/errors.js'; +import type { BashContainment, BashResult, PolicySnapshot, SessionContext } from '../core/types.js'; +import { makeContext } from '../testing/context.js'; +import { NodeToolRuntime } from './runtime.js'; +import { containmentUnavailableReason } from './sandbox.js'; + +const IS_WINDOWS = process.platform === 'win32'; + +let base: string; +let ws: string; +let ctx: SessionContext; +let seq = 0; + +function policyWith(bashContainment: BashContainment): PolicySnapshot { + return { host: 'generic', bashContainment, protectedPaths: [], payload: null }; +} + +async function bash( + command: string, + opts: { timeoutMs?: number; signal?: AbortSignal; containment?: BashContainment; capBytes?: number } = {}, +): Promise { + const rt = new NodeToolRuntime({ stateDir: path.join(base, 'state'), ...(opts.capBytes ? { bashOutputCapBytes: opts.capBytes } : {}) }); + const prepared = await rt.prepare( + { id: `c${++seq}`, tool: 'bash', args: { command, ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}) } }, + ctx, + policyWith(opts.containment ?? { mode: 'none' }), + ); + const result = await rt.commit(prepared, opts.signal ?? new AbortController().signal); + if (!('exitCode' in result)) throw new Error('not a bash result'); + return result; +} + +function alive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function eventually(check: () => boolean, ms = 3000): Promise { + const end = Date.now() + ms; + while (Date.now() < end) { + if (check()) return true; + await new Promise((r) => setTimeout(r, 50)); + } + return check(); +} + +beforeEach(() => { + base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-bash-'))); + ws = path.join(base, 'ws'); + mkdirSync(ws); + ctx = makeContext(ws); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +describe.skipIf(IS_WINDOWS)('bash', () => { + it('returns exit code and output; a non-zero exit is a result', async () => { + const r = await bash('echo out; echo err >&2; exit 3'); + expect(r).toEqual({ exitCode: 3, signal: null, stdout: 'out\n', stderr: 'err\n', truncated: false, timedOut: false }); + }); + + it('kills the whole process group on timeout, grandchildren included', async () => { + const started = Date.now(); + const r = await bash('sleep 100 & echo $! > bg.pid; sleep 100', { timeoutMs: 500 }); + expect(r.timedOut).toBe(true); + expect(r.signal).toBe('SIGKILL'); + expect(Date.now() - started).toBeLessThan(5000); + const pid = Number(readFileSync(path.join(ws, 'bg.pid'), 'utf8')); + expect(await eventually(() => !alive(pid))).toBe(true); + }); + + it('does not leave background processes behind after a normal exit', async () => { + const started = Date.now(); + const r = await bash('sleep 100 & echo $!'); + expect(Date.now() - started).toBeLessThan(5000); + const pid = Number(r.stdout.trim()); + expect(await eventually(() => !alive(pid))).toBe(true); + }); + + it('never starts when the signal is already aborted', async () => { + const ac = new AbortController(); + ac.abort(); + await expect(bash('touch spawned.txt', { signal: ac.signal })).rejects.toMatchObject({ code: 'cancelled' }); + expect(existsSync(path.join(ws, 'spawned.txt'))).toBe(false); + }); + + it('stops a running command on abort', async () => { + const ac = new AbortController(); + setTimeout(() => ac.abort(), 200); + const started = Date.now(); + await expect(bash('sleep 30', { signal: ac.signal })).rejects.toBeInstanceOf(ToolError); + expect(Date.now() - started).toBeLessThan(5000); + }); + + it('caps stdout and stderr', async () => { + const r = await bash("head -c 5000 /dev/zero | tr '\\0' a; head -c 3000 /dev/zero | tr '\\0' b >&2", { capBytes: 1000 }); + expect(r.stdout).toBe('a'.repeat(1000)); + expect(r.stderr).toBe('b'.repeat(1000)); + expect(r.truncated).toBe(true); + }); + + it('refuses a containment with a relative writable root', async () => { + await expect(bash('true', { containment: { mode: 'sandbox', readOnly: false, writableRoots: ['rel'], network: false } })).rejects.toMatchObject({ + code: 'containment-unavailable', + }); + }); +}); + +const unavailable = await containmentUnavailableReason(); +if (unavailable !== null) { + // Logged so a CI run shows why the containment tests were skipped. + console.log(`bash containment tests skipped: ${unavailable}`); +} + +describe.skipIf(unavailable !== null)('bash containment (OS sandbox)', () => { + const readOnly: BashContainment = { mode: 'sandbox', readOnly: true, writableRoots: [], network: false }; + + it('blocks writes under a read-only sandbox', async () => { + const r = await bash('touch x', { containment: readOnly }); + expect(r.exitCode).not.toBe(0); + expect(existsSync(path.join(ws, 'x'))).toBe(false); + }); + + it('allows writes only under the writable roots', async () => { + const r = await bash(`touch y && touch ${JSON.stringify(path.join(base, 'z'))}`, { + containment: { mode: 'sandbox', readOnly: false, writableRoots: [ws], network: false }, + }); + expect(existsSync(path.join(ws, 'y'))).toBe(true); + expect(r.exitCode).not.toBe(0); + expect(existsSync(path.join(base, 'z'))).toBe(false); + }); + + it('blocks the network when network is off', async () => { + const r = await bash("exec 3<>/dev/tcp/1.1.1.1/80 && echo connected", { containment: readOnly, timeoutMs: 15_000 }); + expect(r.exitCode).not.toBe(0); + expect(r.stdout).not.toContain('connected'); + }); + + it('kills the sandboxed command on timeout', async () => { + const started = Date.now(); + const r = await bash('sleep 100', { containment: readOnly, timeoutMs: 1000 }); + expect(r.timedOut).toBe(true); + expect(Date.now() - started).toBeLessThan(8000); + }); +}); diff --git a/src/tools/bash.ts b/src/tools/bash.ts new file mode 100644 index 0000000..8371aa9 --- /dev/null +++ b/src/tools/bash.ts @@ -0,0 +1,190 @@ +import { spawn, spawnSync, type ChildProcess } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; +import type { BashEffect, BashResult } from '../core/types.js'; +import { withSandbox } from './sandbox.js'; + +/** Default `bash` timeout. */ +export const DEFAULT_BASH_TIMEOUT_MS = 120_000; +/** Largest `bash` timeout. */ +export const MAX_BASH_TIMEOUT_MS = 600_000; +/** Bytes kept of each of stdout and stderr. */ +export const DEFAULT_OUTPUT_CAP_BYTES = 1024 * 1024; +/** After the shell exits, how long to wait for the output pipes to close. */ +const DRAIN_MS = 200; + +/** Quotes a string for POSIX sh as one word. */ +export function shellQuote(s: string): string { + return `'${s.replace(/'/g, `'\\''`)}'`; +} + +let cachedShell: string | null | undefined; + +/** The bash to run commands with: `/bin/bash` or `bash` on PATH; Git Bash on Windows. Null when none. */ +export function findBash(): string | null { + if (cachedShell !== undefined) return cachedShell; + if (process.platform === 'win32') { + const candidates = [ + process.env['ProgramFiles'] && path.join(process.env['ProgramFiles'], 'Git', 'bin', 'bash.exe'), + process.env['ProgramFiles(x86)'] && path.join(process.env['ProgramFiles(x86)'], 'Git', 'bin', 'bash.exe'), + process.env['LOCALAPPDATA'] && path.join(process.env['LOCALAPPDATA'], 'Programs', 'Git', 'bin', 'bash.exe'), + ].filter((p): p is string => typeof p === 'string' && p !== ''); + cachedShell = candidates.find((p) => existsSync(p)) ?? null; + return cachedShell; + } + if (existsSync('/bin/bash')) cachedShell = '/bin/bash'; + else { + const which = spawnSync('sh', ['-c', 'command -v bash'], { encoding: 'utf8' }); + const found = which.status === 0 ? which.stdout.trim() : ''; + cachedShell = found !== '' ? found : null; + } + return cachedShell; +} + +class Capture { + readonly #chunks: Buffer[] = []; + #size = 0; + truncated = false; + + constructor(private readonly cap: number) {} + + push(chunk: Buffer): void { + if (this.#size >= this.cap) { + this.truncated = true; + return; + } + const room = this.cap - this.#size; + const kept = chunk.length > room ? chunk.subarray(0, room) : chunk; + if (kept.length < chunk.length) this.truncated = true; + this.#chunks.push(kept); + this.#size += kept.length; + } + + text(): string { + // A cut in the middle of a multi-byte character becomes U+FFFD. + return Buffer.concat(this.#chunks).toString('utf8'); + } +} + +/** Kills the whole process group of `child` (POSIX) or its tree (Windows). */ +function killGroup(child: ChildProcess): void { + const pid = child.pid; + if (pid === undefined) return; + if (process.platform === 'win32') { + spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' }); + return; + } + try { + process.kill(-pid, 'SIGKILL'); + } catch { + try { + child.kill('SIGKILL'); + } catch { + // Already gone. + } + } +} + +export interface BashRunOptions { + readonly outputCapBytes?: number; + /** Paths a sandboxed command may never write (from the host's protected paths). */ + readonly denyWrite?: readonly string[]; +} + +function spawnAndWait( + argv: readonly string[], + env: NodeJS.ProcessEnv, + cwd: string, + timeoutMs: number, + signal: AbortSignal, + cap: number, +): Promise { + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new ToolError('cancelled', 'the run was stopped before bash started')); + return; + } + const [file, ...args] = argv; + if (file === undefined) { + reject(new ToolError('tool-error', 'empty command line')); + return; + } + const child = spawn(file, args, { + cwd, + env, + stdio: ['ignore', 'pipe', 'pipe'], + detached: process.platform !== 'win32', + windowsHide: true, + }); + const out = new Capture(cap); + const err = new Capture(cap); + child.stdout?.on('data', (c: Buffer) => out.push(c)); + child.stderr?.on('data', (c: Buffer) => err.push(c)); + + let timedOut = false; + let settled = false; + let exit: { code: number | null; signal: NodeJS.Signals | null } | undefined; + let drainTimer: NodeJS.Timeout | undefined; + + const finish = (): void => { + if (settled || !exit) return; + settled = true; + clearTimeout(timer); + if (drainTimer) clearTimeout(drainTimer); + signal.removeEventListener('abort', onAbort); + // No process of the call outlives it: background children are killed too. + killGroup(child); + if (signal.aborted && !timedOut) { + reject(new ToolError('cancelled', 'bash was stopped because the run stopped')); + return; + } + resolve({ + exitCode: exit.code, + signal: exit.signal, + stdout: out.text(), + stderr: err.text(), + truncated: out.truncated || err.truncated, + timedOut, + }); + }; + const onAbort = (): void => killGroup(child); + const timer = setTimeout(() => { + timedOut = true; + killGroup(child); + }, timeoutMs); + signal.addEventListener('abort', onAbort, { once: true }); + + child.once('error', (e) => { + if (settled) return; + settled = true; + clearTimeout(timer); + signal.removeEventListener('abort', onAbort); + reject(new ToolError('tool-error', `bash failed to start: ${e.message}`)); + }); + child.once('exit', (code, sig) => { + exit = { code, signal: sig }; + // Background children may keep the pipes open; do not wait for them long. + drainTimer = setTimeout(finish, DRAIN_MS); + }); + child.once('close', () => finish()); + }); +} + +/** Runs a prepared `bash` effect. */ +export async function runBash(effect: BashEffect, signal: AbortSignal, opts: BashRunOptions = {}): Promise { + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before bash started'); + const shell = findBash(); + if (shell === null) { + throw new ToolError('tool-error', process.platform === 'win32' ? 'bash requires Git Bash, which was not found' : 'bash was not found'); + } + const cap = opts.outputCapBytes ?? DEFAULT_OUTPUT_CAP_BYTES; + const containment = effect.containment; + if (containment.mode === 'none') { + return spawnAndWait([shell, '-c', effect.command], process.env, effect.cwd, effect.timeoutMs, signal, cap); + } + return withSandbox(effect.command, shell, effect.cwd, containment, opts.denyWrite ?? [], (wrapped) => { + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before bash started'); + return spawnAndWait(wrapped.argv, { ...process.env, ...wrapped.env }, effect.cwd, effect.timeoutMs, signal, cap); + }); +} diff --git a/src/tools/diff.test.ts b/src/tools/diff.test.ts new file mode 100644 index 0000000..f595a2f --- /dev/null +++ b/src/tools/diff.test.ts @@ -0,0 +1,62 @@ +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { unifiedDiff } from './diff.js'; + +const hasGit = spawnSync('git', ['--version']).status === 0; + +/** Applies `diff` with `git apply` in a scratch repo and returns the result. */ +function gitApply(before: string | null, diff: string): string { + const dir = mkdtempSync(path.join(os.tmpdir(), 'acm-diff-')); + try { + if (before !== null) writeFileSync(path.join(dir, 'f.txt'), before); + writeFileSync(path.join(dir, 'p.diff'), diff); + const r = spawnSync('git', ['apply', '--unsafe-paths', '--whitespace=nowarn', 'p.diff'], { cwd: dir, encoding: 'utf8' }); + if (r.status !== 0) throw new Error(`git apply failed: ${r.stderr}\n${diff}`); + return readFileSync(path.join(dir, 'f.txt'), 'utf8'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +function randomText(rand: () => number): string { + const lines: string[] = []; + const n = Math.floor(rand() * 30); + for (let i = 0; i < n; i++) lines.push(['a', 'b', 'c', 'd', '', 'x y'][Math.floor(rand() * 6)] ?? ''); + return lines.join('\n') + (rand() < 0.5 ? '\n' : ''); +} + +function mulberry(seed: number): () => number { + let t = seed; + return () => { + t = (t + 0x6d2b79f5) | 0; + let r = Math.imul(t ^ (t >>> 15), 1 | t); + r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r; + return ((r ^ (r >>> 14)) >>> 0) / 4294967296; + }; +} + +describe('unifiedDiff', () => { + it('produces a standard hunk with context', () => { + const diff = unifiedDiff('src/a.ts', 'one\ntwo\nthree\n', 'one\n2\nthree\n'); + expect(diff).toBe('--- a/src/a.ts\n+++ b/src/a.ts\n@@ -1,3 +1,3 @@\n one\n-two\n+2\n three\n'); + }); + + it('marks creation and a missing final newline', () => { + expect(unifiedDiff('n.txt', null, 'hi')).toBe('--- /dev/null\n+++ b/n.txt\n@@ -0,0 +1,1 @@\n+hi\n\\ No newline at end of file\n'); + expect(unifiedDiff('n.txt', 'same\n', 'same\n')).toBe(''); + }); + + it.skipIf(!hasGit)('round-trips through git apply on random edits', () => { + const rand = mulberry(42); + for (let i = 0; i < 150; i++) { + const before = randomText(rand); + const after = randomText(rand); + if (before === after) continue; + const diff = unifiedDiff('f.txt', before, after); + expect(gitApply(before, diff)).toBe(after); + } + }); +}); diff --git a/src/tools/diff.ts b/src/tools/diff.ts new file mode 100644 index 0000000..9a8f419 --- /dev/null +++ b/src/tools/diff.ts @@ -0,0 +1,178 @@ +/** + * Unified diff of two texts (line based, Myers O(ND) with a bounded edit + * distance). When the texts differ by more than the bound, the changed middle + * is reported as one replace block, which is wider than the minimal diff but + * never wrong. + */ + +const CONTEXT = 3; +const MAX_EDIT_DISTANCE = 1000; + +interface Line { + readonly text: string; + /** False only for a last line without a trailing newline. */ + readonly eol: boolean; +} + +function splitLines(text: string): Line[] { + if (text === '') return []; + const parts = text.split('\n'); + const last = parts.pop() ?? ''; + const lines: Line[] = parts.map((t) => ({ text: t, eol: true })); + if (last !== '') lines.push({ text: last, eol: false }); + return lines; +} + +type Op = { readonly kind: ' ' | '-' | '+'; readonly line: Line }; + +function same(a: Line | undefined, b: Line | undefined): boolean { + return a !== undefined && b !== undefined && a.text === b.text && a.eol === b.eol; +} + +/** Edit script between a[lo..] and b[lo..] (already trimmed of common prefix/suffix). */ +function myers(a: readonly Line[], b: readonly Line[]): Op[] | null { + const n = a.length; + const m = b.length; + const max = Math.min(n + m, MAX_EDIT_DISTANCE); + const offset = max + 1; + const v = new Int32Array(2 * max + 3); + const trace: Int32Array[] = []; + for (let d = 0; d <= max; d++) { + trace.push(v.slice()); + for (let k = -d; k <= d; k += 2) { + let x: number; + if (k === -d || (k !== d && (v[offset + k - 1] ?? 0) < (v[offset + k + 1] ?? 0))) x = v[offset + k + 1] ?? 0; + else x = (v[offset + k - 1] ?? 0) + 1; + let y = x - k; + while (x < n && y < m && same(a[x], b[y])) { + x++; + y++; + } + v[offset + k] = x; + if (x >= n && y >= m) { + // Backtrack. + const ops: Op[] = []; + let cx = n; + let cy = m; + for (let dd = d; dd > 0; dd--) { + const pv = trace[dd] ?? v; + const kk = cx - cy; + let prevK: number; + if (kk === -dd || (kk !== dd && (pv[offset + kk - 1] ?? 0) < (pv[offset + kk + 1] ?? 0))) prevK = kk + 1; + else prevK = kk - 1; + const prevX = pv[offset + prevK] ?? 0; + const prevY = prevX - prevK; + while (cx > prevX && cy > prevY) { + cx--; + cy--; + ops.push({ kind: ' ', line: a[cx] as Line }); + } + if (cx === prevX) { + cy--; + ops.push({ kind: '+', line: b[cy] as Line }); + } else { + cx--; + ops.push({ kind: '-', line: a[cx] as Line }); + } + } + while (cx > 0 && cy > 0) { + cx--; + cy--; + ops.push({ kind: ' ', line: a[cx] as Line }); + } + return ops.reverse(); + } + } + } + return null; +} + +function editScript(a: readonly Line[], b: readonly Line[]): Op[] { + let start = 0; + while (start < a.length && start < b.length && same(a[start], b[start])) start++; + let endA = a.length; + let endB = b.length; + while (endA > start && endB > start && same(a[endA - 1], b[endB - 1])) { + endA--; + endB--; + } + const midA = a.slice(start, endA); + const midB = b.slice(start, endB); + const middle = myers(midA, midB) ?? [ + ...midA.map((line): Op => ({ kind: '-', line })), + ...midB.map((line): Op => ({ kind: '+', line })), + ]; + return [ + ...a.slice(0, start).map((line): Op => ({ kind: ' ', line })), + ...middle, + ...a.slice(endA).map((line): Op => ({ kind: ' ', line })), + ]; +} + +function renderLine(op: Op): string { + const out = `${op.kind}${op.line.text}\n`; + return op.line.eol ? out : `${out}\\ No newline at end of file\n`; +} + +/** + * Unified diff from `before` to `after`. `before === null` means the file did + * not exist. `file` is shown as `a/` and `b/`. Returns '' when + * nothing changed. + */ +export function unifiedDiff(file: string, before: string | null, after: string): string { + if (before !== null && before === after) return ''; + const a = before === null ? [] : splitLines(before); + const b = splitLines(after); + const ops = editScript(a, b); + const header = `--- ${before === null ? '/dev/null' : `a/${file}`}\n+++ b/${file}\n`; + if (ops.every((op) => op.kind === ' ')) { + // Only possible when before is null and after is empty. + return `${header}`; + } + + let out = header; + let i = 0; + // Line counters at the start of ops[i]. + const posA: number[] = []; + const posB: number[] = []; + let la = 0; + let lb = 0; + for (const op of ops) { + posA.push(la); + posB.push(lb); + if (op.kind !== '+') la++; + if (op.kind !== '-') lb++; + } + while (i < ops.length) { + while (i < ops.length && ops[i]?.kind === ' ') i++; + if (i >= ops.length) break; + const hunkStart = Math.max(0, i - CONTEXT); + let end = i; + // Extend while changes are within 2*CONTEXT of each other. + for (;;) { + while (end < ops.length && ops[end]?.kind !== ' ') end++; + let next = end; + while (next < ops.length && ops[next]?.kind === ' ') next++; + if (next < ops.length && next - end <= 2 * CONTEXT) { + end = next; + continue; + } + break; + } + const hunkEnd = Math.min(ops.length, end + CONTEXT); + const slice = ops.slice(hunkStart, hunkEnd); + const countA = slice.filter((op) => op.kind !== '+').length; + const countB = slice.filter((op) => op.kind !== '-').length; + const startA = countA === 0 ? (posA[hunkStart] ?? 0) : (posA[hunkStart] ?? 0) + 1; + const startB = countB === 0 ? (posB[hunkStart] ?? 0) : (posB[hunkStart] ?? 0) + 1; + out += `@@ -${startA},${countA} +${startB},${countB} @@\n`; + out += slice.map(renderLine).join(''); + i = hunkEnd; + } + return out; +} + +/** Diff header for a binary change. */ +export function binaryDiff(file: string, existed: boolean): string { + return `--- ${existed ? `a/${file}` : '/dev/null'}\n+++ b/${file}\nBinary files differ\n`; +} diff --git a/src/tools/edit-match.test.ts b/src/tools/edit-match.test.ts new file mode 100644 index 0000000..94bb9ed --- /dev/null +++ b/src/tools/edit-match.test.ts @@ -0,0 +1,113 @@ +// Test cases ported from Turnpack's test/edit-match.test.mjs +// (https://github.com/OnlyTerp/turnpack, Copyright 2026 OnlyTerp, Apache-2.0). +// Modified by the agent-code-mode authors: vitest, typed, and checks of the +// `matched` text this port adds. +import { describe, expect, it } from 'vitest'; +import { applySearchReplace, type EditApplied, type EditMiss, type EditOutcome } from './edit-match.js'; + +const apply = (text: string, search: string, replace: string, all = false): EditOutcome => applySearchReplace(text, search, replace, all); + +function ok(out: EditOutcome): EditApplied { + if (!out.ok) throw new Error(`expected a match: ${out.message}`); + return out; +} +function miss(out: EditOutcome): EditMiss { + if (out.ok) throw new Error(`expected no match, got ${out.how}`); + return out; +} + +describe('edit matching (ported from Turnpack)', () => { + it('uses the exact text when it is there, and says where an ambiguous one occurs', () => { + const text = 'a = 1\nb = 2\na = 1\n'; + const once = ok(apply(text, 'b = 2', 'b = 3')); + expect([once.how, once.count, once.text, once.matched]).toEqual(['exact', 1, 'a = 1\nb = 3\na = 1\n', 'b = 2']); + + const twice = miss(apply(text, 'a = 1', 'a = 9')); + expect(twice.kind).toBe('ambiguous'); + expect(twice.message).toMatch(/matches 2 places \(lines 1, 3\)/); + + const all = ok(apply(text, 'a = 1', 'a = 9', true)); + expect([all.count, all.text]).toEqual([2, 'a = 9\nb = 2\na = 9\n']); + + // The replacement is inserted as written: no "$&" or "$1" expansion. + expect(ok(apply('x = 1\n', 'x = 1', "x = '$&$1'")).text).toBe("x = '$&$1'\n"); + expect(miss(apply('x\n', '', 'y')).kind).toBe('empty'); + }); + + it("matches LF text against a CRLF file and keeps the file's line endings", () => { + const out = ok(apply('a\r\nb\r\nc\r\n', 'a\nb', 'x\ny')); + expect([out.how, out.text, out.matched]).toEqual(['line-endings', 'x\r\ny\r\nc\r\n', 'a\r\nb']); + }); + + it('finds a block whose indentation was remembered wrongly, and re-indents what replaces it', () => { + const file = 'function f() {\n if (x) {\n return 1;\n }\n}\n'; + const out = ok(apply(file, 'if (x) {\n return 1;\n}', 'if (x) {\n log();\n return 2;\n}')); + expect(out.how).toBe('indentation'); + expect(out.text).toBe('function f() {\n if (x) {\n log();\n return 2;\n }\n}\n'); + expect(out.matched).toBe(' if (x) {\n return 1;\n }'); + + // Spaces remembered where the file has tabs: converted level by level. + const tabbed = 'class A {\n\trun() {\n\t\treturn 1;\n\t}\n}\n'; + const tabs = ok(apply(tabbed, ' run() {\n return 1;\n }', ' run() {\n if (ok) {\n return 2;\n }\n }')); + expect(tabs.how).toBe('indentation'); + expect(tabs.text).toBe('class A {\n\trun() {\n\t\tif (ok) {\n\t\t\treturn 2;\n\t\t}\n\t}\n}\n'); + + // And the other way round, in a CRLF file, with the trailing newline included in the search. + const crlf = ' a();\r\n b();\r\nend\r\n'; + const mixed = ok(apply(crlf, '\ta();\n\tb();\n', '\ta();\n\tc();\n')); + expect(mixed.text).toBe(' a();\r\n c();\r\nend\r\n'); + }); + + it('ignores line numbers copied from a listing, trailing spaces, and typographic quotes', () => { + const file = 'export const TAX = 0.08;\n\nexport function tax(n) {\n return n * TAX;\n}\n'; + const listing = ok( + apply(file, '3 | export function tax(n) {\n4 | return n * TAX;\n5 | }', '3 | export function tax(n) {\n4 | return round(n * TAX);\n5 | }'), + ); + expect(listing.how).toBe('line-numbers'); + expect(listing.text).toBe('export const TAX = 0.08;\n\nexport function tax(n) {\n return round(n * TAX);\n}\n'); + + // A file that really does contain "12 | x" is matched exactly, not stripped. + expect(ok(apply('12 | x\n', '12 | x', '13 | y')).how).toBe('exact'); + + const spaced = ok(apply('foo(); \nbar();\n', 'foo();\nbar();', 'baz();')); + expect([spaced.how, spaced.text, spaced.matched]).toEqual(['trailing-whitespace', 'baz();\n', 'foo(); \nbar();']); + + const quoted = ok(apply(' const s = “hello”; // it’s\n', 'const s = "hello"; // it\'s', 'const s = "bye";')); + expect([quoted.how, quoted.text, quoted.matched]).toEqual(['punctuation', ' const s = "bye";\n', ' const s = “hello”; // it’s']); + }); + + it('never picks between two places that only match loosely', () => { + const file = 'if (a) {\n go();\n}\nif (b) {\n go();\n}\n'; + const out = miss(apply(file, ' go();', ' stop();')); + expect(out.kind).toBe('ambiguous'); + expect(out.message).toMatch(/matches 2 places \(lines 2, 5\) when indentation is ignored/); + + const all = ok(apply(file, ' go();', ' stop();', true)); + expect(all.text).toBe('if (a) {\n stop();\n}\nif (b) {\n stop();\n}\n'); + + // Blank lines alone are not a place. + expect(miss(apply('a\n\n\nb\n', ' \n ', 'x')).kind).toBe('not-found'); + }); + + it('shows the nearest text and the first difference when nothing matches', () => { + const file = [ + "import { TAX } from './rates.js';", + '', + 'export function invoiceTotal(subtotal) {', + ' const tax = Number((subtotal * TAX).toFixed(2));', + ' return subtotal + tax;', + '}', + '', + ].join('\n'); + const out = miss(apply(file, 'export function invoiceTotal(subtotal) {\n const tax = subtotal * TAX;\n return subtotal + tax;\n}', 'x')); + expect(out.kind).toBe('not-found'); + expect(out.message).toMatch(/closest text is lines 3-6 \(3 of 4 line\(s\) identical/); + expect(out.message).toMatch(/ 4 \| {3}const tax = Number\(\(subtotal \* TAX\)\.toFixed\(2\)\);/); + expect(out.message).toMatch(/First difference, at line 4:/); + expect(out.message).toMatch(/search has: " {2}const tax = subtotal \* TAX;"/); + expect(out.message).toMatch(/file has: {3}" {2}const tax = Number/); + + const nowhere = miss(apply(file, 'class Zebra extends Animal {}', 'x')); + expect(nowhere.message).toMatch(/nothing close to it is in the file \(7 lines\)/); + }); +}); diff --git a/src/tools/edit-match.ts b/src/tools/edit-match.ts new file mode 100644 index 0000000..cdad6c2 --- /dev/null +++ b/src/tools/edit-match.ts @@ -0,0 +1,495 @@ +/* + * Copyright 2026 OnlyTerp (https://github.com/OnlyTerp) + * + * 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. + * + * Ported from Turnpack's src/tools/edit-match.ts + * (https://github.com/OnlyTerp/turnpack, commit b14330d). + * Modified by the agent-code-mode authors: the result also carries the exact + * text that was matched (`matched`), messages name this project's argument + * names, and the patch-hunk helpers that this project does not use were removed. + */ + +/** + * Search/replace matching for `edit`. + * + * A model writes an edit from its memory of a file, and that memory is often right about the + * code and wrong about the bytes: an indent one level off, tabs remembered as spaces, a + * trailing space dropped, the line numbers a listing printed copied along with the code, a curly + * quote typed straight. Refusing each of those costs a full extra turn (re-read, re-send) for a + * difference nobody meant. + * + * So matching is a ladder. The exact text is tried first and wins whenever it is there. Only if + * it is absent are looser comparisons tried, one at a time, each comparing whole lines: + * + * exact → line endings → copied line numbers → trailing whitespace → indentation → punctuation + * + * A looser rung is used only when it identifies the place unambiguously (or `replaceAll` is + * set), and the caller is told which rung matched so the reply can say so. Nothing here guesses + * between two candidate places. + * + * When no rung matches, `describeNearest` finds the most similar region and shows it with line + * numbers and the first differing line, so the next attempt can be written without re-reading. + */ + +export type MatchHow = + | "exact" + | "line-endings" + | "line-numbers" + | "trailing-whitespace" + | "indentation" + | "punctuation"; + +export interface EditApplied { + ok: true; + text: string; + how: MatchHow; + count: number; + /** The exact text of the file that the first match covers (what is replaced). */ + matched: string; +} + +export interface EditMiss { + ok: false; + kind: "empty" | "not-found" | "ambiguous"; + /** Complete, model-readable explanation, without the file name. */ + message: string; +} + +export type EditOutcome = EditApplied | EditMiss; + +/** What a looser match ignored, in the words used in replies. */ +export const HOW_LABEL: Record = { + exact: "exact", + "line-endings": "line endings", + "line-numbers": "line numbers copied from a listing", + "trailing-whitespace": "trailing whitespace", + indentation: "indentation", + punctuation: "indentation and typographic quotes or dashes", +}; + +interface FileLine { + /** Offset of the first character of the line. */ + start: number; + /** Offset just past the last character before the line ending. */ + bodyEnd: number; + /** Offset just past the line ending (equal to bodyEnd on a last line with none). */ + end: number; + body: string; +} + +function splitLines(text: string): FileLine[] { + const lines: FileLine[] = []; + let pos = 0; + for (;;) { + const nl = text.indexOf("\n", pos); + if (nl === -1) { + lines.push({ start: pos, bodyEnd: text.length, end: text.length, body: text.slice(pos) }); + return lines; + } + const bodyEnd = nl > pos && text[nl - 1] === "\r" ? nl - 1 : nl; + lines.push({ start: pos, bodyEnd, end: nl + 1, body: text.slice(pos, bodyEnd) }); + pos = nl + 1; + } +} + +function lineNumberAt(lines: FileLine[], offset: number): number { + let lo = 0; + let hi = lines.length - 1; + while (lo < hi) { + const mid = (lo + hi + 1) >> 1; + if ((lines[mid]?.start ?? 0) <= offset) lo = mid; + else hi = mid - 1; + } + return lo + 1; +} + +function occurrences(haystack: string, needle: string): number[] { + const found: number[] = []; + if (!needle) return found; + let from = 0; + for (;;) { + const at = haystack.indexOf(needle, from); + if (at === -1) return found; + found.push(at); + from = at + needle.length; + } +} + +function listLines(numbers: number[]): string { + const shown = numbers.slice(0, 8).join(", "); + return numbers.length > 8 ? `${shown}, and ${numbers.length - 8} more` : shown; +} + +function ambiguous(lineNumbers: number[], ignoring?: string): EditMiss { + return { + ok: false, + kind: "ambiguous", + message: + `search text matches ${lineNumbers.length} places (lines ${listLines(lineNumbers)})` + + `${ignoring ? ` when ${ignoring} is ignored` : ""}. ` + + "Add a neighbouring line to oldString so it names one place, or pass replaceAll: true.", + }; +} + +// " 12 | code" is how Turnpack's pack prints a line; " 12\tcode" is `cat -n`; "12→code" is another +// common listing style. A search made only of such lines was copied from a listing. +const GUTTER = /^[>\s]*\d+(?: \|(?: |$)|\t|→)/; + +function stripGutter(lines: string[]): string[] | null { + const meaningful = lines.filter((line) => line.trim() !== ""); + if (meaningful.length === 0 || !meaningful.every((line) => GUTTER.test(line))) return null; + return lines.map((line) => line.replace(GUTTER, "")); +} + +const PUNCTUATION: Array<[RegExp, string]> = [ + [/[‘’‚‛′]/g, "'"], + [/[“”„‟″]/g, '"'], + [/[‐‑‒–—―−]/g, "-"], + [/[             ]/g, " "], + [/…/g, "..."], +]; + +function foldPunctuation(value: string): string { + let out = value; + for (const [pattern, plain] of PUNCTUATION) out = out.replace(pattern, plain); + return out; +} + +function leadingWhitespace(value: string): string { + return /^[ \t]*/.exec(value)?.[0] ?? ""; +} + +/** + * Rewrites the indentation of replacement lines from the way the model wrote the block to the + * way the file has it. + * + * The matched lines are the evidence: line k of the search was written with one indent and the + * file has another, which gives a small dictionary from "the model's indent" to "the file's + * indent" (no indent → one tab, four spaces → two tabs). A replacement line whose indent is in + * the dictionary is translated outright. One that is deeper than anything matched is + * extrapolated from the step between two matched depths, and failing that keeps its extra + * indentation on top of the nearest known depth. + */ +function reindentLike(replaceLines: string[], searchLines: string[], fileLines: string[]): string[] { + const known = new Map(); + for (let k = 0; k < searchLines.length; k++) { + const searchLine = searchLines[k] ?? ""; + const fileLine = fileLines[k] ?? ""; + if (searchLine.trim() === "" || fileLine.trim() === "") continue; + const indent = leadingWhitespace(searchLine); + if (!known.has(indent)) known.set(indent, leadingWhitespace(fileLine)); + } + if (known.size === 0 || [...known].every(([from, to]) => from === to)) return replaceLines; + + // One level of nesting, as the model writes it and as the file writes it. + const depths = [...known.keys()].sort((a, b) => a.length - b.length); + let step: { from: number; to: string } | null = null; + for (let i = 1; i < depths.length && !step; i++) { + const shallow = depths[i - 1] ?? ""; + const deep = depths[i] ?? ""; + const fileShallow = known.get(shallow) ?? ""; + const fileDeep = known.get(deep) ?? ""; + if (deep.startsWith(shallow) && fileDeep.startsWith(fileShallow) && fileDeep.length > fileShallow.length) { + step = { from: deep.length - shallow.length, to: fileDeep.slice(fileShallow.length) }; + } + } + // With one matched depth and a file that indents with tabs, a level is taken to be the + // smallest extra indent the replacement itself uses. + const extras = replaceLines + .filter((line) => line.trim() !== "") + .map((line) => leadingWhitespace(line)) + .map((indent) => { + const base = depths.filter((depth) => indent.startsWith(depth)).pop(); + return base === undefined ? 0 : indent.length - base.length; + }) + .filter((extra) => extra > 0); + const smallestExtra = extras.length > 0 ? Math.min(...extras) : 0; + + return replaceLines.map((line) => { + if (line.trim() === "") return line; + const indent = leadingWhitespace(line); + const rest = line.slice(indent.length); + const direct = known.get(indent); + if (direct !== undefined) return direct + rest; + + const base = depths.filter((depth) => indent.startsWith(depth)).pop(); + if (base === undefined) return line; // shallower than anything matched: leave it as written + const fileBase = known.get(base) ?? ""; + const extra = indent.slice(base.length); + if (step && extra.length % step.from === 0) { + return fileBase + step.to.repeat(extra.length / step.from) + rest; + } + if (/^\t+$/.test(fileBase) && /^ +$/.test(extra) && smallestExtra > 0 && extra.length % smallestExtra === 0) { + return fileBase + "\t".repeat(extra.length / smallestExtra) + rest; + } + return fileBase + extra + rest; + }); +} + +interface Rung { + how: MatchHow; + normalize: (line: string) => string; + /** Whether the replacement needs its indentation moved to where the file has it. */ + reindent: boolean; +} + +const RUNGS: Rung[] = [ + { how: "trailing-whitespace", normalize: (line) => line.replace(/[ \t]+$/, ""), reindent: false }, + { how: "indentation", normalize: (line) => line.trim(), reindent: true }, + { how: "punctuation", normalize: (line) => foldPunctuation(line).trim(), reindent: true }, +]; + +function findLineMatches(fileNorm: string[], wanted: string[]): number[] { + const hits: number[] = []; + const n = wanted.length; + const first = wanted[0]; + for (let i = 0; i + n <= fileNorm.length; i++) { + if (fileNorm[i] !== first) continue; + let same = true; + for (let k = 1; k < n; k++) { + if (fileNorm[i + k] !== wanted[k]) { + same = false; + break; + } + } + if (same) { + hits.push(i); + i += n - 1; // matches may not overlap + } + } + return hits; +} + +/** + * Applies one search/replace to `text`. See the file comment for the order of attempts. + */ +export function applySearchReplace( + text: string, + search: string, + replace: string, + replaceAll: boolean, +): EditOutcome { + if (!search) { + return { ok: false, kind: "empty", message: "the search text is empty" }; + } + + // Rung 1: the text exactly as written. + let exact = occurrences(text, search); + let how: MatchHow = "exact"; + let exactSearch = search; + let exactReplace = replace; + + // Rung 2: the same text with the file's line endings. + const fileUsesCrlf = text.includes("\r\n"); + const eol = fileUsesCrlf ? "\r\n" : "\n"; + const toFileEol = (value: string): string => { + const lf = value.replace(/\r\n/g, "\n"); + return fileUsesCrlf ? lf.replace(/\n/g, "\r\n") : lf; + }; + if (exact.length === 0 && /\n/.test(search)) { + const alt = toFileEol(search); + if (alt !== search) { + const altHits = occurrences(text, alt); + if (altHits.length > 0) { + exact = altHits; + exactSearch = alt; + exactReplace = toFileEol(replace); + how = "line-endings"; + } + } + } + + let fileLines: FileLine[] | undefined; + const linesOfFile = (): FileLine[] => (fileLines ??= splitLines(text)); + + if (exact.length > 1 && !replaceAll) { + return ambiguous(exact.map((offset) => lineNumberAt(linesOfFile(), offset))); + } + if (exact.length > 0) { + return { ok: true, text: text.split(exactSearch).join(exactReplace), how, count: exact.length, matched: exactSearch }; + } + + // From here on the comparison is line by line. + let searchLines = search.replace(/\r\n/g, "\n").split("\n"); + let replaceLines = replace.replace(/\r\n/g, "\n").split("\n"); + + // A search that ends in a newline covers its last line's ending too. + const coversLastEnding = searchLines.length > 1 && searchLines[searchLines.length - 1] === ""; + if (coversLastEnding) searchLines = searchLines.slice(0, -1); + + let gutterStripped = false; + const withoutGutter = stripGutter(searchLines); + if (withoutGutter) { + searchLines = withoutGutter; + replaceLines = replaceLines.map((line) => line.replace(GUTTER, "")); + gutterStripped = true; + } + + const file = linesOfFile(); + const bodies = file.map((line) => line.body); + + const rungs: Rung[] = gutterStripped + ? [{ how: "line-numbers", normalize: (line) => line, reindent: false }, ...RUNGS] + : RUNGS; + + for (const rung of rungs) { + const wanted = searchLines.map(rung.normalize); + // A search that normalises to nothing would match every blank line. + if (wanted.every((line) => line === "")) continue; + const hits = findLineMatches(bodies.map(rung.normalize), wanted); + if (hits.length === 0) continue; + const label = rung.how; + if (hits.length > 1 && !replaceAll) { + return ambiguous( + hits.map((index) => index + 1), + HOW_LABEL[label], + ); + } + + const pieces: string[] = []; + let cursor = 0; + let matched: string | undefined; + for (const index of hits) { + const firstLine = file[index]; + const lastLine = file[index + searchLines.length - 1]; + if (!firstLine || !lastLine) continue; + const lines = rung.reindent + ? reindentLike(replaceLines, searchLines, bodies.slice(index, index + searchLines.length)) + : replaceLines; + pieces.push(text.slice(cursor, firstLine.start), lines.join(eol)); + cursor = coversLastEnding ? lastLine.end : lastLine.bodyEnd; + matched ??= text.slice(firstLine.start, cursor); + } + pieces.push(text.slice(cursor)); + return { ok: true, text: pieces.join(""), how: label, count: hits.length, matched: matched ?? "" }; + } + + return { ok: false, kind: "not-found", message: describeNearest(text, searchLines) }; +} + +function tokensOf(line: string): string[] { + return line.match(/[A-Za-z_$][\w$]*|\d+|[^\s\w]/g) ?? []; +} + +/** Token overlap between two lines, 0 to 1. Order-blind, which is fine for "is this the place". */ +function similarity(a: string, b: string): number { + if (a === b) return 1; + const ta = tokensOf(a); + const tb = tokensOf(b); + if (ta.length === 0 || tb.length === 0) return 0; + const counts = new Map(); + for (const token of ta) counts.set(token, (counts.get(token) ?? 0) + 1); + let common = 0; + for (const token of tb) { + const left = counts.get(token); + if (left) { + common += 1; + counts.set(token, left - 1); + } + } + return (2 * common) / (ta.length + tb.length); +} + +const MAX_SCAN_LINES = 60000; +const MAX_SNIPPET_LINES = 12; + +function quoteLine(line: string): string { + const shown = line.length > 160 ? `${line.slice(0, 160)}…` : line; + return JSON.stringify(shown); +} + +/** + * Explains a search that matched nowhere: the most similar region of the file with line + * numbers, how much of it agrees, and the first line that does not. + */ +export function describeNearest(text: string, searchLinesRaw: string[]): string { + const file = splitLines(text); + const total = file.length; + const wanted = searchLinesRaw.map((line) => line.trim()); + const fileTrim = file.slice(0, MAX_SCAN_LINES).map((line) => line.body.trim()); + const nothing = `search text not found, and nothing close to it is in the file (${total} lines). Read the file and write oldString from what is there.`; + + // Find candidate positions through the search's most distinctive line: its longest. + let probe = 0; + for (let k = 1; k < wanted.length; k++) { + if ((wanted[k]?.length ?? 0) > (wanted[probe]?.length ?? 0)) probe = k; + } + const probeLine = wanted[probe] ?? ""; + if (!probeLine) return nothing; + + const candidates: Array<{ start: number; score: number }> = []; + for (let j = 0; j < fileTrim.length; j++) { + const score = similarity(fileTrim[j] ?? "", probeLine); + if (score >= 0.5) candidates.push({ start: j - probe, score }); + } + candidates.sort((a, b) => b.score - a.score); + + let best: { start: number; score: number; identical: number } | null = null; + for (const candidate of candidates.slice(0, 12)) { + let sum = 0; + let identical = 0; + for (let k = 0; k < wanted.length; k++) { + const fileLine = fileTrim[candidate.start + k]; + if (fileLine === undefined) continue; + const score = similarity(fileLine, wanted[k] ?? ""); + sum += score; + if (fileLine === wanted[k]) identical += 1; + } + const mean = sum / wanted.length; + if (!best || mean > best.score) best = { start: candidate.start, score: mean, identical }; + } + if (!best || best.score < 0.35) return nothing; + + const from = Math.max(0, best.start); + const to = Math.min(total, best.start + wanted.length); // exclusive + let firstDiff = -1; + for (let k = 0; k < wanted.length; k++) { + if (fileTrim[best.start + k] !== wanted[k]) { + firstDiff = k; + break; + } + } + + // Show the whole region when it is short, otherwise the part around the first difference. + let showFrom = from; + let showTo = to; + if (to - from > MAX_SNIPPET_LINES) { + const centre = best.start + Math.max(0, firstDiff); + showFrom = Math.max(from, centre - 3); + showTo = Math.min(to, showFrom + MAX_SNIPPET_LINES); + } + const width = String(showTo).length; + const snippet: string[] = []; + for (let i = showFrom; i < showTo; i++) { + const body = file[i]?.body ?? ""; + snippet.push(` ${String(i + 1).padStart(width, " ")} | ${body.length > 200 ? `${body.slice(0, 200)}…` : body}`); + } + + const out = [ + `search text not found. The closest text is lines ${from + 1}-${to} (${best.identical} of ${wanted.length} line(s) identical apart from indentation):`, + ...snippet, + ]; + if (showTo < to || showFrom > from) out.push(` (showing lines ${showFrom + 1}-${showTo})`); + if (firstDiff !== -1) { + const fileLine = file[best.start + firstDiff]; + out.push( + fileLine + ? `First difference, at line ${best.start + firstDiff + 1}:` + : "First difference: the search runs past the end of the file:", + ` search has: ${quoteLine(searchLinesRaw[firstDiff] ?? "")}`, + ` file has: ${fileLine ? quoteLine(fileLine.body) : "(no such line)"}`, + ); + } + return out.join("\n"); +} diff --git a/src/tools/fs-ops.ts b/src/tools/fs-ops.ts new file mode 100644 index 0000000..da3be27 --- /dev/null +++ b/src/tools/fs-ops.ts @@ -0,0 +1,249 @@ +import { createHash, randomBytes } from 'node:crypto'; +import { constants as FS, type Stats } from 'node:fs'; +import fs, { type FileHandle } from 'node:fs/promises'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; + +/** + * File operations that do not let a symlink or a race widen what was + * prepared. Every open of a final component uses `O_NOFOLLOW` where the + * platform has it; the opened file is then checked to be the one at the path + * (Linux: `/proc/self/fd`; elsewhere: `fstat` vs `lstat` identity). + */ + +const NOFOLLOW = FS.O_NOFOLLOW ?? 0; +const IS_LINUX = process.platform === 'linux'; +const IS_WINDOWS = process.platform === 'win32'; + +export function sha256(data: Buffer | string): string { + return createHash('sha256').update(data).digest('hex'); +} + +export function errnoCode(err: unknown): string | undefined { + if (err !== null && typeof err === 'object' && 'code' in err && typeof err.code === 'string') return err.code; + return undefined; +} + +function sameFile(a: Stats, b: Stats): boolean { + return a.ino === b.ino && a.dev === b.dev; +} + +/** Throws `stale` unless the real path of `dir` is still exactly `dir`. */ +export async function assertDirUnchanged(dir: string): Promise { + let real: string; + try { + real = await fs.realpath(dir); + } catch (err) { + throw new ToolError('stale', `${dir} changed since prepared (${errnoCode(err) ?? 'unresolvable'})`); + } + const same = IS_WINDOWS ? real.toLowerCase() === dir.toLowerCase() : real === dir; + if (!same) throw new ToolError('stale', `file changed since prepared: ${dir} now resolves to ${real}`); +} + +/** Verifies an open handle is the file at `abs` and not something reached through a link. */ +async function assertHandleAt(handle: FileHandle, abs: string): Promise { + const st = await handle.stat(); + if (IS_LINUX) { + let actual: string | undefined; + try { + actual = await fs.readlink(`/proc/self/fd/${handle.fd}`); + } catch { + actual = undefined; + } + if (actual !== undefined && actual !== abs) { + throw new ToolError('stale', `file changed since prepared: ${abs} opened as ${actual}`); + } + } + const lst = await fs.lstat(abs).catch(() => null); + if (!lst || lst.isSymbolicLink() || !sameFile(st, lst)) { + throw new ToolError('stale', `file changed since prepared: ${abs} was replaced while it was opened`); + } + return st; +} + +export interface RegularFile { + readonly bytes: Buffer; + readonly mode: number; +} + +/** + * Reads a regular file without following a link at its final component. + * Returns null when it does not exist. `maxBytes` bounds the read. + */ +export async function readRegularFile(abs: string, maxBytes = Number.MAX_SAFE_INTEGER): Promise { + let handle: FileHandle; + try { + handle = await fs.open(abs, FS.O_RDONLY | NOFOLLOW); + } catch (err) { + const code = errnoCode(err); + if (code === 'ENOENT') return null; + if (code === 'ELOOP' || code === 'EMLINK') throw new ToolError('stale', `${abs} is a symbolic link`); + if (code === 'EISDIR') throw new ToolError('invalid-args', `${abs} is a directory`); + throw new ToolError('tool-error', `cannot open ${abs}: ${code ?? String(err)}`); + } + try { + const st = await assertHandleAt(handle, abs); + if (st.isDirectory()) throw new ToolError('invalid-args', `${abs} is a directory`); + if (!st.isFile()) throw new ToolError('invalid-args', `${abs} is not a regular file`); + if (st.size > maxBytes) throw new ToolError('tool-error', `${abs} is ${st.size} bytes, more than the ${maxBytes}-byte limit`); + const bytes = await handle.readFile(); + return { bytes, mode: st.mode & 0o7777 }; + } finally { + await handle.close(); + } +} + +/** What a commit expects to find at the path before it writes. */ +export type Expectation = { readonly kind: 'absent' } | { readonly kind: 'hash'; readonly sha256: string }; + +export interface WriteOutcome { + /** Bytes that were there before (null when absent). */ + readonly before: RegularFile | null; + /** Directories created to hold the file, outermost first. */ + readonly createdDirs: readonly string[]; +} + +async function missingDirs(dir: string): Promise { + const missing: string[] = []; + let cursor = dir; + for (;;) { + const st = await fs.lstat(cursor).catch(() => null); + if (st) { + if (st.isSymbolicLink() || !st.isDirectory()) { + throw new ToolError('stale', `file changed since prepared: ${cursor} is not a directory`); + } + break; + } + missing.push(cursor); + const parent = path.dirname(cursor); + if (parent === cursor) break; + cursor = parent; + } + return missing.reverse(); +} + +/** + * Atomically replaces (or creates) `abs` with `bytes`: + * 1. the parent directory must still resolve to itself (no symlink swapped in); + * 2. the current content must match `expect` (else `ToolError('stale')`, no write); + * 3. the bytes go to a temp file in the same directory (fsync), keep the old mode, + * and are renamed over the target; a create uses `link` so it never replaces + * a file that appeared meanwhile. + * `beforeWrite` runs after the checks and before anything is written (the + * transaction journal snapshots the original there). + */ +export async function atomicWrite( + abs: string, + bytes: Buffer, + expect: Expectation, + beforeWrite?: (before: RegularFile | null, createdDirs: readonly string[]) => Promise, +): Promise { + const dir = path.dirname(abs); + const toCreate = await missingDirs(dir); + const existingAncestor = toCreate.length > 0 ? path.dirname(toCreate[0] ?? dir) : dir; + await assertDirUnchanged(existingAncestor); + + const before = await readRegularFile(abs); + if (expect.kind === 'absent' && before !== null) { + throw new ToolError('stale', `file changed since prepared: ${abs} was created after the call was prepared`); + } + if (expect.kind === 'hash') { + if (before === null) throw new ToolError('stale', `file changed since prepared: ${abs} no longer exists`); + if (sha256(before.bytes) !== expect.sha256) throw new ToolError('stale', `file changed since prepared: ${abs}`); + } + + await beforeWrite?.(before, toCreate); + + for (const d of toCreate) { + try { + await fs.mkdir(d); + } catch (err) { + if (errnoCode(err) !== 'EEXIST') throw err; + } + await assertDirUnchanged(d); + } + await assertDirUnchanged(dir); + + const tmp = path.join(dir, `.${path.basename(abs)}.acm-${randomBytes(6).toString('hex')}.tmp`); + const mode = before?.mode ?? 0o666; + const handle = await fs.open(tmp, FS.O_WRONLY | FS.O_CREAT | FS.O_EXCL | NOFOLLOW, mode); + let placed = false; + try { + try { + await handle.writeFile(bytes); + if (before && !IS_WINDOWS) await handle.chmod(before.mode); + await handle.sync(); + } finally { + await handle.close(); + } + await assertDirUnchanged(dir); + if (expect.kind === 'absent') { + try { + await fs.link(tmp, abs); + placed = true; + } catch (err) { + const code = errnoCode(err); + if (code === 'EEXIST') throw new ToolError('stale', `file changed since prepared: ${abs} was created meanwhile`); + // File systems without hard links: fall back to rename. + if (code !== 'EPERM' && code !== 'ENOTSUP' && code !== 'EOPNOTSUPP' && code !== 'EXDEV') throw err; + } + } + if (!placed) await fs.rename(tmp, abs); + return { before, createdDirs: toCreate }; + } finally { + // After `link` the temp name is still there; after `rename` it is gone. + await fs.rm(tmp, { force: true }).catch(() => undefined); + } +} + +/** Removes `abs` if it is a regular file (never follows a link). */ +export async function removeRegularFile(abs: string): Promise { + const st = await fs.lstat(abs).catch(() => null); + if (!st) return; + if (!st.isFile()) throw new ToolError('stale', `${abs} is no longer a regular file`); + await fs.unlink(abs); +} + +/** fsyncs a directory where the platform allows it. */ +export async function syncDir(dir: string): Promise { + if (IS_WINDOWS) return; + try { + const handle = await fs.open(dir, FS.O_RDONLY); + try { + await handle.sync(); + } finally { + await handle.close(); + } + } catch { + // Not every file system lets a directory be flushed. + } +} + +/** Writes and fsyncs a private file (journal records). */ +export async function writeDurable(file: string, data: Buffer | string): Promise { + const handle = await fs.open(file, FS.O_WRONLY | FS.O_CREAT | FS.O_TRUNC, 0o600); + try { + await handle.writeFile(data); + await handle.sync(); + } finally { + await handle.close(); + } +} + +/** Whether a buffer looks like binary data: a NUL byte in the first 8 KiB, or invalid UTF-8. */ +export function isBinary(bytes: Buffer): boolean { + const head = bytes.subarray(0, 8192); + if (head.includes(0)) return true; + try { + new TextDecoder('utf-8', { fatal: true }).decode(bytes); + return false; + } catch { + return true; + } +} + +/** Decodes UTF-8 text, throwing `ToolError('tool-error', 'binary file')` for binary data. */ +export function decodeText(abs: string, bytes: Buffer): string { + if (isBinary(bytes)) throw new ToolError('tool-error', `binary file: ${abs}`); + return bytes.toString('utf8'); +} diff --git a/src/tools/index.ts b/src/tools/index.ts new file mode 100644 index 0000000..925fd0c --- /dev/null +++ b/src/tools/index.ts @@ -0,0 +1,5 @@ +export { NodeToolRuntime, DEFAULT_READ_LIMIT, READ_CAP_BYTES, MAX_FILE_BYTES, type NodeToolRuntimeOptions } from './runtime.js'; +export { FileTransaction, MAX_JOURNAL_BYTES, recoverStaleJournals, journalRoot, type RecoveredJournal } from './journal.js'; +export { DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS, DEFAULT_OUTPUT_CAP_BYTES } from './bash.js'; +export { DEFAULT_GREP_MAX_RESULTS, DEFAULT_GLOB_MAX_RESULTS } from './search.js'; +export { containmentUnavailableReason } from './sandbox.js'; diff --git a/src/tools/integration.test.ts b/src/tools/integration.test.ts new file mode 100644 index 0000000..971200f --- /dev/null +++ b/src/tools/integration.test.ts @@ -0,0 +1,62 @@ +import { existsSync, mkdirSync, readdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { runScript } from '../core/run.js'; +import { FakeSandbox, StaticHostAdapter, makeContext } from '../testing/index.js'; +import { NodeToolRuntime } from './runtime.js'; + +/** The real tool runtime behind the P0 dispatcher and run pipeline. */ +let base: string; +let ws: string; + +beforeEach(() => { + base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-int-'))); + ws = path.join(base, 'ws'); + mkdirSync(ws); + writeFileSync(path.join(ws, 'a.txt'), 'alpha\n'); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +function deps(adapter = new StaticHostAdapter({ protectedPaths: [] })) { + return { sandbox: new FakeSandbox(), adapter, tools: new NodeToolRuntime({ stateDir: path.join(base, 'state') }), ctx: makeContext(ws) }; +} + +describe('NodeToolRuntime in the run pipeline', () => { + it('commits writes and edits and reports the diff', async () => { + const code = JSON.stringify([ + { tool: 'edit', args: { path: 'a.txt', oldString: 'alpha', newString: 'beta' } }, + { tool: 'write', args: { path: 'b/c.txt', content: 'new\n' } }, + { tool: 'read', args: { path: 'b/c.txt' } }, + ]); + const result = await runScript({ code, transaction: false, timeoutMs: 10_000 }, deps()); + expect(result.ok).toBe(true); + expect(result.changedFiles).toEqual(['a.txt', path.join('b', 'c.txt')]); + expect(result.diff).toContain('-alpha\n+beta\n'); + expect(result.diff).toContain('--- /dev/null\n+++ b/b/c.txt\n'); + expect(readFileSync(path.join(ws, 'a.txt'), 'utf8')).toBe('beta\n'); + }); + + it('rolls a transactional run back when a call is denied', async () => { + const adapter = new StaticHostAdapter({ + protectedPaths: [], + rules: [(p) => (p.tool === 'write' && p.effect.absPath.endsWith('denied.txt') ? { kind: 'deny', reason: 'no' } : undefined)], + }); + const code = JSON.stringify([ + { tool: 'write', args: { path: 'a.txt', content: 'changed\n' } }, + { tool: 'write', args: { path: 'fresh/new.txt', content: 'x' } }, + { tool: 'write', args: { path: 'denied.txt', content: 'x' } }, + ]); + const result = await runScript({ code, transaction: true, timeoutMs: 10_000 }, deps(adapter)); + expect(result.ok).toBe(false); + expect(result.rolledBack?.skipped).toEqual([]); + expect(result.rolledBack?.restored.length).toBe(2); + expect(readFileSync(path.join(ws, 'a.txt'), 'utf8')).toBe('alpha\n'); + expect(existsSync(path.join(ws, 'fresh'))).toBe(false); + // The journal is released once the run is over. + expect(readdirSync(path.join(base, 'state', 'journal'))).toEqual([]); + }); +}); diff --git a/src/tools/jail.ts b/src/tools/jail.ts new file mode 100644 index 0000000..28784b3 --- /dev/null +++ b/src/tools/jail.ts @@ -0,0 +1,224 @@ +/* + * `realpathWithSuffix`, `isInsideDir` and `windowsPathProblem` are adapted + * from Turnpack's src/security.ts (https://github.com/OnlyTerp/turnpack, + * Copyright 2026 OnlyTerp, licensed under the Apache License, Version 2.0: + * http://www.apache.org/licenses/LICENSE-2.0). + * Modified by the agent-code-mode authors: asynchronous, multiple roots, + * errors as ToolError, UNC and device prefixes refused. + */ +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; +import { DEFAULT_CASE_INSENSITIVE, findMatchingPattern } from '../core/paths.js'; + +/** + * Workspace jail: every path a tool touches is resolved to an absolute real + * path and must live under one of the allowed roots. + * + * Resolution follows Turnpack's `realpathWithSuffix`: the deepest part of the + * path that exists is found with `lstat` (not `exists`, which follows links + * and would call a dangling symlink "missing"), resolved with `realpath`, and + * the missing rest is joined back. A dangling link is followed by hand so the + * boundary check sees where a write would really land. + */ + +const MAX_LINK_HOPS = 40; +const IS_WINDOWS = process.platform === 'win32'; + +function errnoCode(err: unknown): string | undefined { + if (err !== null && typeof err === 'object' && 'code' in err && typeof err.code === 'string') return err.code; + return undefined; +} + +async function lstatOrNull(p: string): Promise { + try { + return await fs.lstat(p); + } catch (err) { + const code = errnoCode(err); + if (code === 'ENOENT' || code === 'ENOTDIR') return null; + if (code === 'ENAMETOOLONG') throw new ToolError('invalid-args', `path is too long: ${p.slice(0, 120)}…`); + throw err; + } +} + +/** Real path of `target`, which may not exist yet. */ +export async function realpathWithSuffix(target: string, hops = 0): Promise { + if (hops > MAX_LINK_HOPS) throw new ToolError('outside-workspace', `too many symbolic links while resolving ${target}`); + let cursor = path.resolve(target); + const trailing: string[] = []; + let stat = await lstatOrNull(cursor); + while (!stat) { + const parent = path.dirname(cursor); + if (parent === cursor) throw new ToolError('outside-workspace', `no existing ancestor for ${target}`); + trailing.push(path.basename(cursor)); + cursor = parent; + stat = await lstatOrNull(cursor); + } + let realBase: string; + try { + realBase = await fs.realpath(cursor); + } catch (err) { + if (!stat.isSymbolicLink()) throw err; + // Dangling link: follow it by hand so the check sees its destination. + const linkTarget = await fs.readlink(cursor); + const parentReal = await fs.realpath(path.dirname(cursor)); + realBase = await realpathWithSuffix(path.resolve(parentReal, linkTarget), hops + 1); + } + return trailing.length === 0 ? realBase : path.resolve(realBase, ...trailing.reverse()); +} + +/** True when `target` is `base` or below it. Both must be real absolute paths. */ +export function isInsideDir(base: string, target: string): boolean { + const b = IS_WINDOWS ? base.toLowerCase() : base; + const t = IS_WINDOWS ? target.toLowerCase() : target; + const rel = path.relative(b, t); + if (rel === '') return true; + return !(rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)); +} + +/** + * Windows spellings that alias another name: device and verbatim prefixes + * (`\\?\`, `\\.\`), UNC shares, NTFS alternate data streams (`name:stream`, + * `.git::$INDEX_ALLOCATION`) and segments ending in a dot or space. Plain + * string logic, tested everywhere; enforced only on Windows unless `force`. + */ +export function windowsPathProblem(target: string): string | null { + if (/^[\\/]{2}/.test(target)) return 'UNC, device and verbatim (\\\\?\\) paths are not accepted'; + const rest = target.slice(path.win32.parse(target).root.length); + for (const segment of rest.split(/[\\/]+/)) { + if (segment === '' || segment === '.' || segment === '..') continue; + if (segment.includes(':')) return `"${segment}" contains ":" (NTFS stream syntax is not accepted)`; + if (/[. ]$/.test(segment)) return `"${segment}" ends in a dot or a space, which Windows silently drops`; + } + return null; +} + +/** Expands a leading `~` or `~/` to the home directory. */ +export function expandTilde(p: string, home: string = os.homedir()): string { + if (p === '~') return home; + if (p.startsWith('~/') || (IS_WINDOWS && p.startsWith('~\\'))) return path.join(home, p.slice(2)); + return p; +} + +/** Whether any segment of `absPath` is a `.git` directory (as Windows would also open it). */ +export function isInsideGitDir(absPath: string): boolean { + return absPath + .split(/[\\/]+/) + .some((segment) => { + const lower = segment.toLowerCase(); + const plain = lower.replace(/:.*$/, '').replace(/[. ]+$/, ''); + return (DEFAULT_CASE_INSENSITIVE ? lower : segment) === '.git' || (IS_WINDOWS && plain === '.git'); + }); +} + +export interface JailOptions { + /** Absolute directory relative paths resolve against. */ + readonly cwd: string; + /** Allowed roots (absolute; resolved to real paths by `Jail.create`). */ + readonly roots: readonly string[]; + /** Protected path patterns (`~` expanded here). */ + readonly protectedPaths: readonly string[]; + /** Enforce the Windows alias checks even off Windows (tests). */ + readonly windowsChecks?: boolean; +} + +/** A resolved set of allowed roots for one call. */ +export class Jail { + /** Real path of the session cwd. */ + readonly cwd: string; + /** Real paths of the allowed roots; `roots[0]` is the session cwd. */ + readonly roots: readonly string[]; + readonly #protected: readonly string[]; + readonly #windowsChecks: boolean; + + private constructor(cwd: string, roots: readonly string[], protectedPaths: readonly string[], windowsChecks: boolean) { + this.cwd = cwd; + this.roots = roots; + this.#protected = protectedPaths; + this.#windowsChecks = windowsChecks; + } + + static async create(opts: JailOptions): Promise { + if (!path.isAbsolute(opts.cwd)) throw new ToolError('tool-error', `session cwd is not absolute: ${opts.cwd}`); + let cwd: string; + try { + cwd = await fs.realpath(opts.cwd); + } catch (err) { + throw new ToolError('tool-error', `session cwd ${opts.cwd} cannot be resolved: ${errnoCode(err) ?? String(err)}`); + } + const roots: string[] = [cwd]; + for (const root of opts.roots) { + if (!path.isAbsolute(root)) continue; + try { + const real = await fs.realpath(root); + if (!roots.includes(real)) roots.push(real); + } catch { + // A root that does not exist grants nothing. + } + } + const protectedPaths = opts.protectedPaths.map((p) => expandTilde(p)); + return new Jail(cwd, roots, protectedPaths, opts.windowsChecks ?? IS_WINDOWS); + } + + /** Protected path patterns with `~` expanded. */ + get protectedPaths(): readonly string[] { + return this.#protected; + } + + /** The root that contains `abs`, or undefined. */ + rootOf(abs: string): string | undefined { + return this.roots.find((root) => isInsideDir(root, abs)); + } + + /** + * Resolves `input` (relative to the session cwd, `~` expanded) to an + * absolute real path inside the roots, or throws `ToolError`. + */ + async resolve(input: string): Promise { + if (input.includes('\0')) throw new ToolError('invalid-args', 'path must not contain NUL characters'); + const trimmed = input.trim(); + if (trimmed === '') throw new ToolError('invalid-args', 'path must not be empty'); + if (this.#windowsChecks) { + const problem = windowsPathProblem(trimmed); + if (problem) throw new ToolError('outside-workspace', `${trimmed}: ${problem}`); + } + const expanded = expandTilde(trimmed); + const candidate = path.isAbsolute(expanded) ? path.resolve(expanded) : path.resolve(this.cwd, expanded); + let real: string; + try { + real = await realpathWithSuffix(candidate); + } catch (err) { + if (err instanceof ToolError) throw err; + const code = errnoCode(err); + if (code === 'ENAMETOOLONG') throw new ToolError('invalid-args', `path is too long: ${trimmed.slice(0, 120)}…`); + if (code === 'ELOOP') throw new ToolError('outside-workspace', `${trimmed}: too many symbolic links`); + throw new ToolError('tool-error', `cannot resolve ${trimmed}: ${code ?? String(err)}`); + } + if (this.rootOf(real) === undefined) { + throw new ToolError('outside-workspace', `${trimmed} resolves to ${real}, outside the workspace (${this.roots.join(', ')})`); + } + if (this.#windowsChecks) { + const problem = windowsPathProblem(real); + if (problem) throw new ToolError('outside-workspace', `${trimmed}: ${problem}`); + } + return real; + } + + /** Throws `protected-path` when `abs` must not be written or edited. */ + assertWritable(abs: string): void { + if (isInsideGitDir(abs)) throw new ToolError('protected-path', `${abs} is inside a .git directory`); + const hit = findMatchingPattern(abs, this.#protected); + if (hit !== undefined) throw new ToolError('protected-path', `${abs} is a protected host policy path (${hit})`); + } + + /** Path for diffs and messages: relative to the first root when inside it, else absolute. */ + displayPath(abs: string): string { + const first = this.roots[0] ?? this.cwd; + if (isInsideDir(first, abs)) { + const rel = path.relative(first, abs); + return rel === '' ? '.' : rel.split(path.sep).join('/'); + } + return abs.split(path.sep).join('/'); + } +} diff --git a/src/tools/journal.test.ts b/src/tools/journal.test.ts new file mode 100644 index 0000000..7e857c7 --- /dev/null +++ b/src/tools/journal.test.ts @@ -0,0 +1,185 @@ +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ToolError } from '../core/errors.js'; +import type { PolicySnapshot, SessionContext, ToolCall, Transaction } from '../core/types.js'; +import { makeContext } from '../testing/context.js'; +import { FileTransaction, journalRoot, recoverStaleJournals } from './journal.js'; +import { NodeToolRuntime } from './runtime.js'; + +let base: string; +let ws: string; +let outside: string; +let stateDir: string; +let ctx: SessionContext; +let rt: NodeToolRuntime; +let seq = 0; +const policy: PolicySnapshot = { host: 'generic', bashContainment: { mode: 'none' }, protectedPaths: [], payload: null }; +const signal = new AbortController().signal; + +async function write(rel: string, content: string, tx: Transaction): Promise { + const prepared = await rt.prepare({ id: `c${++seq}`, tool: 'write', args: { path: rel, content } } satisfies ToolCall, ctx, policy); + await rt.commit(prepared, signal, tx); +} + +const read = (rel: string): string => readFileSync(path.join(ws, rel), 'utf8'); + +/** A pid that belonged to a process that has exited. */ +function deadPid(): number { + const r = spawnSync(process.execPath, ['-e', '']); + return r.pid ?? 999_999; +} + +beforeEach(() => { + base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-journal-'))); + ws = path.join(base, 'ws'); + outside = path.join(base, 'outside'); + stateDir = path.join(base, 'state'); + mkdirSync(ws); + mkdirSync(outside); + ctx = makeContext(ws); + rt = new NodeToolRuntime({ stateDir }); + writeFileSync(path.join(ws, 'a.txt'), 'a0\n'); + writeFileSync(path.join(ws, 'b.txt'), 'b0\n'); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +describe('transactions', () => { + it('rolls back three writes (two edits and a create in a new directory)', async () => { + const tx = rt.beginTransaction(); + await write('a.txt', 'a1\n', tx); + await write('a.txt', 'a2\n', tx); + await write('b.txt', 'b1\n', tx); + await write('new/dir/c.txt', 'c1\n', tx); + expect(existsSync(path.join(stateDir, 'journal'))).toBe(true); + const report = await tx.rollback(); + expect(report.skipped).toEqual([]); + expect([...report.restored].sort()).toEqual([path.join(ws, 'a.txt'), path.join(ws, 'b.txt'), path.join(ws, 'new/dir/c.txt')].sort()); + expect(read('a.txt')).toBe('a0\n'); + expect(read('b.txt')).toBe('b0\n'); + expect(existsSync(path.join(ws, 'new'))).toBe(false); + expect(readdirSync(journalRoot(stateDir))).toEqual([]); + }); + + it('does not clobber a file changed externally after our write, and reports it', async () => { + const tx = rt.beginTransaction(); + await write('a.txt', 'a1\n', tx); + await write('b.txt', 'b1\n', tx); + writeFileSync(path.join(ws, 'a.txt'), 'edited by someone else\n'); + const report = await tx.rollback(); + expect(report.restored).toEqual([path.join(ws, 'b.txt')]); + expect(report.skipped).toEqual([{ path: path.join(ws, 'a.txt'), reason: 'changed-externally', detail: expect.any(String) }]); + expect(read('a.txt')).toBe('edited by someone else\n'); + expect(read('b.txt')).toBe('b0\n'); + }); + + it('keeps changes and deletes the journal on dispose, and refuses writes afterwards', async () => { + const tx = rt.beginTransaction(); + await write('a.txt', 'a1\n', tx); + await tx.dispose(); + await tx.dispose(); + expect(read('a.txt')).toBe('a1\n'); + expect(readdirSync(journalRoot(stateDir))).toEqual([]); + await expect(write('b.txt', 'b1\n', tx)).rejects.toBeInstanceOf(ToolError); + expect(read('b.txt')).toBe('b0\n'); + }); + + it('refuses a write that would push the journal past its size cap', async () => { + const big = Buffer.alloc(33 * 1024 * 1024, 0x61); + writeFileSync(path.join(ws, 'big1.txt'), big); + writeFileSync(path.join(ws, 'big2.txt'), big); + const tx = rt.beginTransaction(); + await write('big1.txt', 'small\n', tx); + const err = await write('big2.txt', 'small\n', tx).then( + () => undefined, + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(ToolError); + expect(String(err)).toMatch(/journal is full/); + expect(readFileSync(path.join(ws, 'big2.txt')).length).toBe(big.length); + const report = await tx.rollback(); + expect(report.restored).toEqual([path.join(ws, 'big1.txt')]); + expect(readFileSync(path.join(ws, 'big1.txt')).equals(big)).toBe(true); + }); + + it('refuses a transaction it did not start', async () => { + const foreign: Transaction = { rollback: async () => ({ restored: [], skipped: [] }), dispose: async () => undefined }; + await expect(write('a.txt', 'a1\n', foreign)).rejects.toThrow(/not started by this tool runtime/); + expect(read('a.txt')).toBe('a0\n'); + }); +}); + +describe('crash recovery', () => { + /** Makes the journal of `tx` look like it was left by a process that died. */ + function abandon(tx: FileTransaction): string { + const dir = tx.dir; + const manifestPath = path.join(dir, 'manifest.json'); + const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { pid: number }; + const pid = deadPid(); + manifest.pid = pid; + writeFileSync(manifestPath, JSON.stringify(manifest)); + const [stamp, , hex] = path.basename(dir).split('-'); + const moved = path.join(path.dirname(dir), `${stamp}-${pid}-${hex}`); + renameSync(dir, moved); + return moved; + } + + it('restores a journal whose process is gone, and leaves a live one alone', async () => { + const crashed = rt.beginTransaction(); + if (!(crashed instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'a1\n', crashed); + await write('new.txt', 'n1\n', crashed); + await write('b.txt', 'b1\n', crashed); + writeFileSync(path.join(ws, 'b.txt'), 'changed after the crash\n'); + const moved = abandon(crashed); + + const live = rt.beginTransaction(); + writeFileSync(path.join(ws, 'live.txt'), 'l0\n'); + await write('live.txt', 'l1\n', live); + + const recovered = await recoverStaleJournals(stateDir, [ws]); + expect(recovered).toHaveLength(1); + const report = recovered[0]?.report; + expect([...(report?.restored ?? [])].sort()).toEqual([path.join(ws, 'a.txt'), path.join(ws, 'new.txt')]); + expect(report?.skipped).toEqual([{ path: path.join(ws, 'b.txt'), reason: 'changed-externally', detail: expect.any(String) }]); + expect(read('a.txt')).toBe('a0\n'); + expect(existsSync(path.join(ws, 'new.txt'))).toBe(false); + expect(read('b.txt')).toBe('changed after the crash\n'); + expect(read('live.txt')).toBe('l1\n'); + expect(existsSync(moved)).toBe(false); + await live.dispose(); + }); + + it('ignores journals of other workspaces and never restores outside the roots', async () => { + const tx = rt.beginTransaction(); + if (!(tx instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'a1\n', tx); + const moved = abandon(tx); + // Another workspace: nothing happens. + expect(await recoverStaleJournals(stateDir, [outside])).toEqual([]); + expect(read('a.txt')).toBe('a1\n'); + + // A tampered record pointing outside the roots is not followed. + writeFileSync(path.join(outside, 'victim.txt'), 'victim\n'); + const manifestPath = path.join(moved, 'manifest.json'); + const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { entries: { path: string }[] }; + const first = manifest.entries[0]; + if (first) first.path = path.join(outside, 'victim.txt'); + writeFileSync(manifestPath, JSON.stringify(manifest)); + const recovered = await recoverStaleJournals(stateDir, [ws]); + expect(recovered[0]?.report.restored).toEqual([]); + expect(recovered[0]?.report.skipped[0]?.reason).toBe('error'); + expect(readFileSync(path.join(outside, 'victim.txt'), 'utf8')).toBe('victim\n'); + }); + + it('skips a malformed record', async () => { + mkdirSync(path.join(journalRoot(stateDir), 'zz-1-abcd'), { recursive: true }); + writeFileSync(path.join(journalRoot(stateDir), 'zz-1-abcd', 'manifest.json'), '{"version":1,"entries":"nope"}'); + expect(await recoverStaleJournals(stateDir, [ws])).toEqual([]); + }); +}); diff --git a/src/tools/journal.ts b/src/tools/journal.ts new file mode 100644 index 0000000..0798d0d --- /dev/null +++ b/src/tools/journal.ts @@ -0,0 +1,386 @@ +/* + * The journal design (original bytes written durably before the first change, + * restore only files that still hold what this process wrote, recovery of a + * record whose process is gone) follows Turnpack's src/journal.ts + * (https://github.com/OnlyTerp/turnpack, Copyright 2026 OnlyTerp, Apache-2.0). + * Modified by the agent-code-mode authors: the record grows one file at a time + * across a run instead of being written once per call, and it is restored + * through the workspace jail checks of this project. + */ +import { randomBytes } from 'node:crypto'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { z } from 'zod'; +import { ToolError, errorMessage } from '../core/errors.js'; +import type { RollbackReport, Transaction } from '../core/types.js'; +import { assertDirUnchanged, atomicWrite, errnoCode, readRegularFile, removeRegularFile, sha256, syncDir, writeDurable } from './fs-ops.js'; +import { isInsideDir, isInsideGitDir } from './jail.js'; + +/** Above this many bytes of originals a transaction refuses further writes. */ +export const MAX_JOURNAL_BYTES = 64 * 1024 * 1024; +/** Slack when comparing a start time with the boot time. */ +const BOOT_SLACK_MS = 10_000; +const MANIFEST = 'manifest.json'; +const RECOVERING = '.recovering-'; + +const EntrySchema = z.object({ + path: z.string().min(1), + existed: z.boolean(), + /** SHA-256 of the original bytes ('' when absent). */ + original: z.string(), + mode: z.number().int().nullable(), + /** Blob file name holding the original bytes (null when absent). */ + blob: z.string().regex(/^[0-9]+\.bin$/).nullable(), + /** Hashes this transaction wrote (or was about to write) to the file, oldest first. */ + written: z.array(z.string()), +}); + +const ManifestSchema = z.object({ + version: z.literal(1), + pid: z.number().int(), + host: z.string(), + startedAt: z.number(), + roots: z.array(z.string()), + /** Directories the transaction created, outermost first. */ + dirs: z.array(z.string()), + entries: z.array(EntrySchema), +}); + +type Manifest = z.infer; +type Entry = z.infer; + +/** Journal directory under the server state dir. */ +export function journalRoot(stateDir: string): string { + return path.join(stateDir, 'journal'); +} + +/** Ids of transactions this process still has open; a recovery pass leaves them alone. */ +const openTransactions = new Set(); + +interface LiveEntry { + readonly entry: Entry; + /** Original bytes, kept in memory for the in-process rollback. */ + readonly bytes: Buffer | null; + /** Hash of what this transaction last wrote, or null after a failed write. */ + last: string | null; +} + +/** + * A per-run journal. The first write to a file snapshots its original bytes + * (or "absent") in memory and durably under `/journal//` + * before the file is touched. + */ +export class FileTransaction implements Transaction { + readonly id: string; + readonly dir: string; + readonly #roots: string[] = []; + readonly #startedAt = Date.now(); + readonly #entries = new Map(); + readonly #dirs: string[] = []; + #bytes = 0; + #created = false; + #closed = false; + #queue: Promise = Promise.resolve(); + + constructor(stateDir: string) { + this.id = `${this.#startedAt.toString(36)}-${process.pid}-${randomBytes(4).toString('hex')}`; + this.dir = path.join(journalRoot(stateDir), this.id); + openTransactions.add(this.id); + } + + /** True once rolled back or disposed. */ + get closed(): boolean { + return this.#closed; + } + + #serial(fn: () => Promise): Promise { + const next = this.#queue.then(fn, fn); + this.#queue = next.catch(() => undefined); + return next; + } + + #manifest(): Manifest { + return { + version: 1, + pid: process.pid, + host: os.hostname(), + startedAt: this.#startedAt, + roots: [...this.#roots], + dirs: [...this.#dirs], + entries: [...this.#entries.values()].map((live) => live.entry), + }; + } + + async #persist(): Promise { + if (!this.#created) { + await fs.mkdir(path.dirname(this.dir), { recursive: true, mode: 0o700 }); + await fs.mkdir(this.dir, { mode: 0o700 }); + this.#created = true; + } + const next = path.join(this.dir, `${MANIFEST}.next`); + await writeDurable(next, JSON.stringify(this.#manifest())); + await fs.rename(next, path.join(this.dir, MANIFEST)); + await syncDir(this.dir); + } + + /** + * Called by a commit after the stale check and before the write. Records + * the original on the first write to `absPath` and the hash about to be + * written. Throws when the journal is full or closed. + */ + record( + absPath: string, + root: string, + before: { readonly bytes: Buffer; readonly mode: number } | null, + nextHash: string, + createdDirs: readonly string[], + ): Promise { + return this.#serial(async () => { + if (this.#closed) throw new ToolError('tool-error', 'the transaction is already finished'); + if (!this.#roots.includes(root)) this.#roots.push(root); + const existing = this.#entries.get(absPath); + if (existing) { + existing.entry.written.push(nextHash); + await this.#persist(); + return; + } + const size = before?.bytes.length ?? 0; + if (this.#bytes + size > MAX_JOURNAL_BYTES) { + throw new ToolError( + 'tool-error', + `transaction journal is full: snapshotting ${absPath} (${size} bytes) would exceed ${MAX_JOURNAL_BYTES} bytes, so the write was refused to keep rollback possible`, + ); + } + let blob: string | null = null; + if (before) { + if (!this.#created) await this.#persist(); + blob = `${this.#entries.size}.bin`; + await writeDurable(path.join(this.dir, blob), before.bytes); + } + this.#bytes += size; + for (const d of createdDirs) if (!this.#dirs.includes(d)) this.#dirs.push(d); + this.#entries.set(absPath, { + entry: { + path: absPath, + existed: before !== null, + original: before ? sha256(before.bytes) : '', + mode: before?.mode ?? null, + blob, + written: [nextHash], + }, + bytes: before?.bytes ?? null, + last: null, + }); + await this.#persist(); + }); + } + + /** Called after a successful write. */ + written(absPath: string, hash: string): void { + const live = this.#entries.get(absPath); + if (live) live.last = hash; + } + + rollback(): Promise { + return this.#serial(async () => { + if (this.#closed) return { restored: [], skipped: [] }; + this.#closed = true; + openTransactions.delete(this.id); + const restored: string[] = []; + const skipped: { path: string; reason: 'changed-externally' | 'error'; detail?: string }[] = []; + for (const live of [...this.#entries.values()].reverse()) { + const { entry } = live; + try { + const current = await readRegularFile(entry.path).catch((err: unknown) => { + throw new ToolError('stale', `cannot read: ${errorMessage(err)}`); + }); + const currentHash = current ? sha256(current.bytes) : null; + const originalHash = entry.existed ? entry.original : null; + if (currentHash === originalHash) continue; + if (live.last === null || currentHash !== live.last) { + skipped.push({ path: entry.path, reason: 'changed-externally', detail: 'the file no longer holds what this run wrote' }); + continue; + } + await restoreEntry(entry, live.bytes, currentHash); + restored.push(entry.path); + } catch (err) { + skipped.push({ path: entry.path, reason: 'error', detail: errorMessage(err) }); + } + } + await removeCreatedDirs(this.#dirs); + await this.#removeRecord(); + return { restored, skipped }; + }); + } + + dispose(): Promise { + return this.#serial(async () => { + this.#closed = true; + openTransactions.delete(this.id); + await this.#removeRecord(); + }); + } + + async #removeRecord(): Promise { + if (!this.#created) return; + await fs.rm(this.dir, { recursive: true, force: true }); + this.#created = false; + } +} + +async function restoreEntry(entry: Entry, bytes: Buffer | null, currentHash: string | null): Promise { + if (isInsideGitDir(entry.path)) throw new ToolError('protected-path', 'inside a .git directory'); + if (!entry.existed) { + await assertDirUnchanged(path.dirname(entry.path)); + await removeRegularFile(entry.path); + return; + } + if (bytes === null || sha256(bytes) !== entry.original) throw new ToolError('tool-error', 'the saved original is damaged'); + const expect = currentHash === null ? ({ kind: 'absent' } as const) : ({ kind: 'hash', sha256: currentHash } as const); + await atomicWrite(entry.path, bytes, expect); + if (entry.mode !== null && process.platform !== 'win32') await fs.chmod(entry.path, entry.mode).catch(() => undefined); +} + +async function removeCreatedDirs(dirs: readonly string[]): Promise { + for (const d of [...dirs].sort((a, b) => b.length - a.length)) { + try { + await fs.rmdir(d); + } catch { + // Not empty, or already gone. + } + } +} + +// --------------------------------------------------------------------------- +// Crash recovery. +// --------------------------------------------------------------------------- + +function isAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (err) { + return errnoCode(err) === 'EPERM'; + } +} + +/** Whether the process that wrote a record can no longer be running it. */ +function ownerGone(manifest: Manifest, openHere: ReadonlySet, id: string): boolean { + if (manifest.pid === process.pid) return !openHere.has(id); + if (!isAlive(manifest.pid)) return true; + // A pid alone does not say: the system hands a dead process's id to a new one. + const bootedAt = Date.now() - os.uptime() * 1000; + return bootedAt > manifest.startedAt + BOOT_SLACK_MS; +} + +/** What a recovery pass did for one stale journal. */ +export interface RecoveredJournal { + readonly id: string; + readonly report: RollbackReport; +} + +async function realOrSelf(p: string): Promise { + try { + return await fs.realpath(p); + } catch { + return p; + } +} + +async function readOriginal(dir: string, entry: Entry): Promise { + if (entry.blob === null) return null; + return fs.readFile(path.join(dir, entry.blob)); +} + +async function undoRecord(manifest: Manifest, dir: string, roots: readonly string[]): Promise { + const restored: string[] = []; + const skipped: { path: string; reason: 'changed-externally' | 'error'; detail?: string }[] = []; + for (const entry of [...manifest.entries].reverse()) { + try { + // The record is data on disk: each path is checked like a tool argument. + if (!path.isAbsolute(entry.path) || !roots.some((root) => isInsideDir(root, entry.path))) { + skipped.push({ path: entry.path, reason: 'error', detail: 'outside the workspace roots; not touched' }); + continue; + } + if (!manifest.roots.some((root) => isInsideDir(root, entry.path))) { + skipped.push({ path: entry.path, reason: 'error', detail: 'outside the roots the journal was written for; not touched' }); + continue; + } + await assertDirUnchanged(path.dirname(entry.path)).catch((err: unknown) => { + // A parent that no longer exists is fine for a created file that is gone too. + if (entry.existed) throw err; + }); + const current = await readRegularFile(entry.path); + const currentHash = current ? sha256(current.bytes) : null; + const originalHash = entry.existed ? entry.original : null; + if (currentHash === originalHash) continue; + if (currentHash === null || !entry.written.includes(currentHash)) { + skipped.push({ path: entry.path, reason: 'changed-externally', detail: 'the file no longer holds what the crashed run wrote' }); + continue; + } + const bytes = await readOriginal(dir, entry); + await restoreEntry(entry, bytes, currentHash); + restored.push(entry.path); + } catch (err) { + skipped.push({ path: entry.path, reason: 'error', detail: errorMessage(err) }); + } + } + const dirs = manifest.dirs.filter((d) => path.isAbsolute(d) && roots.some((root) => isInsideDir(root, d) && root !== d)); + await removeCreatedDirs(dirs); + return { restored, skipped }; +} + +/** + * Restores every journal left by a server process that is gone and that + * touched one of `roots` (newest first, so two cut-off runs that changed the + * same file unwind in order). Files are restored only when they still hold + * what that run wrote; anything else is reported in `skipped`. Never throws. + */ +export async function recoverStaleJournals(stateDir: string, roots: readonly string[]): Promise { + const base = journalRoot(stateDir); + let names: string[]; + try { + names = await fs.readdir(base); + } catch { + return []; + } + const realRoots = await Promise.all(roots.filter((r) => path.isAbsolute(r)).map(realOrSelf)); + const records = names + .map((name) => ({ name, id: name.includes(RECOVERING) ? name.slice(0, name.indexOf(RECOVERING)) : name })) + .filter((r) => /^[0-9a-z]+-\d+-[0-9a-f]+$/.test(r.id)) + .sort((a, b) => parseInt(b.id.split('-')[0] ?? '0', 36) - parseInt(a.id.split('-')[0] ?? '0', 36)); + const out: RecoveredJournal[] = []; + for (const record of records) { + const dir = path.join(base, record.name); + try { + const raw: unknown = JSON.parse(await fs.readFile(path.join(dir, MANIFEST), 'utf8')); + const parsed = ManifestSchema.safeParse(raw); + if (!parsed.success) continue; + const manifest = parsed.data; + if (manifest.host !== os.hostname()) continue; + if (!manifest.roots.some((r) => realRoots.some((root) => isInsideDir(root, r) || isInsideDir(r, root)))) continue; + if (record.name.includes(RECOVERING)) { + const claimer = Number(record.name.slice(record.name.indexOf(RECOVERING) + RECOVERING.length)); + if (claimer !== process.pid && isAlive(claimer)) continue; + } else if (!ownerGone(manifest, openTransactions, record.id)) { + continue; + } + const claimed = path.join(base, `${record.id}${RECOVERING}${process.pid}`); + if (claimed !== dir) { + try { + await fs.rename(dir, claimed); + } catch { + continue; + } + } + const report = await undoRecord(manifest, claimed, realRoots); + await fs.rm(claimed, { recursive: true, force: true }); + out.push({ id: record.id, report }); + } catch { + // One bad record must not stop the others. + } + } + return out; +} diff --git a/src/tools/runtime.test.ts b/src/tools/runtime.test.ts new file mode 100644 index 0000000..15912e7 --- /dev/null +++ b/src/tools/runtime.test.ts @@ -0,0 +1,370 @@ +import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ToolError } from '../core/errors.js'; +import type { PolicySnapshot, PreparedCall, SessionContext, ToolArgsMap, ToolCall, ToolName, ToolResult } from '../core/types.js'; +import { makeContext } from '../testing/context.js'; +import { windowsPathProblem } from './jail.js'; +import { NodeToolRuntime } from './runtime.js'; + +const IS_WINDOWS = process.platform === 'win32'; + +let base: string; +let ws: string; +let outside: string; +let ctx: SessionContext; +let policy: PolicySnapshot; +let rt: NodeToolRuntime; +let outsideBefore: Record; +let seq = 0; + +/** Every entry under `dir` with its type and content (links are not followed). */ +function snapshot(dir: string): Record { + const out: Record = {}; + const walk = (d: string): void => { + for (const name of readdirSync(d)) { + const p = path.join(d, name); + const st = lstatSync(p); + if (st.isSymbolicLink()) out[p] = `link:${readlinkSync(p)}`; + else if (st.isDirectory()) { + out[p] = 'dir'; + walk(p); + } else out[p] = `file:${readFileSync(p, 'utf8')}`; + } + }; + walk(dir); + return out; +} + +function call(tool: K, args: ToolArgsMap[K]): ToolCall { + return { id: `c${++seq}`, tool, args } as ToolCall; +} + +async function prep(tool: K, args: ToolArgsMap[K]): Promise { + return rt.prepare(call(tool, args), ctx, policy); +} + +async function run(tool: K, args: ToolArgsMap[K]): Promise { + return rt.commit(await prep(tool, args), new AbortController().signal); +} + +async function code(p: Promise): Promise { + try { + await p; + } catch (err) { + if (err instanceof ToolError) return err.code; + throw err; + } + return 'resolved'; +} + +function link(target: string, at: string): void { + symlinkSync(target, at, statSync(target, { throwIfNoEntry: false })?.isDirectory() ? 'dir' : 'file'); +} + +beforeEach(() => { + base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-tools-'))); + ws = path.join(base, 'ws'); + outside = path.join(base, 'outside'); + mkdirSync(ws); + mkdirSync(outside); + writeFileSync(path.join(outside, 'secret.txt'), 'secret value\n'); + mkdirSync(path.join(outside, 'deep')); + writeFileSync(path.join(outside, 'deep', 'more.txt'), 'secret value too\n'); + ctx = makeContext(ws); + policy = { + host: 'generic', + bashContainment: { mode: 'none' }, + protectedPaths: [`${ws}/.claude/settings*.json`, `${ws}/.claude/hooks/**`, `${ws}/.codex/**`, `${ws}/.mcp.json`], + payload: null, + }; + rt = new NodeToolRuntime({ stateDir: path.join(base, 'state') }); + outsideBefore = snapshot(outside); +}); + +afterEach(() => { + // Every attack test also asserts that nothing outside the jail changed. + expect(snapshot(outside)).toEqual(outsideBefore); + rmSync(base, { recursive: true, force: true }); +}); + +describe('path traversal', () => { + it('refuses ../, absolute paths outside and ~', async () => { + for (const p of ['../outside/secret.txt', `${outside}/secret.txt`, 'a/../../outside/new.txt', '~/acm-must-not-exist.txt', '~']) { + expect(await code(prep('read', { path: p }))).toBe('outside-workspace'); + expect(await code(prep('write', { path: p, content: 'x' }))).toBe('outside-workspace'); + expect(await code(prep('edit', { path: p, oldString: 'secret', newString: 'x' }))).toBe('outside-workspace'); + } + expect(await code(prep('grep', { pattern: 'secret', path: '..' }))).toBe('outside-workspace'); + expect(await code(prep('glob', { pattern: '**/*', path: outside }))).toBe('outside-workspace'); + expect(await code(prep('bash', { command: 'pwd', cwd: '../outside' }))).toBe('outside-workspace'); + expect(existsSync(path.join(os.homedir(), 'acm-must-not-exist.txt'))).toBe(false); + }); + + it('refuses NUL bytes and very long paths', async () => { + expect(await code(prep('write', { path: 'a\0b', content: 'x' }))).toBe('invalid-args'); + const long = `${'a'.repeat(250)}/`.repeat(40) + 'f.txt'; + const result = await code(run('write', { path: long, content: 'x' })); + expect(['invalid-args', 'tool-error']).toContain(result); + expect(readdirSync(ws)).toEqual([]); + }); + + it('keeps unicode lookalikes of .. inside the workspace', async () => { + for (const p of ['\u2025/outside/x.txt', '\uff0e\uff0e/outside/x.txt', '.\u2024/outside/x.txt']) { + const prepared = await prep('write', { path: p, content: 'x' }); + expect(prepared.tool === 'write' && prepared.effect.absPath.startsWith(`${ws}${path.sep}`)).toBe(true); + } + }); + + it('flags Windows alias spellings', () => { + expect(windowsPathProblem('\\\\?\\C:\\x')).not.toBeNull(); + expect(windowsPathProblem('\\\\server\\share\\x')).not.toBeNull(); + expect(windowsPathProblem('C:\\ws\\.env::$DATA')).not.toBeNull(); + expect(windowsPathProblem('C:\\ws\\file.txt:stream')).not.toBeNull(); + expect(windowsPathProblem('C:\\ws\\.git.\\config')).not.toBeNull(); + expect(windowsPathProblem('C:\\ws\\src\\a.ts')).toBeNull(); + }); +}); + +describe.skipIf(IS_WINDOWS)('symlinks', () => { + beforeEach(() => { + link(outside, path.join(ws, 'link-out')); + link(path.join(outside, 'secret.txt'), path.join(ws, 'file-link')); + symlinkSync(path.join(outside, 'not-yet.txt'), path.join(ws, 'dangling')); + writeFileSync(path.join(ws, 'inside.txt'), 'inside secret value\n'); + }); + + it('does not let read, write or edit follow a link out', async () => { + for (const p of ['file-link', 'link-out/secret.txt', 'link-out/deep/more.txt', 'dangling', 'link-out/new.txt']) { + expect(await code(prep('read', { path: p }))).toBe('outside-workspace'); + expect(await code(prep('write', { path: p, content: 'pwned' }))).toBe('outside-workspace'); + expect(await code(prep('edit', { path: p, oldString: 'secret', newString: 'pwned' }))).toBe('outside-workspace'); + } + expect(await code(prep('grep', { pattern: 'x', path: 'link-out' }))).toBe('outside-workspace'); + expect(await code(prep('glob', { pattern: '*', path: 'link-out' }))).toBe('outside-workspace'); + expect(existsSync(path.join(outside, 'not-yet.txt'))).toBe(false); + }); + + it('does not let grep or glob walk through links', async () => { + const grep = await run('grep', { pattern: 'secret' }); + expect('matches' in grep ? grep.matches.map((m) => m.file) : []).toEqual([path.join(ws, 'inside.txt')]); + const glob = await run('glob', { pattern: '**/*' }); + expect('files' in glob ? glob.files : []).toEqual([path.join(ws, 'inside.txt')]); + }); + + it('refuses a write when the file was swapped for a link after prepare', async () => { + writeFileSync(path.join(ws, 'f.txt'), 'one\n'); + const write = await prep('write', { path: 'f.txt', content: 'pwned\n' }); + const edit = await prep('edit', { path: 'f.txt', oldString: 'one', newString: 'pwned' }); + const read = await prep('read', { path: 'f.txt' }); + rmSync(path.join(ws, 'f.txt')); + link(path.join(outside, 'secret.txt'), path.join(ws, 'f.txt')); + const signal = new AbortController().signal; + expect(await code(rt.commit(write, signal))).toBe('stale'); + expect(await code(rt.commit(edit, signal))).toBe('stale'); + expect(await code(rt.commit(read, signal))).toBe('stale'); + }); + + it('refuses a create when a link appears at the name after prepare', async () => { + const write = await prep('write', { path: 'new.txt', content: 'pwned\n' }); + symlinkSync(path.join(outside, 'created-by-link.txt'), path.join(ws, 'new.txt')); + expect(await code(rt.commit(write, new AbortController().signal))).toBe('stale'); + expect(existsSync(path.join(outside, 'created-by-link.txt'))).toBe(false); + }); + + it('refuses a write when a parent directory was replaced by a link after prepare', async () => { + mkdirSync(path.join(ws, 'dir')); + writeFileSync(path.join(ws, 'dir', 'secret.txt'), 'secret value\n'); + const write = await prep('write', { path: 'dir/secret.txt', content: 'pwned\n' }); + const create = await prep('write', { path: 'dir/fresh.txt', content: 'pwned\n' }); + const nested = await prep('write', { path: 'dir/a/b/c.txt', content: 'pwned\n' }); + renameSync(path.join(ws, 'dir'), path.join(ws, 'dir-moved')); + link(outside, path.join(ws, 'dir')); + const signal = new AbortController().signal; + expect(await code(rt.commit(write, signal))).toBe('stale'); + expect(await code(rt.commit(create, signal))).toBe('stale'); + expect(await code(rt.commit(nested, signal))).toBe('stale'); + }); + + it('refuses writing through a link that bash created mid-run', async () => { + const pending = await prep('write', { path: 'via-later.txt', content: 'pwned\n' }); + const bash = await run('bash', { command: `ln -s ${JSON.stringify(path.join(outside, 'secret.txt'))} via.txt && ln -s ${JSON.stringify(path.join(outside, 'later.txt'))} via-later.txt` }); + expect('exitCode' in bash && bash.exitCode).toBe(0); + expect(await code(prep('write', { path: 'via.txt', content: 'pwned\n' }))).toBe('outside-workspace'); + expect(await code(rt.commit(pending, new AbortController().signal))).toBe('stale'); + expect(existsSync(path.join(outside, 'later.txt'))).toBe(false); + }); + + it('follows links that stay inside the workspace', async () => { + link(path.join(ws, 'inside.txt'), path.join(ws, 'alias.txt')); + const read = await run('read', { path: 'alias.txt' }); + expect('content' in read && read.path).toBe(path.join(ws, 'inside.txt')); + }); +}); + +describe('protected paths', () => { + it('refuses writes and edits to host config and .git, but allows reads', async () => { + mkdirSync(path.join(ws, '.git')); + writeFileSync(path.join(ws, '.git', 'config'), '[core]\n'); + mkdirSync(path.join(ws, '.claude')); + writeFileSync(path.join(ws, '.claude', 'settings.json'), '{}\n'); + for (const p of ['.claude/settings.json', '.claude/settings.local.json', '.codex/config.toml', '.git/config', '.git/hooks/pre-commit', 'sub/.git/config', '.mcp.json']) { + expect(await code(prep('write', { path: p, content: 'x' }))).toBe('protected-path'); + } + expect(await code(prep('edit', { path: '.git/config', oldString: '[core]', newString: '[x]' }))).toBe('protected-path'); + expect(await code(prep('edit', { path: '.claude/settings.json', oldString: '{}', newString: '{"x":1}' }))).toBe('protected-path'); + const read = await run('read', { path: '.git/config' }); + expect('content' in read && read.content).toBe('[core]'); + expect(readFileSync(path.join(ws, '.git', 'config'), 'utf8')).toBe('[core]\n'); + }); + + it('expands ~ in protected patterns', async () => { + const home = path.join(ws, 'home'); + mkdirSync(home); + const homeCtx = makeContext(ws); + const p = { ...policy, protectedPaths: [`~/.claude/**`] }; + const prevHome = process.env['HOME']; + process.env['HOME'] = home; + try { + if (os.homedir() !== home) return; // os.homedir ignores HOME on this platform + expect(await code(rt.prepare(call('write', { path: 'home/.claude/x.json', content: '1' }), homeCtx, p))).toBe('protected-path'); + } finally { + process.env['HOME'] = prevHome; + } + }); +}); + +describe('write and edit', () => { + it('refuses an ambiguous edit without writing', async () => { + writeFileSync(path.join(ws, 'a.ts'), 'x = 1\ny = 2\nx = 1\n'); + expect(await code(prep('edit', { path: 'a.ts', oldString: 'x = 1', newString: 'x = 3' }))).toBe('invalid-args'); + expect(await code(prep('edit', { path: 'a.ts', oldString: 'nothing like it', newString: 'z' }))).toBe('not-found'); + expect(readFileSync(path.join(ws, 'a.ts'), 'utf8')).toBe('x = 1\ny = 2\nx = 1\n'); + }); + + it('refuses a commit when the file changed after prepare', async () => { + writeFileSync(path.join(ws, 'a.ts'), 'x = 1\n'); + const edit = await prep('edit', { path: 'a.ts', oldString: 'x = 1', newString: 'x = 2' }); + const write = await prep('write', { path: 'a.ts', content: 'overwritten\n' }); + writeFileSync(path.join(ws, 'a.ts'), 'x = 1 // changed\n'); + expect(await code(rt.commit(edit, new AbortController().signal))).toBe('stale'); + expect(await code(rt.commit(write, new AbortController().signal))).toBe('stale'); + expect(readFileSync(path.join(ws, 'a.ts'), 'utf8')).toBe('x = 1 // changed\n'); + + const create = await prep('write', { path: 'b.ts', content: 'mine\n' }); + writeFileSync(path.join(ws, 'b.ts'), 'theirs\n'); + expect(await code(rt.commit(create, new AbortController().signal))).toBe('stale'); + expect(readFileSync(path.join(ws, 'b.ts'), 'utf8')).toBe('theirs\n'); + }); + + it('applies a tolerant edit and carries the exact matched text and diff', async () => { + writeFileSync(path.join(ws, 'f.js'), 'function f() {\n if (x) {\n return 1;\n }\n}\n'); + const prepared = await prep('edit', { path: 'f.js', oldString: 'if (x) {\n return 1;\n}', newString: 'if (x) {\n return 2;\n}' }); + if (prepared.tool !== 'edit') throw new Error('unreachable'); + expect(prepared.effect.matchStrategy).toBe('indentation-flexible'); + expect(prepared.effect.matchedOldString).toBe(' if (x) {\n return 1;\n }'); + expect(prepared.effect.diff).toContain('--- a/f.js\n+++ b/f.js\n'); + expect(prepared.effect.diff).toContain('- return 1;\n+ return 2;\n'); + const result = await rt.commit(prepared, new AbortController().signal); + expect('replacements' in result && result.replacements).toBe(1); + expect(readFileSync(path.join(ws, 'f.js'), 'utf8')).toBe(prepared.effect.afterContent); + }); + + it.skipIf(IS_WINDOWS)('writes atomically, keeps the mode and creates parents', async () => { + writeFileSync(path.join(ws, 'run.sh'), '#!/bin/sh\necho 1\n'); + chmodSync(path.join(ws, 'run.sh'), 0o751); + const result = await run('write', { path: 'run.sh', content: '#!/bin/sh\necho 2\n' }); + expect('created' in result && result.created).toBe(false); + expect(statSync(path.join(ws, 'run.sh')).mode & 0o777).toBe(0o751); + const created = await run('write', { path: 'new/deep/file.txt', content: 'hi' }); + expect('created' in created && created.created).toBe(true); + expect(readFileSync(path.join(ws, 'new/deep/file.txt'), 'utf8')).toBe('hi'); + expect(readdirSync(path.join(ws, 'new/deep'))).toEqual(['file.txt']); + }); + + it('refuses edits of binary files and directories', async () => { + writeFileSync(path.join(ws, 'b.bin'), Buffer.from([0, 1, 2, 3])); + mkdirSync(path.join(ws, 'd')); + expect(await code(prep('edit', { path: 'b.bin', oldString: 'a', newString: 'b' }))).toBe('tool-error'); + expect(await code(prep('write', { path: 'd', content: 'x' }))).toBe('invalid-args'); + expect(await code(prep('edit', { path: 'missing.txt', oldString: 'a', newString: 'b' }))).toBe('not-found'); + }); +}); + +describe('read', () => { + it('returns a window of lines and the total', async () => { + writeFileSync(path.join(ws, 'r.txt'), 'l1\nl2\nl3\nl4\n'); + const all = await run('read', { path: 'r.txt' }); + expect(all).toEqual({ path: path.join(ws, 'r.txt'), content: 'l1\nl2\nl3\nl4', startLine: 1, totalLines: 4, truncated: false }); + const part = await run('read', { path: 'r.txt', offset: 2, limit: 2 }); + expect(part).toEqual({ path: path.join(ws, 'r.txt'), content: 'l2\nl3', startLine: 2, totalLines: 4, truncated: true }); + }); + + it('caps the bytes returned and refuses binary files', async () => { + writeFileSync(path.join(ws, 'big.txt'), `${'x'.repeat(1000)}\n`.repeat(1000)); + const big = await run('read', { path: 'big.txt' }); + expect('content' in big && big.truncated).toBe(true); + expect('content' in big && Buffer.byteLength(big.content)).toBeLessThanOrEqual(256 * 1024); + writeFileSync(path.join(ws, 'b.bin'), Buffer.from([0x89, 0x50, 0, 0, 1])); + expect(await code(run('read', { path: 'b.bin' }))).toBe('tool-error'); + expect(await code(prep('read', { path: 'missing' }))).toBe('not-found'); + }); +}); + +describe('grep and glob', () => { + beforeEach(() => { + mkdirSync(path.join(ws, 'src')); + mkdirSync(path.join(ws, 'node_modules', 'dep'), { recursive: true }); + mkdirSync(path.join(ws, 'build')); + mkdirSync(path.join(ws, '.git')); + writeFileSync(path.join(ws, '.gitignore'), 'build/\n*.log\n!keep.log\n'); + writeFileSync(path.join(ws, 'src', 'a.ts'), 'const needle = 1;\nother\n'); + writeFileSync(path.join(ws, 'src', 'b.js'), 'needle again\n'); + writeFileSync(path.join(ws, 'src', 'nested.ts'), 'NEEDLE upper\n'); + writeFileSync(path.join(ws, 'node_modules', 'dep', 'i.js'), 'needle in deps\n'); + writeFileSync(path.join(ws, 'build', 'out.js'), 'needle built\n'); + writeFileSync(path.join(ws, 'debug.log'), 'needle log\n'); + writeFileSync(path.join(ws, 'keep.log'), 'needle kept\n'); + writeFileSync(path.join(ws, '.git', 'HEAD'), 'needle git\n'); + }); + + it('grep skips .git, node_modules and gitignored files', async () => { + const r = await run('grep', { pattern: 'needle' }); + if (!('matches' in r)) throw new Error('unreachable'); + expect(r.matches.map((m) => path.relative(ws, m.file)).sort()).toEqual(['keep.log', path.join('src', 'a.ts'), path.join('src', 'b.js')]); + const ci = await run('grep', { pattern: 'needle', ignoreCase: true, glob: '*.ts' }); + if (!('matches' in ci)) throw new Error('unreachable'); + expect(ci.matches.map((m) => [path.basename(m.file), m.line, m.text])).toEqual([ + ['a.ts', 1, 'const needle = 1;'], + ['nested.ts', 1, 'NEEDLE upper'], + ]); + const capped = await run('grep', { pattern: 'needle', maxResults: 1 }); + expect('matches' in capped && [capped.matches.length, capped.truncated]).toEqual([1, true]); + expect(await code(prep('grep', { pattern: '(' }))).toBe('invalid-args'); + }); + + it('glob lists sorted files with the same ignores', async () => { + const r = await run('glob', { pattern: '**/*.{ts,js}' }); + expect('files' in r && r.files).toEqual([path.join(ws, 'src', 'a.ts'), path.join(ws, 'src', 'b.js'), path.join(ws, 'src', 'nested.ts')]); + const capped = await run('glob', { pattern: '**/*', maxResults: 2 }); + expect('files' in capped && [capped.files.length, capped.truncated]).toEqual([2, true]); + expect(await code(prep('glob', { pattern: `${outside}/*` }))).toBe('invalid-args'); + }); +}); + +describe.skipIf(IS_WINDOWS)('bash cwd', () => { + it('moves a non-default cwd into the command and keeps the effect cwd at the session cwd', async () => { + mkdirSync(path.join(ws, "it's here")); + const prepared = await prep('bash', { command: 'pwd', cwd: "it's here" }); + if (prepared.tool !== 'bash') throw new Error('unreachable'); + expect(prepared.effect.cwd).toBe(ws); + expect(prepared.effect.command).toBe(`cd -- '${ws}/it'\\''s here' && pwd`); + expect(prepared.args.command).toBe(prepared.effect.command); + expect(prepared.effect.timeoutMs).toBe(120_000); + const result = await rt.commit(prepared, new AbortController().signal); + expect('stdout' in result && result.stdout.trim()).toBe(path.join(ws, "it's here")); + const same = await prep('bash', { command: 'pwd', cwd: '.' }); + expect(same.tool === 'bash' && same.effect.command).toBe('pwd'); + }); +}); diff --git a/src/tools/runtime.ts b/src/tools/runtime.ts new file mode 100644 index 0000000..5137fbe --- /dev/null +++ b/src/tools/runtime.ts @@ -0,0 +1,372 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { ToolError, errorMessage } from '../core/errors.js'; +import type { + BashContainment, + MatchStrategy, + PolicySnapshot, + PreparedCall, + PreparedCallOf, + ReadResult, + SessionContext, + ToolCall, + ToolResult, + ToolRuntime, + Transaction, +} from '../core/types.js'; +import { DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS, findBash, runBash, shellQuote } from './bash.js'; +import { binaryDiff, unifiedDiff } from './diff.js'; +import { applySearchReplace, type MatchHow } from './edit-match.js'; +import { assertDirUnchanged, atomicWrite, decodeText, errnoCode, isBinary, readRegularFile, sha256 } from './fs-ops.js'; +import { FileTransaction } from './journal.js'; +import { Jail } from './jail.js'; +import { containmentUnavailableReason } from './sandbox.js'; +import { DEFAULT_GLOB_MAX_RESULTS, DEFAULT_GREP_MAX_RESULTS, compileGrep, normalizeGlob, runGlob, runGrep } from './search.js'; + +/** Default number of lines `read` returns. */ +export const DEFAULT_READ_LIMIT = 2000; +/** Most bytes of content one `read` returns. */ +export const READ_CAP_BYTES = 256 * 1024; +/** Largest file `read`, `write` (existing content) and `edit` load. */ +export const MAX_FILE_BYTES = 64 * 1024 * 1024; + +/** + * How each Turnpack rung is reported in the frozen `MatchStrategy` type, + * which has fewer names than the ladder has rungs. + */ +const STRATEGY: Record = { + exact: 'exact', + 'line-endings': 'whitespace-normalized', + 'line-numbers': 'line-trimmed', + 'trailing-whitespace': 'line-trimmed', + indentation: 'indentation-flexible', + punctuation: 'whitespace-normalized', +}; + +export interface NodeToolRuntimeOptions { + /** Server state directory; transaction journals live under `/journal/`. */ + readonly stateDir: string; + /** Extra absolute directories the tools may touch besides the session cwd and MCP roots. */ + readonly additionalRoots?: readonly string[]; + /** Bytes kept of each of bash stdout and stderr. */ + readonly bashOutputCapBytes?: number; +} + +/** What `commit` needs to know about a call besides its frozen effect. */ +interface CallMeta { + /** Workspace root that contains the call's path. */ + readonly root: string; + /** Path shown in diffs. */ + readonly display: string; + /** Paths a sandboxed bash may never write. */ + readonly denyWrite: readonly string[]; +} + +/** + * Literal paths from protected patterns that the OS sandbox can enforce: + * patterns without wildcards, and `dir/**` patterns as `dir`. + */ +function sandboxDenyWrite(patterns: readonly string[]): string[] { + const out: string[] = []; + for (const p of patterns) { + const base = p.endsWith('/**') ? p.slice(0, -3) : p; + if (!/[*?[]/.test(base) && path.isAbsolute(base)) out.push(base); + } + return out; +} + +/** Any failure of the runtime reaches the dispatcher as a `ToolError`. */ +function asToolError(err: unknown): ToolError { + if (err instanceof ToolError) return err; + const code = errnoCode(err); + if (code === 'ENAMETOOLONG') return new ToolError('invalid-args', `path is too long: ${errorMessage(err)}`); + if (code === 'ENOENT') return new ToolError('not-found', errorMessage(err)); + return new ToolError('tool-error', errorMessage(err)); +} + +function assertContainmentShape(c: BashContainment): void { + if (c.mode === 'sandbox' && c.writableRoots.some((r) => !path.isAbsolute(r))) { + throw new ToolError('containment-unavailable', 'bash containment has a writable root that is not absolute'); + } +} + +/** + * The real `ToolRuntime`: workspace jail, tolerant edit, atomic writes with + * stale checks, transactional rollback, and contained `bash`. + */ +export class NodeToolRuntime implements ToolRuntime { + readonly #opts: NodeToolRuntimeOptions; + readonly #meta = new WeakMap(); + + constructor(opts: NodeToolRuntimeOptions) { + this.#opts = opts; + } + + async prepare(call: ToolCall, ctx: SessionContext, policy: PolicySnapshot): Promise { + try { + return await this.#prepareInJail(call, ctx, policy); + } catch (err) { + throw asToolError(err); + } + } + + async #prepareInJail(call: ToolCall, ctx: SessionContext, policy: PolicySnapshot): Promise { + const jail = await Jail.create({ + cwd: ctx.cwd, + roots: [...ctx.roots, ...(this.#opts.additionalRoots ?? [])], + protectedPaths: policy.protectedPaths, + }); + const meta = (abs: string, denyWrite: readonly string[] = []): CallMeta => ({ + root: jail.rootOf(abs) ?? jail.cwd, + display: jail.displayPath(abs), + denyWrite, + }); + return this.#prepare(call, jail, policy, meta); + } + + async #prepare( + call: ToolCall, + jail: Jail, + policy: PolicySnapshot, + meta: (abs: string, denyWrite?: readonly string[]) => CallMeta, + ): Promise { + switch (call.tool) { + case 'bash': { + if (findBash() === null) { + throw new ToolError('tool-error', process.platform === 'win32' ? 'bash requires Git Bash, which was not found' : 'bash was not found'); + } + let cwd = jail.cwd; + if (call.args.cwd !== undefined) { + cwd = await jail.resolve(call.args.cwd); + const st = await fs.stat(cwd).catch(() => null); + if (!st) throw new ToolError('not-found', `bash cwd ${call.args.cwd} does not exist`); + if (!st.isDirectory()) throw new ToolError('invalid-args', `bash cwd ${call.args.cwd} is not a directory`); + } + // What hooks see is exactly what runs: another cwd becomes part of the command. + const command = cwd === jail.cwd ? call.args.command : `cd -- ${shellQuote(cwd)} && ${call.args.command}`; + const timeoutMs = Math.min(call.args.timeoutMs ?? DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS); + const containment = policy.bashContainment; + assertContainmentShape(containment); + if (containment.mode === 'sandbox') { + const reason = await containmentUnavailableReason(); + if (reason !== null) throw new ToolError('containment-unavailable', reason); + } + const prepared: PreparedCallOf<'bash'> = { + id: call.id, + tool: 'bash', + args: { command, timeoutMs }, + effect: { command, cwd: jail.cwd, timeoutMs, containment }, + }; + this.#meta.set(prepared, meta(jail.cwd, sandboxDenyWrite(jail.protectedPaths))); + return prepared; + } + case 'read': { + const absPath = await jail.resolve(call.args.path); + await this.#assertFile(absPath, call.args.path); + const offset = call.args.offset ?? 1; + const limit = call.args.limit ?? DEFAULT_READ_LIMIT; + const prepared: PreparedCallOf<'read'> = { + id: call.id, + tool: 'read', + args: { path: absPath, offset, limit }, + effect: { absPath, offset, limit }, + }; + this.#meta.set(prepared, meta(absPath)); + return prepared; + } + case 'write': { + const absPath = await jail.resolve(call.args.path); + jail.assertWritable(absPath); + const m = meta(absPath); + const current = await this.#readExisting(absPath); + const diff = + current !== null && isBinary(current.bytes) + ? binaryDiff(m.display, true) + : unifiedDiff(m.display, current === null ? null : current.bytes.toString('utf8'), call.args.content); + const prepared: PreparedCallOf<'write'> = { + id: call.id, + tool: 'write', + args: { path: absPath, content: call.args.content }, + effect: { + absPath, + beforeHash: current === null ? null : sha256(current.bytes), + afterContent: call.args.content, + diff, + }, + }; + this.#meta.set(prepared, m); + return prepared; + } + case 'edit': { + const absPath = await jail.resolve(call.args.path); + jail.assertWritable(absPath); + const m = meta(absPath); + const current = await this.#readExisting(absPath); + if (current === null) throw new ToolError('not-found', `${m.display} does not exist`); + const text = decodeText(m.display, current.bytes); + if (call.args.oldString === call.args.newString) { + throw new ToolError('invalid-args', 'oldString and newString are the same; the edit would change nothing'); + } + const outcome = applySearchReplace(text, call.args.oldString, call.args.newString, call.args.replaceAll === true); + if (!outcome.ok) { + const code = outcome.kind === 'not-found' ? 'not-found' : 'invalid-args'; + throw new ToolError(code, `${m.display}: ${outcome.message}`); + } + const prepared: PreparedCallOf<'edit'> = { + id: call.id, + tool: 'edit', + args: { ...call.args, path: absPath }, + effect: { + absPath, + beforeHash: sha256(current.bytes), + afterContent: outcome.text, + diff: unifiedDiff(m.display, text, outcome.text), + matchedOldString: outcome.matched, + matchStrategy: STRATEGY[outcome.how], + replacements: outcome.count, + }, + }; + this.#meta.set(prepared, m); + return prepared; + } + case 'grep': { + const absRoot = await jail.resolve(call.args.path ?? '.'); + await this.#assertExists(absRoot, call.args.path ?? '.'); + const ignoreCase = call.args.ignoreCase ?? false; + compileGrep(call.args.pattern, ignoreCase); + const effect = { + absRoot, + pattern: call.args.pattern, + glob: call.args.glob ?? null, + ignoreCase, + maxResults: call.args.maxResults ?? DEFAULT_GREP_MAX_RESULTS, + }; + const prepared: PreparedCallOf<'grep'> = { id: call.id, tool: 'grep', args: { ...call.args, path: absRoot }, effect }; + this.#meta.set(prepared, meta(absRoot)); + return prepared; + } + case 'glob': { + const absRoot = await jail.resolve(call.args.path ?? '.'); + const st = await this.#assertExists(absRoot, call.args.path ?? '.'); + if (!st.isDirectory()) throw new ToolError('invalid-args', `glob path ${call.args.path ?? '.'} is not a directory`); + normalizeGlob(call.args.pattern, absRoot); + const effect = { absRoot, pattern: call.args.pattern, maxResults: call.args.maxResults ?? DEFAULT_GLOB_MAX_RESULTS }; + const prepared: PreparedCallOf<'glob'> = { id: call.id, tool: 'glob', args: { ...call.args, path: absRoot }, effect }; + this.#meta.set(prepared, meta(absRoot)); + return prepared; + } + } + } + + async #assertExists(abs: string, shown: string): Promise { + const st = await fs.lstat(abs).catch((err: unknown) => { + if (errnoCode(err) === 'ENOENT' || errnoCode(err) === 'ENOTDIR') return null; + throw new ToolError('tool-error', `cannot stat ${shown}: ${errnoCode(err) ?? String(err)}`); + }); + if (!st) throw new ToolError('not-found', `${shown} does not exist`); + return st; + } + + async #assertFile(abs: string, shown: string): Promise { + const st = await this.#assertExists(abs, shown); + if (st.isDirectory()) throw new ToolError('invalid-args', `${shown} is a directory`); + if (!st.isFile()) throw new ToolError('invalid-args', `${shown} is not a regular file`); + } + + async #readExisting(abs: string): Promise<{ bytes: Buffer; mode: number } | null> { + const st = await fs.lstat(abs).catch(() => null); + if (st?.isDirectory()) throw new ToolError('invalid-args', `${abs} is a directory`); + return readRegularFile(abs, MAX_FILE_BYTES); + } + + #metaOf(prepared: PreparedCall, fallbackPath: string): CallMeta { + return this.#meta.get(prepared) ?? { root: path.dirname(fallbackPath), display: fallbackPath, denyWrite: [] }; + } + + async commit(prepared: PreparedCall, signal: AbortSignal, tx?: Transaction): Promise { + try { + return await this.#commit(prepared, signal, tx); + } catch (err) { + throw asToolError(err); + } + } + + 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 'bash': { + const m = this.#metaOf(prepared, prepared.effect.cwd); + return runBash(prepared.effect, signal, { + ...(this.#opts.bashOutputCapBytes !== undefined ? { outputCapBytes: this.#opts.bashOutputCapBytes } : {}), + denyWrite: m.denyWrite, + }); + } + case 'read': + return this.#commitRead(prepared); + case 'write': + case 'edit': + return this.#commitWrite(prepared, tx); + case 'grep': { + await assertDirUnchanged(prepared.effect.absRoot); + return runGrep(prepared.effect, this.#metaOf(prepared, prepared.effect.absRoot).root, signal); + } + case 'glob': { + await assertDirUnchanged(prepared.effect.absRoot); + return runGlob(prepared.effect, this.#metaOf(prepared, prepared.effect.absRoot).root, signal); + } + } + } + + async #commitRead(prepared: PreparedCallOf<'read'>): Promise { + const { absPath, offset, limit } = prepared.effect; + await assertDirUnchanged(path.dirname(absPath)); + const file = await readRegularFile(absPath, MAX_FILE_BYTES); + if (file === null) throw new ToolError('not-found', `${absPath} does not exist`); + const text = decodeText(absPath, file.bytes); + const lines = text === '' ? [] : text.split('\n'); + if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop(); + const window: string[] = []; + let bytes = 0; + let truncated = false; + for (let i = offset - 1; i < lines.length && window.length < limit; i++) { + const line = lines[i] ?? ''; + const size = Buffer.byteLength(line, 'utf8') + 1; + if (bytes + size > READ_CAP_BYTES) { + truncated = true; + break; + } + window.push(line); + bytes += size; + } + if (offset - 1 + window.length < lines.length) truncated = true; + return { path: absPath, content: window.join('\n'), startLine: offset, totalLines: lines.length, truncated }; + } + + async #commitWrite(prepared: PreparedCallOf<'write'> | PreparedCallOf<'edit'>, tx: Transaction | undefined): Promise { + if (tx !== undefined && !(tx instanceof FileTransaction)) { + throw new ToolError('tool-error', 'the transaction was not started by this tool runtime; refusing to write without a journal'); + } + const { absPath, beforeHash, afterContent } = prepared.effect; + const m = this.#metaOf(prepared, absPath); + const bytes = Buffer.from(afterContent, 'utf8'); + const nextHash = sha256(bytes); + const outcome = await atomicWrite( + absPath, + bytes, + beforeHash === null ? { kind: 'absent' } : { kind: 'hash', sha256: beforeHash }, + tx ? (before, createdDirs) => tx.record(absPath, m.root, before, nextHash, createdDirs) : undefined, + ); + tx?.written(absPath, nextHash); + if (prepared.tool === 'write') return { path: absPath, created: outcome.before === null, diff: prepared.effect.diff }; + return { + path: absPath, + replacements: prepared.effect.replacements, + matchStrategy: prepared.effect.matchStrategy, + diff: prepared.effect.diff, + }; + } + + beginTransaction(): Transaction { + return new FileTransaction(this.#opts.stateDir); + } +} diff --git a/src/tools/sandbox.ts b/src/tools/sandbox.ts new file mode 100644 index 0000000..f09c201 --- /dev/null +++ b/src/tools/sandbox.ts @@ -0,0 +1,133 @@ +import { ToolError, errorMessage } from '../core/errors.js'; +import type { BashContainment } from '../core/types.js'; + +/** + * OS containment for `bash` through `@anthropic-ai/sandbox-runtime` + * (bubblewrap on Linux, Seatbelt on macOS). The library keeps one global + * configuration and one network proxy per process, so this module owns it: + * it is initialized once, lazily, with no network allowed, and each command + * passes its own filesystem rules. + * + * Network: the library routes all traffic through its proxy and refuses an + * allow-everything domain list, so "network on" is implemented with the + * library's ask callback, which allows a host only while a network-enabled + * command holds the sandbox. Sandboxed commands are therefore serialized in + * this process, so a network-off command never runs while the gate is open. + * On Linux the command has no network namespace of its own either way: with + * network on, only clients that honor the proxy variables the library sets + * (curl, git, npm, ...) reach the network; raw sockets never do. + */ + +type SandboxModule = typeof import('@anthropic-ai/sandbox-runtime'); +type Manager = SandboxModule['SandboxManager']; + +let loading: Promise | undefined; +let networkOpen = false; +let tail: Promise = Promise.resolve(); + +/** Why containment is unavailable on this machine, or null when it is available. */ +let availability: Promise | undefined; + +async function loadManager(): Promise { + const mod: SandboxModule = await import('@anthropic-ai/sandbox-runtime'); + return mod.SandboxManager; +} + +/** Returns null when OS containment can be enforced here, else the reason. Cached. */ +export function containmentUnavailableReason(): Promise { + availability ??= (async () => { + if (process.platform !== 'linux' && process.platform !== 'darwin') { + return `bash containment is not supported on ${process.platform}`; + } + try { + const manager = await loadManager(); + if (!manager.isSupportedPlatform()) return 'the sandbox runtime does not support this platform'; + const check = manager.checkDependencies(); + if (check.errors.length > 0) return `sandbox dependencies missing: ${check.errors.join('; ')}`; + return null; + } catch (err) { + return `sandbox runtime failed to load: ${errorMessage(err)}`; + } + })(); + return availability; +} + +async function manager(): Promise { + loading ??= (async () => { + const m = await loadManager(); + await m.initialize( + { network: { allowedDomains: [], deniedDomains: [] }, filesystem: { denyRead: [], allowWrite: [], denyWrite: [] } }, + async () => networkOpen, + ); + return m; + })(); + try { + return await loading; + } catch (err) { + loading = undefined; + throw err; + } +} + +/** A command wrapped for the sandbox. */ +export interface WrappedCommand { + readonly argv: readonly string[]; + readonly env: NodeJS.ProcessEnv; +} + +/** + * Runs `fn` with `command` wrapped for `containment`. Sandboxed commands are + * serialized in this process (see the module comment). `denyWrite` adds + * paths the command may never write even inside a writable root. + */ +export function withSandbox( + command: string, + shell: string, + cwd: string, + containment: Extract, + denyWrite: readonly string[], + fn: (wrapped: WrappedCommand) => Promise, +): Promise { + const run = async (): Promise => { + const reason = await containmentUnavailableReason(); + if (reason !== null) throw new ToolError('containment-unavailable', reason); + let m: Manager; + try { + m = await manager(); + } catch (err) { + throw new ToolError('containment-unavailable', `sandbox runtime failed to start: ${errorMessage(err)}`); + } + let wrapped: WrappedCommand; + try { + wrapped = await m.wrapWithSandboxArgv( + command, + shell, + { + filesystem: { + denyRead: [], + allowWrite: containment.readOnly ? [] : [...containment.writableRoots], + denyWrite: [...denyWrite], + }, + }, + undefined, + cwd, + ); + } catch (err) { + throw new ToolError('containment-unavailable', `sandbox runtime could not wrap the command: ${errorMessage(err)}`); + } + networkOpen = containment.network; + try { + return await fn(wrapped); + } finally { + networkOpen = false; + try { + m.cleanupAfterCommand(); + } catch { + // Cleanup is best effort. + } + } + }; + const next = tail.then(run, run); + tail = next.catch(() => undefined); + return next; +} diff --git a/src/tools/search.ts b/src/tools/search.ts new file mode 100644 index 0000000..7208018 --- /dev/null +++ b/src/tools/search.ts @@ -0,0 +1,338 @@ +import { constants as FS } from 'node:fs'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { ToolError } from '../core/errors.js'; +import { DEFAULT_CASE_INSENSITIVE, matchesPathPattern } from '../core/paths.js'; +import type { GlobEffect, GlobResult, GrepEffect, GrepMatch, GrepResult } from '../core/types.js'; + +/** Default `grep` result count. */ +export const DEFAULT_GREP_MAX_RESULTS = 500; +/** Default `glob` result count. */ +export const DEFAULT_GLOB_MAX_RESULTS = 1000; +/** Longest matching line returned by `grep`. */ +const MAX_LINE_CHARS = 2000; +/** Files larger than this are not searched by `grep`. */ +const MAX_GREP_FILE_BYTES = 16 * 1024 * 1024; +/** Upper bound of directory entries visited by one call. */ +const MAX_VISITED = 500_000; + +const ALWAYS_IGNORED = new Set(['.git', 'node_modules']); + +// --------------------------------------------------------------------------- +// gitignore +// --------------------------------------------------------------------------- + +interface IgnoreRule { + readonly re: RegExp; + readonly negate: boolean; + readonly dirOnly: boolean; +} + +function globToRegExpSource(glob: string): string { + let src = ''; + for (let i = 0; i < glob.length; i++) { + const ch = glob[i] ?? ''; + if (ch === '\\' && i + 1 < glob.length) { + src += (glob[++i] ?? '').replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'); + } else if (ch === '*') { + if (glob[i + 1] === '*') { + const prevSlash = i === 0 || glob[i - 1] === '/'; + const nextSlash = glob[i + 2] === '/' || i + 2 === glob.length; + if (prevSlash && nextSlash) { + if (i + 2 === glob.length) src += '.*'; + else { + src += '(?:.*/)?'; + i++; + } + i++; + continue; + } + i++; + } + src += '[^/]*'; + } else if (ch === '?') { + src += '[^/]'; + } else if (ch === '[') { + const close = glob.indexOf(']', i + 1); + if (close === -1) src += '\\['; + else { + let body = glob.slice(i + 1, close); + if (body.startsWith('!')) body = `^${body.slice(1)}`; + src += `[${body.replace(/\\/g, '\\\\')}]`; + i = close; + } + } else { + src += ch.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'); + } + } + return src; +} + +/** Parses a `.gitignore` file. Patterns are relative to the directory holding it. */ +export function parseGitignore(text: string): IgnoreRule[] { + const rules: IgnoreRule[] = []; + for (const rawLine of text.split(/\r?\n/)) { + let line = rawLine.replace(/(? 0 && !matchedParent; i--) { + if (rule.re.test(parts.slice(0, i).join('/'))) matchedParent = true; + } + if (matchedParent) ignored = !rule.negate; + continue; + } + if (rule.re.test(rel)) ignored = !rule.negate; + } + } + return ignored; +} + +async function loadIgnore(dir: string): Promise { + try { + const handle = await fs.open(path.join(dir, '.gitignore'), FS.O_RDONLY | (FS.O_NOFOLLOW ?? 0)); + try { + const st = await handle.stat(); + if (!st.isFile() || st.size > 1024 * 1024) return null; + return { base: dir, rules: parseGitignore(await handle.readFile('utf8')) }; + } finally { + await handle.close(); + } + } catch { + return null; + } +} + +/** `.gitignore` layers of the directories from `top` down to `dir` (inclusive). */ +async function ancestorLayers(top: string, dir: string): Promise { + const chain: string[] = []; + let cursor = dir; + for (;;) { + chain.push(cursor); + if (cursor === top) break; + const parent = path.dirname(cursor); + if (parent === cursor || path.relative(top, parent).startsWith('..')) break; + cursor = parent; + } + const layers: IgnoreLayer[] = []; + for (const d of chain.reverse()) { + const layer = await loadIgnore(d); + if (layer) layers.push(layer); + } + return layers; +} + +// --------------------------------------------------------------------------- +// Walking +// --------------------------------------------------------------------------- + +/** + * Lists regular files below `absRoot` (real path, inside the jail), sorted, + * skipping `.git`, `node_modules` and gitignored entries. Symbolic links are + * never followed, whether they point inside or outside the workspace. + * `jailRoot` is the workspace root above it whose `.gitignore` files apply. + */ +async function* walkFiles(absRoot: string, jailRoot: string, signal: AbortSignal): AsyncGenerator { + const rootStat = await fs.lstat(absRoot); + if (rootStat.isFile()) { + yield absRoot; + return; + } + if (!rootStat.isDirectory()) return; + const startLayers = await ancestorLayers(jailRoot, absRoot); + let visited = 0; + const stack: { dir: string; layers: IgnoreLayer[] }[] = [{ dir: absRoot, layers: startLayers }]; + while (stack.length > 0) { + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped'); + const { dir, layers } = stack.pop() as { dir: string; layers: IgnoreLayer[] }; + let entries: import('node:fs').Dirent[]; + try { + entries = await fs.readdir(dir, { withFileTypes: true }); + } catch { + continue; + } + const own = dir === absRoot ? null : await loadIgnore(dir); + const here = own ? [...layers, own] : layers; + entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + const subdirs: string[] = []; + for (const entry of entries) { + if (++visited > MAX_VISITED) throw new ToolError('tool-error', `too many files under ${absRoot} (more than ${MAX_VISITED}); narrow the path`); + const abs = path.join(dir, entry.name); + if (entry.isSymbolicLink()) continue; + if (entry.isDirectory()) { + if (ALWAYS_IGNORED.has(entry.name)) continue; + if (isIgnored(here, abs, true)) continue; + subdirs.push(abs); + } else if (entry.isFile()) { + if (isIgnored(here, abs, false)) continue; + yield abs; + } + } + // Depth first, in name order: push in reverse so the first name pops first. + // Files of a directory come before its subdirectories' files. + for (const sub of subdirs.reverse()) stack.push({ dir: sub, layers: here }); + } +} + +// --------------------------------------------------------------------------- +// Patterns +// --------------------------------------------------------------------------- + +/** Expands `{a,b}` alternations (nested allowed, at most 256 results). */ +export function expandBraces(pattern: string): string[] { + const open = pattern.indexOf('{'); + if (open === -1) return [pattern]; + let depth = 0; + let close = -1; + const commas: number[] = []; + for (let i = open; i < pattern.length; i++) { + const ch = pattern[i]; + if (ch === '{') depth++; + else if (ch === '}') { + depth--; + if (depth === 0) { + close = i; + break; + } + } else if (ch === ',' && depth === 1) commas.push(i); + } + if (close === -1 || commas.length === 0) return [pattern]; + const head = pattern.slice(0, open); + const tail = pattern.slice(close + 1); + const cuts = [open, ...commas, close]; + const out: string[] = []; + for (let i = 0; i + 1 < cuts.length; i++) { + const alt = pattern.slice((cuts[i] ?? 0) + 1, cuts[i + 1]); + for (const expanded of expandBraces(head + alt + tail)) { + out.push(expanded); + if (out.length >= 256) return out; + } + } + return out; +} + +/** Normalizes a glob pattern given relative to `absRoot`; refuses patterns that leave it. */ +export function normalizeGlob(pattern: string, absRoot: string): string { + let p = pattern.replace(/\\/g, '/'); + const rootFwd = absRoot.replace(/\\/g, '/'); + if (p.startsWith(`${rootFwd}/`)) p = p.slice(rootFwd.length + 1); + else if (p.startsWith('/') || /^[A-Za-z]:\//.test(p)) { + throw new ToolError('invalid-args', `glob pattern ${pattern} is absolute and not under ${absRoot}; pass the directory as path and a relative pattern`); + } + if (p.startsWith('./')) p = p.slice(2); + if (p.split('/').includes('..')) throw new ToolError('invalid-args', `glob pattern ${pattern} must not contain ..`); + return p; +} + +function toRel(absRoot: string, abs: string): string { + return path.relative(absRoot, abs).split(path.sep).join('/'); +} + +// --------------------------------------------------------------------------- +// grep and glob +// --------------------------------------------------------------------------- + +/** Compiles a grep pattern (JavaScript RegExp syntax). */ +export function compileGrep(pattern: string, ignoreCase: boolean): RegExp { + try { + return new RegExp(pattern, ignoreCase ? 'i' : ''); + } catch (err) { + throw new ToolError('invalid-args', `invalid regular expression ${JSON.stringify(pattern)}: ${err instanceof Error ? err.message : String(err)}`); + } +} + +function matchesFileGlob(rel: string, globs: readonly string[]): boolean { + const base = rel.slice(rel.lastIndexOf('/') + 1); + return globs.some((g) => (g.includes('/') ? matchesPathPattern(rel, g) : matchesPathPattern(base, g))); +} + +export async function runGrep(effect: GrepEffect, jailRoot: string, signal: AbortSignal): Promise { + const re = compileGrep(effect.pattern, effect.ignoreCase); + const globs = effect.glob === null ? null : expandBraces(effect.glob.replace(/\\/g, '/')); + const matches: GrepMatch[] = []; + let truncated = false; + for await (const file of walkFiles(effect.absRoot, jailRoot, signal)) { + if (globs && file !== effect.absRoot && !matchesFileGlob(toRel(effect.absRoot, file), globs)) continue; + let bytes: Buffer; + try { + const handle = await fs.open(file, FS.O_RDONLY | (FS.O_NOFOLLOW ?? 0)); + try { + const st = await handle.stat(); + if (!st.isFile() || st.size > MAX_GREP_FILE_BYTES) continue; + bytes = await handle.readFile(); + } finally { + await handle.close(); + } + } catch { + continue; + } + if (bytes.subarray(0, 8192).includes(0)) continue; + const lines = bytes.toString('utf8').split('\n'); + for (let i = 0; i < lines.length; i++) { + let text = lines[i] ?? ''; + if (text.endsWith('\r')) text = text.slice(0, -1); + if (i === lines.length - 1 && text === '') break; + if (!re.test(text)) continue; + if (matches.length >= effect.maxResults) { + truncated = true; + return { matches, truncated }; + } + matches.push({ file, line: i + 1, text: text.length > MAX_LINE_CHARS ? `${text.slice(0, MAX_LINE_CHARS)}…` : text }); + } + } + return { matches, truncated }; +} + +export async function runGlob(effect: GlobEffect, jailRoot: string, signal: AbortSignal): Promise { + const patterns = expandBraces(normalizeGlob(effect.pattern, effect.absRoot)); + const all: string[] = []; + for await (const file of walkFiles(effect.absRoot, jailRoot, signal)) { + if (file === effect.absRoot) continue; + const rel = toRel(effect.absRoot, file); + if (patterns.some((p) => matchesPathPattern(rel, p))) all.push(file); + } + all.sort(); + return { files: all.slice(0, effect.maxResults), truncated: all.length > effect.maxResults }; +} + From 8e8a3f0cd07865a875fa825c858e692db836411a Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:31:01 -0300 Subject: [PATCH 04/17] Match protected patterns written through an alias of the workspace Protected path patterns are built by the host adapter from the session cwd as the host spells it. Paths are checked as real paths, so a cwd reached through a symlink, macOS /var or a Windows 8.3 short name made the patterns miss. Each pattern now also matches with its literal prefix resolved. Tests use native real paths so they agree with the runtime on Windows. Co-Authored-By: Claude Opus 5.5 --- src/tools/bash.test.ts | 2 +- src/tools/diff.test.ts | 2 +- src/tools/integration.test.ts | 2 +- src/tools/jail.ts | 35 ++++++++++++++++++++++++++++++++++- src/tools/journal.test.ts | 2 +- src/tools/runtime.test.ts | 20 +++++++++++++++++--- 6 files changed, 55 insertions(+), 8 deletions(-) diff --git a/src/tools/bash.test.ts b/src/tools/bash.test.ts index 0806edf..fdccf1b 100644 --- a/src/tools/bash.test.ts +++ b/src/tools/bash.test.ts @@ -53,7 +53,7 @@ async function eventually(check: () => boolean, ms = 3000): Promise { } beforeEach(() => { - base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-bash-'))); + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-bash-'))); ws = path.join(base, 'ws'); mkdirSync(ws); ctx = makeContext(ws); diff --git a/src/tools/diff.test.ts b/src/tools/diff.test.ts index f595a2f..d6e72f1 100644 --- a/src/tools/diff.test.ts +++ b/src/tools/diff.test.ts @@ -13,7 +13,7 @@ function gitApply(before: string | null, diff: string): string { try { if (before !== null) writeFileSync(path.join(dir, 'f.txt'), before); writeFileSync(path.join(dir, 'p.diff'), diff); - const r = spawnSync('git', ['apply', '--unsafe-paths', '--whitespace=nowarn', 'p.diff'], { cwd: dir, encoding: 'utf8' }); + const r = spawnSync('git', ['-c', 'core.autocrlf=false', 'apply', '--unsafe-paths', '--whitespace=nowarn', 'p.diff'], { cwd: dir, encoding: 'utf8' }); if (r.status !== 0) throw new Error(`git apply failed: ${r.stderr}\n${diff}`); return readFileSync(path.join(dir, 'f.txt'), 'utf8'); } finally { diff --git a/src/tools/integration.test.ts b/src/tools/integration.test.ts index 971200f..74f8933 100644 --- a/src/tools/integration.test.ts +++ b/src/tools/integration.test.ts @@ -11,7 +11,7 @@ let base: string; let ws: string; beforeEach(() => { - base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-int-'))); + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-int-'))); ws = path.join(base, 'ws'); mkdirSync(ws); writeFileSync(path.join(ws, 'a.txt'), 'alpha\n'); diff --git a/src/tools/jail.ts b/src/tools/jail.ts index 28784b3..7d3a64d 100644 --- a/src/tools/jail.ts +++ b/src/tools/jail.ts @@ -112,6 +112,39 @@ export function isInsideGitDir(absPath: string): boolean { }); } +/** + * Adds, for each pattern, the same pattern with its literal directory prefix + * replaced by that directory's real path. Paths are checked as real paths, so + * a pattern written through an alias of the workspace (a symlinked cwd, + * macOS `/var` vs `/private/var`, a Windows 8.3 short name) must match too. + */ +async function withRealPrefixes(patterns: readonly string[]): Promise { + const out = new Set(patterns); + for (const pattern of patterns) { + const fwd = pattern.replace(/\\/g, '/'); + const wild = fwd.search(/[*?[]/); + const literal = wild === -1 ? fwd : fwd.slice(0, wild); + const cut = literal.lastIndexOf('/'); + if (cut <= 0) continue; + // Resolve the deepest existing directory of the literal prefix. + let dir = fwd.slice(0, cut); + let rest = fwd.slice(cut); + for (;;) { + try { + const real = (await fs.realpath(dir)).replace(/\\/g, '/'); + if (real !== dir) out.add(real + rest); + break; + } catch { + const up = dir.lastIndexOf('/'); + if (up <= 0 || /^[A-Za-z]:$/.test(dir.slice(0, up))) break; + rest = dir.slice(up) + rest; + dir = dir.slice(0, up); + } + } + } + return [...out]; +} + export interface JailOptions { /** Absolute directory relative paths resolve against. */ readonly cwd: string; @@ -157,7 +190,7 @@ export class Jail { // A root that does not exist grants nothing. } } - const protectedPaths = opts.protectedPaths.map((p) => expandTilde(p)); + const protectedPaths = await withRealPrefixes(opts.protectedPaths.map((p) => expandTilde(p))); return new Jail(cwd, roots, protectedPaths, opts.windowsChecks ?? IS_WINDOWS); } diff --git a/src/tools/journal.test.ts b/src/tools/journal.test.ts index 7e857c7..91bf991 100644 --- a/src/tools/journal.test.ts +++ b/src/tools/journal.test.ts @@ -33,7 +33,7 @@ function deadPid(): number { } beforeEach(() => { - base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-journal-'))); + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-journal-'))); ws = path.join(base, 'ws'); outside = path.join(base, 'outside'); stateDir = path.join(base, 'state'); diff --git a/src/tools/runtime.test.ts b/src/tools/runtime.test.ts index 15912e7..f21deff 100644 --- a/src/tools/runtime.test.ts +++ b/src/tools/runtime.test.ts @@ -64,7 +64,7 @@ function link(target: string, at: string): void { } beforeEach(() => { - base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'acm-tools-'))); + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-tools-'))); ws = path.join(base, 'ws'); outside = path.join(base, 'outside'); mkdirSync(ws); @@ -106,8 +106,12 @@ describe('path traversal', () => { expect(await code(prep('write', { path: 'a\0b', content: 'x' }))).toBe('invalid-args'); const long = `${'a'.repeat(250)}/`.repeat(40) + 'f.txt'; const result = await code(run('write', { path: long, content: 'x' })); - expect(['invalid-args', 'tool-error']).toContain(result); - expect(readdirSync(ws)).toEqual([]); + // Windows with long-path support accepts it; it must then be inside the workspace. + if (result === 'resolved') expect(readFileSync(path.join(ws, long), 'utf8')).toBe('x'); + else { + expect(['invalid-args', 'tool-error']).toContain(result); + expect(readdirSync(ws)).toEqual([]); + } }); it('keeps unicode lookalikes of .. inside the workspace', async () => { @@ -219,6 +223,16 @@ describe('protected paths', () => { expect(readFileSync(path.join(ws, '.git', 'config'), 'utf8')).toBe('[core]\n'); }); + it.skipIf(IS_WINDOWS)('matches patterns written through an alias of the workspace', async () => { + const alias = path.join(base, 'alias'); + link(ws, alias); + const aliasCtx = makeContext(alias); + const p = { ...policy, protectedPaths: [`${alias}/.claude/settings*.json`, `${alias}/.codex/**`] }; + expect(await code(rt.prepare(call('write', { path: '.claude/settings.json', content: '{}' }), aliasCtx, p))).toBe('protected-path'); + expect(await code(rt.prepare(call('write', { path: '.codex/config.toml', content: '' }), aliasCtx, p))).toBe('protected-path'); + expect(await code(rt.prepare(call('write', { path: 'ok.txt', content: '' }), aliasCtx, p))).toBe('resolved'); + }); + it('expands ~ in protected patterns', async () => { const home = path.join(ws, 'home'); mkdirSync(home); From 204b82353e579e64186cde1cdc46c1237711c6e0 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:32:04 -0300 Subject: [PATCH 05/17] Expect forward slashes in changedFiles on every platform Co-Authored-By: Claude Opus 5.5 --- src/tools/integration.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/integration.test.ts b/src/tools/integration.test.ts index 74f8933..7d8b89a 100644 --- a/src/tools/integration.test.ts +++ b/src/tools/integration.test.ts @@ -34,7 +34,7 @@ describe('NodeToolRuntime in the run pipeline', () => { ]); const result = await runScript({ code, transaction: false, timeoutMs: 10_000 }, deps()); expect(result.ok).toBe(true); - expect(result.changedFiles).toEqual(['a.txt', path.join('b', 'c.txt')]); + expect(result.changedFiles).toEqual(['a.txt', 'b/c.txt']); expect(result.diff).toContain('-alpha\n+beta\n'); expect(result.diff).toContain('--- /dev/null\n+++ b/b/c.txt\n'); expect(readFileSync(path.join(ws, 'a.txt'), 'utf8')).toBe('beta\n'); From 20318a5bdd2908060838d1f854a18e382156a63f Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:48:22 -0300 Subject: [PATCH 06/17] Close races and path gaps found by the correctness review - Paths resolve component by component with POSIX semantics, so `link/..` is the parent of the link's target; an oracle test checks that a path is accepted exactly when its real path is inside the roots. - Writes and edits check protected patterns on the real path and on every link the resolution went through, and refuse a final-component link. - grep and glob re-check each directory after listing it and open each file without following links, checking the handle is the file at that path, so a directory swapped for a link mid-walk leads nowhere. - grep runs the regular expression in a worker thread with a per-file time budget; an abort or an exhausted budget terminates it. - Commits record dev+ino of the file and its directories at prepare and refuse when any changed; check-and-replace of one path holds a per-path lock and re-checks the abort signal, identity and content hash right before the rename. - Rollback and crash recovery remove files and directories only through real directories strictly inside the roots, never through a link. Co-Authored-By: Claude Opus 5.5 --- src/tools/fs-ops.ts | 176 +++++++++++++++++++++--- src/tools/hardening.test.ts | 263 ++++++++++++++++++++++++++++++++++++ src/tools/jail.ts | 157 ++++++++++++++++----- src/tools/journal.ts | 59 ++++---- src/tools/runtime.test.ts | 4 +- src/tools/runtime.ts | 40 +++--- src/tools/search.ts | 157 ++++++++++++++++----- 7 files changed, 732 insertions(+), 124 deletions(-) create mode 100644 src/tools/hardening.test.ts diff --git a/src/tools/fs-ops.ts b/src/tools/fs-ops.ts index da3be27..c78a523 100644 --- a/src/tools/fs-ops.ts +++ b/src/tools/fs-ops.ts @@ -58,9 +58,91 @@ async function assertHandleAt(handle: FileHandle, abs: string): Promise { if (!lst || lst.isSymbolicLink() || !sameFile(st, lst)) { throw new ToolError('stale', `file changed since prepared: ${abs} was replaced while it was opened`); } + // Without /proc, the directory holding the opened file must still be itself: + // a parent swapped for a link would make `lstat(abs)` agree with the handle. + if (!IS_LINUX) await assertDirUnchanged(path.dirname(abs)); return st; } +/** + * Opens a regular file for reading and checks the handle is the file at + * `abs` reached without any link (final component or parent). Returns null + * when the file is not there or not a regular file reachable that way. + */ +export async function readFileInside(abs: string, maxBytes: number): Promise { + let handle: FileHandle; + try { + handle = await fs.open(abs, FS.O_RDONLY | NOFOLLOW); + } catch { + return null; + } + try { + const st = await assertHandleAt(handle, abs); + if (!st.isFile() || st.size > maxBytes) return null; + return await handle.readFile(); + } catch { + return null; + } finally { + await handle.close(); + } +} + +// --------------------------------------------------------------------------- +// Identity: what a commit checks to know the path still names what prepare saw. +// --------------------------------------------------------------------------- + +/** dev+ino of a path and of each directory above it up to a root. */ +export interface PathIdentity { + readonly entries: readonly { readonly path: string; readonly dev: bigint; readonly ino: bigint }[]; +} + +/** + * Records the identity of `abs` (when it exists) and of every existing + * directory from its parent up to `root` (inclusive). + */ +export async function captureIdentity(abs: string, root: string): Promise { + const entries: { path: string; dev: bigint; ino: bigint }[] = []; + let cursor = abs; + for (;;) { + const st = await fs.lstat(cursor, { bigint: true }).catch(() => null); + if (st) entries.push({ path: cursor, dev: st.dev, ino: st.ino }); + const same = IS_WINDOWS ? cursor.toLowerCase() === root.toLowerCase() : cursor === root; + const parent = path.dirname(cursor); + if (same || parent === cursor) break; + cursor = parent; + } + return { entries }; +} + +/** Throws `stale` when any path recorded by `captureIdentity` now names something else. */ +export async function assertIdentity(identity: PathIdentity): Promise { + for (const e of identity.entries) { + const st = await fs.lstat(e.path, { bigint: true }).catch(() => null); + if (!st || st.dev !== e.dev || st.ino !== e.ino) { + throw new ToolError('stale', `file changed since prepared: ${e.path} was replaced`); + } + } +} + +// --------------------------------------------------------------------------- +// Per-path lock: check-and-replace of one path is atomic within the process. +// --------------------------------------------------------------------------- + +const locks = new Map>(); + +/** Runs `fn` while holding the in-process lock of `abs`. */ +export function withPathLock(abs: string, fn: () => Promise): Promise { + const key = IS_WINDOWS || process.platform === 'darwin' ? abs.toLowerCase() : abs; + const prev = locks.get(key) ?? Promise.resolve(); + const next = prev.then(fn, fn); + const tail = next.catch(() => undefined); + locks.set(key, tail); + void tail.then(() => { + if (locks.get(key) === tail) locks.delete(key); + }); + return next; +} + export interface RegularFile { readonly bytes: Buffer; readonly mode: number; @@ -122,22 +204,46 @@ async function missingDirs(dir: string): Promise { return missing.reverse(); } +export interface AtomicWriteOptions { + /** Runs after the checks and before anything is written (the journal snapshots there). */ + readonly beforeWrite?: (before: RegularFile | null, createdDirs: readonly string[]) => Promise; + /** Checked again right before the rename; an abort refuses the write. */ + readonly signal?: AbortSignal; + /** Identity recorded at prepare; checked before writing and right before the rename. */ + readonly identity?: PathIdentity; + /** Mode of the new file; defaults to the mode of the file it replaces. */ + readonly mode?: number; +} + +function hashMatches(expect: Expectation, current: RegularFile | null): boolean { + if (expect.kind === 'absent') return current === null; + return current !== null && sha256(current.bytes) === expect.sha256; +} + +/** Atomically replaces (or creates) `abs` under its per-path lock; see `writeLocked`. */ +export function atomicWrite(abs: string, bytes: Buffer, expect: Expectation, opts: AtomicWriteOptions = {}): Promise { + return withPathLock(abs, () => writeLocked(abs, bytes, expect, opts)); +} + +function assertNotAborted(signal: AbortSignal | undefined, abs: string): void { + if (signal?.aborted) throw new ToolError('cancelled', `the run was stopped before ${abs} was written`); +} + /** - * Atomically replaces (or creates) `abs` with `bytes`: + * Replaces (or creates) `abs` with `bytes`, holding its per-path lock: * 1. the parent directory must still resolve to itself (no symlink swapped in); - * 2. the current content must match `expect` (else `ToolError('stale')`, no write); + * 2. the identity recorded at prepare and the content must match (else `stale`, no write); * 3. the bytes go to a temp file in the same directory (fsync), keep the old mode, * and are renamed over the target; a create uses `link` so it never replaces * a file that appeared meanwhile. - * `beforeWrite` runs after the checks and before anything is written (the + * Right before the rename the signal, the identity and the content hash are + * checked again. `beforeWrite` runs after the checks and before anything is written (the * transaction journal snapshots the original there). */ -export async function atomicWrite( - abs: string, - bytes: Buffer, - expect: Expectation, - beforeWrite?: (before: RegularFile | null, createdDirs: readonly string[]) => Promise, -): Promise { +async function writeLocked(abs: string, bytes: Buffer, expect: Expectation, opts: AtomicWriteOptions): Promise { + const { beforeWrite, signal, identity } = opts; + assertNotAborted(signal, abs); + if (identity) await assertIdentity(identity); const dir = path.dirname(abs); const toCreate = await missingDirs(dir); const existingAncestor = toCreate.length > 0 ? path.dirname(toCreate[0] ?? dir) : dir; @@ -165,18 +271,24 @@ export async function atomicWrite( await assertDirUnchanged(dir); const tmp = path.join(dir, `.${path.basename(abs)}.acm-${randomBytes(6).toString('hex')}.tmp`); - const mode = before?.mode ?? 0o666; + const mode = opts.mode ?? before?.mode ?? 0o666; const handle = await fs.open(tmp, FS.O_WRONLY | FS.O_CREAT | FS.O_EXCL | NOFOLLOW, mode); let placed = false; try { try { await handle.writeFile(bytes); - if (before && !IS_WINDOWS) await handle.chmod(before.mode); + if ((opts.mode !== undefined || before) && !IS_WINDOWS) await handle.chmod(mode); await handle.sync(); } finally { await handle.close(); } + // Last checks before the irreversible step. + assertNotAborted(signal, abs); await assertDirUnchanged(dir); + if (identity) await assertIdentity(identity); + if (!hashMatches(expect, await readRegularFile(abs))) { + throw new ToolError('stale', `file changed since prepared: ${abs} changed while it was being written`); + } if (expect.kind === 'absent') { try { await fs.link(tmp, abs); @@ -196,12 +308,42 @@ export async function atomicWrite( } } -/** Removes `abs` if it is a regular file (never follows a link). */ -export async function removeRegularFile(abs: string): Promise { - const st = await fs.lstat(abs).catch(() => null); - if (!st) return; - if (!st.isFile()) throw new ToolError('stale', `${abs} is no longer a regular file`); - await fs.unlink(abs); +/** + * Removes `abs` when it is a regular file holding `expectHash`, reached + * without any link (its directory must still resolve to itself). + */ +export function removeRegularFile(abs: string, expectHash: string): Promise { + return withPathLock(abs, async () => { + await assertDirUnchanged(path.dirname(abs)); + const current = await readRegularFile(abs); + if (current === null) return; + if (sha256(current.bytes) !== expectHash) throw new ToolError('stale', `${abs} changed; not removed`); + await fs.unlink(abs); + }); +} + +/** + * Removes `dir` when it is an empty real directory (not a link, not reached + * through one) strictly inside one of `roots`. Returns whether it was removed. + */ +export async function removeEmptyDirInside(dir: string, roots: readonly string[]): Promise { + if (!path.isAbsolute(dir)) return false; + const st = await fs.lstat(dir).catch(() => null); + if (!st || st.isSymbolicLink() || !st.isDirectory()) return false; + const real = await fs.realpath(dir).catch(() => null); + const same = real !== null && (IS_WINDOWS ? real.toLowerCase() === dir.toLowerCase() : real === dir); + if (!same) return false; + const inside = roots.some((root) => { + const rel = path.relative(IS_WINDOWS ? root.toLowerCase() : root, IS_WINDOWS ? dir.toLowerCase() : dir); + return rel !== '' && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); + }); + if (!inside) return false; + try { + await fs.rmdir(dir); + return true; + } catch { + return false; + } } /** fsyncs a directory where the platform allows it. */ diff --git a/src/tools/hardening.test.ts b/src/tools/hardening.test.ts new file mode 100644 index 0000000..1adcf3b --- /dev/null +++ b/src/tools/hardening.test.ts @@ -0,0 +1,263 @@ +import { linkSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync, existsSync } from 'node:fs'; +import fsp from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ToolError } from '../core/errors.js'; +import type { PolicySnapshot, PreparedCall, SessionContext, ToolCall } from '../core/types.js'; +import { makeContext } from '../testing/context.js'; +import { FileTransaction, journalRoot, recoverStaleJournals } from './journal.js'; +import { NodeToolRuntime } from './runtime.js'; + +/** + * One test per defect found by the correctness review of the first version: + * each failed (or hung) before its fix. + */ + +const IS_WINDOWS = process.platform === 'win32'; + +let base: string; +let ws: string; +let outside: string; +let ctx: SessionContext; +let rt: NodeToolRuntime; +let seq = 0; +const policy: PolicySnapshot = { host: 'generic', bashContainment: { mode: 'none' }, protectedPaths: [], payload: null }; + +async function code(p: Promise): Promise { + try { + await p; + } catch (err) { + if (err instanceof ToolError) return err.code; + throw err; + } + return 'resolved'; +} + +function prepWrite(rel: string, content: string, p: PolicySnapshot = policy): Promise { + return rt.prepare({ id: `c${++seq}`, tool: 'write', args: { path: rel, content } } satisfies ToolCall, ctx, p); +} + +beforeEach(() => { + base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), 'acm-hard-'))); + ws = path.join(base, 'ws'); + outside = path.join(base, 'outside'); + mkdirSync(ws); + mkdirSync(outside); + writeFileSync(path.join(outside, 'secret'), 'EXTERNAL_SECRET\n'); + ctx = makeContext(ws); + rt = new NodeToolRuntime({ stateDir: path.join(base, 'state') }); +}); + +afterEach(() => { + rmSync(base, { recursive: true, force: true }); +}); + +describe.skipIf(IS_WINDOWS)('1. grep and glob re-check every directory and file they open', () => { + /** Swaps `ws/sub` for a link to `outside` around the walk's listing of it. */ + async function withSwap(when: 'before-list' | 'after-list', fn: () => Promise): Promise { + const sub = path.join(ws, 'sub'); + const original = fsp.readdir; + let swapped = false; + const swap = async (): Promise => { + swapped = true; + renameSync(sub, `${sub}-old`); + symlinkSync(outside, sub, 'dir'); + }; + const patched = async function (this: unknown, ...args: Parameters): Promise { + if (args[0] === sub && !swapped && when === 'before-list') await swap(); + const result: unknown = await Reflect.apply(original, this, args); + if (args[0] === sub && !swapped && when === 'after-list') await swap(); + return result; + }; + Object.assign(fsp, { readdir: patched }); + try { + return await fn(); + } finally { + Object.assign(fsp, { readdir: original }); + } + } + + beforeEach(() => { + mkdirSync(path.join(ws, 'sub')); + writeFileSync(path.join(ws, 'sub', 'secret'), 'inside\n'); + }); + + it('grep does not read a file through a parent swapped for a link mid-walk', async () => { + const prepared = await rt.prepare({ id: 'g', tool: 'grep', args: { pattern: 'SECRET' } }, ctx, policy); + const result = await withSwap('after-list', () => rt.commit(prepared, new AbortController().signal)); + expect('matches' in result ? result.matches : null).toEqual([]); + }); + + it('glob does not list names from a directory swapped for a link before it is listed', async () => { + const prepared = await rt.prepare({ id: 'g', tool: 'glob', args: { pattern: '**/*' } }, ctx, policy); + const result = await withSwap('before-list', () => rt.commit(prepared, new AbortController().signal)); + expect('files' in result ? result.files : null).toEqual([]); + }); +}); + +describe.skipIf(IS_WINDOWS)('2. crash recovery never deletes through a link', () => { + it('leaves a directory outside the roots alone when a created dir path now goes through a link', async () => { + mkdirSync(path.join(outside, 'empty')); + symlinkSync(outside, path.join(ws, 'sub'), 'dir'); + const dir = path.join(journalRoot(path.join(base, 'state')), 'abc-99999999-dead'); + mkdirSync(dir, { recursive: true }); + writeFileSync( + path.join(dir, 'manifest.json'), + JSON.stringify({ version: 1, pid: 99_999_999, host: os.hostname(), startedAt: 0, roots: [ws], dirs: [path.join(ws, 'sub', 'empty')], entries: [] }), + ); + await recoverStaleJournals(path.join(base, 'state'), [ws]); + expect(existsSync(path.join(outside, 'empty'))).toBe(true); + }); +}); + +describe.skipIf(IS_WINDOWS)('3. protected paths are checked on every path the resolution goes through', () => { + it('refuses writing a protected path that is a link to an unprotected file', async () => { + writeFileSync(path.join(ws, 'f'), 'old'); + symlinkSync(path.join(ws, 'f'), path.join(ws, 'config.json')); + const p = { ...policy, protectedPaths: [path.join(ws, 'config.json')] }; + expect(await code(prepWrite('config.json', 'overwritten', p))).toBe('protected-path'); + expect(readFileSync(path.join(ws, 'f'), 'utf8')).toBe('old'); + }); + + it('refuses writing through a final-component link even inside the workspace', async () => { + writeFileSync(path.join(ws, 'target.txt'), 'old'); + symlinkSync(path.join(ws, 'target.txt'), path.join(ws, 'alias.txt')); + expect(await code(prepWrite('alias.txt', 'new'))).toBe('invalid-args'); + expect(await code(rt.prepare({ id: 'e', tool: 'edit', args: { path: 'alias.txt', oldString: 'old', newString: 'new' } }, ctx, policy))).toBe('invalid-args'); + expect(readFileSync(path.join(ws, 'target.txt'), 'utf8')).toBe('old'); + }); +}); + +describe('4. abort stops a write that already entered commit', () => { + it('refuses the rename after the signal aborted', async () => { + writeFileSync(path.join(ws, 'f'), 'old'); + const prepared = await prepWrite('f', 'new'); + const ac = new AbortController(); + const work = rt.commit(prepared, ac.signal); + ac.abort(); + expect(await code(work)).toBe('cancelled'); + expect(readFileSync(path.join(ws, 'f'), 'utf8')).toBe('old'); + }); +}); + +describe('5. concurrent commits on one path', () => { + it('lets only the first of two writes prepared against the same content succeed', async () => { + writeFileSync(path.join(ws, 'f'), 'old'); + const a = await prepWrite('f', 'first'); + const b = await prepWrite('f', 'second'); + class SlowTransaction extends FileTransaction { + override async record(...args: Parameters): Promise { + await super.record(...args); + await new Promise((r) => setTimeout(r, 50)); + } + } + const tx = new SlowTransaction(path.join(base, 'state')); + const signal = new AbortController().signal; + const results = await Promise.allSettled([rt.commit(a, signal, tx), rt.commit(b, signal, tx)]); + expect(results.map((r) => r.status)).toEqual(['fulfilled', 'rejected']); + const second = results[1]; + expect(second?.status === 'rejected' && second.reason instanceof ToolError && second.reason.code).toBe('stale'); + expect(readFileSync(path.join(ws, 'f'), 'utf8')).toBe('first'); + await tx.dispose(); + }); +}); + +describe.skipIf(IS_WINDOWS)('6. identity of the file and its directories', () => { + it('refuses a commit when the file was replaced by a hard link with the same content', async () => { + writeFileSync(path.join(ws, 'f'), 'old'); + const prepared = await prepWrite('f', 'new'); + writeFileSync(path.join(ws, 'other'), 'old'); + rmSync(path.join(ws, 'f')); + linkSync(path.join(ws, 'other'), path.join(ws, 'f')); + expect(await code(rt.commit(prepared, new AbortController().signal))).toBe('stale'); + expect(readFileSync(path.join(ws, 'other'), 'utf8')).toBe('old'); + }); + + it('refuses a commit when a parent directory was replaced by another one', async () => { + mkdirSync(path.join(ws, 'd')); + writeFileSync(path.join(ws, 'd', 'f'), 'old'); + const prepared = await prepWrite('d/f', 'new'); + const created = await prepWrite('d/new.txt', 'new'); + renameSync(path.join(ws, 'd'), path.join(ws, 'd-moved')); + mkdirSync(path.join(ws, 'd')); + writeFileSync(path.join(ws, 'd', 'f'), 'old'); + expect(statSync(path.join(ws, 'd')).isDirectory()).toBe(true); + expect(await code(rt.commit(prepared, new AbortController().signal))).toBe('stale'); + expect(await code(rt.commit(created, new AbortController().signal))).toBe('stale'); + expect(readFileSync(path.join(ws, 'd', 'f'), 'utf8')).toBe('old'); + }); +}); + +describe('7. a pathological grep pattern can be stopped', () => { + beforeEach(() => { + writeFileSync(path.join(ws, 'f'), `${'a'.repeat(40)}!\n`); + }); + + it('fails with a ToolError when the per-file budget runs out', async () => { + const budgeted = new NodeToolRuntime({ stateDir: path.join(base, 'state'), grepFileBudgetMs: 200 }); + const prepared = await budgeted.prepare({ id: 'g', tool: 'grep', args: { pattern: '(a+)+$' } }, ctx, policy); + const started = Date.now(); + const err = await budgeted.commit(prepared, new AbortController().signal).then( + () => undefined, + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(ToolError); + expect(String(err)).toMatch(/too expensive/); + expect(Date.now() - started).toBeLessThan(5000); + }); + + it('stops on abort', async () => { + const prepared = await rt.prepare({ id: 'g', tool: 'grep', args: { pattern: '(a+)+$' } }, ctx, policy); + const ac = new AbortController(); + setTimeout(() => ac.abort(), 50); + const started = Date.now(); + expect(await code(rt.commit(prepared, ac.signal))).toBe('cancelled'); + expect(Date.now() - started).toBeLessThan(5000); + }); +}); + +describe.skipIf(IS_WINDOWS)('8. path oracle: accepted iff the real path is inside the roots', () => { + it('agrees with the operating system on links followed by ..', async () => { + mkdirSync(path.join(outside, 'sub')); + mkdirSync(path.join(ws, 'dir')); + writeFileSync(path.join(ws, 'f'), 'inside'); + writeFileSync(path.join(outside, 'f'), 'outside'); + writeFileSync(path.join(outside, 'sub', 'f'), 'outside sub'); + symlinkSync(path.join(outside, 'sub'), path.join(ws, 'link')); + symlinkSync(path.join(ws, 'dir'), path.join(ws, 'inlink')); + symlinkSync('../outside/sub', path.join(ws, 'rel-link')); + const parts = ['f', '.', '..', 'link', 'inlink', 'rel-link', 'dir', 'sub', 'ws', 'outside']; + let seed = 1234; + let checked = 0; + for (let i = 0; i < 400; i++) { + const n = 1 + (i % 5); + const comps: string[] = []; + for (let k = 0; k < n; k++) { + seed = (1664525 * seed + 1013904223) >>> 0; + comps.push(parts[seed % parts.length] ?? 'f'); + } + comps.push('f'); + const input = comps.join('/'); + let real: string | null; + try { + // Native realpath resolves components in order, as the kernel does. + real = await fsp.realpath(`${ws}/${input}`); + } catch { + real = null; + } + if (real === null) continue; // the OS cannot open it; the jail may refuse it any way it likes + checked++; + const inside = real === ws || real.startsWith(`${ws}${path.sep}`); + let prepared: PreparedCall | undefined; + try { + prepared = await rt.prepare({ id: `o${i}`, tool: 'read', args: { path: input } }, ctx, policy); + } catch { + prepared = undefined; + } + expect({ input, accepted: prepared !== undefined }).toEqual({ input, accepted: inside }); + if (prepared?.tool === 'read') expect({ input, abs: prepared.effect.absPath }).toEqual({ input, abs: real }); + } + expect(checked).toBeGreaterThan(30); + }); +}); diff --git a/src/tools/jail.ts b/src/tools/jail.ts index 7d3a64d..fcd3cfb 100644 --- a/src/tools/jail.ts +++ b/src/tools/jail.ts @@ -1,5 +1,5 @@ /* - * `realpathWithSuffix`, `isInsideDir` and `windowsPathProblem` are adapted + * `isInsideDir` and `windowsPathProblem` are adapted * from Turnpack's src/security.ts (https://github.com/OnlyTerp/turnpack, * Copyright 2026 OnlyTerp, licensed under the Apache License, Version 2.0: * http://www.apache.org/licenses/LICENSE-2.0). @@ -16,11 +16,9 @@ import { DEFAULT_CASE_INSENSITIVE, findMatchingPattern } from '../core/paths.js' * Workspace jail: every path a tool touches is resolved to an absolute real * path and must live under one of the allowed roots. * - * Resolution follows Turnpack's `realpathWithSuffix`: the deepest part of the - * path that exists is found with `lstat` (not `exists`, which follows links - * and would call a dangling symlink "missing"), resolved with `realpath`, and - * the missing rest is joined back. A dangling link is followed by hand so the - * boundary check sees where a write would really land. + * Resolution walks the path one component at a time with `lstat` and follows + * each link by hand (`resolvePhysical`), so a dangling link and `link/..` are + * judged by where the operating system would really land. */ const MAX_LINK_HOPS = 40; @@ -42,30 +40,103 @@ async function lstatOrNull(p: string): Promise { } } -/** Real path of `target`, which may not exist yet. */ -export async function realpathWithSuffix(target: string, hops = 0): Promise { - if (hops > MAX_LINK_HOPS) throw new ToolError('outside-workspace', `too many symbolic links while resolving ${target}`); - let cursor = path.resolve(target); - const trailing: string[] = []; - let stat = await lstatOrNull(cursor); - while (!stat) { - const parent = path.dirname(cursor); - if (parent === cursor) throw new ToolError('outside-workspace', `no existing ancestor for ${target}`); - trailing.push(path.basename(cursor)); - cursor = parent; - stat = await lstatOrNull(cursor); +/** What resolving a path found. */ +export interface Resolution { + /** Absolute real path (the missing tail, if any, joined to the deepest existing real directory). */ + readonly real: string; + /** Absolute locations of every symbolic link followed on the way, in order. */ + readonly links: readonly string[]; + /** True when the path's own last component is a symbolic link. */ + readonly finalIsLink: boolean; +} + +function splitComponents(p: string): string[] { + return p.split(IS_WINDOWS ? /[\\/]+/ : /\/+/); +} + +function stripVerbatim(target: string): string { + return IS_WINDOWS && target.startsWith('\\\\?\\') ? target.slice(4) : target; +} + +/** + * Resolves `input` (absolute, or relative to the real directory `base`) + * component by component with POSIX semantics: a symbolic link is replaced + * by its target before the next component is looked at, so `link/..` is the + * parent of the link's target, not the directory holding the link. Nothing + * is normalized lexically first. A `..` after a component that does not + * exist is refused, as the operating system would refuse it. + */ +export async function resolvePhysical(input: string, base: string): Promise { + let current: string; + let rest: string; + if (path.isAbsolute(input)) { + const root = path.parse(input).root; + current = path.resolve(root); + rest = input.slice(root.length); + } else { + current = base; + rest = input; + } + const queue = splitComponents(rest); + const links: string[] = []; + const meaningful = (q: readonly string[]): boolean => q.some((c) => c !== '' && c !== '.'); + let hops = 0; + let missing = false; + let finalIsLink = false; + while (queue.length > 0) { + const c = queue.shift() ?? ''; + if (c === '' || c === '.') continue; + if (c === '..') { + if (missing) throw new ToolError('not-found', `${input}: ".." after a component that does not exist`); + current = path.dirname(current); + continue; + } + const next = path.join(current, c); + if (missing) { + current = next; + continue; + } + const st = await lstatOrNull(next); + if (!st) { + missing = true; + current = next; + continue; + } + if (st.isSymbolicLink()) { + if (++hops > MAX_LINK_HOPS) throw new ToolError('outside-workspace', `${input}: too many symbolic links`); + links.push(next); + if (!meaningful(queue)) finalIsLink = true; + const target = stripVerbatim(await fs.readlink(next)); + if (path.isAbsolute(target)) { + const root = path.parse(target).root; + current = path.resolve(root); + queue.unshift(...splitComponents(target.slice(root.length))); + } else { + queue.unshift(...splitComponents(target)); + } + continue; + } + if (!st.isDirectory() && meaningful(queue)) { + throw new ToolError('not-found', `${input}: ${next} is not a directory`); + } + current = next; } - let realBase: string; + // Canonical spelling (case, Windows short names) of the existing part. + let existing = current; + const tail: string[] = []; + while (!(await lstatOrNull(existing))) { + const parent = path.dirname(existing); + if (parent === existing) break; + tail.unshift(path.basename(existing)); + existing = parent; + } + let realExisting = existing; try { - realBase = await fs.realpath(cursor); - } catch (err) { - if (!stat.isSymbolicLink()) throw err; - // Dangling link: follow it by hand so the check sees its destination. - const linkTarget = await fs.readlink(cursor); - const parentReal = await fs.realpath(path.dirname(cursor)); - realBase = await realpathWithSuffix(path.resolve(parentReal, linkTarget), hops + 1); + realExisting = await fs.realpath(existing); + } catch { + // Dangling final link target: keep the spelling. } - return trailing.length === 0 ? realBase : path.resolve(realBase, ...trailing.reverse()); + return { real: tail.length === 0 ? realExisting : path.join(realExisting, ...tail), links, finalIsLink }; } /** True when `target` is `base` or below it. Both must be real absolute paths. */ @@ -209,6 +280,25 @@ export class Jail { * absolute real path inside the roots, or throws `ToolError`. */ async resolve(input: string): Promise { + return (await this.#resolve(input)).real; + } + + /** + * Like `resolve`, for a write or an edit: also refuses a path whose last + * component is a symbolic link (write to its target instead), and refuses a + * protected path whether it is named by the real path or by any link the + * resolution went through. + */ + async resolveForWrite(input: string): Promise { + const r = await this.#resolve(input); + for (const p of [r.real, ...r.links]) this.assertWritable(p); + if (r.finalIsLink) { + throw new ToolError('invalid-args', `${input} is a symbolic link; write to its target (${r.real}) instead`); + } + return r.real; + } + + async #resolve(input: string): Promise { if (input.includes('\0')) throw new ToolError('invalid-args', 'path must not contain NUL characters'); const trimmed = input.trim(); if (trimmed === '') throw new ToolError('invalid-args', 'path must not be empty'); @@ -217,10 +307,9 @@ export class Jail { if (problem) throw new ToolError('outside-workspace', `${trimmed}: ${problem}`); } const expanded = expandTilde(trimmed); - const candidate = path.isAbsolute(expanded) ? path.resolve(expanded) : path.resolve(this.cwd, expanded); - let real: string; + let r: Resolution; try { - real = await realpathWithSuffix(candidate); + r = await resolvePhysical(expanded, this.cwd); } catch (err) { if (err instanceof ToolError) throw err; const code = errnoCode(err); @@ -228,14 +317,14 @@ export class Jail { if (code === 'ELOOP') throw new ToolError('outside-workspace', `${trimmed}: too many symbolic links`); throw new ToolError('tool-error', `cannot resolve ${trimmed}: ${code ?? String(err)}`); } - if (this.rootOf(real) === undefined) { - throw new ToolError('outside-workspace', `${trimmed} resolves to ${real}, outside the workspace (${this.roots.join(', ')})`); + if (this.rootOf(r.real) === undefined) { + throw new ToolError('outside-workspace', `${trimmed} resolves to ${r.real}, outside the workspace (${this.roots.join(', ')})`); } if (this.#windowsChecks) { - const problem = windowsPathProblem(real); + const problem = windowsPathProblem(r.real); if (problem) throw new ToolError('outside-workspace', `${trimmed}: ${problem}`); } - return real; + return r; } /** Throws `protected-path` when `abs` must not be written or edited. */ diff --git a/src/tools/journal.ts b/src/tools/journal.ts index 0798d0d..bd2e793 100644 --- a/src/tools/journal.ts +++ b/src/tools/journal.ts @@ -14,7 +14,18 @@ import path from 'node:path'; import { z } from 'zod'; import { ToolError, errorMessage } from '../core/errors.js'; import type { RollbackReport, Transaction } from '../core/types.js'; -import { assertDirUnchanged, atomicWrite, errnoCode, readRegularFile, removeRegularFile, sha256, syncDir, writeDurable } from './fs-ops.js'; +import { + type RegularFile, + assertDirUnchanged, + atomicWrite, + errnoCode, + readRegularFile, + removeEmptyDirInside, + removeRegularFile, + sha256, + syncDir, + writeDurable, +} from './fs-ops.js'; import { isInsideDir, isInsideGitDir } from './jail.js'; /** Above this many bytes of originals a transaction refuses further writes. */ @@ -192,9 +203,7 @@ export class FileTransaction implements Transaction { for (const live of [...this.#entries.values()].reverse()) { const { entry } = live; try { - const current = await readRegularFile(entry.path).catch((err: unknown) => { - throw new ToolError('stale', `cannot read: ${errorMessage(err)}`); - }); + const current = await currentContent(entry.path); const currentHash = current ? sha256(current.bytes) : null; const originalHash = entry.existed ? entry.original : null; if (currentHash === originalHash) continue; @@ -208,7 +217,7 @@ export class FileTransaction implements Transaction { skipped.push({ path: entry.path, reason: 'error', detail: errorMessage(err) }); } } - await removeCreatedDirs(this.#dirs); + await removeCreatedDirs(this.#dirs, this.#roots); await this.#removeRecord(); return { restored, skipped }; }); @@ -229,27 +238,32 @@ export class FileTransaction implements Transaction { } } +/** + * Content at `abs`, read only through real directories: null when the file + * (or its directory) is gone; `stale` when its directory now resolves + * elsewhere (a link was swapped in), so nothing outside is read or touched. + */ +async function currentContent(abs: string): Promise { + const parent = await fs.lstat(path.dirname(abs)).catch(() => null); + if (!parent) return null; + await assertDirUnchanged(path.dirname(abs)); + return readRegularFile(abs); +} + async function restoreEntry(entry: Entry, bytes: Buffer | null, currentHash: string | null): Promise { if (isInsideGitDir(entry.path)) throw new ToolError('protected-path', 'inside a .git directory'); if (!entry.existed) { - await assertDirUnchanged(path.dirname(entry.path)); - await removeRegularFile(entry.path); + if (currentHash !== null) await removeRegularFile(entry.path, currentHash); return; } if (bytes === null || sha256(bytes) !== entry.original) throw new ToolError('tool-error', 'the saved original is damaged'); const expect = currentHash === null ? ({ kind: 'absent' } as const) : ({ kind: 'hash', sha256: currentHash } as const); - await atomicWrite(entry.path, bytes, expect); - if (entry.mode !== null && process.platform !== 'win32') await fs.chmod(entry.path, entry.mode).catch(() => undefined); + await atomicWrite(entry.path, bytes, expect, entry.mode !== null ? { mode: entry.mode } : {}); } -async function removeCreatedDirs(dirs: readonly string[]): Promise { - for (const d of [...dirs].sort((a, b) => b.length - a.length)) { - try { - await fs.rmdir(d); - } catch { - // Not empty, or already gone. - } - } +/** Removes created directories that are empty, real and strictly inside `roots`, deepest first. */ +async function removeCreatedDirs(dirs: readonly string[], roots: readonly string[]): Promise { + for (const d of [...dirs].sort((a, b) => b.length - a.length)) await removeEmptyDirInside(d, roots); } // --------------------------------------------------------------------------- @@ -308,11 +322,7 @@ async function undoRecord(manifest: Manifest, dir: string, roots: readonly strin skipped.push({ path: entry.path, reason: 'error', detail: 'outside the roots the journal was written for; not touched' }); continue; } - await assertDirUnchanged(path.dirname(entry.path)).catch((err: unknown) => { - // A parent that no longer exists is fine for a created file that is gone too. - if (entry.existed) throw err; - }); - const current = await readRegularFile(entry.path); + const current = await currentContent(entry.path); const currentHash = current ? sha256(current.bytes) : null; const originalHash = entry.existed ? entry.original : null; if (currentHash === originalHash) continue; @@ -327,8 +337,9 @@ async function undoRecord(manifest: Manifest, dir: string, roots: readonly strin skipped.push({ path: entry.path, reason: 'error', detail: errorMessage(err) }); } } - const dirs = manifest.dirs.filter((d) => path.isAbsolute(d) && roots.some((root) => isInsideDir(root, d) && root !== d)); - await removeCreatedDirs(dirs); + // Only directories inside both the given roots and the roots the journal was written for. + const dirs = manifest.dirs.filter((d) => manifest.roots.some((root) => isInsideDir(root, d))); + await removeCreatedDirs(dirs, roots); return { restored, skipped }; } diff --git a/src/tools/runtime.test.ts b/src/tools/runtime.test.ts index f21deff..95cb68d 100644 --- a/src/tools/runtime.test.ts +++ b/src/tools/runtime.test.ts @@ -91,7 +91,9 @@ afterEach(() => { describe('path traversal', () => { it('refuses ../, absolute paths outside and ~', async () => { - for (const p of ['../outside/secret.txt', `${outside}/secret.txt`, 'a/../../outside/new.txt', '~/acm-must-not-exist.txt', '~']) { + // `..` after a missing component fails as the operating system would. + expect(await code(prep('write', { path: 'a/../../outside/new.txt', content: 'x' }))).toBe('not-found'); + for (const p of ['../outside/secret.txt', `${outside}/secret.txt`, '~/acm-must-not-exist.txt', '~']) { expect(await code(prep('read', { path: p }))).toBe('outside-workspace'); expect(await code(prep('write', { path: p, content: 'x' }))).toBe('outside-workspace'); expect(await code(prep('edit', { path: p, oldString: 'secret', newString: 'x' }))).toBe('outside-workspace'); diff --git a/src/tools/runtime.ts b/src/tools/runtime.ts index 5137fbe..ca7b379 100644 --- a/src/tools/runtime.ts +++ b/src/tools/runtime.ts @@ -17,7 +17,7 @@ import type { import { DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS, findBash, runBash, shellQuote } from './bash.js'; import { binaryDiff, unifiedDiff } from './diff.js'; import { applySearchReplace, type MatchHow } from './edit-match.js'; -import { assertDirUnchanged, atomicWrite, decodeText, errnoCode, isBinary, readRegularFile, sha256 } from './fs-ops.js'; +import { type PathIdentity, type RegularFile, assertDirUnchanged, atomicWrite, captureIdentity, decodeText, errnoCode, isBinary, readRegularFile, sha256 } from './fs-ops.js'; import { FileTransaction } from './journal.js'; import { Jail } from './jail.js'; import { containmentUnavailableReason } from './sandbox.js'; @@ -50,6 +50,8 @@ export interface NodeToolRuntimeOptions { readonly additionalRoots?: readonly string[]; /** Bytes kept of each of bash stdout and stderr. */ readonly bashOutputCapBytes?: number; + /** Time the grep regular expression may run on one file before grep fails. */ + readonly grepFileBudgetMs?: number; } /** What `commit` needs to know about a call besides its frozen effect. */ @@ -60,6 +62,8 @@ interface CallMeta { readonly display: string; /** Paths a sandboxed bash may never write. */ readonly denyWrite: readonly string[]; + /** For write and edit: identity of the file and its directories at prepare. */ + readonly identity?: PathIdentity; } /** @@ -175,9 +179,8 @@ export class NodeToolRuntime implements ToolRuntime { return prepared; } case 'write': { - const absPath = await jail.resolve(call.args.path); - jail.assertWritable(absPath); - const m = meta(absPath); + const absPath = await jail.resolveForWrite(call.args.path); + const m = { ...meta(absPath), identity: await captureIdentity(absPath, jail.rootOf(absPath) ?? jail.cwd) }; const current = await this.#readExisting(absPath); const diff = current !== null && isBinary(current.bytes) @@ -198,9 +201,8 @@ export class NodeToolRuntime implements ToolRuntime { return prepared; } case 'edit': { - const absPath = await jail.resolve(call.args.path); - jail.assertWritable(absPath); - const m = meta(absPath); + const absPath = await jail.resolveForWrite(call.args.path); + const m = { ...meta(absPath), identity: await captureIdentity(absPath, jail.rootOf(absPath) ?? jail.cwd) }; const current = await this.#readExisting(absPath); if (current === null) throw new ToolError('not-found', `${m.display} does not exist`); const text = decodeText(m.display, current.bytes); @@ -305,10 +307,10 @@ export class NodeToolRuntime implements ToolRuntime { return this.#commitRead(prepared); case 'write': case 'edit': - return this.#commitWrite(prepared, tx); + return this.#commitWrite(prepared, signal, tx); case 'grep': { await assertDirUnchanged(prepared.effect.absRoot); - return runGrep(prepared.effect, this.#metaOf(prepared, prepared.effect.absRoot).root, signal); + return runGrep(prepared.effect, this.#metaOf(prepared, prepared.effect.absRoot).root, signal, this.#opts.grepFileBudgetMs); } case 'glob': { await assertDirUnchanged(prepared.effect.absRoot); @@ -342,20 +344,24 @@ export class NodeToolRuntime implements ToolRuntime { return { path: absPath, content: window.join('\n'), startLine: offset, totalLines: lines.length, truncated }; } - async #commitWrite(prepared: PreparedCallOf<'write'> | PreparedCallOf<'edit'>, tx: Transaction | undefined): Promise { + async #commitWrite( + prepared: PreparedCallOf<'write'> | PreparedCallOf<'edit'>, + signal: AbortSignal, + tx: Transaction | undefined, + ): Promise { if (tx !== undefined && !(tx instanceof FileTransaction)) { throw new ToolError('tool-error', 'the transaction was not started by this tool runtime; refusing to write without a journal'); } const { absPath, beforeHash, afterContent } = prepared.effect; - const m = this.#metaOf(prepared, absPath); + const m = this.#meta.get(prepared); + if (m?.identity === undefined) throw new ToolError('tool-error', 'this write was not prepared by this tool runtime'); const bytes = Buffer.from(afterContent, 'utf8'); const nextHash = sha256(bytes); - const outcome = await atomicWrite( - absPath, - bytes, - beforeHash === null ? { kind: 'absent' } : { kind: 'hash', sha256: beforeHash }, - tx ? (before, createdDirs) => tx.record(absPath, m.root, before, nextHash, createdDirs) : undefined, - ); + const outcome = await atomicWrite(absPath, bytes, beforeHash === null ? { kind: 'absent' } : { kind: 'hash', sha256: beforeHash }, { + signal, + identity: m.identity, + ...(tx ? { beforeWrite: (before: RegularFile | null, createdDirs: readonly string[]) => tx.record(absPath, m.root, before, nextHash, createdDirs) } : {}), + }); tx?.written(absPath, nextHash); if (prepared.tool === 'write') return { path: absPath, created: outcome.before === null, diff: prepared.effect.diff }; return { diff --git a/src/tools/search.ts b/src/tools/search.ts index 7208018..684a56a 100644 --- a/src/tools/search.ts +++ b/src/tools/search.ts @@ -1,8 +1,11 @@ import { constants as FS } from 'node:fs'; +import { Worker } from 'node:worker_threads'; +import { z } from 'zod'; import fs from 'node:fs/promises'; import path from 'node:path'; import { ToolError } from '../core/errors.js'; import { DEFAULT_CASE_INSENSITIVE, matchesPathPattern } from '../core/paths.js'; +import { readFileInside } from './fs-ops.js'; import type { GlobEffect, GlobResult, GrepEffect, GrepMatch, GrepResult } from '../core/types.js'; /** Default `grep` result count. */ @@ -167,6 +170,13 @@ async function ancestorLayers(top: string, dir: string): Promise // Walking // --------------------------------------------------------------------------- +async function isRealDir(dir: string): Promise { + const st = await fs.lstat(dir).catch(() => null); + if (!st || st.isSymbolicLink() || !st.isDirectory()) return false; + const real = await fs.realpath(dir).catch(() => null); + return real !== null && (process.platform === 'win32' ? real.toLowerCase() === dir.toLowerCase() : real === dir); +} + /** * Lists regular files below `absRoot` (real path, inside the jail), sorted, * skipping `.git`, `node_modules` and gitignored entries. Symbolic links are @@ -192,6 +202,9 @@ async function* walkFiles(absRoot: string, jailRoot: string, signal: AbortSignal } catch { continue; } + // A directory swapped for a link while it was listed is skipped whole: + // its names may come from outside the workspace. + if (!(await isRealDir(dir))) continue; const own = dir === absRoot ? null : await loadIgnore(dir); const here = own ? [...layers, own] : layers; entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); @@ -287,41 +300,123 @@ function matchesFileGlob(rel: string, globs: readonly string[]): boolean { return globs.some((g) => (g.includes('/') ? matchesPathPattern(rel, g) : matchesPathPattern(base, g))); } -export async function runGrep(effect: GrepEffect, jailRoot: string, signal: AbortSignal): Promise { - const re = compileGrep(effect.pattern, effect.ignoreCase); +/** + * Matches lines in a worker thread, so a pathological pattern (catastrophic + * backtracking) can be stopped: each file gets a time budget, and an abort + * terminates the worker at once. + */ +const MATCH_WORKER_SOURCE = ` +const { parentPort, workerData } = require('node:worker_threads'); +const re = new RegExp(workerData.pattern, workerData.flags); +parentPort.on('message', (m) => { + const lines = m.text.split('\\n'); + const hits = []; + let more = false; + for (let i = 0; i < lines.length; i++) { + let t = lines[i]; + if (t.endsWith('\\r')) t = t.slice(0, -1); + if (i === lines.length - 1 && t === '') break; + if (!re.test(t)) continue; + if (hits.length >= m.room) { more = true; break; } + hits.push([i + 1, t.length > m.lineMax ? t.slice(0, m.lineMax) + '\\u2026' : t]); + } + parentPort.postMessage({ hits, more }); +}); +`; + +const HitsSchema = z.object({ hits: z.array(z.tuple([z.number().int(), z.string()])), more: z.boolean() }); +type Hits = z.infer; + +class MatchWorker { + readonly #worker: Worker; + #dead = false; + + constructor(pattern: string, flags: string) { + this.#worker = new Worker(MATCH_WORKER_SOURCE, { + eval: true, + workerData: { pattern, flags }, + resourceLimits: { maxOldGenerationSizeMb: 256 }, + }); + this.#worker.once('exit', () => (this.#dead = true)); + } + + match(file: string, text: string, room: number, budgetMs: number, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (this.#dead) return reject(new ToolError('tool-error', 'grep worker stopped')); + const done = (): void => { + clearTimeout(timer); + signal.removeEventListener('abort', onAbort); + this.#worker.off('message', onMessage); + this.#worker.off('error', onError); + }; + const onMessage = (msg: unknown): void => { + done(); + const parsed = HitsSchema.safeParse(msg); + if (parsed.success) resolve(parsed.data); + else reject(new ToolError('tool-error', 'grep worker returned an invalid reply')); + }; + const onError = (err: Error): void => { + done(); + reject(new ToolError('tool-error', `grep failed on ${file}: ${err.message}`)); + }; + const onAbort = (): void => { + done(); + this.close(); + reject(new ToolError('cancelled', 'grep was stopped because the run stopped')); + }; + const timer = setTimeout(() => { + done(); + this.close(); + reject( + new ToolError( + 'tool-error', + `grep pattern ran for more than ${budgetMs} ms on ${file} and was stopped; the regular expression is too expensive (catastrophic backtracking?)`, + ), + ); + }, budgetMs); + if (signal.aborted) return onAbort(); + signal.addEventListener('abort', onAbort, { once: true }); + this.#worker.on('message', onMessage); + this.#worker.once('error', onError); + this.#worker.postMessage({ text, room, lineMax: MAX_LINE_CHARS }); + }); + } + + close(): void { + this.#dead = true; + void this.#worker.terminate(); + } +} + +/** Default time budget of the regex on one file. */ +export const DEFAULT_GREP_FILE_BUDGET_MS = 10_000; + +export async function runGrep( + effect: GrepEffect, + jailRoot: string, + signal: AbortSignal, + fileBudgetMs: number = DEFAULT_GREP_FILE_BUDGET_MS, +): Promise { + compileGrep(effect.pattern, effect.ignoreCase); const globs = effect.glob === null ? null : expandBraces(effect.glob.replace(/\\/g, '/')); const matches: GrepMatch[] = []; - let truncated = false; - for await (const file of walkFiles(effect.absRoot, jailRoot, signal)) { - if (globs && file !== effect.absRoot && !matchesFileGlob(toRel(effect.absRoot, file), globs)) continue; - let bytes: Buffer; - try { - const handle = await fs.open(file, FS.O_RDONLY | (FS.O_NOFOLLOW ?? 0)); - try { - const st = await handle.stat(); - if (!st.isFile() || st.size > MAX_GREP_FILE_BYTES) continue; - bytes = await handle.readFile(); - } finally { - await handle.close(); - } - } catch { - continue; - } - if (bytes.subarray(0, 8192).includes(0)) continue; - const lines = bytes.toString('utf8').split('\n'); - for (let i = 0; i < lines.length; i++) { - let text = lines[i] ?? ''; - if (text.endsWith('\r')) text = text.slice(0, -1); - if (i === lines.length - 1 && text === '') break; - if (!re.test(text)) continue; - if (matches.length >= effect.maxResults) { - truncated = true; - return { matches, truncated }; - } - matches.push({ file, line: i + 1, text: text.length > MAX_LINE_CHARS ? `${text.slice(0, MAX_LINE_CHARS)}…` : text }); + const worker = new MatchWorker(effect.pattern, effect.ignoreCase ? 'i' : ''); + try { + for await (const file of walkFiles(effect.absRoot, jailRoot, signal)) { + if (globs && file !== effect.absRoot && !matchesFileGlob(toRel(effect.absRoot, file), globs)) continue; + // Opened without following links and checked to be the file at this path, + // so a directory swapped for a link mid-walk cannot lead outside. + const bytes = await readFileInside(file, MAX_GREP_FILE_BYTES); + if (bytes === null || bytes.subarray(0, 8192).includes(0)) continue; + const room = effect.maxResults - matches.length; + const found = await worker.match(file, bytes.toString('utf8'), room, fileBudgetMs, signal); + for (const [line, text] of found.hits) matches.push({ file, line, text }); + if (found.more) return { matches, truncated: true }; } + } finally { + worker.close(); } - return { matches, truncated }; + return { matches, truncated: false }; } export async function runGlob(effect: GlobEffect, jailRoot: string, signal: AbortSignal): Promise { From 9a1789d1830869cb73f7c900991974b1cc6eaee1 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:49:36 -0300 Subject: [PATCH 07/17] Let the kernel decide whether an oracle path resolves macOS realpath(3) accepts `file/..` that open(2) refuses. Co-Authored-By: Claude Opus 5.5 --- src/tools/hardening.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/tools/hardening.test.ts b/src/tools/hardening.test.ts index 1adcf3b..d6c6e0e 100644 --- a/src/tools/hardening.test.ts +++ b/src/tools/hardening.test.ts @@ -241,7 +241,9 @@ describe.skipIf(IS_WINDOWS)('8. path oracle: accepted iff the real path is insid const input = comps.join('/'); let real: string | null; try { - // Native realpath resolves components in order, as the kernel does. + // The kernel decides whether the path resolves (macOS realpath(3) alone + // accepts `file/..`); native realpath then gives where it lands. + await fsp.stat(`${ws}/${input}`); real = await fsp.realpath(`${ws}/${input}`); } catch { real = null; From 28f276be85a5cc9b7bb951445311623b142b865a Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:51:52 -0300 Subject: [PATCH 08/17] Key prepare metadata by content, not by object identity The dispatcher now commits a frozen structured clone of the prepared call, so metadata kept by object identity was lost and every write was refused. It is now kept in a bounded map keyed by a digest of the call's id, tool and effect, and taken out at commit, so a prepared write commits once. Co-Authored-By: Claude Opus 5.5 --- src/tools/hardening.test.ts | 10 +++++++ src/tools/runtime.ts | 57 ++++++++++++++++++++++++++++++------- 2 files changed, 57 insertions(+), 10 deletions(-) diff --git a/src/tools/hardening.test.ts b/src/tools/hardening.test.ts index d6c6e0e..3961252 100644 --- a/src/tools/hardening.test.ts +++ b/src/tools/hardening.test.ts @@ -263,3 +263,13 @@ describe.skipIf(IS_WINDOWS)('8. path oracle: accepted iff the real path is insid expect(checked).toBeGreaterThan(30); }); }); + +describe('commit works on the copy the dispatcher hands it', () => { + it('commits a structured clone of the prepared call once', async () => { + writeFileSync(path.join(ws, 'f'), 'old'); + const copy = structuredClone(await prepWrite('f', 'new')); + await rt.commit(copy, new AbortController().signal); + expect(readFileSync(path.join(ws, 'f'), 'utf8')).toBe('new'); + expect(await code(rt.commit(structuredClone(copy), new AbortController().signal))).toBe('tool-error'); + }); +}); diff --git a/src/tools/runtime.ts b/src/tools/runtime.ts index ca7b379..bbcca54 100644 --- a/src/tools/runtime.ts +++ b/src/tools/runtime.ts @@ -66,6 +66,35 @@ interface CallMeta { readonly identity?: PathIdentity; } +/** Most prepared calls whose metadata is kept while they wait for commit. */ +const MAX_PENDING_META = 4096; + +function metaKey(prepared: PreparedCall): string { + return sha256(JSON.stringify([prepared.id, prepared.tool, prepared.effect])); +} + +class MetaStore { + readonly #map = new Map(); + + put(prepared: PreparedCall, meta: CallMeta): void { + const key = metaKey(prepared); + this.#map.delete(key); + this.#map.set(key, meta); + while (this.#map.size > MAX_PENDING_META) { + const oldest = this.#map.keys().next(); + if (oldest.done === true) break; + this.#map.delete(oldest.value); + } + } + + take(prepared: PreparedCall): CallMeta | undefined { + const key = metaKey(prepared); + const meta = this.#map.get(key); + this.#map.delete(key); + return meta; + } +} + /** * Literal paths from protected patterns that the OS sandbox can enforce: * patterns without wildcards, and `dir/**` patterns as `dir`. @@ -100,7 +129,13 @@ function assertContainmentShape(c: BashContainment): void { */ export class NodeToolRuntime implements ToolRuntime { readonly #opts: NodeToolRuntimeOptions; - readonly #meta = new WeakMap(); + /** + * What prepare learned about each call, keyed by a digest of the prepared + * call's content: the dispatcher hands commit a frozen copy, not the object + * prepare returned. Taken out at commit; bounded so calls that never commit + * (denied ones) do not accumulate. + */ + readonly #meta = new MetaStore(); constructor(opts: NodeToolRuntimeOptions) { this.#opts = opts; @@ -161,7 +196,7 @@ export class NodeToolRuntime implements ToolRuntime { args: { command, timeoutMs }, effect: { command, cwd: jail.cwd, timeoutMs, containment }, }; - this.#meta.set(prepared, meta(jail.cwd, sandboxDenyWrite(jail.protectedPaths))); + this.#meta.put(prepared, meta(jail.cwd, sandboxDenyWrite(jail.protectedPaths))); return prepared; } case 'read': { @@ -175,7 +210,7 @@ export class NodeToolRuntime implements ToolRuntime { args: { path: absPath, offset, limit }, effect: { absPath, offset, limit }, }; - this.#meta.set(prepared, meta(absPath)); + this.#meta.put(prepared, meta(absPath)); return prepared; } case 'write': { @@ -197,7 +232,7 @@ export class NodeToolRuntime implements ToolRuntime { diff, }, }; - this.#meta.set(prepared, m); + this.#meta.put(prepared, m); return prepared; } case 'edit': { @@ -228,7 +263,7 @@ export class NodeToolRuntime implements ToolRuntime { replacements: outcome.count, }, }; - this.#meta.set(prepared, m); + this.#meta.put(prepared, m); return prepared; } case 'grep': { @@ -244,7 +279,7 @@ export class NodeToolRuntime implements ToolRuntime { maxResults: call.args.maxResults ?? DEFAULT_GREP_MAX_RESULTS, }; const prepared: PreparedCallOf<'grep'> = { id: call.id, tool: 'grep', args: { ...call.args, path: absRoot }, effect }; - this.#meta.set(prepared, meta(absRoot)); + this.#meta.put(prepared, meta(absRoot)); return prepared; } case 'glob': { @@ -254,7 +289,7 @@ export class NodeToolRuntime implements ToolRuntime { normalizeGlob(call.args.pattern, absRoot); const effect = { absRoot, pattern: call.args.pattern, maxResults: call.args.maxResults ?? DEFAULT_GLOB_MAX_RESULTS }; const prepared: PreparedCallOf<'glob'> = { id: call.id, tool: 'glob', args: { ...call.args, path: absRoot }, effect }; - this.#meta.set(prepared, meta(absRoot)); + this.#meta.put(prepared, meta(absRoot)); return prepared; } } @@ -282,7 +317,7 @@ export class NodeToolRuntime implements ToolRuntime { } #metaOf(prepared: PreparedCall, fallbackPath: string): CallMeta { - return this.#meta.get(prepared) ?? { root: path.dirname(fallbackPath), display: fallbackPath, denyWrite: [] }; + return this.#meta.take(prepared) ?? { root: path.dirname(fallbackPath), display: fallbackPath, denyWrite: [] }; } async commit(prepared: PreparedCall, signal: AbortSignal, tx?: Transaction): Promise { @@ -353,8 +388,10 @@ export class NodeToolRuntime implements ToolRuntime { throw new ToolError('tool-error', 'the transaction was not started by this tool runtime; refusing to write without a journal'); } const { absPath, beforeHash, afterContent } = prepared.effect; - const m = this.#meta.get(prepared); - if (m?.identity === undefined) throw new ToolError('tool-error', 'this write was not prepared by this tool runtime'); + const m = this.#meta.take(prepared); + if (m?.identity === undefined) { + throw new ToolError('tool-error', 'this write was not prepared by this tool runtime (or was already committed); prepare it again'); + } const bytes = Buffer.from(afterContent, 'utf8'); const nextHash = sha256(bytes); const outcome = await atomicWrite(absPath, bytes, beforeHash === null ? { kind: 'absent' } : { kind: 'hash', sha256: beforeHash }, { From 2dec0026b650d519f1bb18eb7f214d56335778d0 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:51:20 -0300 Subject: [PATCH 09/17] CI: run once per push and cancel superseded PR runs Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3f03ff8..2acc048 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,8 +2,15 @@ name: CI on: push: + branches: [main] pull_request: +# One run per PR, replaced by the next push. Each push to main gets its own group, because a group +# without cancellation still replaces its pending runs. +concurrency: + group: ${{ github.event_name == 'pull_request' && format('ci-pr-{0}', github.event.pull_request.number) || format('ci-main-{0}', github.run_id) }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + permissions: contents: read From 535304be39cebd3536c5f897832df89d0d073976 Mon Sep 17 00:00:00 2001 From: mths-mcfs Date: Thu, 19 Nov 2026 03:03:03 -0300 Subject: [PATCH 10/17] fix(review): round 1 - Validate adapter decisions with a schema, reject non-string tool names and refresh the call summary after a hook rewrite. - Keep overflow output out of non-private state directories and off Windows. - Match path patterns across newlines and treat "..name" as inside a root. - Run a single deadline from the start of the run, counting policy loading, and give the sandbox the time left rounded up. - Roll back only after queued writes and edits end, report a pending rollback, and dispose the journal after the rollback has really finished. - Make the fake sandbox check its deadline before steps and calls, yield between steps, and tie its deadline and sleeps to one signal. - Describe the placeholder runtime the default server serves, with a runnable example. - Resolve in-memory paths against the session cwd and roots (Windows paths included), track file revisions for rollback, and run grep and glob in a stoppable worker thread. - Accept only a single --host option in serve. - Skip spawning a hook whose run was already cancelled and stop recording calls in the default runtime. Co-Authored-By: Claude Opus 5.5 --- src/cli.ts | 10 +- src/core/command-hook.test.ts | 5 + src/core/command-hook.ts | 13 +- src/core/dispatcher.test.ts | 21 +- src/core/dispatcher.ts | 78 +++---- src/core/output.test.ts | 27 ++- src/core/paths.test.ts | 1 + src/core/paths.ts | 7 +- src/core/run.test.ts | 115 ++++++++++- src/core/run.ts | 60 ++++-- src/core/schemas.ts | 21 +- src/core/state-dir.ts | 10 +- src/server/context.test.ts | 3 + src/server/context.ts | 2 +- src/server/mcp.test.ts | 40 +++- src/server/mcp.ts | 37 +++- src/server/runtime.ts | 5 +- src/testing/fake-sandbox.test.ts | 26 +++ src/testing/fake-sandbox.ts | 48 ++++- src/testing/memory-tool-runtime.test.ts | 61 ++++++ src/testing/memory-tool-runtime.ts | 259 +++++++++++++++++------- src/testing/static-host-adapter.ts | 7 +- 22 files changed, 671 insertions(+), 185 deletions(-) create mode 100644 src/testing/fake-sandbox.test.ts create mode 100644 src/testing/memory-tool-runtime.test.ts diff --git a/src/cli.ts b/src/cli.ts index d02c6dd..5ffcda8 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -28,12 +28,12 @@ function readVersion(): string { 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 [arg, valueAfterFlag] = args; + if (arg === undefined) return undefined; + const value = arg === '--host' && args.length === 2 ? valueAfterFlag : + args.length === 1 && arg.startsWith('--host=') ? arg.slice('--host='.length) : undefined; const parsed = HostSchema.safeParse(value); - return parsed.success ? parsed.data : new Error(`--host must be one of claude, codex, generic`); + return parsed.success ? parsed.data : new Error('serve accepts only one --host option: claude, codex or generic'); } export async function main(argv: readonly string[]): Promise { diff --git a/src/core/command-hook.test.ts b/src/core/command-hook.test.ts index c73798e..b6482a4 100644 --- a/src/core/command-hook.test.ts +++ b/src/core/command-hook.test.ts @@ -92,6 +92,11 @@ describe.skipIf(!posix)('runCommandHook (POSIX)', () => { }); describe('runCommandHook', () => { + it('reports an already-cancelled hook without attempting to start it', async () => { + const r = await runCommandHook({ ...base, cwd: '/definitely/missing/dir', command: 'echo hi', stdin: '', signal: AbortSignal.abort() }); + expect(r).toMatchObject({ aborted: true, exitCode: null, spawnError: null }); + }); + 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(); diff --git a/src/core/command-hook.ts b/src/core/command-hook.ts index 916e1e1..788b1f0 100644 --- a/src/core/command-hook.ts +++ b/src/core/command-hook.ts @@ -98,6 +98,11 @@ function killTree(child: ChildProcess): void { * with its whole process group on timeout or abort. Never rejects. */ export function runCommandHook(opts: CommandHookOptions): Promise { + const noProcess = { + exitCode: null, signal: null, stdout: '', stderr: '', + stdoutTruncated: false, stderrTruncated: false, timedOut: false, + }; + if (opts.signal?.aborted) return Promise.resolve({ ...noProcess, aborted: true, spawnError: null }); const max = opts.maxOutputBytes ?? DEFAULT_HOOK_MAX_OUTPUT_BYTES; const stdout = new Capture(max); const stderr = new Capture(max); @@ -150,13 +155,7 @@ export function runCommandHook(opts: CommandHookOptions): Promise { expect(dispatcher.calls.map((c) => c.decision)).toEqual(['error', 'error', 'error']); }); + it('rejects a non-string binding name', async () => { + const { dispatcher, tools } = await setup(); + const namedObject = { toString: () => 'write' }; + const reply = await dispatcher.dispatch(namedObject, { path: 'notes.txt', content: 'notes' }); + expect(errorOf(reply)).toMatchObject({ code: 'invalid-args' }); + expect(tools.read('notes.txt')).toBeUndefined(); + }); + 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[] = []; @@ -118,11 +126,13 @@ describe('Dispatcher', () => { 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' }), + hook: (p) => (p.tool === 'write' && p.effect.afterContent === 'secret' ? { kind: 'updatedArgs', args: { path: 'redacted.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'); + expect(tools.read('a.txt')).toBeUndefined(); + expect(tools.read('redacted.txt')).toBe('redacted'); + expect(dispatcher.calls[0]).toMatchObject({ decision: 'allowed', summary: 'write redacted.txt' }); // Hooks ran once; static rules ran on both the original and the updated call. expect(adapter.authorized).toHaveLength(1); expect(adapter.staticChecked).toHaveLength(2); @@ -149,6 +159,13 @@ describe('Dispatcher', () => { expect(ruled.tools.commits).toHaveLength(0); }); + it('refuses a hook rewrite with no replacement arguments', async () => { + const { dispatcher, tools } = await setup({ hook: { kind: 'updatedArgs', args: undefined } }); + const reply = await dispatcher.dispatch('write', { path: 'notes.txt', content: 'notes' }); + expect(errorOf(reply)).toMatchObject({ name: 'PermissionDenied', source: 'hook' }); + expect(tools.read('notes.txt')).toBeUndefined(); + }); + it('refuses writes to protected paths even through updatedArgs', async () => { const { dispatcher, tools } = await setup({ protectedPaths: ['/ws/.claude/**'], diff --git a/src/core/dispatcher.ts b/src/core/dispatcher.ts index 400fcce..30a1ecc 100644 --- a/src/core/dispatcher.ts +++ b/src/core/dispatcher.ts @@ -2,7 +2,7 @@ import path from 'node:path'; import { ToolError, errorMessage } from './errors.js'; import { frozenCopy } from './freeze.js'; import { findMatchingPattern } from './paths.js'; -import { isMutating, parseToolCall } from './schemas.js'; +import { DecisionSchema, isMutating, parseToolCall } from './schemas.js'; import type { BashContainment, BindingError, @@ -33,6 +33,8 @@ export interface DispatcherOptions

{ readonly transaction?: Transaction; /** Called once, on the first denied call. A transactional run aborts there. */ readonly onDeny?: (entry: CallLogEntry) => void; + /** Lets a run stop this dispatcher when its deadline has passed. */ + readonly checkDeadline?: () => void; /** Clock, for tests. */ readonly now?: () => number; } @@ -57,7 +59,7 @@ function clip(s: string, max: number): string { } function oneLine(s: string): string { - return s.replace(/\s*\n\s*/g, ' ⏎ '); + return clip(s, MAX_SUMMARY_CHARS).replace(/\s*\n\s*/g, ' ⏎ '); } function containmentEquals(a: BashContainment, b: BashContainment): boolean { @@ -70,18 +72,6 @@ function containmentEquals(a: BashContainment, b: BashContainment): boolean { ); } -/** 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); @@ -129,6 +119,7 @@ export class Dispatcher

{ #stopReason: StopReason | undefined; #nextId = 1; #mutationTail: Promise = Promise.resolve(); + #journalWrite: Promise | undefined; 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 }[] = []; @@ -182,6 +173,11 @@ export class Dispatcher

{ return this.#stopReason; } + /** Settles when the active journaled commit ends. */ + get pendingWrites(): Promise | undefined { + return this.#journalWrite; + } + /** * Handles one binding call from the script. Never rejects. `tool` and * `args` are untrusted. @@ -190,9 +186,9 @@ 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 toolLabel = typeof tool === 'string' ? clip(tool, 40) : 'unknown'; + this.#labels.push({ id, tool: toolLabel, summary: toolLabel }); const started = this.#now(); - const toolLabel = clip(typeof tool === 'string' ? tool : String(tool), 40); let handled: Promise; try { @@ -248,12 +244,17 @@ export class Dispatcher

{ } } + #hasStopped(): boolean { + this.#opts.checkDeadline?.(); + return this.#stopReason !== undefined; + } + #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) { + if (this.#hasStopped()) { return Promise.resolve(this.#fail(slot, id, toolLabel, toolLabel, started, this.#stoppedFailure())); } - const parsed = parseToolCall(typeof tool === 'string' ? tool : String(tool), args, id); + const parsed = parseToolCall(tool, args, id); if (parsed instanceof ToolError) { return Promise.resolve(this.#fail(slot, id, toolLabel, toolLabel, started, { kind: 'error', error: parsed })); } @@ -285,24 +286,25 @@ export class Dispatcher

{ 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()); + if (this.#hasStopped()) 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()); + if (this.#hasStopped()) return fail(this.#stoppedFailure()); const staticFailure = this.#checkStatic(prepared, policy); + if (this.#hasStopped()) return fail(this.#stoppedFailure()); if (staticFailure) return fail(staticFailure); const decision = await this.#authorize(prepared, policy); - if (decision === ABORTED || this.#stopReason !== undefined) return fail(this.#stoppedFailure()); + if (decision === ABORTED || this.#hasStopped()) 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) { + if (Object.hasOwn(decision, 'updatedArgs')) { 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}` }); @@ -315,9 +317,11 @@ export class Dispatcher

{ const recheck = this.#checkStatic(second.prepared, policy); if (recheck) return fail(recheck); prepared = second.prepared; - if (this.#stopReason !== undefined) return fail(this.#stoppedFailure()); + summary = summarize(reparsed, this.#opts.ctx.cwd); + this.#labels[slot] = { id: call.id, tool: call.tool, summary }; } + if (this.#hasStopped()) return fail(this.#stoppedFailure()); return this.#commit(slot, prepared, summary, policy, started); } @@ -349,17 +353,17 @@ export class Dispatcher

{ } #checkStatic(prepared: PreparedCall, policy: PolicySnapshot

): Failure | undefined { - let decision: unknown; try { - decision = this.#opts.adapter.checkStatic(prepared, this.#opts.ctx, policy); + const parsed = DecisionSchema.safeParse(this.#opts.adapter.checkStatic(prepared, this.#opts.ctx, policy)); + if (!parsed.success) return { kind: 'deny', source: 'rule', reason: 'permission rule check returned an invalid decision' }; + const decision = parsed.data; + 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}` }; + } } 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; } @@ -375,8 +379,8 @@ export class Dispatcher

{ 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; + const parsed = DecisionSchema.safeParse(decision); + return parsed.success ? parsed.data : { kind: 'deny', source: 'hook-error', reason: 'hook adapter returned an invalid decision' }; } catch (err) { if (signal.aborted) return ABORTED; return { kind: 'deny', source: 'hook-error', reason: `hook failed: ${errorMessage(err)}` }; @@ -391,9 +395,13 @@ export class Dispatcher

{ started: number, ): Promise { const signal = this.#abort.signal; + const transaction = this.#opts.transaction; + const journaled = transaction !== undefined && (prepared.tool === 'write' || prepared.tool === 'edit'); let result: ToolResult; try { - result = await this.#opts.tools.commit(prepared, signal, this.#opts.transaction); + const pending = this.#opts.tools.commit(prepared, signal, transaction); + if (journaled) this.#journalWrite = pending.then(() => undefined, () => undefined); + result = await pending; } catch (err) { if (signal.aborted) { this.#warnings.push( @@ -402,6 +410,8 @@ export class Dispatcher

{ 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)); + } finally { + if (journaled) this.#journalWrite = undefined; } if (signal.aborted) { @@ -490,7 +500,7 @@ export class Dispatcher

{ /** 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; + return rel !== '' && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel.split(path.sep).join('/') : absPath; } /** Short description of a call for the call log. */ diff --git a/src/core/output.test.ts b/src/core/output.test.ts index 409c2af..29101dc 100644 --- a/src/core/output.test.ts +++ b/src/core/output.test.ts @@ -1,7 +1,8 @@ -import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'; +import { chmod, mkdir, 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 { z } from 'zod'; import { ERROR_CAP_CHARS, SUCCESS_CAP_CHARS, formatRunResult, truncateStructurally } from './output.js'; import { stateDirPath } from './state-dir.js'; import type { RunResult } from './types.js'; @@ -32,15 +33,29 @@ describe('formatRunResult', () => { 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 }; + const preview = z.object({ overflowPath: z.string().optional(), note: z.string(), truncated: z.boolean(), ok: z.boolean() }).parse(JSON.parse(text)); expect(preview.truncated).toBe(true); expect(preview.ok).toBe(true); + if (process.platform === 'win32') { + expect(preview.overflowPath).toBeUndefined(); + expect(preview.note).toContain('private overflow storage is unavailable'); + return; + } + if (preview.overflowPath === undefined) throw new Error('expected an overflow file'); 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); - } + expect((await stat(preview.overflowPath)).mode & 0o777).toBe(0o600); + expect((await stat(stateDir)).mode & 0o777).toBe(0o700); + }); + + it.skipIf(process.platform === 'win32')('keeps oversized results out of a shared directory', async () => { + const stateDir = await tmp(); + await mkdir(stateDir); + await chmod(stateDir, 0o755); + const out = await formatRunResult({ ...base, result: 'x'.repeat(60_000) }, { stateDir }); + expect(JSON.parse(out.content[0]?.text ?? '')).toMatchObject({ truncated: true, note: expect.stringContaining('private directory') }); + expect(JSON.parse(out.content[0]?.text ?? '')).not.toHaveProperty('overflowPath'); + expect((await stat(stateDir)).mode & 0o777).toBe(0o755); }); it('caps error results lower', async () => { diff --git a/src/core/paths.test.ts b/src/core/paths.test.ts index 3f6c479..0e1e354 100644 --- a/src/core/paths.test.ts +++ b/src/core/paths.test.ts @@ -10,6 +10,7 @@ describe('matchesPathPattern', () => { ['/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/week\n1/example.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], diff --git a/src/core/paths.ts b/src/core/paths.ts index 1195022..f75704d 100644 --- a/src/core/paths.ts +++ b/src/core/paths.ts @@ -10,7 +10,8 @@ const cache = new Map(); -function toRegExp(pattern: string, caseInsensitive: boolean): RegExp { +/** The compiled form of a path pattern, e.g. to evaluate it off the main thread. */ +export function pathPatternRegExp(pattern: string, caseInsensitive = DEFAULT_CASE_INSENSITIVE): RegExp { const key = `${caseInsensitive ? 'i' : 's'}:${pattern}`; const hit = cache.get(key); if (hit) return hit; @@ -40,7 +41,7 @@ function toRegExp(pattern: string, caseInsensitive: boolean): RegExp { src += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&'); } } - const re = new RegExp(`^${src}$`, caseInsensitive ? 'i' : ''); + const re = new RegExp(`^${src}$`, caseInsensitive ? 'is' : 's'); cache.set(key, re); return re; } @@ -55,7 +56,7 @@ export const DEFAULT_CASE_INSENSITIVE = process.platform === 'darwin' || process /** 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)); + return pathPatternRegExp(pattern, caseInsensitive).test(normalizeSeparators(path)); } /** The first pattern `path` matches, or undefined. */ diff --git a/src/core/run.test.ts b/src/core/run.test.ts index f147f27..1f9c3f9 100644 --- a/src/core/run.test.ts +++ b/src/core/run.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } 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'; @@ -212,6 +212,119 @@ describe('runScript', () => { expect(result.warnings.join('\n')).toContain('rollback did not finish within 30 ms'); }); + it('rolls back a commit still running after the grace once it has landed', async () => { + const tools = new MemoryToolRuntime({ root: '/ws', commitDelayMs: 60, honorAbortInCommit: false }); + const sandbox: Sandbox = { + run: async (_code, opts) => { + void opts.onCall('write', { path: 'late.txt', content: 'late' }); + await new Promise((r) => setTimeout(r, 5)); + return { ok: false, kind: 'error', error: { name: 'Error', message: 'boom' } }; + }, + }; + const result = await runScript({ code: 'x', transaction: true, timeoutMs: 5_000 }, { ...deps(), tools, sandbox, stopGraceMs: 10 }); + expect(result.error?.kind).toBe('error'); + expect(result.rolledBack).toBeUndefined(); + expect(result.warnings.join('\n')).toContain('the rollback is pending'); + await vi.waitFor(() => expect(tools.commits).toHaveLength(1)); + await vi.waitFor(() => expect(tools.read('late.txt')).toBeUndefined()); + }); + + it.each(['read', 'bash'] as const)('rolls back a finished write without waiting for %s that ignores abort', async (stalled) => { + const d = deps({}, { 'a.txt': 'a' }); + const commit = d.tools.commit.bind(d.tools); + let started = (): void => undefined; + const reached = new Promise((resolve) => { started = resolve; }); + d.tools.commit = (p, signal, tx) => { + if (p.tool !== stalled) return commit(p, signal, tx); + started(); + return new Promise(() => undefined); + }; + const sandbox: Sandbox = { + run: async (_code, opts) => { + await opts.onCall('write', { path: 'b.txt', content: 'b' }); + void opts.onCall(stalled, stalled === 'read' ? { path: 'a.txt' } : { command: 'echo hello' }); + await reached; + void opts.onCall('write', { path: 'c.txt', content: 'c' }); + return { ok: false, kind: 'error', error: { name: 'Error', message: 'boom' } }; + }, + }; + const result = await runScript({ code: 'x', transaction: true, timeoutMs: 5_000 }, { ...d, sandbox, stopGraceMs: 10 }); + expect(result.rolledBack).toBeDefined(); + expect(result.warnings.join('\n')).not.toContain('the rollback is pending'); + expect(d.tools.read('b.txt')).toBeUndefined(); + expect(d.tools.read('c.txt')).toBeUndefined(); + }); + + it('releases the journal only after a rollback that outlived its bound has ended', async () => { + const d = deps(denyForbidden); + const events: string[] = []; + let finishRollback = (): void => undefined; + const gate = new Promise((r) => (finishRollback = r)); + d.tools.beginTransaction = () => ({ + rollback: async () => { + await gate; + events.push('rollback'); + return { restored: [], skipped: [] }; + }, + dispose: async () => { + events.push('dispose'); + }, + }); + const result = await runScript( + { code: script([{ tool: 'write', args: { path: 'forbidden.txt', content: 'x' } }]), transaction: true, timeoutMs: 5_000 }, + { ...d, rollbackTimeoutMs: 10 }, + ); + expect(result.warnings.join('\n')).toContain('rollback did not finish within 10 ms'); + await new Promise((r) => setTimeout(r, 20)); + expect(events).toEqual([]); + finishRollback(); + await vi.waitFor(() => expect(events).toEqual(['rollback', 'dispose'])); + }); + + it('counts policy loading against the deadline and gives the sandbox only the time left', async () => { + let clock = 0; + const budgets: number[] = []; + const sandbox: Sandbox = { + run: async (_code, opts) => { + budgets.push(opts.timeoutMs); + return { ok: true, value: 1 }; + }, + }; + const d = deps({}, {}, sandbox); + const load = d.adapter.loadPolicy.bind(d.adapter); + let loadMs = 300.5; + d.adapter.loadPolicy = (ctx) => { + clock += loadMs; + return load(ctx); + }; + expect(await runScript({ code: 'x', transaction: false, timeoutMs: 1_000 }, { ...d, now: () => clock })).toMatchObject({ ok: true }); + expect(budgets).toEqual([700]); + + clock = 0; + loadMs = 1_000; + const late = await runScript({ code: 'x', transaction: false, timeoutMs: 1_000 }, { ...d, now: () => clock }); + expect(late.error?.kind).toBe('timeout'); + expect(budgets).toEqual([700]); + }); + + it('refuses a commit when authorization completes after the deadline', async () => { + let clock = 0; + const sandbox: Sandbox = { + run: async (_code, opts) => { + await opts.onCall('write', { path: 'notes.txt', content: 'notes' }); + return { ok: true, value: null }; + }, + }; + const d = deps({}, {}, sandbox); + d.adapter.authorize = async () => { + clock = 1_001; + return { kind: 'allow' }; + }; + const result = await runScript({ code: 'x', transaction: false, timeoutMs: 1_000 }, { ...d, now: () => clock }); + expect(result.error?.kind).toBe('timeout'); + expect(d.tools.read('notes.txt')).toBeUndefined(); + }); + 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 eb9a44e..bd57c46 100644 --- a/src/core/run.ts +++ b/src/core/run.ts @@ -41,6 +41,8 @@ export interface RunDeps

{ readonly stopGraceMs?: number; /** Upper bound of a transaction rollback. */ readonly rollbackTimeoutMs?: number; + /** Monotonic clock in ms, for tests. */ + readonly now?: () => number; } type Bounded = { readonly done: true; readonly value: T } | { readonly done: false; readonly why: 'aborted' | 'timeout' }; @@ -88,15 +90,30 @@ function bounded(work: () => Promise, opts: { signal?: AbortSignal; ms?: n }); } -async function rollbackBounded(tx: Transaction, ms: number, warnings: string[]): Promise { +/** + * Rolls back once no write or edit can still land. While some are running, + * the rollback waits for them in the background and a warning says so. + * `done` settles when the rollback has really ended, even past `ms`. + */ +async function rollbackBounded( + tx: Transaction, + writes: Promise | undefined, + ms: number, + warnings: string[], +): Promise<{ readonly report?: RollbackReport; readonly done: Promise }> { + if (writes) { + warnings.push('the rollback is pending: some writes were still running when the run stopped; their files are restored once they end.'); + return { done: writes.then(() => tx.rollback()) }; + } + const done = Promise.resolve().then(() => tx.rollback()); try { - const r = await bounded(() => tx.rollback(), { ms }); - if (r.done) return r.value; + const r = await bounded(() => done, { ms }); + if (r.done) return { report: r.value, done }; 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; + return { done }; } /** Applies defaults and clamps the timeout to `[1, min(maxTimeoutMs, MAX_RUN_TIMEOUT_MS)]`. */ @@ -186,7 +203,10 @@ function runError(stopReason: StopReason | undefined, outcome: SandboxOutcome, d * Never rejects. */ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise { + const now = deps.now ?? (() => performance.now()); const timeoutMs = resolveTimeoutMs(req.timeoutMs, deps.maxTimeoutMs); + // One deadline for the whole run, policy loading included; the grace after it is for stopping and finishing. + const deadline = now() + timeoutMs; const graceMs = deps.stopGraceMs ?? DEFAULT_STOP_GRACE_MS; const logs = new LogCollector(); const controller = new AbortController(); @@ -194,6 +214,8 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise | undefined; let denied: CallLogEntry | undefined; let tx: Transaction | undefined; + /** What must end before the journal is disposed: running writes, then the rollback. */ + let journalBusy: Promise | undefined; const stop = (reason: StopReason): void => { if (stopReason !== undefined) return; @@ -201,14 +223,15 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise { + if (now() >= deadline) stop('timeout'); + }; const onExternalAbort = (): void => stop('cancelled'); deps.signal?.addEventListener('abort', onExternalAbort, { once: true }); if (deps.signal?.aborted) stop('cancelled'); const rollbackMs = deps.rollbackTimeoutMs ?? DEFAULT_ROLLBACK_TIMEOUT_MS; - // Backup deadline for the whole run, policy loading included. The sandbox - // enforces `timeoutMs` itself; this fires only if something does not return. - let timer: NodeJS.Timeout | undefined = setTimeout(() => stop('timeout'), timeoutMs + graceMs); + let timer: NodeJS.Timeout | undefined = setTimeout(() => stop('timeout'), timeoutMs); try { let policy: PolicySnapshot

| PolicyLoadError; try { @@ -217,6 +240,8 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise({ @@ -224,6 +249,7 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise ((denied = entry), stop('denied')) } : {}), }); const active = dispatcher; @@ -236,7 +262,7 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise; try { started = deps.sandbox.run(req.code, { - timeoutMs, + timeoutMs: Math.ceil(leftMs), memoryBytes: deps.memoryBytes ?? DEFAULT_MEMORY_BYTES, signal: controller.signal, onCall: (tool, args) => active.dispatch(tool, args), @@ -246,18 +272,22 @@ 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.`); } @@ -275,8 +305,14 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise(req: RunRequest, deps: RunDeps

): Promise journal.dispose(), { ms: graceMs }).catch(() => undefined); + // Released only after every commit and the rollback have ended; it never holds the result. + void Promise.resolve(journalBusy).catch(() => undefined).then(() => journal.dispose()).catch(() => undefined); } } } diff --git a/src/core/schemas.ts b/src/core/schemas.ts index 248d5cf..b0c21b7 100644 --- a/src/core/schemas.ts +++ b/src/core/schemas.ts @@ -1,6 +1,6 @@ import { z } from 'zod'; import { ToolError } from './errors.js'; -import type { ToolArgsMap, ToolCall, ToolName } from './types.js'; +import type { Decision, ToolArgsMap, ToolCall, ToolName } from './types.js'; /** * Boundary schemas. Everything that crosses into the server (MCP request @@ -28,9 +28,19 @@ export function isMutating(tool: ToolName): boolean { /** Narrows an untrusted string to a `ToolName`. */ export function isToolName(tool: string): tool is ToolName { - return (TOOL_NAMES as readonly string[]).includes(tool); + return TOOL_NAMES.some((name) => name === tool); } +export const DecisionSchema = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('allow'), reason: z.string().optional(), updatedArgs: z.unknown().optional() }), + z.object({ kind: z.literal('ask'), reason: z.string() }), + z.object({ + kind: z.literal('deny'), + reason: z.string(), + source: z.enum(['rule', 'hook', 'hook-error', 'hook-timeout', 'unsupported-config', 'ask-unavailable', 'containment-unavailable']), + }), +]) satisfies z.ZodType; + const pathString = z .string() .min(1, 'must not be empty') @@ -104,9 +114,10 @@ function formatIssues(error: z.ZodError): string { * 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(', ')}`); +export function parseToolCall(tool: unknown, args: unknown, id: string): ToolCall | ToolError { + if (typeof tool !== 'string') return new ToolError('invalid-args', 'tool name must be a string'); + if (!isToolName(tool)) { + return new ToolError('invalid-args', `unknown tool ${JSON.stringify(tool.slice(0, 80))}; expected one of ${TOOL_NAMES.join(', ')}`); } switch (tool) { case 'bash': { diff --git a/src/core/state-dir.ts b/src/core/state-dir.ts index f59c304..9c0716d 100644 --- a/src/core/state-dir.ts +++ b/src/core/state-dir.ts @@ -1,4 +1,4 @@ -import { chmod, mkdir } from 'node:fs/promises'; +import { lstat, mkdir } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; @@ -12,9 +12,13 @@ export function stateDirPath(env: Readonly> = 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. */ +/** Creates or verifies a private state directory. Returns its path. */ export async function ensureStateDir(dir: string = stateDirPath()): Promise { + if (process.platform === 'win32') throw new Error('private overflow storage is unavailable on Windows'); await mkdir(dir, { recursive: true, mode: 0o700 }); - if (process.platform !== 'win32') await chmod(dir, 0o700); + const entry = await lstat(dir); + if (!entry.isDirectory() || entry.uid !== process.getuid?.() || (entry.mode & 0o077) !== 0) { + throw new Error('overflow storage must use a private directory owned by the server user'); + } return dir; } diff --git a/src/server/context.test.ts b/src/server/context.test.ts index 8696655..dccddc9 100644 --- a/src/server/context.test.ts +++ b/src/server/context.test.ts @@ -23,6 +23,9 @@ describe('context providers', () => { const good = await new ClaudeContextProvider(store(record)).resolve(input); expect(good).toMatchObject({ permissionMode: 'acceptEdits', agentId: 'a1', cwd: '/ws/sub', sources: { permissionMode: 'ctx-file' } }); + const nested = await new ClaudeContextProvider(store({ ...record, cwd: '/ws/..samples' })).resolve(input); + expect(nested.cwd).toBe('/ws/..samples'); + 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); diff --git a/src/server/context.ts b/src/server/context.ts index b3376f1..748119e 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -37,7 +37,7 @@ function metaObject(meta: unknown): Record { function isInside(child: string, parent: string): boolean { const rel = path.relative(parent, child); - return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel)); + return rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); } class Builder { diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 6863a74..2d44db1 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -4,12 +4,12 @@ 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 type { Sandbox, 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 { PLACEHOLDER_EXAMPLE, createMcpServer } from './mcp.js'; import type { Runtime } from './runtime.js'; const root = os.tmpdir(); @@ -18,7 +18,7 @@ afterEach(async () => { await Promise.all(closers.splice(0).map((c) => c())); }); -async function connect(opts: { env?: Record; host?: 'claude' | 'codex' | 'generic' } = {}) { +async function connect(opts: { env?: Record; host?: 'claude' | 'codex' | 'generic'; sandbox?: Sandbox; defaultRuntime?: boolean } = {}) { const seen: SessionContext[] = []; const tools = new MemoryToolRuntime({ root, files: { 'notes.txt': 'hello\n' } }); const adapter = new StaticHostAdapter({ @@ -34,7 +34,7 @@ async function connect(opts: { env?: Record; host?: 'claude' | ' contextProvider: host === 'claude' ? new ClaudeContextProvider() : host === 'codex' ? new CodexContextProvider() : new GenericContextProvider(), adapter, tools, - sandbox: new FakeSandbox(), + sandbox: opts.sandbox ?? new FakeSandbox(), maxTimeoutMs: 10_000, }); const server = createMcpServer({ @@ -42,7 +42,7 @@ async function connect(opts: { env?: Record; host?: 'claude' | ' env: opts.env ?? {}, serverCwd: root, stateDir: `${root}/acm-test-state`, - createRuntime: runtime, + ...(opts.defaultRuntime ? {} : { createRuntime: runtime }), ...(opts.host ? { host: opts.host } : {}), }); const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { roots: {} } }); @@ -156,15 +156,39 @@ describe('MCP server', () => { 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 body: unknown = JSON.parse(text); + expect(body).toMatchObject({ truncated: true }); + if (process.platform === 'win32') expect(body).not.toHaveProperty('overflowPath'); + else expect(body).toHaveProperty('overflowPath', expect.any(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('describes the placeholder runtime it serves by default and runs its example', async () => { + const { client } = await connect({ defaultRuntime: true }); + expect(client.getInstructions()).toContain(`Example code: ${PLACEHOLDER_EXAMPLE}`); + expect(client.getInstructions()).not.toContain('async JavaScript function'); + const [tool] = (await client.listTools()).tools; + expect(tool?.description).toContain('placeholder'); + expect(JSON.stringify(tool?.inputSchema)).not.toContain('JavaScript'); + + const result = await client.callTool({ name: 'run', arguments: { code: PLACEHOLDER_EXAMPLE } }); + expect(result.isError).toBe(false); + expect(JSON.parse(textOf(result))).toMatchObject({ ok: true, result: [{ created: true }, { content: 'hello\n' }] }); + }); + + it('stops a fake script at its deadline before a later write, even when no timer could fire', async () => { + let clock = 0; + const { client, tools } = await connect({ sandbox: new FakeSandbox({ now: () => (clock += 1_000) }) }); + const code = JSON.stringify([{ tool: 'write', args: { path: 'late.txt', content: 'x' } }]); + const result = await client.callTool({ name: 'run', arguments: { code, timeoutMs: 1_500 } }); + expect(result.isError).toBe(true); + expect(JSON.parse(textOf(result))).toMatchObject({ ok: false, error: { kind: 'timeout' } }); + expect(tools.read('late.txt')).toBeUndefined(); + }); + 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 9f3961c..d523356 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -33,6 +33,27 @@ export const RUN_TOOL: Tool = { _meta: { 'anthropic/alwaysLoad': true }, }; +/** A runnable `code` for the placeholder runtime that `createRuntime` builds today. */ +export const PLACEHOLDER_EXAMPLE = JSON.stringify([ + { tool: 'write', args: { path: 'example.txt', content: 'hello\n' } }, + { tool: 'read', args: { path: 'example.txt' } }, +]); + +/** Instructions served with the default runtime, whose components are placeholders. */ +export const PLACEHOLDER_INSTRUCTIONS = `This build serves placeholder components: run does not execute JavaScript yet. +Its code is a JSON array of steps run in order, and the result is the array of step results. Steps: {"tool": name, "args": {...}}, {"parallel": [steps]}, {"log": text}, {"sleep": ms}, {"throw": message}, {"throwOnError": true}. +read, write, edit, grep and glob act on an in-memory file system that starts empty; bash only echoes the command. A fixed placeholder policy stands in for the host's rules and hooks. +Example code: ${PLACEHOLDER_EXAMPLE}`; + +const PLACEHOLDER_RUN_TOOL: Tool = { + ...RUN_TOOL, + description: 'Run a JSON array of placeholder steps (see the server instructions) against an in-memory file system.', + inputSchema: { + ...RUN_INPUT_JSON_SCHEMA, + properties: { ...RUN_INPUT_JSON_SCHEMA.properties, code: { type: 'string', description: `JSON array of placeholder steps, e.g. ${PLACEHOLDER_EXAMPLE}` } }, + }, +}; + export interface McpServerOptions { readonly version: string; /** `--host` flag; skips detection. */ @@ -69,6 +90,8 @@ export function createMcpServer(opts: McpServerOptions): Server { const serverCwd = opts.serverCwd ?? process.cwd(); const stateDir = opts.stateDir ?? stateDirPath(env); const factory = opts.createRuntime ?? createRuntime; + const placeholder = opts.createRuntime === undefined; + const runTool = placeholder ? PLACEHOLDER_RUN_TOOL : RUN_TOOL; const runtimes = new Map(); const runtimeFor = (host: HostKind): Runtime => { let runtime = runtimes.get(host); @@ -79,19 +102,22 @@ export function createMcpServer(opts: McpServerOptions): Server { return runtime; }; - const server = new Server({ name: SERVER_NAME, version: opts.version }, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS }); + const server = new Server({ name: SERVER_NAME, version: opts.version }, { + capabilities: { tools: {} }, + instructions: placeholder ? PLACEHOLDER_INSTRUCTIONS : SERVER_INSTRUCTIONS, + }); - const listRoots = async (): Promise => { + const listRoots = async (signal: AbortSignal): Promise => { if (!server.getClientCapabilities()?.roots) return []; try { - const result = await server.listRoots(undefined, { timeout: opts.rootsTimeoutMs ?? 5_000 }); + const result = await server.listRoots(undefined, { timeout: opts.rootsTimeoutMs ?? 5_000, signal }); return rootPaths(result.roots); } catch { return []; } }; - server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [RUN_TOOL] })); + server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [runTool] })); server.setRequestHandler(CallToolRequestSchema, async (request, extra): Promise => { const respond = (result: RunResult): Promise => formatRunResult(result, { stateDir }); @@ -102,7 +128,8 @@ export function createMcpServer(opts: McpServerOptions): Server { const meta: unknown = request.params._meta; const host = detectHost({ flag: opts.host, env, meta }); const runtime = runtimeFor(host); - const roots = await listRoots(); + const roots = await listRoots(extra.signal); + if (extra.signal.aborted) return respond(errorResult('the run was cancelled before context resolution')); const ctx = await runtime.contextProvider.resolve({ env, meta, roots, serverCwd }); const result = await runScript(toRunRequest(args.value, runtime.maxTimeoutMs), { sandbox: runtime.sandbox, diff --git a/src/server/runtime.ts b/src/server/runtime.ts index 5b85da1..64a951c 100644 --- a/src/server/runtime.ts +++ b/src/server/runtime.ts @@ -36,10 +36,11 @@ export function createRuntime(host: HostKind): Runtime { contextProvider, adapter: new StaticHostAdapter({ host, + recordCalls: false, 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(), + tools: new MemoryToolRuntime({ recordCalls: false }), + sandbox: new FakeSandbox({ recordRuns: false }), maxTimeoutMs: host === 'codex' ? CODEX_MAX_TIMEOUT_MS : MAX_RUN_TIMEOUT_MS, }; } diff --git a/src/testing/fake-sandbox.test.ts b/src/testing/fake-sandbox.test.ts new file mode 100644 index 0000000..c017af5 --- /dev/null +++ b/src/testing/fake-sandbox.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest'; +import type { SandboxRunOptions } from '../core/types.js'; +import { FakeSandbox } from './fake-sandbox.js'; + +function options(overrides: Partial = {}): SandboxRunOptions { + return { + timeoutMs: 1_000, + memoryBytes: 1, + signal: new AbortController().signal, + onCall: async () => ({ ok: true, value: { files: [], truncated: false } }), + onLog: () => undefined, + ...overrides, + }; +} + +describe('FakeSandbox', () => { + it('leaves no timer behind when a script finishes or times out during a sleep', async () => { + const timers = (): number => process.getActiveResourcesInfo().filter((r) => r === 'Timeout').length; + const before = timers(); + const sandbox = new FakeSandbox(); + expect(await sandbox.run('[]', options())).toMatchObject({ ok: true }); + expect(timers()).toBe(before); + expect(await sandbox.run(JSON.stringify([{ sleep: 60_000 }]), options({ timeoutMs: 20 }))).toMatchObject({ ok: false, kind: 'timeout' }); + expect(timers()).toBe(before); + }); +}); diff --git a/src/testing/fake-sandbox.ts b/src/testing/fake-sandbox.ts index f3c9e9e..617328f 100644 --- a/src/testing/fake-sandbox.ts +++ b/src/testing/fake-sandbox.ts @@ -1,3 +1,4 @@ +import { setImmediate as yieldToLoop, setTimeout as sleep } from 'node:timers/promises'; import { z } from 'zod'; import type { CallReply, Sandbox, SandboxOutcome, SandboxRunOptions } from '../core/types.js'; @@ -47,9 +48,18 @@ class Stopped extends Error {} */ export class FakeSandbox implements Sandbox { readonly runs: string[] = []; + readonly #recordRuns: boolean; + readonly #now: () => number; + + /** `now` is a monotonic clock in ms, for tests. */ + constructor({ recordRuns = true, now = () => performance.now() }: { readonly recordRuns?: boolean; readonly now?: () => number } = {}) { + this.#recordRuns = recordRuns; + this.#now = now; + } async run(code: string, opts: SandboxRunOptions): Promise { - this.runs.push(code); + const deadline = this.#now() + opts.timeoutMs; + if (this.#recordRuns) this.runs.push(code); let steps: FakeStep[]; try { steps = ScriptSchema.parse(JSON.parse(code)); @@ -58,20 +68,29 @@ export class FakeSandbox implements Sandbox { } 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(() => { + // Aborted when the run ends, so neither the deadline nor a sleep outlives it. + const finished = new AbortController(); + const signal = AbortSignal.any([opts.signal, finished.signal]); + const stopped = sleep(Math.max(0, deadline - this.#now()), undefined, { signal }).then( + () => { timedOut = true; - reject(new Stopped()); - }, opts.timeoutMs).unref(); - }); + throw new Stopped(); + }, + () => { + throw new Stopped(); + }, + ); stopped.catch(() => undefined); + // A run of steps that never yields gives no timer a chance to fire, so the clock is checked too. + const check = (): void => { + if (this.#now() >= deadline) timedOut = true; + if (timedOut || opts.signal.aborted) throw new Stopped(); + }; const state = { throwOnError: false }; const exec = async (step: FakeStep): Promise => { if ('tool' in step) { + check(); 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); @@ -84,7 +103,7 @@ export class FakeSandbox implements Sandbox { } if ('throw' in step) throw new ScriptFailure('Error', step.throw); if ('sleep' in step) { - await new Promise((resolve) => setTimeout(resolve, step.sleep)); + await sleep(step.sleep, undefined, { signal }).catch(() => Promise.reject(new Stopped())); return null; } state.throwOnError = step.throwOnError; @@ -93,7 +112,12 @@ export class FakeSandbox implements Sandbox { try { const results: unknown[] = []; - for (const step of steps) results.push(await Promise.race([exec(step), stopped])); + for (const step of steps) { + await yieldToLoop(); + check(); + results.push(await Promise.race([exec(step), stopped])); + } + check(); return { ok: true, value: results }; } catch (err) { if (err instanceof Stopped) { @@ -103,6 +127,8 @@ export class FakeSandbox implements Sandbox { } const e = err instanceof Error ? err : new Error(String(err)); return { ok: false, kind: 'error', error: { name: e.name, message: e.message } }; + } finally { + finished.abort(); } } } diff --git a/src/testing/memory-tool-runtime.test.ts b/src/testing/memory-tool-runtime.test.ts new file mode 100644 index 0000000..4890fac --- /dev/null +++ b/src/testing/memory-tool-runtime.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest'; +import { ToolError } from '../core/errors.js'; +import { parseToolCall } from '../core/schemas.js'; +import type { PolicySnapshot, SessionContext } from '../core/types.js'; +import { makeContext } from './context.js'; +import { MemoryToolRuntime } from './memory-tool-runtime.js'; + +const policy: PolicySnapshot = { host: 'generic', bashContainment: { mode: 'none' }, protectedPaths: [], payload: null }; +let nextId = 1; + +async function prepare(tools: MemoryToolRuntime, tool: string, args: unknown, ctx: SessionContext = makeContext('/ws')) { + const call = parseToolCall(tool, args, `c${nextId++}`); + if (call instanceof ToolError) throw call; + return tools.prepare(call, ctx, policy); +} + +describe('MemoryToolRuntime', () => { + it('resolves paths against the session cwd and keeps disjoint roots apart', async () => { + const tools = new MemoryToolRuntime({}); + const a = makeContext('/client/a'); + const b = makeContext('/client/b'); + await tools.commit(await prepare(tools, 'write', { path: 'notes.txt', content: 'a' }, a), new AbortController().signal); + expect(tools.files.get('/client/a/notes.txt')).toBe('a'); + + await expect(prepare(tools, 'read', { path: '/client/a/notes.txt' }, b)).rejects.toMatchObject({ code: 'outside-workspace' }); + await expect(prepare(tools, 'read', { path: 'notes.txt' }, b)).rejects.toMatchObject({ code: 'not-found' }); + const listed = await tools.commit(await prepare(tools, 'glob', { pattern: '**' }, b), new AbortController().signal); + expect(listed).toEqual({ files: [], truncated: false }); + const extraRoot = makeContext('/client/b', { roots: ['/client/b', '/client/a'] }); + expect(await prepare(tools, 'read', { path: '/client/a/notes.txt' }, extraRoot)).toMatchObject({ effect: { absPath: '/client/a/notes.txt' } }); + expect(await prepare(tools, 'read', { path: 'C:\\ws\\a.txt' }, makeContext('C:\\ws')).catch((e: unknown) => e)).toMatchObject({ code: 'not-found', message: '/C:/ws/a.txt does not exist' }); + }); + + it('keeps a later write of the same text by someone else on rollback', async () => { + const tools = new MemoryToolRuntime({ root: '/ws', files: { 'a.txt': 'original' } }); + const tx = tools.beginTransaction(); + await tools.commit(await prepare(tools, 'write', { path: 'a.txt', content: 'shared' }), new AbortController().signal, tx); + const other = tools.beginTransaction(); + await tools.commit(await prepare(tools, 'write', { path: 'a.txt', content: 'other' }), new AbortController().signal, other); + await tools.commit(await prepare(tools, 'write', { path: 'a.txt', content: 'shared' }), new AbortController().signal, other); + await other.dispose(); + + expect(await tx.rollback()).toEqual({ restored: [], skipped: [{ path: '/ws/a.txt', reason: 'changed-externally' }] }); + expect(tools.read('a.txt')).toBe('shared'); + }); + + it('searches off the main thread, stops at the first extra match and can be stopped', async () => { + const atRoot = new MemoryToolRuntime({ files: { '/a.txt': 'one' } }); + expect(await atRoot.commit(await prepare(atRoot, 'glob', { pattern: '*.txt' }, makeContext('/')), new AbortController().signal)).toEqual({ files: ['/a.txt'], truncated: false }); + const tools = new MemoryToolRuntime({ root: '/ws', files: { 'a.txt': 'one\ntwo\none', 'src/b.ts': 'one', 'src/c.md': 'one' } }); + const found = await tools.commit(await prepare(tools, 'grep', { pattern: 'o.e', glob: '*.ts' }), new AbortController().signal); + expect(found).toEqual({ matches: [{ file: '/ws/src/b.ts', line: 1, text: 'one' }], truncated: false }); + const capped = await tools.commit(await prepare(tools, 'grep', { pattern: 'ONE', ignoreCase: true, maxResults: 1 }), new AbortController().signal); + expect(capped).toEqual({ matches: [{ file: '/ws/a.txt', line: 1, text: 'one' }], truncated: true }); + + const controller = new AbortController(); + const pending = tools.commit(await prepare(tools, 'grep', { pattern: 'one' }), controller.signal); + controller.abort(); + await expect(pending).rejects.toMatchObject({ code: 'cancelled' }); + }); +}); diff --git a/src/testing/memory-tool-runtime.ts b/src/testing/memory-tool-runtime.ts index 740212e..f092a97 100644 --- a/src/testing/memory-tool-runtime.ts +++ b/src/testing/memory-tool-runtime.ts @@ -1,7 +1,10 @@ import { createHash } from 'node:crypto'; import path from 'node:path'; +import { Worker } from 'node:worker_threads'; +import { z } from 'zod'; import { ToolError } from '../core/errors.js'; -import { findMatchingPattern, matchesPathPattern } from '../core/paths.js'; +import { findMatchingPattern, normalizeSeparators, pathPatternRegExp } from '../core/paths.js'; +import { MAX_ARG_CHARS } from '../core/schemas.js'; import type { PolicySnapshot, PreparedCall, @@ -26,12 +29,18 @@ export function simpleDiff(file: string, before: string | null, after: string): 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(''); + const side = (prefix: string, content: string, rows: readonly string[]): string => + rows.map((row) => `${prefix}${row}\n`).join('') + (rows.length > 0 && !content.endsWith('\n') ? '\\ No newline at end of file\n' : ''); + return head + side('-', before ?? '', a) + side('+', after, b); } export interface MemoryToolRuntimeOptions { - /** Absolute POSIX workspace root of the virtual file system, e.g. `/ws`. */ - readonly root: string; + /** + * Absolute POSIX root that every path must stay inside, e.g. `/ws`. Without + * it, paths must stay inside the session cwd or one of its roots. + */ + readonly root?: string; + readonly recordCalls?: boolean; /** 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. */ @@ -51,7 +60,81 @@ export interface CommitRecord { interface JournalEntry { readonly original: string | null; - lastWritten: string; + /** Revision of the file this transaction last wrote. */ + revision: number; +} + +/** + * Runs a grep or glob job in a worker thread, so a costly user pattern never + * blocks the server and can be stopped. Files with no content are only listed. + */ +const SEARCH_WORKER = ` +const { parentPort, workerData } = require('node:worker_threads'); +const { names, lines, maxResults, files } = workerData; +const nameRe = names === null ? null : new RegExp(names.source, names.flags); +const lineRe = lines === null ? null : new RegExp(lines.source, lines.flags); +const found = []; +let truncated = false; +scan: for (const [file, candidates, content] of files) { + if (nameRe !== null && !candidates.some((name) => nameRe.test(name))) continue; + const rows = lineRe === null ? [null] : content.split('\\n'); + for (let i = 0; i < rows.length; i++) { + if (lineRe !== null && !lineRe.test(rows[i])) continue; + if (found.length >= maxResults) { + truncated = true; + break scan; + } + found.push(lineRe === null ? file : { file, line: i + 1, text: rows[i] }); + } +} +parentPort.postMessage(lineRe === null ? { files: found, truncated } : { matches: found, truncated }); +`; + +const GrepReplySchema = z.object({ + matches: z.array(z.object({ file: z.string(), line: z.number(), text: z.string() })), + truncated: z.boolean(), +}); +const GlobReplySchema = z.object({ files: z.array(z.string()), truncated: z.boolean() }); + +interface SearchJob { + readonly names: { readonly source: string; readonly flags: string } | null; + readonly lines: { readonly source: string; readonly flags: string } | null; + readonly maxResults: number; + /** `[absolute path, names the name pattern is tried on, content]`, sorted. */ + readonly files: readonly (readonly [string, readonly string[], string])[]; +} + +function searchInWorker(job: SearchJob, schema: z.ZodType, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal.aborted) return reject(new ToolError('cancelled', 'the search was stopped')); + const worker = new Worker(SEARCH_WORKER, { eval: true, workerData: job }); + const finish = (settle: () => void): void => { + signal.removeEventListener('abort', onAbort); + void worker.terminate(); + settle(); + }; + const onAbort = (): void => finish(() => reject(new ToolError('cancelled', 'the search was stopped'))); + signal.addEventListener('abort', onAbort, { once: true }); + worker.once('message', (message: unknown) => { + const reply = schema.safeParse(message); + finish(() => (reply.success ? resolve(reply.data) : reject(new ToolError('tool-error', 'the search returned an invalid reply')))); + }); + worker.once('error', (err) => finish(() => reject(new ToolError('tool-error', `the search failed: ${err.message}`)))); + worker.once('exit', (code) => finish(() => reject(new ToolError('tool-error', `the search stopped with exit code ${code}`)))); + }); +} + +const regExpSource = (re: RegExp): { source: string; flags: string } => ({ source: re.source, flags: re.flags }); + +/** POSIX form of a host path, so a Windows cwd such as `C:\ws` becomes `/C:/ws` instead of a relative path. */ +function virtualPath(p: string): string { + const s = normalizeSeparators(p); + return /^[A-Za-z]:(\/|$)/.test(s) ? `/${s}` : s; +} + +function isInside(abs: string, root: string): boolean { + const rel = posix.relative(root, abs); + return rel !== '..' && !rel.startsWith('../') && !posix.isAbsolute(rel); } function sleep(ms: number, signal?: AbortSignal): Promise { @@ -75,24 +158,23 @@ class MemoryTransaction implements Transaction { constructor(private readonly runtime: MemoryToolRuntime) {} - record(absPath: string, before: string | null, after: string): void { + record(absPath: string, before: string | null, revision: number): 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 }); + if (entry) entry.revision = revision; + else this.journal.set(absPath, { original: before, revision }); } 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) { + // A later write by anyone else, even of the same text, has another revision. + if (this.runtime.revision(absPath) !== entry.revision) { 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); + this.runtime.setFile(absPath, entry.original); restored.push(absPath); } this.journal.clear(); @@ -111,8 +193,10 @@ class MemoryTransaction implements Transaction { * `bash` that only echoes the command. */ export class MemoryToolRuntime implements ToolRuntime { - readonly root: string; + readonly root: string | undefined; readonly files = new Map(); + readonly #revisions = new Map(); + #nextRevision = 1; readonly commits: CommitRecord[] = []; /** Highest number of concurrent prepare/commit calls of read-only tools seen. */ maxConcurrentReads = 0; @@ -121,24 +205,43 @@ export class MemoryToolRuntime implements ToolRuntime { 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); + this.root = opts.root === undefined ? undefined : posix.resolve(opts.root); + for (const [p, content] of Object.entries(opts.files ?? {})) this.files.set(this.#abs(p), content); + } + + #abs(p: string): string { + return posix.resolve(this.root ?? '/', p); + } + + /** Sets a file, or deletes it when `content` is null, and returns its new revision. */ + setFile(absPath: string, content: string | null): number { + if (content === null) this.files.delete(absPath); + else this.files.set(absPath, content); + const revision = this.#nextRevision++; + this.#revisions.set(absPath, revision); + return revision; + } + + /** Revision of the last change made through this runtime, if any. */ + revision(absPath: string): number | undefined { + return this.#revisions.get(absPath); } /** Simulates a change made outside the run. */ externalWrite(p: string, content: string): void { - this.files.set(posix.resolve(this.root, p), content); + this.setFile(this.#abs(p), content); } read(p: string): string | undefined { - return this.files.get(posix.resolve(this.root, p)); + return this.files.get(this.#abs(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}`); + /** Resolves `p` against the session cwd and keeps it inside the fixed root, or else the session cwd and roots. */ + #resolve(p: string, ctx: SessionContext): string { + const abs = posix.resolve(virtualPath(ctx.cwd), virtualPath(p)); + const roots = this.root === undefined ? [ctx.cwd, ...ctx.roots].map((root) => posix.resolve(virtualPath(root))) : [this.root]; + if (!roots.some((root) => isInside(abs, root))) { + throw new ToolError('outside-workspace', `${p} is outside the workspace ${roots.join(', ')}`); } return abs; } @@ -148,12 +251,12 @@ export class MemoryToolRuntime implements ToolRuntime { if (max > 0) await sleep(Math.random() * max, signal); } - async prepare(call: ToolCall, _ctx: SessionContext, policy: PolicySnapshot): Promise { + 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); + return this.#prepareNow(call, ctx, policy); } finally { if (readOnly) this.#reading--; } @@ -170,22 +273,22 @@ export class MemoryToolRuntime implements ToolRuntime { } } - #prepareNow(call: ToolCall, policy: PolicySnapshot): PreparedCall { + #prepareNow(call: ToolCall, ctx: SessionContext, policy: PolicySnapshot): PreparedCall { switch (call.tool) { case 'bash': { - const cwd = this.#resolve(call.args.cwd ?? '.'); + const cwd = this.#resolve(call.args.cwd ?? '.', ctx); 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); + const absPath = this.#resolve(call.args.path, ctx); 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); + const absPath = this.#resolve(call.args.path, ctx); this.#protect(absPath, policy); const before = this.files.get(absPath) ?? null; return { @@ -201,18 +304,20 @@ export class MemoryToolRuntime implements ToolRuntime { }; } case 'edit': { - const absPath = this.#resolve(call.args.path); + const absPath = this.#resolve(call.args.path, ctx); 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; + const parts = before.split(call.args.oldString); + const count = parts.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); + const replacements = call.args.replaceAll === true ? count : 1; + const afterLength = before.length + replacements * (call.args.newString.length - call.args.oldString.length); + if (afterLength > MAX_ARG_CHARS) throw new ToolError('invalid-args', 'edited content is too large'); + const afterContent = parts.join(call.args.newString); return { id: call.id, tool: 'edit', @@ -224,12 +329,12 @@ export class MemoryToolRuntime implements ToolRuntime { diff: simpleDiff(absPath, before, afterContent), matchedOldString: call.args.oldString, matchStrategy: 'exact', - replacements: call.args.replaceAll === true ? count : 1, + replacements, }, }; } case 'grep': { - const absRoot = this.#resolve(call.args.path ?? '.'); + const absRoot = this.#resolve(call.args.path ?? '.', ctx); const effect = { absRoot, pattern: call.args.pattern, @@ -245,7 +350,7 @@ export class MemoryToolRuntime implements ToolRuntime { return { id: call.id, tool: 'grep', args: { ...call.args, path: absRoot }, effect }; } case 'glob': { - const absRoot = this.#resolve(call.args.path ?? '.'); + const absRoot = this.#resolve(call.args.path ?? '.', ctx); const effect = { absRoot, pattern: call.args.pattern, maxResults: call.args.maxResults ?? 200 }; return { id: call.id, tool: 'glob', args: { ...call.args, path: absRoot }, effect }; } @@ -261,7 +366,7 @@ export class MemoryToolRuntime implements ToolRuntime { this.#enterRead(); try { await this.#jitter(signal); - return this.#commitRead(prepared); + return prepared.tool === 'read' ? this.#commitRead(prepared) : await this.#search(prepared, signal); } finally { this.#reading--; } @@ -277,49 +382,45 @@ export class MemoryToolRuntime implements ToolRuntime { } } - #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 }; - } + async #search(prepared: Extract, signal: AbortSignal): Promise { + const { absRoot, maxResults } = prepared.effect; + const inRoot = [...this.files.entries()].filter(([file]) => isInside(file, absRoot)); + const rel = (file: string): string => normalizeSeparators(posix.relative(absRoot, file)); + let result: ToolResult; + if (prepared.tool === 'grep') { + const { pattern, ignoreCase, glob } = prepared.effect; + const files = inRoot + .sort(([a], [b]) => a.localeCompare(b)) + .map(([file, content]) => [file, [normalizeSeparators(posix.basename(file)), rel(file)], content] as const); + const names = glob === null ? null : regExpSource(pathPatternRegExp(glob, false)); + result = await searchInWorker({ names, lines: { source: pattern, flags: ignoreCase ? 'i' : '' }, maxResults, files }, GrepReplySchema, signal); + } else { + const files = inRoot + .filter(([file]) => file !== absRoot) + .map(([file]) => file) + .sort() + .map((file) => [file, [rel(file)], ''] as const); + const names = regExpSource(pathPatternRegExp(prepared.effect.pattern, false)); + result = await searchInWorker({ names, lines: null, maxResults, files }, GlobReplySchema, signal); } + this.#recordCommit(prepared, absRoot); + return result; + } + + #commitRead(prepared: Extract): ToolResult { + 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.#recordCommit(prepared, absPath); + return { path: absPath, content: window.join('\n'), startLine: offset, totalLines: lines.length, truncated: offset - 1 + limit < lines.length }; } #commitMutation(prepared: Extract, tx: Transaction | undefined): ToolResult { switch (prepared.tool) { case 'bash': { - this.commits.push({ id: prepared.id, tool: 'bash', target: prepared.effect.command }); + this.#recordCommit(prepared, prepared.effect.command); return { exitCode: 0, signal: null, stdout: `fake: ${prepared.effect.command}\n`, stderr: '', truncated: false, timedOut: false }; } case 'write': @@ -328,15 +429,19 @@ export class MemoryToolRuntime implements ToolRuntime { 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 }); + const revision = this.setFile(absPath, afterContent); + if (tx instanceof MemoryTransaction) tx.record(absPath, current, revision); + this.#recordCommit(prepared, absPath); if (prepared.tool === 'write') return { path: absPath, created: current === null, diff }; return { path: absPath, replacements: prepared.effect.replacements, matchStrategy: prepared.effect.matchStrategy, diff }; } } } + #recordCommit(prepared: PreparedCall, target: string): void { + if (this.#opts.recordCalls !== false) this.commits.push({ id: prepared.id, tool: prepared.tool, target }); + } + beginTransaction(): Transaction { return new MemoryTransaction(this); } diff --git a/src/testing/static-host-adapter.ts b/src/testing/static-host-adapter.ts index 5b1b2f0..fe3e778 100644 --- a/src/testing/static-host-adapter.ts +++ b/src/testing/static-host-adapter.ts @@ -28,6 +28,7 @@ export type HookBehavior = export interface StaticHostAdapterOptions { readonly host?: HostKind; + readonly recordCalls?: boolean; readonly rules?: readonly StaticRule[]; /** Fixed behavior, or one chosen per call. Default allow. */ readonly hook?: HookBehavior | ((prepared: PreparedCall) => HookBehavior); @@ -64,7 +65,7 @@ export class StaticHostAdapter implements HostAdapter { } checkStatic(prepared: PreparedCall, ctx: SessionContext): Decision { - this.staticChecked.push(prepared); + if (this.#opts.recordCalls !== false) 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 }; @@ -74,7 +75,7 @@ export class StaticHostAdapter implements HostAdapter { } authorize(prepared: PreparedCall, _ctx: SessionContext, _policy: PolicySnapshot, signal: AbortSignal): Promise { - this.authorized.push(prepared); + if (this.#opts.recordCalls !== false) this.authorized.push(prepared); const hook = this.#opts.hook; const behavior: HookBehavior = typeof hook === 'function' ? hook(prepared) : (hook ?? { kind: 'allow' }); switch (behavior.kind) { @@ -99,6 +100,6 @@ export class StaticHostAdapter implements HostAdapter { } async postToolUse(prepared: PreparedCall, result: ToolResult): Promise { - this.postToolUses.push({ prepared, result }); + if (this.#opts.recordCalls !== false) this.postToolUses.push({ prepared, result }); } } From 3cba6aea72a1db732e3acca9e8e9b92c0c6225a2 Mon Sep 17 00:00:00 2001 From: mths-mcfs Date: Thu, 19 Nov 2026 03:43:58 -0300 Subject: [PATCH 11/17] fix(review): round 2 - Fake runtime: cap concurrent search workers per runtime; extra searches wait in a cancelable queue and a slot is reused only after its worker exits. - Fake runtime: build the search job after a slot is held, send grep content only for files that pass the name filter, and reject a search that would copy more than the text limit. - Fake runtime: count edit occurrences and build the diff without per-match or per-line arrays. - Normalize Windows drive paths in the fake runtime and path patterns, and restore original revisions on rollback. - Run: check the deadline before opening a transaction and word the pending-rollback warning accurately. Co-Authored-By: Claude Opus 5.5 --- src/core/paths.test.ts | 1 + src/core/paths.ts | 10 +- src/core/run.test.ts | 14 ++ src/core/run.ts | 7 +- src/testing/memory-tool-runtime.test.ts | 72 ++++++- src/testing/memory-tool-runtime.ts | 272 +++++++++++++++++------- 6 files changed, 295 insertions(+), 81 deletions(-) diff --git a/src/core/paths.test.ts b/src/core/paths.test.ts index 0e1e354..b0e79e2 100644 --- a/src/core/paths.test.ts +++ b/src/core/paths.test.ts @@ -13,6 +13,7 @@ describe('matchesPathPattern', () => { ['/ws/src/week\n1/example.ts', '/ws/src/**/*.ts', true], ['/ws/src/c.ts', '/ws/src/**/*.ts', true], ['C:\\ws\\.codex\\config.toml', 'C:/ws/.codex/**', true], + ['/C:/ws/project/notes.txt', 'C:\\ws\\project\\*.txt', 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) => { diff --git a/src/core/paths.ts b/src/core/paths.ts index f75704d..d060d8c 100644 --- a/src/core/paths.ts +++ b/src/core/paths.ts @@ -15,7 +15,7 @@ export function pathPatternRegExp(pattern: string, caseInsensitive = DEFAULT_CAS const key = `${caseInsensitive ? 'i' : 's'}:${pattern}`; const hit = cache.get(key); if (hit) return hit; - const p = normalizeSeparators(pattern); + const p = normalizeDrivePath(pattern); let src = ''; for (let i = 0; i < p.length; i++) { const ch = p[i] ?? ''; @@ -51,12 +51,18 @@ export function normalizeSeparators(p: string): string { return p.replace(/\\/g, '/'); } +/** Normalizes drive-letter paths for comparison with the in-memory filesystem. */ +export function normalizeDrivePath(p: string): string { + const normalized = normalizeSeparators(p); + return /^[A-Za-z]:(\/|$)/.test(normalized) ? `/${normalized}` : normalized; +} + /** 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 pathPatternRegExp(pattern, caseInsensitive).test(normalizeSeparators(path)); + return pathPatternRegExp(pattern, caseInsensitive).test(normalizeDrivePath(path)); } /** The first pattern `path` matches, or undefined. */ diff --git a/src/core/run.test.ts b/src/core/run.test.ts index 1f9c3f9..7918581 100644 --- a/src/core/run.test.ts +++ b/src/core/run.test.ts @@ -325,6 +325,20 @@ describe('runScript', () => { expect(d.tools.read('notes.txt')).toBeUndefined(); }); + it('keeps the sandbox stopped when opening the journal uses up the deadline', async () => { + let clock = 0; + const run = vi.fn(async () => ({ ok: true as const, value: 'done' })); + const d = deps({}, {}, { run }); + const begin = d.tools.beginTransaction.bind(d.tools); + d.tools.beginTransaction = () => { + clock = 11; + return begin(); + }; + const result = await runScript({ code: 'x', transaction: true, timeoutMs: 10 }, { ...d, now: () => clock }); + expect(result.error?.kind).toBe('timeout'); + expect(run).not.toHaveBeenCalled(); + }); + 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 bd57c46..ddc3185 100644 --- a/src/core/run.ts +++ b/src/core/run.ts @@ -102,7 +102,7 @@ async function rollbackBounded( warnings: string[], ): Promise<{ readonly report?: RollbackReport; readonly done: Promise }> { if (writes) { - warnings.push('the rollback is pending: some writes were still running when the run stopped; their files are restored once they end.'); + warnings.push('the rollback is pending: some writes were still running when the run stopped; the final rollback outcome is unknown.'); return { done: writes.then(() => tx.rollback()) }; } const done = Promise.resolve().then(() => tx.rollback()); @@ -240,10 +240,11 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise({ adapter: deps.adapter, tools: deps.tools, diff --git a/src/testing/memory-tool-runtime.test.ts b/src/testing/memory-tool-runtime.test.ts index 4890fac..fb84615 100644 --- a/src/testing/memory-tool-runtime.test.ts +++ b/src/testing/memory-tool-runtime.test.ts @@ -1,9 +1,23 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { ToolError } from '../core/errors.js'; import { parseToolCall } from '../core/schemas.js'; import type { PolicySnapshot, SessionContext } from '../core/types.js'; import { makeContext } from './context.js'; -import { MemoryToolRuntime } from './memory-tool-runtime.js'; +import { MemoryToolRuntime, simpleDiff } from './memory-tool-runtime.js'; + +const workers = vi.hoisted(() => ({ live: 0, max: 0 })); +vi.mock('node:worker_threads', async (importOriginal) => { + const real = await importOriginal(); + class CountingWorker extends real.Worker { + constructor(...args: ConstructorParameters) { + super(...args); + workers.live++; + workers.max = Math.max(workers.max, workers.live); + this.once('exit', () => workers.live--); + } + } + return { ...real, Worker: CountingWorker }; +}); const policy: PolicySnapshot = { host: 'generic', bashContainment: { mode: 'none' }, protectedPaths: [], payload: null }; let nextId = 1; @@ -44,6 +58,27 @@ describe('MemoryToolRuntime', () => { expect(tools.read('a.txt')).toBe('shared'); }); + it('reads seeded files under an explicit Windows root', async () => { + const root = 'C:\\workspace'; + const file = `${root}\\notes.txt`; + const tools = new MemoryToolRuntime({ root, files: { [file]: 'hello' } }); + const read = await prepare(tools, 'read', { path: 'notes.txt' }, makeContext(root)); + expect(await tools.commit(read, new AbortController().signal)).toMatchObject({ content: 'hello' }); + expect(tools.read(file)).toBe('hello'); + }); + + it('allows two overlapping writes to roll back in reverse order', async () => { + const tools = new MemoryToolRuntime({ root: '/ws', files: { 'notes.txt': 'original' } }); + const outer = tools.beginTransaction(); + const inner = tools.beginTransaction(); + const signal = new AbortController().signal; + await tools.commit(await prepare(tools, 'write', { path: 'notes.txt', content: 'first' }), signal, outer); + await tools.commit(await prepare(tools, 'write', { path: 'notes.txt', content: 'second' }), signal, inner); + expect(await inner.rollback()).toMatchObject({ restored: ['/ws/notes.txt'] }); + expect(await outer.rollback()).toMatchObject({ restored: ['/ws/notes.txt'], skipped: [] }); + expect(tools.read('notes.txt')).toBe('original'); + }); + it('searches off the main thread, stops at the first extra match and can be stopped', async () => { const atRoot = new MemoryToolRuntime({ files: { '/a.txt': 'one' } }); expect(await atRoot.commit(await prepare(atRoot, 'glob', { pattern: '*.txt' }, makeContext('/')), new AbortController().signal)).toEqual({ files: ['/a.txt'], truncated: false }); @@ -58,4 +93,37 @@ describe('MemoryToolRuntime', () => { controller.abort(); await expect(pending).rejects.toMatchObject({ code: 'cancelled' }); }); + + it('caps concurrent search workers, cancels queued searches and reuses freed slots', async () => { + const tools = new MemoryToolRuntime({ root: '/ws', files: { 'a.txt': 'one', 'b.ts': 'one' } }); + await vi.waitFor(() => expect(workers.live).toBe(0)); + workers.max = 0; + const signal = new AbortController().signal; + const searches = await Promise.all(Array.from({ length: 10 }, () => prepare(tools, 'grep', { pattern: 'one' }))); + const queued = new AbortController(); + const running = searches.map((call) => tools.commit(call, signal)); + const cancelled = tools.commit(await prepare(tools, 'glob', { pattern: '*' }), queued.signal); + queued.abort(); + await expect(cancelled).rejects.toMatchObject({ code: 'cancelled' }); + for (const result of await Promise.all(running)) expect(result).toMatchObject({ matches: [{ line: 1 }, { line: 1 }], truncated: false }); + expect(workers.max).toBeGreaterThan(0); + expect(workers.max).toBeLessThanOrEqual(4); + await expect(tools.commit(await prepare(tools, 'glob', { pattern: '*.ts' }), signal)).resolves.toEqual({ files: ['/ws/b.ts'], truncated: false }); + }); + + it('copies only the content a search needs and rejects a search over the size limit', async () => { + const big = 'x'.repeat(11_000_000); + const tools = new MemoryToolRuntime({ root: '/ws', files: { 'a.txt': big, 'b.txt': big, 'c.ts': 'one' } }); + const signal = new AbortController().signal; + expect(await tools.commit(await prepare(tools, 'grep', { pattern: 'one', glob: '*.ts' }), signal)).toEqual({ matches: [{ file: '/ws/c.ts', line: 1, text: 'one' }], truncated: false }); + await expect(tools.commit(await prepare(tools, 'grep', { pattern: 'one' }), signal)).rejects.toMatchObject({ code: 'tool-error', message: expect.stringContaining('narrow') }); + }); + + it('edits literally and diffs without per-line arrays', async () => { + const tools = new MemoryToolRuntime({ root: '/ws', files: { 'a.txt': 'a-a\na' } }); + const edit = await prepare(tools, 'edit', { path: 'a.txt', oldString: 'a', newString: '$&$1', replaceAll: true }); + expect(edit).toMatchObject({ effect: { afterContent: '$&$1-$&$1\n$&$1', replacements: 3 } }); + expect(simpleDiff('/f', 'x\n\n', 'y')).toBe('--- a/f\n+++ b/f\n@@ -1,2 +1,1 @@\n-x\n-\n+y\n\\ No newline at end of file\n'); + await expect(prepare(tools, 'edit', { path: 'a.txt', oldString: 'a', newString: 'b' })).rejects.toMatchObject({ message: expect.stringContaining('3 times') }); + }); }); diff --git a/src/testing/memory-tool-runtime.ts b/src/testing/memory-tool-runtime.ts index f092a97..dbf4f17 100644 --- a/src/testing/memory-tool-runtime.ts +++ b/src/testing/memory-tool-runtime.ts @@ -2,8 +2,8 @@ import { createHash } from 'node:crypto'; import path from 'node:path'; import { Worker } from 'node:worker_threads'; import { z } from 'zod'; -import { ToolError } from '../core/errors.js'; -import { findMatchingPattern, normalizeSeparators, pathPatternRegExp } from '../core/paths.js'; +import { ToolError, errorMessage } from '../core/errors.js'; +import { findMatchingPattern, normalizeDrivePath, normalizeSeparators, pathPatternRegExp } from '../core/paths.js'; import { MAX_ARG_CHARS } from '../core/schemas.js'; import type { PolicySnapshot, @@ -23,15 +23,28 @@ export function sha256(text: string): string { return createHash('sha256').update(text, 'utf8').digest('hex'); } -/** Minimal whole-file unified diff, good enough for tests. */ +/** Minimal whole-file unified diff, good enough for tests. Builds no per-line arrays. */ 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`; - const side = (prefix: string, content: string, rows: readonly string[]): string => - rows.map((row) => `${prefix}${row}\n`).join('') + (rows.length > 0 && !content.endsWith('\n') ? '\\ No newline at end of file\n' : ''); - return head + side('-', before ?? '', a) + side('+', after, b); + const side = (prefix: string, content: string): { rows: number; text: string } => { + if (content === '') return { rows: 0, text: '' }; + const newline = content.endsWith('\n'); + const body = newline ? content.slice(0, -1) : content; + let rows = 1; + for (let at = body.indexOf('\n'); at !== -1; at = body.indexOf('\n', at + 1)) rows++; + const text = `${prefix}${body.replaceAll('\n', `\n${prefix}`)}\n${newline ? '' : '\\ No newline at end of file\n'}`; + return { rows, text }; + }; + const a = side('-', before ?? ''); + const b = side('+', after); + const head = `--- ${before === null ? '/dev/null' : `a${file}`}\n+++ b${file}\n@@ -${a.rows > 0 ? 1 : 0},${a.rows} +${b.rows > 0 ? 1 : 0},${b.rows} @@\n`; + return head + a.text + b.text; +} + +/** Non-overlapping literal occurrences of `needle` (not empty) in `text`, without building arrays. */ +function countOccurrences(text: string, needle: string): number { + let count = 0; + for (let at = text.indexOf(needle); at !== -1; at = text.indexOf(needle, at + needle.length)) count++; + return count; } export interface MemoryToolRuntimeOptions { @@ -60,36 +73,56 @@ export interface CommitRecord { interface JournalEntry { readonly original: string | null; + readonly originalRevision: number; /** Revision of the file this transaction last wrote. */ revision: number; } /** * Runs a grep or glob job in a worker thread, so a costly user pattern never - * blocks the server and can be stopped. Files with no content are only listed. + * blocks the server and can be stopped. The worker first filters the file + * names; a grep then asks for the content of the kept files only. */ const SEARCH_WORKER = ` const { parentPort, workerData } = require('node:worker_threads'); const { names, lines, maxResults, files } = workerData; const nameRe = names === null ? null : new RegExp(names.source, names.flags); -const lineRe = lines === null ? null : new RegExp(lines.source, lines.flags); -const found = []; -let truncated = false; -scan: for (const [file, candidates, content] of files) { - if (nameRe !== null && !candidates.some((name) => nameRe.test(name))) continue; - const rows = lineRe === null ? [null] : content.split('\\n'); - for (let i = 0; i < rows.length; i++) { - if (lineRe !== null && !lineRe.test(rows[i])) continue; - if (found.length >= maxResults) { - truncated = true; - break scan; +const keep = []; +for (let i = 0; i < files.length; i++) { + if (nameRe === null || files[i][1].some((name) => nameRe.test(name))) keep.push(i); +} +if (lines === null) { + const truncated = keep.length > maxResults; + parentPort.postMessage({ files: keep.slice(0, maxResults).map((i) => files[i][0]), truncated }); +} else { + const lineRe = new RegExp(lines.source, lines.flags); + parentPort.once('message', (contents) => { + const found = []; + let truncated = false; + scan: for (let k = 0; k < keep.length; k++) { + const rows = contents[k].split('\\n'); + for (let i = 0; i < rows.length; i++) { + if (!lineRe.test(rows[i])) continue; + if (found.length >= maxResults) { + truncated = true; + break scan; + } + found.push({ file: files[keep[k]][0], line: i + 1, text: rows[i] }); + } } - found.push(lineRe === null ? file : { file, line: i + 1, text: rows[i] }); - } + parentPort.postMessage({ matches: found, truncated }); + }); + parentPort.postMessage({ keep }); } -parentPort.postMessage(lineRe === null ? { files: found, truncated } : { matches: found, truncated }); `; +/** Searches that may run at once per runtime; more wait for a free slot. */ +const MAX_CONCURRENT_SEARCHES = 4; +/** Characters of names and content one search may copy to its worker. */ +const MAX_SEARCH_CHARS = MAX_ARG_CHARS; + +const KeepReplySchema = z.object({ keep: z.array(z.number().int().nonnegative()) }); + const GrepReplySchema = z.object({ matches: z.array(z.object({ file: z.string(), line: z.number(), text: z.string() })), truncated: z.boolean(), @@ -100,38 +133,83 @@ interface SearchJob { readonly names: { readonly source: string; readonly flags: string } | null; readonly lines: { readonly source: string; readonly flags: string } | null; readonly maxResults: number; - /** `[absolute path, names the name pattern is tried on, content]`, sorted. */ - readonly files: readonly (readonly [string, readonly string[], string])[]; + /** `[absolute path, names the name pattern is tried on]`, sorted. */ + readonly files: readonly (readonly [string, readonly string[]])[]; } -function searchInWorker(job: SearchJob, schema: z.ZodType, signal: AbortSignal): Promise { +const tooLarge = (): ToolError => + new ToolError('tool-error', `the search covers more than ${MAX_SEARCH_CHARS} characters; narrow its path or glob`); + +/** + * Runs `job` in a worker. `contents` lines up with `job.files` for a grep and + * is null for a glob. `onExit` runs once, after the worker has stopped (or at + * once when no worker starts), so its slot is reused only then. + */ +function searchInWorker( + job: SearchJob, + contents: readonly string[] | null, + budget: number, + schema: z.ZodType, + signal: AbortSignal, + onExit: () => void, +): Promise { return new Promise((resolve, reject) => { - if (signal.aborted) return reject(new ToolError('cancelled', 'the search was stopped')); - const worker = new Worker(SEARCH_WORKER, { eval: true, workerData: job }); + if (signal.aborted) { + onExit(); + return reject(new ToolError('cancelled', 'the search was stopped')); + } + let worker: Worker; + try { + worker = new Worker(SEARCH_WORKER, { eval: true, workerData: job }); + } catch (err) { + onExit(); + return reject(new ToolError('tool-error', `the search failed: ${errorMessage(err)}`)); + } + worker.once('exit', onExit); + let sentContents = false; + let settled = false; const finish = (settle: () => void): void => { + if (settled) return; + settled = true; signal.removeEventListener('abort', onAbort); - void worker.terminate(); + void worker.terminate().catch(() => undefined); settle(); }; - const onAbort = (): void => finish(() => reject(new ToolError('cancelled', 'the search was stopped'))); + const fail = (err: ToolError): void => finish(() => reject(err)); + const onAbort = (): void => fail(new ToolError('cancelled', 'the search was stopped')); signal.addEventListener('abort', onAbort, { once: true }); - worker.once('message', (message: unknown) => { + worker.on('message', (message: unknown) => { + if (settled) return; + if (contents !== null && !sentContents) { + sentContents = true; + const want = KeepReplySchema.safeParse(message); + if (!want.success) return fail(new ToolError('tool-error', 'the search returned an invalid reply')); + const kept: string[] = []; + let size = budget; + for (const i of want.data.keep) { + const content = contents[i]; + if (content === undefined) return fail(new ToolError('tool-error', 'the search returned an invalid reply')); + size += content.length; + if (size > MAX_SEARCH_CHARS) return fail(tooLarge()); + kept.push(content); + } + try { + worker.postMessage(kept); + } catch (err) { + fail(new ToolError('tool-error', `the search failed: ${errorMessage(err)}`)); + } + return; + } const reply = schema.safeParse(message); finish(() => (reply.success ? resolve(reply.data) : reject(new ToolError('tool-error', 'the search returned an invalid reply')))); }); - worker.once('error', (err) => finish(() => reject(new ToolError('tool-error', `the search failed: ${err.message}`)))); - worker.once('exit', (code) => finish(() => reject(new ToolError('tool-error', `the search stopped with exit code ${code}`)))); + worker.once('error', (err) => fail(new ToolError('tool-error', `the search failed: ${err.message}`))); + worker.once('exit', (code) => fail(new ToolError('tool-error', `the search stopped with exit code ${code}`))); }); } const regExpSource = (re: RegExp): { source: string; flags: string } => ({ source: re.source, flags: re.flags }); -/** POSIX form of a host path, so a Windows cwd such as `C:\ws` becomes `/C:/ws` instead of a relative path. */ -function virtualPath(p: string): string { - const s = normalizeSeparators(p); - return /^[A-Za-z]:(\/|$)/.test(s) ? `/${s}` : s; -} - function isInside(abs: string, root: string): boolean { const rel = posix.relative(root, abs); return rel !== '..' && !rel.startsWith('../') && !posix.isAbsolute(rel); @@ -158,11 +236,11 @@ class MemoryTransaction implements Transaction { constructor(private readonly runtime: MemoryToolRuntime) {} - record(absPath: string, before: string | null, revision: number): void { + record(absPath: string, before: string | null, originalRevision: number, revision: number): void { if (this.disposed) return; const entry = this.journal.get(absPath); if (entry) entry.revision = revision; - else this.journal.set(absPath, { original: before, revision }); + else this.journal.set(absPath, { original: before, originalRevision, revision }); } async rollback(): Promise { @@ -174,7 +252,7 @@ class MemoryTransaction implements Transaction { skipped.push({ path: absPath, reason: 'changed-externally' }); continue; } - this.runtime.setFile(absPath, entry.original); + this.runtime.setFile(absPath, entry.original, entry.originalRevision); restored.push(absPath); } this.journal.clear(); @@ -201,30 +279,32 @@ export class MemoryToolRuntime implements ToolRuntime { /** Highest number of concurrent prepare/commit calls of read-only tools seen. */ maxConcurrentReads = 0; #reading = 0; + #searches = 0; + readonly #searchQueue: (() => void)[] = []; readonly #opts: MemoryToolRuntimeOptions; constructor(opts: MemoryToolRuntimeOptions) { this.#opts = opts; - this.root = opts.root === undefined ? undefined : posix.resolve(opts.root); + this.root = opts.root === undefined ? undefined : posix.resolve(normalizeDrivePath(opts.root)); for (const [p, content] of Object.entries(opts.files ?? {})) this.files.set(this.#abs(p), content); } #abs(p: string): string { - return posix.resolve(this.root ?? '/', p); + return posix.resolve(this.root ?? '/', normalizeDrivePath(p)); } /** Sets a file, or deletes it when `content` is null, and returns its new revision. */ - setFile(absPath: string, content: string | null): number { + setFile(absPath: string, content: string | null, revision: number = this.#nextRevision++): number { if (content === null) this.files.delete(absPath); else this.files.set(absPath, content); - const revision = this.#nextRevision++; - this.#revisions.set(absPath, revision); + if (revision === 0) this.#revisions.delete(absPath); + else this.#revisions.set(absPath, revision); return revision; } /** Revision of the last change made through this runtime, if any. */ - revision(absPath: string): number | undefined { - return this.#revisions.get(absPath); + revision(absPath: string): number { + return this.#revisions.get(absPath) ?? 0; } /** Simulates a change made outside the run. */ @@ -238,8 +318,8 @@ export class MemoryToolRuntime implements ToolRuntime { /** Resolves `p` against the session cwd and keeps it inside the fixed root, or else the session cwd and roots. */ #resolve(p: string, ctx: SessionContext): string { - const abs = posix.resolve(virtualPath(ctx.cwd), virtualPath(p)); - const roots = this.root === undefined ? [ctx.cwd, ...ctx.roots].map((root) => posix.resolve(virtualPath(root))) : [this.root]; + const abs = posix.resolve(normalizeDrivePath(ctx.cwd), normalizeDrivePath(p)); + const roots = this.root === undefined ? [ctx.cwd, ...ctx.roots].map((root) => posix.resolve(normalizeDrivePath(root))) : [this.root]; if (!roots.some((root) => isInside(abs, root))) { throw new ToolError('outside-workspace', `${p} is outside the workspace ${roots.join(', ')}`); } @@ -308,8 +388,7 @@ export class MemoryToolRuntime implements ToolRuntime { this.#protect(absPath, policy); const before = this.files.get(absPath); if (before === undefined) throw new ToolError('not-found', `${absPath} does not exist`); - const parts = before.split(call.args.oldString); - const count = parts.length - 1; + const count = countOccurrences(before, call.args.oldString); 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`); @@ -317,7 +396,9 @@ export class MemoryToolRuntime implements ToolRuntime { const replacements = call.args.replaceAll === true ? count : 1; const afterLength = before.length + replacements * (call.args.newString.length - call.args.oldString.length); if (afterLength > MAX_ARG_CHARS) throw new ToolError('invalid-args', 'edited content is too large'); - const afterContent = parts.join(call.args.newString); + const newString = call.args.newString; + const afterContent = + call.args.replaceAll === true ? before.replaceAll(call.args.oldString, () => newString) : before.replace(call.args.oldString, () => newString); return { id: call.id, tool: 'edit', @@ -382,29 +463,71 @@ export class MemoryToolRuntime implements ToolRuntime { } } + /** Waits, cancelably, for a search slot and returns its release, which runs at most once. */ + async #takeSearchSlot(signal: AbortSignal): Promise<() => void> { + if (signal.aborted) throw new ToolError('cancelled', 'the search was stopped'); + if (this.#searches < MAX_CONCURRENT_SEARCHES) this.#searches++; + else { + await new Promise((resolve, reject) => { + const grant = (): void => { + signal.removeEventListener('abort', onAbort); + resolve(); + }; + const onAbort = (): void => { + this.#searchQueue.splice(this.#searchQueue.indexOf(grant), 1); + reject(new ToolError('cancelled', 'the search was stopped')); + }; + this.#searchQueue.push(grant); + signal.addEventListener('abort', onAbort, { once: true }); + }); + } + let released = false; + return () => { + if (released) return; + released = true; + const next = this.#searchQueue.shift(); + if (next === undefined) this.#searches--; + else next(); + }; + } + async #search(prepared: Extract, signal: AbortSignal): Promise { + const release = await this.#takeSearchSlot(signal); + let pending: Promise; + try { + pending = this.#startSearch(prepared, signal, release); + } catch (err) { + // No worker started, so the slot is free again. + release(); + throw err; + } + const result = await pending; + this.#recordCommit(prepared, prepared.effect.absRoot); + return result; + } + + /** Builds the job once a slot is held; the content stays here until the worker asks for it. */ + #startSearch(prepared: Extract, signal: AbortSignal, release: () => void): Promise { const { absRoot, maxResults } = prepared.effect; - const inRoot = [...this.files.entries()].filter(([file]) => isInside(file, absRoot)); - const rel = (file: string): string => normalizeSeparators(posix.relative(absRoot, file)); - let result: ToolResult; + const inRoot = [...this.files.entries()].filter(([file]) => isInside(file, absRoot) && (prepared.tool === 'grep' || file !== absRoot)); + inRoot.sort(([a], [b]) => (prepared.tool === 'grep' ? a.localeCompare(b) : a < b ? -1 : a > b ? 1 : 0)); + let budget = 0; + const files = inRoot.map(([file]) => { + const rel = normalizeSeparators(posix.relative(absRoot, file)); + const names = prepared.tool === 'grep' ? [normalizeSeparators(posix.basename(file)), rel] : [rel]; + budget += file.length + names.reduce((sum, name) => sum + name.length, 0); + return [file, names] as const; + }); + if (budget > MAX_SEARCH_CHARS) throw tooLarge(); if (prepared.tool === 'grep') { const { pattern, ignoreCase, glob } = prepared.effect; - const files = inRoot - .sort(([a], [b]) => a.localeCompare(b)) - .map(([file, content]) => [file, [normalizeSeparators(posix.basename(file)), rel(file)], content] as const); const names = glob === null ? null : regExpSource(pathPatternRegExp(glob, false)); - result = await searchInWorker({ names, lines: { source: pattern, flags: ignoreCase ? 'i' : '' }, maxResults, files }, GrepReplySchema, signal); - } else { - const files = inRoot - .filter(([file]) => file !== absRoot) - .map(([file]) => file) - .sort() - .map((file) => [file, [rel(file)], ''] as const); - const names = regExpSource(pathPatternRegExp(prepared.effect.pattern, false)); - result = await searchInWorker({ names, lines: null, maxResults, files }, GlobReplySchema, signal); + const job = { names, lines: { source: pattern, flags: ignoreCase ? 'i' : '' }, maxResults, files }; + const contents = inRoot.map(([, content]) => content); + return searchInWorker(job, contents, budget, GrepReplySchema, signal, release); } - this.#recordCommit(prepared, absRoot); - return result; + const names = regExpSource(pathPatternRegExp(prepared.effect.pattern, false)); + return searchInWorker({ names, lines: null, maxResults, files }, null, budget, GlobReplySchema, signal, release); } #commitRead(prepared: Extract): ToolResult { @@ -429,8 +552,9 @@ export class MemoryToolRuntime implements ToolRuntime { 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`); + const originalRevision = this.revision(absPath); const revision = this.setFile(absPath, afterContent); - if (tx instanceof MemoryTransaction) tx.record(absPath, current, revision); + if (tx instanceof MemoryTransaction) tx.record(absPath, current, originalRevision, revision); this.#recordCommit(prepared, absPath); if (prepared.tool === 'write') return { path: absPath, created: current === null, diff }; return { path: absPath, replacements: prepared.effect.replacements, matchStrategy: prepared.effect.matchStrategy, diff }; From 9824d9d0c38fc1d4849c78a738d1de6fc6059f08 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:09:18 -0300 Subject: [PATCH 12/17] Refuse UNC workspace roots and bound edit preparation in the memory runtime Network-share (UNC) paths are not supported: POSIX resolution folds their leading `//` while protected-path patterns keep it, so a protected share could go unrecognized. The fixed root, seeded files, session cwd and roots, and call paths now refuse UNC paths before any call is prepared. Edit and write preparation now size the change from cheap counts first and refuse, before building the edited text or the diff, an edit with more than MAX_EDIT_REPLACEMENTS (50,000) replacements or a diff over MAX_DIFF_LINES (200,000) lines. Changes under the budget produce the same text and diff. Co-Authored-By: Claude Opus 5.5 --- src/core/paths.ts | 8 ++ src/testing/memory-tool-runtime.test.ts | 59 +++++++++++++- src/testing/memory-tool-runtime.ts | 100 ++++++++++++++++++------ 3 files changed, 140 insertions(+), 27 deletions(-) diff --git a/src/core/paths.ts b/src/core/paths.ts index d060d8c..fc2bbf3 100644 --- a/src/core/paths.ts +++ b/src/core/paths.ts @@ -57,6 +57,14 @@ export function normalizeDrivePath(p: string): string { return /^[A-Za-z]:(\/|$)/.test(normalized) ? `/${normalized}` : normalized; } +/** + * Whether `p` is a Windows network-share (UNC) path such as `\\server\share` + * or `//server/share`, including `\\?\` device paths. Not supported. + */ +export function isUncPath(p: string): boolean { + return /^[\\/]{2}/.test(p); +} + /** Whether file names on this platform are usually case-insensitive. */ export const DEFAULT_CASE_INSENSITIVE = process.platform === 'darwin' || process.platform === 'win32'; diff --git a/src/testing/memory-tool-runtime.test.ts b/src/testing/memory-tool-runtime.test.ts index fb84615..e6473a0 100644 --- a/src/testing/memory-tool-runtime.test.ts +++ b/src/testing/memory-tool-runtime.test.ts @@ -3,7 +3,7 @@ import { ToolError } from '../core/errors.js'; import { parseToolCall } from '../core/schemas.js'; import type { PolicySnapshot, SessionContext } from '../core/types.js'; import { makeContext } from './context.js'; -import { MemoryToolRuntime, simpleDiff } from './memory-tool-runtime.js'; +import { MAX_DIFF_LINES, MAX_EDIT_REPLACEMENTS, MemoryToolRuntime, simpleDiff } from './memory-tool-runtime.js'; const workers = vi.hoisted(() => ({ live: 0, max: 0 })); vi.mock('node:worker_threads', async (importOriginal) => { @@ -126,4 +126,61 @@ describe('MemoryToolRuntime', () => { expect(simpleDiff('/f', 'x\n\n', 'y')).toBe('--- a/f\n+++ b/f\n@@ -1,2 +1,1 @@\n-x\n-\n+y\n\\ No newline at end of file\n'); await expect(prepare(tools, 'edit', { path: 'a.txt', oldString: 'a', newString: 'b' })).rejects.toMatchObject({ message: expect.stringContaining('3 times') }); }); + + it('refuses network-share (UNC) roots and paths before preparing a call', async () => { + for (const share of ['\\\\server\\share', '//server/share']) { + expect(() => new MemoryToolRuntime({ root: share })).toThrow(expect.objectContaining({ code: 'outside-workspace', message: expect.stringContaining('network share') })); + expect(() => new MemoryToolRuntime({ root: '/ws', files: { [`${share}/a.txt`]: 'x' } })).toThrow(expect.objectContaining({ code: 'outside-workspace' })); + const tools = new MemoryToolRuntime({ files: { '/server/share/a.txt': 'x' } }); + const write = { path: 'a.txt', content: 'y' }; + await expect(prepare(tools, 'write', write, makeContext(share))).rejects.toMatchObject({ code: 'outside-workspace', message: expect.stringContaining('network share') }); + await expect(prepare(tools, 'write', write, makeContext('/server/share', { roots: [share] }))).rejects.toMatchObject({ code: 'outside-workspace' }); + await expect(prepare(tools, 'write', { ...write, path: `${share}/a.txt` }, makeContext('/'))).rejects.toMatchObject({ code: 'outside-workspace' }); + await expect(prepare(new MemoryToolRuntime({ root: '/' }), 'read', { path: 'a.txt' }, makeContext(share))).rejects.toMatchObject({ code: 'outside-workspace' }); + } + }); + + it('refuses an edit over the replacement or diff budget before building its text or diff', async () => { + const tooMany = 'a'.repeat(MAX_EDIT_REPLACEMENTS + 1); + const tooLong = `head\n${'x\n'.repeat(MAX_DIFF_LINES / 2 - 1)}`; + const tools = new MemoryToolRuntime({ root: '/ws', files: { 'many.txt': tooMany, 'long.txt': tooLong } }); + const replaceAll = vi.spyOn(String.prototype, 'replaceAll'); + const replace = vi.spyOn(String.prototype, 'replace'); + try { + await expect(prepare(tools, 'edit', { path: 'many.txt', oldString: 'a', newString: 'b', replaceAll: true })).rejects.toMatchObject({ + code: 'invalid-args', + message: expect.stringContaining(`more than ${MAX_EDIT_REPLACEMENTS}`), + }); + await expect(prepare(tools, 'edit', { path: 'long.txt', oldString: 'head', newString: 'y' })).rejects.toMatchObject({ + code: 'invalid-args', + message: expect.stringContaining(`more than ${MAX_DIFF_LINES} lines`), + }); + await expect(prepare(tools, 'write', { path: 'long.txt', content: tooLong })).rejects.toMatchObject({ code: 'invalid-args' }); + expect(replaceAll).not.toHaveBeenCalled(); + expect(replace.mock.contexts.filter((self) => self === tooMany || self === tooLong)).toEqual([]); + } finally { + replaceAll.mockRestore(); + replace.mockRestore(); + } + expect(tools.read('many.txt')).toBe(tooMany); + expect(tools.read('long.txt')).toBe(tooLong); + }); + + it('prepares an edit just under the budget with the same text and diff as before', async () => { + const many = 'a'.repeat(MAX_EDIT_REPLACEMENTS); + const lines = MAX_DIFF_LINES / 2 - 1; + const long = `head\n${'x\n'.repeat(lines - 1)}`; + const tools = new MemoryToolRuntime({ root: '/ws', files: { 'many.txt': many, 'long.txt': long } }); + const wide = await prepare(tools, 'edit', { path: 'many.txt', oldString: 'a', newString: 'b', replaceAll: true }); + const after = 'b'.repeat(MAX_EDIT_REPLACEMENTS); + expect(wide).toMatchObject({ effect: { afterContent: after, replacements: MAX_EDIT_REPLACEMENTS } }); + expect(wide.tool === 'edit' && wide.effect.diff).toBe( + `--- a/ws/many.txt\n+++ b/ws/many.txt\n@@ -1,1 +1,1 @@\n-${many}\n\\ No newline at end of file\n+${after}\n\\ No newline at end of file\n`, + ); + const tall = await prepare(tools, 'edit', { path: 'long.txt', oldString: 'head', newString: 'y' }); + expect(tall).toMatchObject({ effect: { afterContent: `y${long.slice(4)}`, replacements: 1 } }); + expect(tall.tool === 'edit' && tall.effect.diff).toBe( + `--- a/ws/long.txt\n+++ b/ws/long.txt\n@@ -1,${lines} +1,${lines} @@\n-head\n${'-x\n'.repeat(lines - 1)}+y\n${'+x\n'.repeat(lines - 1)}`, + ); + }); }); diff --git a/src/testing/memory-tool-runtime.ts b/src/testing/memory-tool-runtime.ts index dbf4f17..c009038 100644 --- a/src/testing/memory-tool-runtime.ts +++ b/src/testing/memory-tool-runtime.ts @@ -3,7 +3,7 @@ import path from 'node:path'; import { Worker } from 'node:worker_threads'; import { z } from 'zod'; import { ToolError, errorMessage } from '../core/errors.js'; -import { findMatchingPattern, normalizeDrivePath, normalizeSeparators, pathPatternRegExp } from '../core/paths.js'; +import { findMatchingPattern, isUncPath, normalizeDrivePath, normalizeSeparators, pathPatternRegExp } from '../core/paths.js'; import { MAX_ARG_CHARS } from '../core/schemas.js'; import type { PolicySnapshot, @@ -23,28 +23,56 @@ export function sha256(text: string): string { return createHash('sha256').update(text, 'utf8').digest('hex'); } -/** Minimal whole-file unified diff, good enough for tests. Builds no per-line arrays. */ +/** Lines one prepared diff may cover, before and after together. */ +export const MAX_DIFF_LINES = 200_000; +/** Replacements one prepared edit may make. */ +export const MAX_EDIT_REPLACEMENTS = 50_000; + +/** + * Non-overlapping literal occurrences of `needle` (not empty) in `text`, + * counting at most `limit`, without building arrays. + */ +function countOccurrences(text: string, needle: string, limit: number): number { + let count = 0; + for (let at = text.indexOf(needle); at !== -1 && count < limit; at = text.indexOf(needle, at + needle.length)) count++; + return count; +} + +/** + * Diff lines a text of this length and number of line breaks counts against + * `MAX_DIFF_LINES`: an upper bound of its diff rows that needs no text, so an + * edit can be sized before its result exists. + */ +const budgetLines = (length: number, newlines: number): number => (length === 0 ? 0 : newlines + 1); + +/** Refuses a diff over `MAX_DIFF_LINES` before any of it is built. */ +function checkDiffLines(lines: number): void { + if (lines > MAX_DIFF_LINES) { + throw new ToolError('invalid-args', `the change would diff more than ${MAX_DIFF_LINES} lines; split it into smaller changes`); + } +} + +/** + * Minimal whole-file unified diff, good enough for tests. Builds no per-line + * arrays and refuses, before building anything, a diff over `MAX_DIFF_LINES`. + */ export function simpleDiff(file: string, before: string | null, after: string): string { - const side = (prefix: string, content: string): { rows: number; text: string } => { - if (content === '') return { rows: 0, text: '' }; + const measure = (content: string): { newlines: number; rows: number } => { + const newlines = countOccurrences(content, '\n', MAX_DIFF_LINES + 1); + return { newlines, rows: content === '' ? 0 : content.endsWith('\n') ? newlines : newlines + 1 }; + }; + const a = measure(before ?? ''); + checkDiffLines(budgetLines(before?.length ?? 0, a.newlines)); + const b = measure(after); + checkDiffLines(budgetLines(before?.length ?? 0, a.newlines) + budgetLines(after.length, b.newlines)); + const side = (prefix: string, content: string): string => { + if (content === '') return ''; const newline = content.endsWith('\n'); const body = newline ? content.slice(0, -1) : content; - let rows = 1; - for (let at = body.indexOf('\n'); at !== -1; at = body.indexOf('\n', at + 1)) rows++; - const text = `${prefix}${body.replaceAll('\n', `\n${prefix}`)}\n${newline ? '' : '\\ No newline at end of file\n'}`; - return { rows, text }; + return `${prefix}${body.replaceAll('\n', `\n${prefix}`)}\n${newline ? '' : '\\ No newline at end of file\n'}`; }; - const a = side('-', before ?? ''); - const b = side('+', after); const head = `--- ${before === null ? '/dev/null' : `a${file}`}\n+++ b${file}\n@@ -${a.rows > 0 ? 1 : 0},${a.rows} +${b.rows > 0 ? 1 : 0},${b.rows} @@\n`; - return head + a.text + b.text; -} - -/** Non-overlapping literal occurrences of `needle` (not empty) in `text`, without building arrays. */ -function countOccurrences(text: string, needle: string): number { - let count = 0; - for (let at = text.indexOf(needle); at !== -1; at = text.indexOf(needle, at + needle.length)) count++; - return count; + return head + side('-', before ?? '') + side('+', after); } export interface MemoryToolRuntimeOptions { @@ -210,6 +238,16 @@ function searchInWorker( const regExpSource = (re: RegExp): { source: string; flags: string } => ({ source: re.source, flags: re.flags }); +/** + * Returns `p`, or refuses a network-share (UNC) path: POSIX resolution folds + * its leading `//` while protected-path patterns keep it, so the two would + * name the same share differently. + */ +function refuseUnc(p: string): string { + if (isUncPath(p)) throw new ToolError('outside-workspace', `${p} is a network share path, which is not supported`); + return p; +} + function isInside(abs: string, root: string): boolean { const rel = posix.relative(root, abs); return rel !== '..' && !rel.startsWith('../') && !posix.isAbsolute(rel); @@ -285,12 +323,12 @@ export class MemoryToolRuntime implements ToolRuntime { constructor(opts: MemoryToolRuntimeOptions) { this.#opts = opts; - this.root = opts.root === undefined ? undefined : posix.resolve(normalizeDrivePath(opts.root)); + this.root = opts.root === undefined ? undefined : posix.resolve(normalizeDrivePath(refuseUnc(opts.root))); for (const [p, content] of Object.entries(opts.files ?? {})) this.files.set(this.#abs(p), content); } #abs(p: string): string { - return posix.resolve(this.root ?? '/', normalizeDrivePath(p)); + return posix.resolve(this.root ?? '/', normalizeDrivePath(refuseUnc(p))); } /** Sets a file, or deletes it when `content` is null, and returns its new revision. */ @@ -318,8 +356,8 @@ export class MemoryToolRuntime implements ToolRuntime { /** Resolves `p` against the session cwd and keeps it inside the fixed root, or else the session cwd and roots. */ #resolve(p: string, ctx: SessionContext): string { - const abs = posix.resolve(normalizeDrivePath(ctx.cwd), normalizeDrivePath(p)); - const roots = this.root === undefined ? [ctx.cwd, ...ctx.roots].map((root) => posix.resolve(normalizeDrivePath(root))) : [this.root]; + const abs = posix.resolve(normalizeDrivePath(refuseUnc(ctx.cwd)), normalizeDrivePath(refuseUnc(p))); + const roots = this.root === undefined ? [ctx.cwd, ...ctx.roots].map((root) => posix.resolve(normalizeDrivePath(refuseUnc(root)))) : [this.root]; if (!roots.some((root) => isInside(abs, root))) { throw new ToolError('outside-workspace', `${p} is outside the workspace ${roots.join(', ')}`); } @@ -388,15 +426,25 @@ export class MemoryToolRuntime implements ToolRuntime { this.#protect(absPath, policy); const before = this.files.get(absPath); if (before === undefined) throw new ToolError('not-found', `${absPath} does not exist`); - const count = countOccurrences(before, call.args.oldString); + const { oldString, newString } = call.args; + const count = countOccurrences(before, oldString, MAX_EDIT_REPLACEMENTS + 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 times = count > MAX_EDIT_REPLACEMENTS ? `more than ${MAX_EDIT_REPLACEMENTS}` : `${count}`; + throw new ToolError('invalid-args', `oldString matches ${times} times in ${absPath}; pass replaceAll or a longer oldString`); + } + if (count > MAX_EDIT_REPLACEMENTS) { + throw new ToolError('invalid-args', `oldString matches more than ${MAX_EDIT_REPLACEMENTS} times in ${absPath}; split the edit`); } const replacements = call.args.replaceAll === true ? count : 1; - const afterLength = before.length + replacements * (call.args.newString.length - call.args.oldString.length); + const afterLength = before.length + replacements * (newString.length - oldString.length); if (afterLength > MAX_ARG_CHARS) throw new ToolError('invalid-args', 'edited content is too large'); - const newString = call.args.newString; + // Size the diff from counts alone, so an oversized edit builds neither its text nor its diff. + const newlines = (text: string): number => countOccurrences(text, '\n', MAX_DIFF_LINES + 1); + const newlinesBefore = newlines(before); + checkDiffLines(budgetLines(before.length, newlinesBefore)); + const newlinesAfter = newlinesBefore + replacements * (newlines(newString) - newlines(oldString)); + checkDiffLines(budgetLines(before.length, newlinesBefore) + budgetLines(afterLength, newlinesAfter)); const afterContent = call.args.replaceAll === true ? before.replaceAll(call.args.oldString, () => newString) : before.replace(call.args.oldString, () => newString); return { From c61beddef7a8e302539a27b8e496a1970cd97b72 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:19:40 -0300 Subject: [PATCH 13/17] Refuse UNC session roots under a fixed root and count diff rows exactly - The session roots are checked for network-share (UNC) paths even when a fixed root replaces them, so a UNC session root is refused, not ignored. - setFile and revision refuse UNC paths like every other path entry point. - The diff line budget counts the rows the diff actually has: a text that ends with a line break no longer counts one extra row. Edit preparation works out whether the edited text ends with one from where the replaced occurrences sit, still before building the text or the diff, so diffs of up to MAX_DIFF_LINES rows are prepared and only larger ones refused. Co-Authored-By: Claude Opus 5.5 --- src/testing/memory-tool-runtime.test.ts | 49 +++++++++++++- src/testing/memory-tool-runtime.ts | 89 +++++++++++++++++-------- 2 files changed, 109 insertions(+), 29 deletions(-) diff --git a/src/testing/memory-tool-runtime.test.ts b/src/testing/memory-tool-runtime.test.ts index e6473a0..29d8de8 100644 --- a/src/testing/memory-tool-runtime.test.ts +++ b/src/testing/memory-tool-runtime.test.ts @@ -142,7 +142,7 @@ describe('MemoryToolRuntime', () => { it('refuses an edit over the replacement or diff budget before building its text or diff', async () => { const tooMany = 'a'.repeat(MAX_EDIT_REPLACEMENTS + 1); - const tooLong = `head\n${'x\n'.repeat(MAX_DIFF_LINES / 2 - 1)}`; + const tooLong = `head\n${'x\n'.repeat(MAX_DIFF_LINES / 2)}`; const tools = new MemoryToolRuntime({ root: '/ws', files: { 'many.txt': tooMany, 'long.txt': tooLong } }); const replaceAll = vi.spyOn(String.prototype, 'replaceAll'); const replace = vi.spyOn(String.prototype, 'replace'); @@ -183,4 +183,51 @@ describe('MemoryToolRuntime', () => { `--- a/ws/long.txt\n+++ b/ws/long.txt\n@@ -1,${lines} +1,${lines} @@\n-head\n${'-x\n'.repeat(lines - 1)}+y\n${'+x\n'.repeat(lines - 1)}`, ); }); + + it('refuses a network-share session root even when a fixed root replaces the session roots', async () => { + for (const share of ['\\\\server\\share', '//server/share']) { + const tools = new MemoryToolRuntime({ root: '/ws', files: { 'note.txt': 'before' } }); + const ctx = makeContext('/ws', { roots: ['/ws', share] }); + await expect(prepare(tools, 'write', { path: 'note.txt', content: 'after' }, ctx)).rejects.toMatchObject({ code: 'outside-workspace', message: expect.stringContaining('network share') }); + expect(tools.read('note.txt')).toBe('before'); + } + }); + + it('refuses network-share paths in setFile and revision', () => { + const tools = new MemoryToolRuntime({}); + for (const file of ['\\\\server\\share\\note.txt', '//server/share/note.txt']) { + expect(() => tools.setFile(file, 'x')).toThrow(expect.objectContaining({ code: 'outside-workspace' })); + expect(() => tools.revision(file)).toThrow(expect.objectContaining({ code: 'outside-workspace' })); + } + expect(tools.files.size).toBe(0); + }); + + it('counts diff rows exactly at the line budget when both texts end with a line break', async () => { + // 100,000 rows before; the edits below leave 99,999, 100,000 or 100,001 rows after. + const before = `head\n${'x\n'.repeat(MAX_DIFF_LINES / 2 - 2)}x\n`; + const rows = (diff: string): number => { + const header = /^@@ -\d+,(\d+) \+\d+,(\d+) @@$/m.exec(diff); + return Number(header?.[1]) + Number(header?.[2]); + }; + for (const [oldString, total] of [['head\nx\n', MAX_DIFF_LINES - 1], ['head\n', MAX_DIFF_LINES]] as const) { + const tools = new MemoryToolRuntime({ root: '/ws', files: { 'a.txt': before } }); + const newString = 'post\n'; + const edit = await prepare(tools, 'edit', { path: 'a.txt', oldString, newString }); + const after = `${newString}${before.slice(oldString.length)}`; + expect(edit).toMatchObject({ effect: { afterContent: after, diff: simpleDiff('/ws/a.txt', before, after) } }); + expect(edit.tool === 'edit' && rows(edit.effect.diff)).toBe(total); + } + const over = new MemoryToolRuntime({ root: '/ws', files: { 'a.txt': before } }); + await expect(prepare(over, 'edit', { path: 'a.txt', oldString: 'head\n', newString: 'post\nnew\n' })).rejects.toMatchObject({ code: 'invalid-args' }); + // Deleting a back-to-back run at the end leaves a text ending with the line break before the run: + // 100,002 rows before and 99,998 after, since the first match also joins two lines. + const lines = 'x\n'.repeat(MAX_DIFF_LINES / 2 - 3); + const trimmed = new MemoryToolRuntime({ root: '/ws', files: { 'a.txt': `a\nzb\n${lines}\nz\nz` } }); + const trim = await prepare(trimmed, 'edit', { path: 'a.txt', oldString: '\nz', newString: '', replaceAll: true }); + expect(trim).toMatchObject({ effect: { afterContent: `ab\n${lines}`, replacements: 3 } }); + expect(trim.tool === 'edit' && rows(trim.effect.diff)).toBe(MAX_DIFF_LINES); + expect(rows(simpleDiff('/f', before, before.slice('head\n'.length)))).toBe(MAX_DIFF_LINES - 1); + expect(rows(simpleDiff('/f', before, `y${before}`))).toBe(MAX_DIFF_LINES); + expect(() => simpleDiff('/f', before, `y\n${before}`)).toThrow(expect.objectContaining({ code: 'invalid-args' })); + }); }); diff --git a/src/testing/memory-tool-runtime.ts b/src/testing/memory-tool-runtime.ts index c009038..438ad01 100644 --- a/src/testing/memory-tool-runtime.ts +++ b/src/testing/memory-tool-runtime.ts @@ -28,22 +28,42 @@ export const MAX_DIFF_LINES = 200_000; /** Replacements one prepared edit may make. */ export const MAX_EDIT_REPLACEMENTS = 50_000; +/** Where the non-overlapping literal occurrences of a needle sit in a text. */ +interface Matches { + /** Occurrences found, at most the scan limit. */ + readonly count: number; + /** Start of the first occurrence, or -1. */ + readonly first: number; + /** End of the last occurrence found. */ + readonly lastEnd: number; + /** Start of the run of back-to-back occurrences that ends with the last one. */ + readonly lastRunStart: number; +} + /** - * Non-overlapping literal occurrences of `needle` (not empty) in `text`, - * counting at most `limit`, without building arrays. + * Scans the non-overlapping literal occurrences of `needle` (not empty) in + * `text`, stopping after `limit`, without building arrays. */ -function countOccurrences(text: string, needle: string, limit: number): number { +function scanMatches(text: string, needle: string, limit: number): Matches { let count = 0; - for (let at = text.indexOf(needle); at !== -1 && count < limit; at = text.indexOf(needle, at + needle.length)) count++; - return count; + let first = -1; + let lastEnd = -1; + let lastRunStart = -1; + for (let at = text.indexOf(needle); at !== -1 && count < limit; at = text.indexOf(needle, at + needle.length)) { + if (count === 0) first = at; + if (at !== lastEnd) lastRunStart = at; + lastEnd = at + needle.length; + count++; + } + return { count, first, lastEnd, lastRunStart }; } -/** - * Diff lines a text of this length and number of line breaks counts against - * `MAX_DIFF_LINES`: an upper bound of its diff rows that needs no text, so an - * edit can be sized before its result exists. - */ -const budgetLines = (length: number, newlines: number): number => (length === 0 ? 0 : newlines + 1); +/** Line breaks in `text`, counting at most one more than `MAX_DIFF_LINES`. */ +const countNewlines = (text: string): number => scanMatches(text, '\n', MAX_DIFF_LINES + 1).count; + +/** Diff rows of a text from its length, line breaks and whether it ends with one, as `simpleDiff` counts them. */ +const diffRows = (length: number, newlines: number, endsWithNewline: boolean): number => + length === 0 ? 0 : endsWithNewline ? newlines : newlines + 1; /** Refuses a diff over `MAX_DIFF_LINES` before any of it is built. */ function checkDiffLines(lines: number): void { @@ -57,21 +77,18 @@ function checkDiffLines(lines: number): void { * arrays and refuses, before building anything, a diff over `MAX_DIFF_LINES`. */ export function simpleDiff(file: string, before: string | null, after: string): string { - const measure = (content: string): { newlines: number; rows: number } => { - const newlines = countOccurrences(content, '\n', MAX_DIFF_LINES + 1); - return { newlines, rows: content === '' ? 0 : content.endsWith('\n') ? newlines : newlines + 1 }; - }; - const a = measure(before ?? ''); - checkDiffLines(budgetLines(before?.length ?? 0, a.newlines)); - const b = measure(after); - checkDiffLines(budgetLines(before?.length ?? 0, a.newlines) + budgetLines(after.length, b.newlines)); + const rows = (content: string): number => diffRows(content.length, countNewlines(content), content.endsWith('\n')); + const rowsBefore = rows(before ?? ''); + checkDiffLines(rowsBefore); + const rowsAfter = rows(after); + checkDiffLines(rowsBefore + rowsAfter); const side = (prefix: string, content: string): string => { if (content === '') return ''; const newline = content.endsWith('\n'); const body = newline ? content.slice(0, -1) : content; return `${prefix}${body.replaceAll('\n', `\n${prefix}`)}\n${newline ? '' : '\\ No newline at end of file\n'}`; }; - const head = `--- ${before === null ? '/dev/null' : `a${file}`}\n+++ b${file}\n@@ -${a.rows > 0 ? 1 : 0},${a.rows} +${b.rows > 0 ? 1 : 0},${b.rows} @@\n`; + const head = `--- ${before === null ? '/dev/null' : `a${file}`}\n+++ b${file}\n@@ -${rowsBefore > 0 ? 1 : 0},${rowsBefore} +${rowsAfter > 0 ? 1 : 0},${rowsAfter} @@\n`; return head + side('-', before ?? '') + side('+', after); } @@ -238,6 +255,18 @@ function searchInWorker( const regExpSource = (re: RegExp): { source: string; flags: string } => ({ source: re.source, flags: re.flags }); +/** + * Whether the edited text ends with a line break, read from where the + * replaced occurrences sit instead of from the text, which does not exist yet. + * The character before a replaced run is never itself replaced. + */ +function editEndsWithNewline(before: string, matches: Matches, replaceAll: boolean, oldString: string, newString: string): boolean { + const replacedEnd = replaceAll ? matches.lastEnd : matches.first + oldString.length; + if (replacedEnd !== before.length) return before.endsWith('\n'); + if (newString !== '') return newString.endsWith('\n'); + return before[(replaceAll ? matches.lastRunStart : matches.first) - 1] === '\n'; +} + /** * Returns `p`, or refuses a network-share (UNC) path: POSIX resolution folds * its leading `//` while protected-path patterns keep it, so the two would @@ -333,6 +362,7 @@ export class MemoryToolRuntime implements ToolRuntime { /** Sets a file, or deletes it when `content` is null, and returns its new revision. */ setFile(absPath: string, content: string | null, revision: number = this.#nextRevision++): number { + refuseUnc(absPath); if (content === null) this.files.delete(absPath); else this.files.set(absPath, content); if (revision === 0) this.#revisions.delete(absPath); @@ -342,7 +372,7 @@ export class MemoryToolRuntime implements ToolRuntime { /** Revision of the last change made through this runtime, if any. */ revision(absPath: string): number { - return this.#revisions.get(absPath) ?? 0; + return this.#revisions.get(refuseUnc(absPath)) ?? 0; } /** Simulates a change made outside the run. */ @@ -356,8 +386,10 @@ export class MemoryToolRuntime implements ToolRuntime { /** Resolves `p` against the session cwd and keeps it inside the fixed root, or else the session cwd and roots. */ #resolve(p: string, ctx: SessionContext): string { + // The session cwd and roots are refused even when a fixed root replaces them. + for (const root of ctx.roots) refuseUnc(root); const abs = posix.resolve(normalizeDrivePath(refuseUnc(ctx.cwd)), normalizeDrivePath(refuseUnc(p))); - const roots = this.root === undefined ? [ctx.cwd, ...ctx.roots].map((root) => posix.resolve(normalizeDrivePath(refuseUnc(root)))) : [this.root]; + const roots = this.root === undefined ? [ctx.cwd, ...ctx.roots].map((root) => posix.resolve(normalizeDrivePath(root))) : [this.root]; if (!roots.some((root) => isInside(abs, root))) { throw new ToolError('outside-workspace', `${p} is outside the workspace ${roots.join(', ')}`); } @@ -427,7 +459,8 @@ export class MemoryToolRuntime implements ToolRuntime { const before = this.files.get(absPath); if (before === undefined) throw new ToolError('not-found', `${absPath} does not exist`); const { oldString, newString } = call.args; - const count = countOccurrences(before, oldString, MAX_EDIT_REPLACEMENTS + 1); + const matches = scanMatches(before, oldString, MAX_EDIT_REPLACEMENTS + 1); + const count = matches.count; if (count === 0) throw new ToolError('not-found', `oldString not found in ${absPath}`); if (count > 1 && call.args.replaceAll !== true) { const times = count > MAX_EDIT_REPLACEMENTS ? `more than ${MAX_EDIT_REPLACEMENTS}` : `${count}`; @@ -440,11 +473,11 @@ export class MemoryToolRuntime implements ToolRuntime { const afterLength = before.length + replacements * (newString.length - oldString.length); if (afterLength > MAX_ARG_CHARS) throw new ToolError('invalid-args', 'edited content is too large'); // Size the diff from counts alone, so an oversized edit builds neither its text nor its diff. - const newlines = (text: string): number => countOccurrences(text, '\n', MAX_DIFF_LINES + 1); - const newlinesBefore = newlines(before); - checkDiffLines(budgetLines(before.length, newlinesBefore)); - const newlinesAfter = newlinesBefore + replacements * (newlines(newString) - newlines(oldString)); - checkDiffLines(budgetLines(before.length, newlinesBefore) + budgetLines(afterLength, newlinesAfter)); + const newlinesBefore = countNewlines(before); + const rowsBefore = diffRows(before.length, newlinesBefore, before.endsWith('\n')); + checkDiffLines(rowsBefore); + const newlinesAfter = newlinesBefore + replacements * (countNewlines(newString) - countNewlines(oldString)); + checkDiffLines(rowsBefore + diffRows(afterLength, newlinesAfter, editEndsWithNewline(before, matches, call.args.replaceAll === true, oldString, newString))); const afterContent = call.args.replaceAll === true ? before.replaceAll(call.args.oldString, () => newString) : before.replace(call.args.oldString, () => newString); return { From 7396009c3572746acdec2eda879fec96ba75b71a Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:44:07 -0300 Subject: [PATCH 14/17] fix(review): round 1 Keep POSIX paths with redundant leading slashes local. Return actionable guidance when an edit exceeds the replacement limit. Stop glob after its first extra match and skip setup for cancelled searches. --- src/core/paths.ts | 3 ++- src/testing/memory-tool-runtime.test.ts | 17 +++++++++++++++-- src/testing/memory-tool-runtime.ts | 16 +++++++--------- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/core/paths.ts b/src/core/paths.ts index fc2bbf3..26c7a3f 100644 --- a/src/core/paths.ts +++ b/src/core/paths.ts @@ -60,9 +60,10 @@ export function normalizeDrivePath(p: string): string { /** * Whether `p` is a Windows network-share (UNC) path such as `\\server\share` * or `//server/share`, including `\\?\` device paths. Not supported. + * Three or more leading forward slashes in a POSIX path are redundant. */ export function isUncPath(p: string): boolean { - return /^[\\/]{2}/.test(p); + return /^[\\/]{2}/.test(p) && !(p.startsWith('///') && !p.includes('\\')); } /** Whether file names on this platform are usually case-insensitive. */ diff --git a/src/testing/memory-tool-runtime.test.ts b/src/testing/memory-tool-runtime.test.ts index 29d8de8..fec882d 100644 --- a/src/testing/memory-tool-runtime.test.ts +++ b/src/testing/memory-tool-runtime.test.ts @@ -67,6 +67,13 @@ describe('MemoryToolRuntime', () => { expect(tools.read(file)).toBe('hello'); }); + it('resolves a local POSIX root and file with redundant leading slashes', async () => { + const root = '///ws'; + const tools = new MemoryToolRuntime({ root, files: { 'note.txt': 'hello' } }); + const read = await prepare(tools, 'read', { path: `${root}/note.txt` }, makeContext(root)); + expect(await tools.commit(read, new AbortController().signal)).toMatchObject({ content: 'hello' }); + }); + it('allows two overlapping writes to roll back in reverse order', async () => { const tools = new MemoryToolRuntime({ root: '/ws', files: { 'notes.txt': 'original' } }); const outer = tools.beginTransaction(); @@ -81,8 +88,10 @@ describe('MemoryToolRuntime', () => { it('searches off the main thread, stops at the first extra match and can be stopped', async () => { const atRoot = new MemoryToolRuntime({ files: { '/a.txt': 'one' } }); - expect(await atRoot.commit(await prepare(atRoot, 'glob', { pattern: '*.txt' }, makeContext('/')), new AbortController().signal)).toEqual({ files: ['/a.txt'], truncated: false }); + expect(await atRoot.commit(await prepare(atRoot, 'glob', { pattern: '*.txt', maxResults: 1 }, makeContext('/')), new AbortController().signal)).toEqual({ files: ['/a.txt'], truncated: false }); const tools = new MemoryToolRuntime({ root: '/ws', files: { 'a.txt': 'one\ntwo\none', 'src/b.ts': 'one', 'src/c.md': 'one' } }); + const listed = await tools.commit(await prepare(tools, 'glob', { pattern: '**', maxResults: 1 }), new AbortController().signal); + expect(listed).toEqual({ files: ['/ws/a.txt'], truncated: true }); const found = await tools.commit(await prepare(tools, 'grep', { pattern: 'o.e', glob: '*.ts' }), new AbortController().signal); expect(found).toEqual({ matches: [{ file: '/ws/src/b.ts', line: 1, text: 'one' }], truncated: false }); const capped = await tools.commit(await prepare(tools, 'grep', { pattern: 'ONE', ignoreCase: true, maxResults: 1 }), new AbortController().signal); @@ -90,7 +99,7 @@ describe('MemoryToolRuntime', () => { const controller = new AbortController(); const pending = tools.commit(await prepare(tools, 'grep', { pattern: 'one' }), controller.signal); - controller.abort(); + queueMicrotask(() => controller.abort()); await expect(pending).rejects.toMatchObject({ code: 'cancelled' }); }); @@ -151,6 +160,10 @@ describe('MemoryToolRuntime', () => { code: 'invalid-args', message: expect.stringContaining(`more than ${MAX_EDIT_REPLACEMENTS}`), }); + await expect(prepare(tools, 'edit', { path: 'many.txt', oldString: 'a', newString: 'b' })).rejects.toMatchObject({ + code: 'invalid-args', + message: expect.stringContaining('split the edit'), + }); await expect(prepare(tools, 'edit', { path: 'long.txt', oldString: 'head', newString: 'y' })).rejects.toMatchObject({ code: 'invalid-args', message: expect.stringContaining(`more than ${MAX_DIFF_LINES} lines`), diff --git a/src/testing/memory-tool-runtime.ts b/src/testing/memory-tool-runtime.ts index 438ad01..d02634c 100644 --- a/src/testing/memory-tool-runtime.ts +++ b/src/testing/memory-tool-runtime.ts @@ -134,7 +134,9 @@ const { names, lines, maxResults, files } = workerData; const nameRe = names === null ? null : new RegExp(names.source, names.flags); const keep = []; for (let i = 0; i < files.length; i++) { - if (nameRe === null || files[i][1].some((name) => nameRe.test(name))) keep.push(i); + if (nameRe !== null && !files[i][1].some((name) => nameRe.test(name))) continue; + keep.push(i); + if (lines === null && keep.length > maxResults) break; } if (lines === null) { const truncated = keep.length > maxResults; @@ -199,10 +201,6 @@ function searchInWorker( onExit: () => void, ): Promise { return new Promise((resolve, reject) => { - if (signal.aborted) { - onExit(); - return reject(new ToolError('cancelled', 'the search was stopped')); - } let worker: Worker; try { worker = new Worker(SEARCH_WORKER, { eval: true, workerData: job }); @@ -462,13 +460,12 @@ export class MemoryToolRuntime implements ToolRuntime { const matches = scanMatches(before, oldString, MAX_EDIT_REPLACEMENTS + 1); const count = matches.count; if (count === 0) throw new ToolError('not-found', `oldString not found in ${absPath}`); - if (count > 1 && call.args.replaceAll !== true) { - const times = count > MAX_EDIT_REPLACEMENTS ? `more than ${MAX_EDIT_REPLACEMENTS}` : `${count}`; - throw new ToolError('invalid-args', `oldString matches ${times} times in ${absPath}; pass replaceAll or a longer oldString`); - } if (count > MAX_EDIT_REPLACEMENTS) { throw new ToolError('invalid-args', `oldString matches more than ${MAX_EDIT_REPLACEMENTS} times in ${absPath}; split the edit`); } + 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 replacements = call.args.replaceAll === true ? count : 1; const afterLength = before.length + replacements * (newString.length - oldString.length); if (afterLength > MAX_ARG_CHARS) throw new ToolError('invalid-args', 'edited content is too large'); @@ -576,6 +573,7 @@ export class MemoryToolRuntime implements ToolRuntime { const release = await this.#takeSearchSlot(signal); let pending: Promise; try { + if (signal.aborted) throw new ToolError('cancelled', 'the search was stopped'); pending = this.#startSearch(prepared, signal, release); } catch (err) { // No worker started, so the slot is free again. From fc6026bfd397384d5120be046a9e5d0cc9e7a8e0 Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:57:13 -0300 Subject: [PATCH 15/17] fix(review): round 2 Match local protection patterns and resolved paths with the same leading-slash normalization. Use one resolved key for in-memory reads, writes and file revisions. Co-Authored-By: Claude Opus 5.5 --- src/core/paths.test.ts | 6 ++++++ src/core/paths.ts | 7 ++++++- src/testing/memory-tool-runtime.test.ts | 11 +++++++++++ src/testing/memory-tool-runtime.ts | 10 +++++----- 4 files changed, 28 insertions(+), 6 deletions(-) diff --git a/src/core/paths.test.ts b/src/core/paths.test.ts index b0e79e2..abce18e 100644 --- a/src/core/paths.test.ts +++ b/src/core/paths.test.ts @@ -16,6 +16,12 @@ describe('matchesPathPattern', () => { ['/C:/ws/project/notes.txt', 'C:\\ws\\project\\*.txt', true], ['/ws/a+b.txt', '/ws/a+b.txt', true], ['/ws/aab.txt', '/ws/a+b.txt', false], + ['/ws/.claude/settings.json', '///ws/.claude/settings*.json', true], + ['/ws/.claude/hooks/a.sh', '////ws/.claude/hooks/**', true], + ['///ws/.claude/hooks/a.sh', '/ws/.claude/hooks/**', true], + ['//ws/.claude/settings.json', '/ws/.claude/settings*.json', false], + ['/ws/.claude/settings.json', '//ws/.claude/settings*.json', false], + ['/ws/.claude/settings.json', '///ws\\.claude\\settings*.json', false], ])('%s vs %s → %s', (p, pattern, expected) => { expect(matchesPathPattern(p, pattern, false)).toBe(expected); }); diff --git a/src/core/paths.ts b/src/core/paths.ts index 26c7a3f..7bbed0d 100644 --- a/src/core/paths.ts +++ b/src/core/paths.ts @@ -51,8 +51,13 @@ export function normalizeSeparators(p: string): string { return p.replace(/\\/g, '/'); } -/** Normalizes drive-letter paths for comparison with the in-memory filesystem. */ +/** + * Normalizes drive-letter paths for comparison with the in-memory filesystem, + * and collapses redundant leading slashes of a POSIX path the way path + * resolution does (see `isUncPath`). + */ export function normalizeDrivePath(p: string): string { + if (p.startsWith('///') && !isUncPath(p)) return p.replace(/^\/+/, '/'); const normalized = normalizeSeparators(p); return /^[A-Za-z]:(\/|$)/.test(normalized) ? `/${normalized}` : normalized; } diff --git a/src/testing/memory-tool-runtime.test.ts b/src/testing/memory-tool-runtime.test.ts index fec882d..ddb44b2 100644 --- a/src/testing/memory-tool-runtime.test.ts +++ b/src/testing/memory-tool-runtime.test.ts @@ -206,6 +206,17 @@ describe('MemoryToolRuntime', () => { } }); + it('uses one key for aliased local paths when setting, reading and deleting files', () => { + const tools = new MemoryToolRuntime({ root: '/ws', files: { 'note.txt': 'before' } }); + const revision = tools.setFile('///ws/note.txt', 'after'); + expect(tools.read('/ws/note.txt')).toBe('after'); + expect(tools.revision('/ws/note.txt')).toBe(revision); + expect(tools.revision('///ws/note.txt')).toBe(revision); + + tools.setFile('///ws/note.txt', null); + expect(tools.read('/ws/note.txt')).toBeUndefined(); + }); + it('refuses network-share paths in setFile and revision', () => { const tools = new MemoryToolRuntime({}); for (const file of ['\\\\server\\share\\note.txt', '//server/share/note.txt']) { diff --git a/src/testing/memory-tool-runtime.ts b/src/testing/memory-tool-runtime.ts index d02634c..32ebcda 100644 --- a/src/testing/memory-tool-runtime.ts +++ b/src/testing/memory-tool-runtime.ts @@ -359,8 +359,8 @@ export class MemoryToolRuntime implements ToolRuntime { } /** Sets a file, or deletes it when `content` is null, and returns its new revision. */ - setFile(absPath: string, content: string | null, revision: number = this.#nextRevision++): number { - refuseUnc(absPath); + setFile(path: string, content: string | null, revision: number = this.#nextRevision++): number { + const absPath = this.#abs(path); if (content === null) this.files.delete(absPath); else this.files.set(absPath, content); if (revision === 0) this.#revisions.delete(absPath); @@ -369,13 +369,13 @@ export class MemoryToolRuntime implements ToolRuntime { } /** Revision of the last change made through this runtime, if any. */ - revision(absPath: string): number { - return this.#revisions.get(refuseUnc(absPath)) ?? 0; + revision(path: string): number { + return this.#revisions.get(this.#abs(path)) ?? 0; } /** Simulates a change made outside the run. */ externalWrite(p: string, content: string): void { - this.setFile(this.#abs(p), content); + this.setFile(p, content); } read(p: string): string | undefined { From d1e09f5d34c3b2d89f096a9d30a638cf1ac5b2ab Mon Sep 17 00:00:00 2001 From: mths-mcfs <214165874+mths-mcfs@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:32:19 -0300 Subject: [PATCH 16/17] Finalize the transaction journal before reporting success A successful run returned ok: true while its journal directory still held the manifest, so a crash before the background cleanup let startup recovery undo writes already acknowledged. Transaction.dispose() now commits by renaming the journal directory to .committed and fsyncing the journal root; recovery never undoes such a directory and only deletes it. runScript awaits that commit before returning ok: true. Writes still running after the grace period, or a failed rename, roll the run back; a rename that succeeded with a failed fsync returns TransactionIndeterminate without a rollback. File systems that do not support directory fsync (EINVAL, ENOTSUP, EOPNOTSUPP) get the same guarantee as Windows. Fixes #14. Co-Authored-By: Claude Opus 5.5 --- src/core/errors.ts | 16 ++++++ src/core/run.test.ts | 104 ++++++++++++++++++++++++++++++++++++++ src/core/run.ts | 35 +++++++++++-- src/core/types.ts | 6 ++- src/tools/fs-ops.test.ts | 20 ++++++++ src/tools/fs-ops.ts | 34 ++++++++++--- src/tools/journal.test.ts | 70 +++++++++++++++++++++++-- src/tools/journal.ts | 67 ++++++++++++++++++++++-- 8 files changed, 332 insertions(+), 20 deletions(-) create mode 100644 src/tools/fs-ops.test.ts diff --git a/src/core/errors.ts b/src/core/errors.ts index 0fa9c1c..7bd475a 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -18,6 +18,22 @@ export class ToolError extends Error { } } +/** + * Thrown by `Transaction.dispose()` when the journal could not be finalized. + * `committed: false`: the journal is intact and can still be rolled back. + * `committed: true`: the journal is out of recovery's reach (the changes are + * kept), but the step that makes that durable failed. + */ +export class TransactionFinalizeError extends Error { + override readonly name = 'TransactionFinalizeError'; + readonly committed: boolean; + + constructor(committed: boolean, message: string) { + super(message); + this.committed = committed; + } +} + /** Message of any thrown value, without trusting its shape. */ export function errorMessage(err: unknown): string { if (err instanceof Error) return err.message; diff --git a/src/core/run.test.ts b/src/core/run.test.ts index 7918581..9280698 100644 --- a/src/core/run.test.ts +++ b/src/core/run.test.ts @@ -3,6 +3,7 @@ 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 { TransactionFinalizeError } from './errors.js'; import { resolveTimeoutMs, runScript, toRunRequest } from './run.js'; import type { Sandbox } from './types.js'; @@ -281,6 +282,109 @@ describe('runScript', () => { await vi.waitFor(() => expect(events).toEqual(['rollback', 'dispose'])); }); + it('reports success only after the journal is finalized', async () => { + const d = deps(); + let finalize = (): void => undefined; + const gate = new Promise((r) => (finalize = r)); + let disposeCalls = 0; + const begin = d.tools.beginTransaction.bind(d.tools); + d.tools.beginTransaction = () => { + const tx = begin(); + const dispose = tx.dispose.bind(tx); + tx.dispose = async () => { + disposeCalls++; + await gate; + await dispose(); + }; + return tx; + }; + let settled = false; + const running = runScript( + { code: script([{ tool: 'write', args: { path: 'a.txt', content: 'x' } }]), transaction: true, timeoutMs: 5_000 }, + d, + ).then((r) => ((settled = true), r)); + await vi.waitFor(() => expect(disposeCalls).toBe(1)); + await new Promise((r) => setTimeout(r, 20)); + expect(settled).toBe(false); + finalize(); + const result = await running; + expect(result.ok).toBe(true); + expect(d.tools.read('a.txt')).toBe('x'); + await new Promise((r) => setTimeout(r, 10)); + expect(disposeCalls).toBe(1); + }); + + it('fails and rolls back a successful script when the journal cannot be finalized', async () => { + const d = deps({}, { 'a.txt': 'original' }); + const begin = d.tools.beginTransaction.bind(d.tools); + const rollbacks = vi.fn(); + d.tools.beginTransaction = () => { + const tx = begin(); + const rollback = tx.rollback.bind(tx); + tx.dispose = async () => { + throw new TransactionFinalizeError(false, 'rename failed'); + }; + tx.rollback = () => (rollbacks(), rollback()); + return tx; + }; + const result = await runScript( + { code: script([{ tool: 'write', args: { path: 'a.txt', content: 'changed' } }]), transaction: true, timeoutMs: 5_000 }, + d, + ); + expect(result.ok).toBe(false); + expect(result.error).toMatchObject({ kind: 'internal', name: 'TransactionNotFinalized' }); + expect(result.error?.message).toContain('rename failed'); + expect(rollbacks).toHaveBeenCalledTimes(1); + expect(result.rolledBack?.restored).toEqual(['/ws/a.txt']); + expect(d.tools.read('a.txt')).toBe('original'); + }); + + it('reports an indeterminate outcome when the journal was committed but not flushed, without rolling back', async () => { + const d = deps({}, { 'a.txt': 'original' }); + const begin = d.tools.beginTransaction.bind(d.tools); + const rollbacks = vi.fn(); + let disposeCalls = 0; + d.tools.beginTransaction = () => { + const tx = begin(); + const rollback = tx.rollback.bind(tx); + tx.dispose = async () => { + disposeCalls++; + throw new TransactionFinalizeError(true, 'the transaction journal was finalized, but flushing it to disk failed'); + }; + tx.rollback = () => (rollbacks(), rollback()); + return tx; + }; + const result = await runScript( + { code: script([{ tool: 'write', args: { path: 'a.txt', content: 'changed' } }]), transaction: true, timeoutMs: 5_000 }, + d, + ); + expect(result.ok).toBe(false); + expect(result.error).toMatchObject({ kind: 'internal', name: 'TransactionIndeterminate' }); + expect(result.rolledBack).toBeUndefined(); + expect(result.warnings.join('\n')).toContain('are on disk and were not rolled back'); + await new Promise((r) => setTimeout(r, 20)); + expect(rollbacks).not.toHaveBeenCalled(); + expect(disposeCalls).toBe(1); + expect(d.tools.read('a.txt')).toBe('changed'); + }); + + it('fails and rolls back a successful script whose write is still running after the grace', async () => { + const tools = new MemoryToolRuntime({ root: '/ws', commitDelayMs: 60, honorAbortInCommit: false }); + const sandbox: Sandbox = { + run: async (_code, opts) => { + void opts.onCall('write', { path: 'late.txt', content: 'late' }); + await new Promise((r) => setTimeout(r, 5)); + return { ok: true, value: 'done' }; + }, + }; + const result = await runScript({ code: 'x', transaction: true, timeoutMs: 5_000 }, { ...deps(), tools, sandbox, stopGraceMs: 10 }); + expect(result.ok).toBe(false); + expect(result.error).toMatchObject({ kind: 'internal', name: 'TransactionNotFinalized' }); + expect(result.warnings.join('\n')).toContain('the rollback is pending'); + await vi.waitFor(() => expect(tools.commits).toHaveLength(1)); + await vi.waitFor(() => expect(tools.read('late.txt')).toBeUndefined()); + }); + it('counts policy loading against the deadline and gives the sandbox only the time left', async () => { let clock = 0; const budgets: number[] = []; diff --git a/src/core/run.ts b/src/core/run.ts index ddc3185..d492f54 100644 --- a/src/core/run.ts +++ b/src/core/run.ts @@ -1,5 +1,5 @@ import { Dispatcher, type StopReason } from './dispatcher.js'; -import { errorMessage } from './errors.js'; +import { TransactionFinalizeError, errorMessage } from './errors.js'; import { DEFAULT_RUN_TIMEOUT_MS, MAX_RUN_TIMEOUT_MS, type RunArgs } from './schemas.js'; import type { CallLogEntry, @@ -216,6 +216,8 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise | undefined; + /** Set once the journal was committed (durably or not); nothing after may roll back or finalize again. */ + let finalized = false; const stop = (reason: StopReason): void => { if (stopReason !== undefined) return; @@ -282,10 +284,33 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise(req: RunRequest, deps: RunDeps

): Promise(req: RunRequest, deps: RunDeps

): Promise undefined).then(() => journal.dispose()).catch(() => undefined); diff --git a/src/core/types.ts b/src/core/types.ts index 34193eb..acf6462 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -499,7 +499,11 @@ export interface RollbackReport { export interface Transaction { /** Restores every journaled file whose content is still what this run wrote. */ rollback(): Promise; - /** Releases the journal (keeps the changes). Idempotent. */ + /** + * Finalizes the journal (keeps the changes): once it resolves, no recovery + * can undo them. Idempotent; a no-op after a rollback. Rejects with a + * `TransactionFinalizeError` when finalization failed. + */ dispose(): Promise; } diff --git a/src/tools/fs-ops.test.ts b/src/tools/fs-ops.test.ts new file mode 100644 index 0000000..6ae5885 --- /dev/null +++ b/src/tools/fs-ops.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; +import { syncDirStrict } from './fs-ops.js'; + +const failWith = (code: string) => async (): Promise => { + throw Object.assign(new Error(`${code}: directory fsync`), { code }); +}; + +describe.skipIf(process.platform === 'win32')('syncDirStrict', () => { + it.each(['EINVAL', 'ENOTSUP', 'EOPNOTSUPP'])('treats %s as a file system without directory fsync', async (code) => { + await expect(syncDirStrict('/any', failWith(code))).resolves.toBeUndefined(); + }); + + it.each(['EIO', 'ENOSPC'])('rethrows %s', async (code) => { + await expect(syncDirStrict('/any', failWith(code))).rejects.toMatchObject({ code }); + }); + + it('flushes a real directory', async () => { + await expect(syncDirStrict(process.cwd())).resolves.toBeUndefined(); + }); +}); diff --git a/src/tools/fs-ops.ts b/src/tools/fs-ops.ts index c78a523..b19ba15 100644 --- a/src/tools/fs-ops.ts +++ b/src/tools/fs-ops.ts @@ -348,19 +348,39 @@ export async function removeEmptyDirInside(dir: string, roots: readonly string[] /** fsyncs a directory where the platform allows it. */ export async function syncDir(dir: string): Promise { - if (IS_WINDOWS) return; try { - const handle = await fs.open(dir, FS.O_RDONLY); - try { - await handle.sync(); - } finally { - await handle.close(); - } + await syncDirStrict(dir); } catch { // Not every file system lets a directory be flushed. } } +/** Opens a directory and fsyncs it. */ +async function flushDir(dir: string): Promise { + const handle = await fs.open(dir, FS.O_RDONLY); + try { + await handle.sync(); + } finally { + await handle.close(); + } +} + +/** Errors that mean the file system cannot fsync a directory at all (FUSE, 9p, some NFS). */ +const UNSUPPORTED_SYNC = new Set(['EINVAL', 'ENOTSUP', 'EOPNOTSUPP']); + +/** fsyncs a directory and rethrows any failure, except where directory fsync is not supported. */ +export async function syncDirStrict(dir: string, flush: (dir: string) => Promise = flushDir): Promise { + // Windows, and file systems that answer EINVAL/ENOTSUP/EOPNOTSUPP, cannot fsync a directory: a rename there stays atomic but is not guaranteed to survive a power loss. + if (IS_WINDOWS) return; + try { + await flush(dir); + } catch (err) { + const code = errnoCode(err); + if (code !== undefined && UNSUPPORTED_SYNC.has(code)) return; + throw err; + } +} + /** Writes and fsyncs a private file (journal records). */ export async function writeDurable(file: string, data: Buffer | string): Promise { const handle = await fs.open(file, FS.O_WRONLY | FS.O_CREAT | FS.O_TRUNC, 0o600); diff --git a/src/tools/journal.test.ts b/src/tools/journal.test.ts index 91bf991..7a99106 100644 --- a/src/tools/journal.test.ts +++ b/src/tools/journal.test.ts @@ -2,11 +2,12 @@ import { spawnSync } from 'node:child_process'; import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { ToolError } from '../core/errors.js'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { ToolError, TransactionFinalizeError } from '../core/errors.js'; import type { PolicySnapshot, SessionContext, ToolCall, Transaction } from '../core/types.js'; import { makeContext } from '../testing/context.js'; -import { FileTransaction, journalRoot, recoverStaleJournals } from './journal.js'; +import { COMMITTED, FileTransaction, type JournalIo, journalRoot, recoverStaleJournals } from './journal.js'; +import { syncDirStrict } from './fs-ops.js'; import { NodeToolRuntime } from './runtime.js'; let base: string; @@ -84,7 +85,7 @@ describe('transactions', () => { await tx.dispose(); await tx.dispose(); expect(read('a.txt')).toBe('a1\n'); - expect(readdirSync(journalRoot(stateDir))).toEqual([]); + await vi.waitFor(() => expect(readdirSync(journalRoot(stateDir))).toEqual([])); await expect(write('b.txt', 'b1\n', tx)).rejects.toBeInstanceOf(ToolError); expect(read('b.txt')).toBe('b0\n'); }); @@ -183,3 +184,64 @@ describe('crash recovery', () => { expect(await recoverStaleJournals(stateDir, [ws])).toEqual([]); }); }); + +describe('finalization', () => { + /** Keeps the delete of a finalized journal pending, as if the process died right after the commit. */ + const held = (): Promise => new Promise(() => undefined); + + it('commits by renaming the journal, so recovery never undoes a finalized run', async () => { + const tx = new FileTransaction(stateDir, { syncDir: syncDirStrict, removeDir: held }); + await write('a.txt', 'a1\n', tx); + await write('new.txt', 'n1\n', tx); + await tx.dispose(); + // The delete never ran: the record is still complete, under the committed name. + expect(existsSync(tx.dir)).toBe(false); + expect(existsSync(path.join(`${tx.dir}${COMMITTED}`, 'manifest.json'))).toBe(true); + + expect(await recoverStaleJournals(stateDir, [ws])).toEqual([]); + expect(read('a.txt')).toBe('a1\n'); + expect(read('new.txt')).toBe('n1\n'); + // Recovery deletes what a finalized run left behind. + expect(readdirSync(journalRoot(stateDir))).toEqual([]); + }); + + it('reports a committed but not flushed journal and never rolls it back', async () => { + const io: JournalIo = { + syncDir: async () => { + throw new Error('EIO: flush failed'); + }, + removeDir: held, + }; + const tx = new FileTransaction(stateDir, io); + await write('a.txt', 'a1\n', tx); + const err = await tx.dispose().then( + () => undefined, + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(TransactionFinalizeError); + expect(err).toMatchObject({ committed: true }); + expect(String(err)).toMatch(/durability is not guaranteed/); + expect(existsSync(path.join(`${tx.dir}${COMMITTED}`, 'manifest.json'))).toBe(true); + expect(await tx.rollback()).toEqual({ restored: [], skipped: [] }); + expect(await recoverStaleJournals(stateDir, [ws])).toEqual([]); + expect(read('a.txt')).toBe('a1\n'); + }); + + it('keeps the journal open for a rollback when the commit rename fails', async () => { + const tx = rt.beginTransaction(); + if (!(tx instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'a1\n', tx); + // A non-empty directory in the way makes the rename fail. + mkdirSync(path.join(`${tx.dir}${COMMITTED}`, 'blocker'), { recursive: true }); + const err = await tx.dispose().then( + () => undefined, + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(TransactionFinalizeError); + expect(err).toMatchObject({ committed: false }); + expect(existsSync(path.join(tx.dir, 'manifest.json'))).toBe(true); + const report = await tx.rollback(); + expect(report.restored).toEqual([path.join(ws, 'a.txt')]); + expect(read('a.txt')).toBe('a0\n'); + }); +}); diff --git a/src/tools/journal.ts b/src/tools/journal.ts index bd2e793..28ca080 100644 --- a/src/tools/journal.ts +++ b/src/tools/journal.ts @@ -12,7 +12,7 @@ import fs from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { z } from 'zod'; -import { ToolError, errorMessage } from '../core/errors.js'; +import { ToolError, TransactionFinalizeError, errorMessage } from '../core/errors.js'; import type { RollbackReport, Transaction } from '../core/types.js'; import { type RegularFile, @@ -24,6 +24,7 @@ import { removeRegularFile, sha256, syncDir, + syncDirStrict, writeDurable, } from './fs-ops.js'; import { isInsideDir, isInsideGitDir } from './jail.js'; @@ -34,6 +35,12 @@ export const MAX_JOURNAL_BYTES = 64 * 1024 * 1024; const BOOT_SLACK_MS = 10_000; const MANIFEST = 'manifest.json'; const RECOVERING = '.recovering-'; +/** + * Suffix of a finalized transaction directory. Renaming `` to + * `.committed` is the commit point: recovery never undoes such a + * directory, whatever is left in it, and only deletes it. + */ +export const COMMITTED = '.committed'; const EntrySchema = z.object({ path: z.string().min(1), @@ -66,6 +73,19 @@ export function journalRoot(stateDir: string): string { return path.join(stateDir, 'journal'); } +/** File system steps of finalization; replaceable in tests. */ +export interface JournalIo { + /** fsyncs a directory and rejects when that fails. */ + readonly syncDir: (dir: string) => Promise; + /** Deletes a finalized transaction directory. */ + readonly removeDir: (dir: string) => Promise; +} + +const defaultIo: JournalIo = { + syncDir: syncDirStrict, + removeDir: (dir) => fs.rm(dir, { recursive: true, force: true }), +}; + /** Ids of transactions this process still has open; a recovery pass leaves them alone. */ const openTransactions = new Set(); @@ -93,8 +113,10 @@ export class FileTransaction implements Transaction { #created = false; #closed = false; #queue: Promise = Promise.resolve(); + readonly #io: JournalIo; - constructor(stateDir: string) { + constructor(stateDir: string, io: JournalIo = defaultIo) { + this.#io = io; this.id = `${this.#startedAt.toString(36)}-${process.pid}-${randomBytes(4).toString('hex')}`; this.dir = path.join(journalRoot(stateDir), this.id); openTransactions.add(this.id); @@ -223,11 +245,41 @@ export class FileTransaction implements Transaction { }); } + /** + * Commits the journal: renames its directory to `.committed`, which + * recovery never undoes, then fsyncs the journal root so the rename is + * durable. The recursive delete of the renamed directory runs afterwards + * and is not awaited. Rejects with `TransactionFinalizeError`: not + * committed when the rename failed (the journal stays open for a + * rollback), committed when only the fsync failed. + */ dispose(): Promise { return this.#serial(async () => { + if (this.#closed) return; + if (!this.#created) { + this.#closed = true; + openTransactions.delete(this.id); + return; + } + const committed = `${this.dir}${COMMITTED}`; + try { + await fs.rename(this.dir, committed); + } catch (err) { + throw new TransactionFinalizeError(false, `could not finalize the transaction journal: ${errorMessage(err)}`); + } this.#closed = true; + this.#created = false; openTransactions.delete(this.id); - await this.#removeRecord(); + try { + await this.#io.syncDir(path.dirname(this.dir)); + } catch (err) { + throw new TransactionFinalizeError( + true, + `the transaction journal was finalized, but flushing it to disk failed (${errorMessage(err)}); the changes are on disk, but their durability is not guaranteed`, + ); + } finally { + void this.#io.removeDir(committed).catch(() => undefined); + } }); } @@ -343,6 +395,10 @@ async function undoRecord(manifest: Manifest, dir: string, roots: readonly strin return { restored, skipped }; } +function isCommitted(name: string): boolean { + return name.endsWith(COMMITTED); +} + /** * Restores every journal left by a server process that is gone and that * touched one of `roots` (newest first, so two cut-off runs that changed the @@ -358,6 +414,11 @@ export async function recoverStaleJournals(stateDir: string, roots: readonly str return []; } const realRoots = await Promise.all(roots.filter((r) => path.isAbsolute(r)).map(realOrSelf)); + // A finalized run is never undone, whatever its directory still holds; it is only deleted. + for (const name of names.filter(isCommitted)) { + await fs.rm(path.join(base, name), { recursive: true, force: true }).catch(() => undefined); + } + // The id pattern below also rejects `.committed`, so a finalized run is never read as pending. const records = names .map((name) => ({ name, id: name.includes(RECOVERING) ? name.slice(0, name.indexOf(RECOVERING)) : name })) .filter((r) => /^[0-9a-z]+-\d+-[0-9a-f]+$/.test(r.id)) From 03d8f90d3600e70221df325e8dbeb324a3bb31c8 Mon Sep 17 00:00:00 2001 From: mths-mcfs Date: Fri, 20 Nov 2026 02:09:15 -0300 Subject: [PATCH 17/17] fix(review): round 1 - Bound journal finalization by the run deadline and cancellation; never report success or a rollback that has not happened. - Make finalization settle the same way when called again, and keep a committed record whose flush failed. - Refuse a second journaled write to a file another writer changed; roll back only directories the run created. - Undo crashed runs newest write first, skip protected paths, keep records with unhandled files, and read or delete journals only in a private directory with transaction-shaped names. - Flush the journal directories strictly before a write is authorized. - Create files only through an exclusive hard link; check cancellation last before placing a file; use short temporary names. - Open files non-blocking and stop reading at the byte limit. - Protect canonical targets of literal protected paths and the directories a write creates; stop trimming path input; refuse links as search roots. - Refuse commits without prepared policy metadata, and sandboxed bash when a protected pattern cannot be enforced. - Stop the whole bash command when its cwd is gone; strip startup state from the sandbox bootstrap shell; probe that the sandbox can start; do not report a drained exit as a timeout. - Quote diff paths like git and describe empty file creation; reject overlapping and ambiguous-indentation edit matches and oversized edit results; hide file content from edit misses. - Fix gitignore relative paths and directory negation, skip .git files, apply the glob filter to a single file, and treat invalid UTF-8 as binary. - Require Node >=22.12.0, as the sandbox runtime does. Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 2 +- package.json | 2 +- src/core/run.test.ts | 63 +++++++++++ src/core/run.ts | 23 +++- src/tools/bash.test.ts | 11 ++ src/tools/bash.ts | 22 +++- src/tools/diff.test.ts | 16 ++- src/tools/diff.ts | 28 ++++- src/tools/edit-match.test.ts | 20 ++++ src/tools/edit-match.ts | 44 ++++++-- src/tools/fs-ops.test.ts | 9 +- src/tools/fs-ops.ts | 46 +++++--- src/tools/hardening.test.ts | 4 +- src/tools/jail.ts | 39 +++++-- src/tools/journal.test.ts | 134 ++++++++++++++++++++-- src/tools/journal.ts | 212 +++++++++++++++++++++++++---------- src/tools/runtime.test.ts | 123 +++++++++++++++++++- src/tools/runtime.ts | 64 ++++++----- src/tools/sandbox.ts | 38 ++++++- src/tools/search.ts | 23 ++-- 20 files changed, 774 insertions(+), 149 deletions(-) diff --git a/package-lock.json b/package-lock.json index 321bc15..0b8cab9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,7 +22,7 @@ "vitest": "^5.1.0" }, "engines": { - "node": ">=22" + "node": ">=22.12.0" } }, "node_modules/@anthropic-ai/sandbox-runtime": { diff --git a/package.json b/package.json index 0f8d93a..5709af6 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "NOTICE" ], "engines": { - "node": ">=22" + "node": ">=22.12.0" }, "repository": { "type": "git", diff --git a/src/core/run.test.ts b/src/core/run.test.ts index 9280698..5139759 100644 --- a/src/core/run.test.ts +++ b/src/core/run.test.ts @@ -368,6 +368,69 @@ describe('runScript', () => { expect(d.tools.read('a.txt')).toBe('changed'); }); + /** A transaction whose finalization waits for `gate` and then ends as `end` says. */ + function slowFinalization(d: ReturnType, gate: Promise, end: () => Promise, onDispose = (): void => undefined) { + const rollbacks = vi.fn(); + const begin = d.tools.beginTransaction.bind(d.tools); + d.tools.beginTransaction = () => { + const tx = begin(); + const rollback = tx.rollback.bind(tx); + const dispose = tx.dispose.bind(tx); + tx.dispose = async () => { + onDispose(); + await gate; + await end(); + await dispose(); + }; + tx.rollback = () => (rollbacks(), rollback()); + return tx; + }; + return rollbacks; + } + + it('stops waiting for a finalization that outlasts the run, and reports neither success nor a rollback', async () => { + const d = { ...deps({}, { 'a.txt': 'original' }), stopGraceMs: 20 }; + let release = (): void => undefined; + const rollbacks = slowFinalization(d, new Promise((r) => (release = r)), async () => undefined); + const result = await runScript({ code: script([{ tool: 'write', args: { path: 'a.txt', content: 'changed' } }]), transaction: true, timeoutMs: 50 }, d); + expect(result.ok).toBe(false); + expect(result.error).toMatchObject({ kind: 'internal', name: 'TransactionIndeterminate' }); + expect(result.error?.message).toContain('time limit'); + expect(result.rolledBack).toBeUndefined(); + release(); + await new Promise((r) => setTimeout(r, 20)); + expect(rollbacks).not.toHaveBeenCalled(); + expect(d.tools.read('a.txt')).toBe('changed'); + }); + + it('rolls back once a finalization that outlasted the run fails to commit', async () => { + const d = { ...deps({}, { 'a.txt': 'original' }), stopGraceMs: 20 }; + let release = (): void => undefined; + const rollbacks = slowFinalization(d, new Promise((r) => (release = r)), async () => { + throw new TransactionFinalizeError(false, 'rename failed'); + }); + const result = await runScript({ code: script([{ tool: 'write', args: { path: 'a.txt', content: 'changed' } }]), transaction: true, timeoutMs: 50 }, d); + expect(result.error).toMatchObject({ kind: 'internal', name: 'TransactionIndeterminate' }); + release(); + await vi.waitFor(() => expect(rollbacks).toHaveBeenCalledTimes(1)); + await vi.waitFor(() => expect(d.tools.read('a.txt')).toBe('original')); + }); + + it('does not report success when the client cancels while the journal is being finalized', async () => { + const controller = new AbortController(); + const d = deps({}, { 'a.txt': 'original' }); + let release = (): void => undefined; + slowFinalization(d, new Promise((r) => (release = r)), async () => undefined, () => controller.abort()); + const result = await runScript( + { code: script([{ tool: 'write', args: { path: 'a.txt', content: 'changed' } }]), transaction: true, timeoutMs: 5_000 }, + { ...d, signal: controller.signal }, + ); + release(); + expect(result.ok).toBe(false); + expect(result.error).toMatchObject({ kind: 'internal', name: 'TransactionIndeterminate' }); + expect(result.error?.message).toContain('cancelled'); + }); + it('fails and rolls back a successful script whose write is still running after the grace', async () => { const tools = new MemoryToolRuntime({ root: '/ws', commitDelayMs: 60, honorAbortInCommit: false }); const sandbox: Sandbox = { diff --git a/src/core/run.ts b/src/core/run.ts index d492f54..b3b35e0 100644 --- a/src/core/run.ts +++ b/src/core/run.ts @@ -293,19 +293,36 @@ export async function runScript

(req: RunRequest, deps: RunDeps

): Promise journal.dispose()); try { - await tx.dispose(); + // Bounded like the rest of the run: the script's deadline plus the stop grace, and cancellation. + const r = await bounded(() => finalizing, { signal: controller.signal, ms: deadline + graceMs - now() }); finalized = true; + if (!r.done) { + const why = r.why === 'aborted' ? 'the run was cancelled' : 'the run reached its time limit'; + error = { + kind: 'internal', + name: 'TransactionIndeterminate', + message: `${why} while the transaction was being finalized; the outcome is not known yet`, + }; + warnings.push('the writes of this run are kept if the finalization still completes, and rolled back if it fails.'); + // Not a rollback: the finalization is left to end, and only a failed commit is undone. + void finalizing.catch((err: unknown) => { + if (err instanceof TransactionFinalizeError && err.committed) return undefined; + return journal.rollback(); + }).catch(() => undefined); + } } catch (err) { if (err instanceof TransactionFinalizeError && err.committed) { finalized = true; error = { kind: 'internal', name: 'TransactionIndeterminate', message: err.message }; warnings.push('the writes of this run are on disk and were not rolled back, but they may not survive a power loss or crash.'); } else { - error = { kind: 'internal', name: 'TransactionNotFinalized', message: `the transaction could not be finalized and is rolled back: ${errorMessage(err)}` }; + error = { kind: 'internal', name: 'TransactionNotFinalized', message: `the transaction could not be finalized: ${errorMessage(err)}` }; } } } diff --git a/src/tools/bash.test.ts b/src/tools/bash.test.ts index fdccf1b..0568d85 100644 --- a/src/tools/bash.test.ts +++ b/src/tools/bash.test.ts @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { ToolError } from '../core/errors.js'; import type { BashContainment, BashResult, PolicySnapshot, SessionContext } from '../core/types.js'; import { makeContext } from '../testing/context.js'; +import { bootstrapEnv } from './bash.js'; import { NodeToolRuntime } from './runtime.js'; import { containmentUnavailableReason } from './sandbox.js'; @@ -109,6 +110,16 @@ describe.skipIf(IS_WINDOWS)('bash', () => { expect(r.truncated).toBe(true); }); + it('does not report a timeout when the shell exited and only its output was draining', async () => { + const r = await bash('sleep 5 & exit 0', { timeoutMs: 100 }); + expect([r.exitCode, r.timedOut]).toEqual([0, false]); + }); + + it('gives the sandbox bootstrap shell no startup files, exported functions or shell options', () => { + const env = bootstrapEnv({ PATH: '/bin', BASH_ENV: '/x', ENV: '/y', SHELLOPTS: 'xtrace', BASHOPTS: 'extglob', 'BASH_FUNC_example%%': 'unused' }); + expect(env).toEqual({ PATH: '/bin' }); + }); + it('refuses a containment with a relative writable root', async () => { await expect(bash('true', { containment: { mode: 'sandbox', readOnly: false, writableRoots: ['rel'], network: false } })).rejects.toMatchObject({ code: 'containment-unavailable', diff --git a/src/tools/bash.ts b/src/tools/bash.ts index 8371aa9..bc6c7a7 100644 --- a/src/tools/bash.ts +++ b/src/tools/bash.ts @@ -92,7 +92,7 @@ export interface BashRunOptions { readonly denyWrite?: readonly string[]; } -function spawnAndWait( +export function spawnAndWait( argv: readonly string[], env: NodeJS.ProcessEnv, cwd: string, @@ -150,6 +150,8 @@ function spawnAndWait( }; const onAbort = (): void => killGroup(child); const timer = setTimeout(() => { + // The shell already exited: only its output was still draining. + if (exit) return finish(); timedOut = true; killGroup(child); }, timeoutMs); @@ -171,6 +173,20 @@ function spawnAndWait( }); } +/** + * The environment of the sandbox bootstrap: the wrapper runs ` -c` + * before the sandbox applies, so nothing may make that shell run code of its + * own first (startup files, exported functions, shell options). + */ +export function bootstrapEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + const out: NodeJS.ProcessEnv = {}; + for (const [key, value] of Object.entries(env)) { + if (key === 'BASH_ENV' || key === 'ENV' || key === 'SHELLOPTS' || key === 'BASHOPTS' || key.startsWith('BASH_FUNC_')) continue; + out[key] = value; + } + return out; +} + /** Runs a prepared `bash` effect. */ export async function runBash(effect: BashEffect, signal: AbortSignal, opts: BashRunOptions = {}): Promise { if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before bash started'); @@ -183,8 +199,8 @@ export async function runBash(effect: BashEffect, signal: AbortSignal, opts: Bas if (containment.mode === 'none') { return spawnAndWait([shell, '-c', effect.command], process.env, effect.cwd, effect.timeoutMs, signal, cap); } - return withSandbox(effect.command, shell, effect.cwd, containment, opts.denyWrite ?? [], (wrapped) => { + return withSandbox(effect.command, shell, effect.cwd, containment, opts.denyWrite ?? [], signal, (wrapped) => { if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before bash started'); - return spawnAndWait(wrapped.argv, { ...process.env, ...wrapped.env }, effect.cwd, effect.timeoutMs, signal, cap); + return spawnAndWait(wrapped.argv, bootstrapEnv({ ...process.env, ...wrapped.env }), effect.cwd, effect.timeoutMs, signal, cap); }); } diff --git a/src/tools/diff.test.ts b/src/tools/diff.test.ts index d6e72f1..d7ec748 100644 --- a/src/tools/diff.test.ts +++ b/src/tools/diff.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { describe, expect, it } from 'vitest'; -import { unifiedDiff } from './diff.js'; +import { quotePath, unifiedDiff } from './diff.js'; const hasGit = spawnSync('git', ['--version']).status === 0; @@ -60,3 +60,17 @@ describe('unifiedDiff', () => { } }); }); + +describe('diff headers', () => { + it('quotes a path that a quote, a backslash or a control character would change', () => { + expect(unifiedDiff('plain name.txt', 'a\n', 'b\n')).toContain('--- a/plain name.txt\n+++ b/plain name.txt\n'); + expect(unifiedDiff('x\n+++ b/y', 'a\n', 'b\n')).toContain('--- "a/x\\n+++ b/y"\n+++ "b/x\\n+++ b/y"\n'); + expect(quotePath('a/q"b\\c\td')).toBe('"a/q\\"b\\\\c\\td"'); + }); + + it.skipIf(!hasGit)('describes the creation of an empty file in a patch git applies', () => { + const diff = unifiedDiff('f.txt', null, ''); + expect(diff).toContain('new file mode'); + expect(gitApply(null, diff)).toBe(''); + }); +}); diff --git a/src/tools/diff.ts b/src/tools/diff.ts index 9a8f419..1659203 100644 --- a/src/tools/diff.ts +++ b/src/tools/diff.ts @@ -124,11 +124,11 @@ export function unifiedDiff(file: string, before: string | null, after: string): const a = before === null ? [] : splitLines(before); const b = splitLines(after); const ops = editScript(a, b); - const header = `--- ${before === null ? '/dev/null' : `a/${file}`}\n+++ b/${file}\n`; if (ops.every((op) => op.kind === ' ')) { - // Only possible when before is null and after is empty. - return `${header}`; + // Only possible when before is null and after is empty: a creation has no hunk, so git's header says it. + return `diff --git ${quotePath(`a/${file}`)} ${quotePath(`b/${file}`)}\nnew file mode 100644\n`; } + const header = `--- ${before === null ? '/dev/null' : quotePath(`a/${file}`)}\n+++ ${quotePath(`b/${file}`)}\n`; let out = header; let i = 0; @@ -174,5 +174,25 @@ export function unifiedDiff(file: string, before: string | null, after: string): /** Diff header for a binary change. */ export function binaryDiff(file: string, existed: boolean): string { - return `--- ${existed ? `a/${file}` : '/dev/null'}\n+++ b/${file}\nBinary files differ\n`; + return `--- ${existed ? quotePath(`a/${file}`) : '/dev/null'}\n+++ ${quotePath(`b/${file}`)}\nBinary files differ\n`; +} + +const ESCAPES: Record = { '"': '\\"', '\\': '\\\\', '\t': '\\t', '\n': '\\n', '\r': '\\r', '\b': '\\b', '\f': '\\f', '\v': '\\v', '\x07': '\\a' }; + +/** + * A path as git writes it in a patch header: unchanged when plain, else in + * double quotes with C escapes, so a quote, a backslash, a control character + * or a trailing space cannot change which file the header names. + */ +export function quotePath(p: string): string { + if (!/["\\\x00-\x1f\x7f]|\s$/.test(p)) return p; + let out = ''; + for (const ch of p) { + const code = ch.charCodeAt(0); + const escaped = ESCAPES[ch]; + if (escaped !== undefined) out += escaped; + else if (code < 0x20 || code === 0x7f) out += `\\${code.toString(8).padStart(3, '0')}`; + else out += ch; + } + return `"${out}"`; } diff --git a/src/tools/edit-match.test.ts b/src/tools/edit-match.test.ts index 94bb9ed..30cf2f9 100644 --- a/src/tools/edit-match.test.ts +++ b/src/tools/edit-match.test.ts @@ -111,3 +111,23 @@ describe('edit matching (ported from Turnpack)', () => { expect(nowhere.message).toMatch(/nothing close to it is in the file \(7 lines\)/); }); }); + +describe('edit matching guards', () => { + it('treats overlapping occurrences as two places', () => { + expect(miss(apply('aaa', 'aa', 'b')).kind).toBe('ambiguous'); + expect(miss(apply('x\nx\nx\n', 'x\nx', 'y')).kind).toBe('ambiguous'); + expect(miss(apply('x\nx\nx\n', ' x\n x', 'y')).kind).toBe('ambiguous'); + }); + + it('refuses an indentation match where one indent of the search stands for two in the file', () => { + const out = miss(apply('\tif (a) {\n\t\tb();\n', 'if (a) {\nb();', 'if (a) {\nc();')); + expect(out.kind).toBe('ambiguous'); + expect(out.message).toMatch(/indentation/); + }); + + it('refuses an edit whose result would exceed the size limit', () => { + expect(miss(applySearchReplace('a b a', 'a', 'x'.repeat(100), true, 50)).kind).toBe('too-large'); + expect(miss(applySearchReplace(' a\n b\n', 'a\nb', 'x'.repeat(100), false, 50)).kind).toBe('too-large'); + expect(ok(applySearchReplace('a b a', 'a', 'xy', true, 50)).text).toBe('xy b xy'); + }); +}); diff --git a/src/tools/edit-match.ts b/src/tools/edit-match.ts index cdad6c2..9dbc4dc 100644 --- a/src/tools/edit-match.ts +++ b/src/tools/edit-match.ts @@ -61,7 +61,7 @@ export interface EditApplied { export interface EditMiss { ok: false; - kind: "empty" | "not-found" | "ambiguous"; + kind: "empty" | "not-found" | "ambiguous" | "too-large"; /** Complete, model-readable explanation, without the file name. */ message: string; } @@ -181,14 +181,18 @@ function leadingWhitespace(value: string): string { * extrapolated from the step between two matched depths, and failing that keeps its extra * indentation on top of the nearest known depth. */ -function reindentLike(replaceLines: string[], searchLines: string[], fileLines: string[]): string[] { +function reindentLike(replaceLines: string[], searchLines: string[], fileLines: string[]): string[] | null { const known = new Map(); for (let k = 0; k < searchLines.length; k++) { const searchLine = searchLines[k] ?? ""; const fileLine = fileLines[k] ?? ""; if (searchLine.trim() === "" || fileLine.trim() === "") continue; const indent = leadingWhitespace(searchLine); - if (!known.has(indent)) known.set(indent, leadingWhitespace(fileLine)); + const fileIndent = leadingWhitespace(fileLine); + const seen = known.get(indent); + // One indent of the search standing for two of the file: no translation is right for both. + if (seen !== undefined && seen !== fileIndent) return null; + known.set(indent, fileIndent); } if (known.size === 0 || [...known].every(([from, to]) => from === to)) return replaceLines; @@ -250,7 +254,7 @@ const RUNGS: Rung[] = [ { how: "punctuation", normalize: (line) => foldPunctuation(line).trim(), reindent: true }, ]; -function findLineMatches(fileNorm: string[], wanted: string[]): number[] { +function findLineMatches(fileNorm: string[], wanted: string[], overlapping: boolean): number[] { const hits: number[] = []; const n = wanted.length; const first = wanted[0]; @@ -265,7 +269,8 @@ function findLineMatches(fileNorm: string[], wanted: string[]): number[] { } if (same) { hits.push(i); - i += n - 1; // matches may not overlap + // Replacements may not overlap; counting places for uniqueness, they may. + if (!overlapping) i += n - 1; } } return hits; @@ -279,10 +284,16 @@ export function applySearchReplace( search: string, replace: string, replaceAll: boolean, + maxResultLength = Number.MAX_SAFE_INTEGER, ): EditOutcome { if (!search) { return { ok: false, kind: "empty", message: "the search text is empty" }; } + const tooLarge = (): EditMiss => ({ + ok: false, + kind: "too-large", + message: `the edited file would be longer than ${maxResultLength} characters`, + }); // Rung 1: the text exactly as written. let exact = occurrences(text, search); @@ -313,10 +324,14 @@ export function applySearchReplace( let fileLines: FileLine[] | undefined; const linesOfFile = (): FileLine[] => (fileLines ??= splitLines(text)); + // A second occurrence overlapping the first still names another place. + const overlap = exact.length === 1 && !replaceAll ? text.indexOf(exactSearch, (exact[0] ?? 0) + 1) : -1; + if (overlap !== -1) exact.push(overlap); if (exact.length > 1 && !replaceAll) { return ambiguous(exact.map((offset) => lineNumberAt(linesOfFile(), offset))); } if (exact.length > 0) { + if (text.length + exact.length * (exactReplace.length - exactSearch.length) > maxResultLength) return tooLarge(); return { ok: true, text: text.split(exactSearch).join(exactReplace), how, count: exact.length, matched: exactSearch }; } @@ -347,7 +362,7 @@ export function applySearchReplace( const wanted = searchLines.map(rung.normalize); // A search that normalises to nothing would match every blank line. if (wanted.every((line) => line === "")) continue; - const hits = findLineMatches(bodies.map(rung.normalize), wanted); + const hits = findLineMatches(bodies.map(rung.normalize), wanted, !replaceAll); if (hits.length === 0) continue; const label = rung.how; if (hits.length > 1 && !replaceAll) { @@ -359,6 +374,7 @@ export function applySearchReplace( const pieces: string[] = []; let cursor = 0; + let length = 0; let matched: string | undefined; for (const index of hits) { const firstLine = file[index]; @@ -367,10 +383,24 @@ export function applySearchReplace( const lines = rung.reindent ? reindentLike(replaceLines, searchLines, bodies.slice(index, index + searchLines.length)) : replaceLines; - pieces.push(text.slice(cursor, firstLine.start), lines.join(eol)); + if (lines === null) { + return { + ok: false, + kind: "ambiguous", + message: + `search text matches at line ${index + 1} when ${HOW_LABEL[label]} is ignored, but one indentation of oldString ` + + "stands for two different indentations of the file there. Write oldString with the file's indentation.", + }; + } + const before = text.slice(cursor, firstLine.start); + const replaced = lines.join(eol); + length += before.length + replaced.length; + if (length > maxResultLength) return tooLarge(); + pieces.push(before, replaced); cursor = coversLastEnding ? lastLine.end : lastLine.bodyEnd; matched ??= text.slice(firstLine.start, cursor); } + if (length + text.length - cursor > maxResultLength) return tooLarge(); pieces.push(text.slice(cursor)); return { ok: true, text: pieces.join(""), how: label, count: hits.length, matched: matched ?? "" }; } diff --git a/src/tools/fs-ops.test.ts b/src/tools/fs-ops.test.ts index 6ae5885..c8ab6dc 100644 --- a/src/tools/fs-ops.test.ts +++ b/src/tools/fs-ops.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { syncDirStrict } from './fs-ops.js'; +import { readRegularFile, syncDirStrict } from './fs-ops.js'; const failWith = (code: string) => async (): Promise => { throw Object.assign(new Error(`${code}: directory fsync`), { code }); @@ -18,3 +18,10 @@ describe.skipIf(process.platform === 'win32')('syncDirStrict', () => { await expect(syncDirStrict(process.cwd())).resolves.toBeUndefined(); }); }); + +describe.skipIf(process.platform !== 'linux')('readRegularFile', () => { + it('stops at the byte limit even when the file is larger than its reported size', async () => { + // A /proc file reports size 0 and holds more. + await expect(readRegularFile(`/proc/${process.pid}/status`, 16)).rejects.toThrow(/more than the 16-byte limit/); + }); +}); diff --git a/src/tools/fs-ops.ts b/src/tools/fs-ops.ts index b19ba15..6565605 100644 --- a/src/tools/fs-ops.ts +++ b/src/tools/fs-ops.ts @@ -12,6 +12,8 @@ import { ToolError } from '../core/errors.js'; */ const NOFOLLOW = FS.O_NOFOLLOW ?? 0; +/** Opening a FIFO or a device for reading must not wait for a writer before the type check. */ +const NONBLOCK = FS.O_NONBLOCK ?? 0; const IS_LINUX = process.platform === 'linux'; const IS_WINDOWS = process.platform === 'win32'; @@ -72,14 +74,14 @@ async function assertHandleAt(handle: FileHandle, abs: string): Promise { export async function readFileInside(abs: string, maxBytes: number): Promise { let handle: FileHandle; try { - handle = await fs.open(abs, FS.O_RDONLY | NOFOLLOW); + handle = await fs.open(abs, FS.O_RDONLY | NOFOLLOW | NONBLOCK); } catch { return null; } try { const st = await assertHandleAt(handle, abs); if (!st.isFile() || st.size > maxBytes) return null; - return await handle.readFile(); + return await readAtMost(handle, maxBytes); } catch { return null; } finally { @@ -87,6 +89,20 @@ export async function readFileInside(abs: string, maxBytes: number): Promise { + const chunks: Buffer[] = []; + let total = 0; + for (;;) { + const chunk = Buffer.allocUnsafe(64 * 1024); + const { bytesRead } = await handle.read(chunk, 0, chunk.length, null); + if (bytesRead === 0) return Buffer.concat(chunks, total); + total += bytesRead; + if (total > maxBytes) return null; + chunks.push(chunk.subarray(0, bytesRead)); + } +} + // --------------------------------------------------------------------------- // Identity: what a commit checks to know the path still names what prepare saw. // --------------------------------------------------------------------------- @@ -155,7 +171,7 @@ export interface RegularFile { export async function readRegularFile(abs: string, maxBytes = Number.MAX_SAFE_INTEGER): Promise { let handle: FileHandle; try { - handle = await fs.open(abs, FS.O_RDONLY | NOFOLLOW); + handle = await fs.open(abs, FS.O_RDONLY | NOFOLLOW | NONBLOCK); } catch (err) { const code = errnoCode(err); if (code === 'ENOENT') return null; @@ -167,8 +183,10 @@ export async function readRegularFile(abs: string, maxBytes = Number.MAX_SAFE_IN const st = await assertHandleAt(handle, abs); if (st.isDirectory()) throw new ToolError('invalid-args', `${abs} is a directory`); if (!st.isFile()) throw new ToolError('invalid-args', `${abs} is not a regular file`); - if (st.size > maxBytes) throw new ToolError('tool-error', `${abs} is ${st.size} bytes, more than the ${maxBytes}-byte limit`); - const bytes = await handle.readFile(); + const tooBig = (size: number | string): ToolError => new ToolError('tool-error', `${abs} is ${size} bytes, more than the ${maxBytes}-byte limit`); + if (st.size > maxBytes) throw tooBig(st.size); + const bytes = await readAtMost(handle, maxBytes); + if (bytes === null) throw tooBig(`over ${maxBytes}`); return { bytes, mode: st.mode & 0o7777 }; } finally { await handle.close(); @@ -181,7 +199,7 @@ export type Expectation = { readonly kind: 'absent' } | { readonly kind: 'hash'; export interface WriteOutcome { /** Bytes that were there before (null when absent). */ readonly before: RegularFile | null; - /** Directories created to hold the file, outermost first. */ + /** Directories this write created to hold the file (not ones that appeared meanwhile), outermost first. */ readonly createdDirs: readonly string[]; } @@ -260,9 +278,11 @@ async function writeLocked(abs: string, bytes: Buffer, expect: Expectation, opts await beforeWrite?.(before, toCreate); + const createdDirs: string[] = []; for (const d of toCreate) { try { await fs.mkdir(d); + createdDirs.push(d); } catch (err) { if (errnoCode(err) !== 'EEXIST') throw err; } @@ -270,10 +290,9 @@ async function writeLocked(abs: string, bytes: Buffer, expect: Expectation, opts } await assertDirUnchanged(dir); - const tmp = path.join(dir, `.${path.basename(abs)}.acm-${randomBytes(6).toString('hex')}.tmp`); + const tmp = path.join(dir, `.acm-${randomBytes(6).toString('hex')}.tmp`); const mode = opts.mode ?? before?.mode ?? 0o666; const handle = await fs.open(tmp, FS.O_WRONLY | FS.O_CREAT | FS.O_EXCL | NOFOLLOW, mode); - let placed = false; try { try { await handle.writeFile(bytes); @@ -283,25 +302,24 @@ async function writeLocked(abs: string, bytes: Buffer, expect: Expectation, opts await handle.close(); } // Last checks before the irreversible step. - assertNotAborted(signal, abs); await assertDirUnchanged(dir); if (identity) await assertIdentity(identity); if (!hashMatches(expect, await readRegularFile(abs))) { throw new ToolError('stale', `file changed since prepared: ${abs} changed while it was being written`); } + assertNotAborted(signal, abs); if (expect.kind === 'absent') { try { await fs.link(tmp, abs); - placed = true; } catch (err) { const code = errnoCode(err); if (code === 'EEXIST') throw new ToolError('stale', `file changed since prepared: ${abs} was created meanwhile`); - // File systems without hard links: fall back to rename. - if (code !== 'EPERM' && code !== 'ENOTSUP' && code !== 'EOPNOTSUPP' && code !== 'EXDEV') throw err; + throw err; } + } else { + await fs.rename(tmp, abs); } - if (!placed) await fs.rename(tmp, abs); - return { before, createdDirs: toCreate }; + return { before, createdDirs }; } finally { // After `link` the temp name is still there; after `rename` it is gone. await fs.rm(tmp, { force: true }).catch(() => undefined); diff --git a/src/tools/hardening.test.ts b/src/tools/hardening.test.ts index 3961252..ab099df 100644 --- a/src/tools/hardening.test.ts +++ b/src/tools/hardening.test.ts @@ -101,12 +101,12 @@ describe.skipIf(IS_WINDOWS)('2. crash recovery never deletes through a link', () mkdirSync(path.join(outside, 'empty')); symlinkSync(outside, path.join(ws, 'sub'), 'dir'); const dir = path.join(journalRoot(path.join(base, 'state')), 'abc-99999999-dead'); - mkdirSync(dir, { recursive: true }); + mkdirSync(dir, { recursive: true, mode: 0o700 }); writeFileSync( path.join(dir, 'manifest.json'), JSON.stringify({ version: 1, pid: 99_999_999, host: os.hostname(), startedAt: 0, roots: [ws], dirs: [path.join(ws, 'sub', 'empty')], entries: [] }), ); - await recoverStaleJournals(path.join(base, 'state'), [ws]); + await recoverStaleJournals(path.join(base, 'state'), [ws], []); expect(existsSync(path.join(outside, 'empty'))).toBe(true); }); }); diff --git a/src/tools/jail.ts b/src/tools/jail.ts index fcd3cfb..e88b67b 100644 --- a/src/tools/jail.ts +++ b/src/tools/jail.ts @@ -195,6 +195,11 @@ async function withRealPrefixes(patterns: readonly string[]): Promise const fwd = pattern.replace(/\\/g, '/'); const wild = fwd.search(/[*?[]/); const literal = wild === -1 ? fwd : fwd.slice(0, wild); + if (wild === -1) { + // A literal path that is a link protects what it names, too. + const real = await fs.realpath(fwd).then((r) => r.replace(/\\/g, '/'), () => null); + if (real !== null && real !== fwd) out.add(real); + } const cut = literal.lastIndexOf('/'); if (cut <= 0) continue; // Resolve the deepest existing directory of the literal prefix. @@ -292,37 +297,51 @@ export class Jail { async resolveForWrite(input: string): Promise { const r = await this.#resolve(input); for (const p of [r.real, ...r.links]) this.assertWritable(p); + // The directories the write will create are names it affects too. + for (let dir = path.dirname(r.real); this.rootOf(dir) !== undefined && !(await lstatOrNull(dir)); dir = path.dirname(dir)) { + this.assertWritable(dir); + } if (r.finalIsLink) { throw new ToolError('invalid-args', `${input} is a symbolic link; write to its target (${r.real}) instead`); } return r.real; } + /** + * Like `resolve`, for the path grep and glob search: refuses a path whose + * last component is a symbolic link, since search never follows links. + */ + async resolveSearchRoot(input: string): Promise { + const r = await this.#resolve(input); + if (r.finalIsLink) throw new ToolError('invalid-args', `${input} is a symbolic link; search its target (${r.real}) instead`); + return r.real; + } + async #resolve(input: string): Promise { if (input.includes('\0')) throw new ToolError('invalid-args', 'path must not contain NUL characters'); - const trimmed = input.trim(); - if (trimmed === '') throw new ToolError('invalid-args', 'path must not be empty'); + // Not trimmed: spaces are part of a file name. + if (input.trim() === '') throw new ToolError('invalid-args', 'path must not be empty'); if (this.#windowsChecks) { - const problem = windowsPathProblem(trimmed); - if (problem) throw new ToolError('outside-workspace', `${trimmed}: ${problem}`); + const problem = windowsPathProblem(input); + if (problem) throw new ToolError('outside-workspace', `${input}: ${problem}`); } - const expanded = expandTilde(trimmed); + const expanded = expandTilde(input); let r: Resolution; try { r = await resolvePhysical(expanded, this.cwd); } catch (err) { if (err instanceof ToolError) throw err; const code = errnoCode(err); - if (code === 'ENAMETOOLONG') throw new ToolError('invalid-args', `path is too long: ${trimmed.slice(0, 120)}…`); - if (code === 'ELOOP') throw new ToolError('outside-workspace', `${trimmed}: too many symbolic links`); - throw new ToolError('tool-error', `cannot resolve ${trimmed}: ${code ?? String(err)}`); + if (code === 'ENAMETOOLONG') throw new ToolError('invalid-args', `path is too long: ${input.slice(0, 120)}…`); + if (code === 'ELOOP') throw new ToolError('outside-workspace', `${input}: too many symbolic links`); + throw new ToolError('tool-error', `cannot resolve ${input}: ${code ?? String(err)}`); } if (this.rootOf(r.real) === undefined) { - throw new ToolError('outside-workspace', `${trimmed} resolves to ${r.real}, outside the workspace (${this.roots.join(', ')})`); + throw new ToolError('outside-workspace', `${input} resolves to ${r.real}, outside the workspace (${this.roots.join(', ')})`); } if (this.#windowsChecks) { const problem = windowsPathProblem(r.real); - if (problem) throw new ToolError('outside-workspace', `${trimmed}: ${problem}`); + if (problem) throw new ToolError('outside-workspace', `${input}: ${problem}`); } return r; } diff --git a/src/tools/journal.test.ts b/src/tools/journal.test.ts index 7a99106..1a944c7 100644 --- a/src/tools/journal.test.ts +++ b/src/tools/journal.test.ts @@ -1,5 +1,5 @@ import { spawnSync } from 'node:child_process'; -import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -7,7 +7,7 @@ import { ToolError, TransactionFinalizeError } from '../core/errors.js'; import type { PolicySnapshot, SessionContext, ToolCall, Transaction } from '../core/types.js'; import { makeContext } from '../testing/context.js'; import { COMMITTED, FileTransaction, type JournalIo, journalRoot, recoverStaleJournals } from './journal.js'; -import { syncDirStrict } from './fs-ops.js'; +import { atomicWrite, sha256, syncDirStrict } from './fs-ops.js'; import { NodeToolRuntime } from './runtime.js'; let base: string; @@ -27,6 +27,8 @@ async function write(rel: string, content: string, tx: Transaction): Promise readFileSync(path.join(ws, rel), 'utf8'); +const IS_WINDOWS = process.platform === 'win32'; + /** A pid that belonged to a process that has exited. */ function deadPid(): number { const r = spawnSync(process.execPath, ['-e', '']); @@ -108,6 +110,36 @@ describe('transactions', () => { expect(readFileSync(path.join(ws, 'big1.txt')).equals(big)).toBe(true); }); + it('refuses to write again a file another writer changed since this transaction wrote it', async () => { + const mine = rt.beginTransaction(); + const other = rt.beginTransaction(); + await write('a.txt', 'mine\n', mine); + await write('a.txt', 'other\n', other); + await other.dispose(); + await expect(write('a.txt', 'mine again\n', mine)).rejects.toMatchObject({ code: 'stale' }); + await mine.rollback(); + expect(read('a.txt')).toBe('other\n'); + }); + + it('rolls back only directories its own writes created', async () => { + const tx = rt.beginTransaction(); + if (!(tx instanceof FileTransaction)) throw new Error('unreachable'); + const dir = path.join(ws, 'shared'); + const abs = path.join(dir, 'x.txt'); + const bytes = Buffer.from('x\n'); + const outcome = await atomicWrite(abs, bytes, { kind: 'absent' }, { + beforeWrite: async (before, dirs) => { + await tx.record(abs, ws, before, sha256(bytes), dirs); + // Another writer creates the directory between the checks and the write. + mkdirSync(dir); + }, + }); + tx.written(abs, sha256(bytes), outcome.createdDirs); + await tx.rollback(); + expect(existsSync(abs)).toBe(false); + expect(existsSync(dir)).toBe(true); + }); + it('refuses a transaction it did not start', async () => { const foreign: Transaction = { rollback: async () => ({ restored: [], skipped: [] }), dispose: async () => undefined }; await expect(write('a.txt', 'a1\n', foreign)).rejects.toThrow(/not started by this tool runtime/); @@ -130,6 +162,29 @@ describe('crash recovery', () => { return moved; } + it('recovers a journal without write timestamps and preserves directories with unknown ownership', async () => { + const pid = deadPid(); + const dir = path.join(journalRoot(stateDir), `old-${pid}-abcd`); + const shared = path.join(ws, 'shared'); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + mkdirSync(shared); + writeFileSync(path.join(ws, 'a.txt'), 'a1\n'); + writeFileSync(path.join(dir, '0.bin'), 'a0\n'); + writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify({ + version: 1, pid, host: os.hostname(), startedAt: 0, roots: [ws], dirs: [shared], + entries: [{ + path: path.join(ws, 'a.txt'), existed: true, original: sha256('a0\n'), + mode: 0o644, blob: '0.bin', written: [sha256('a1\n')], + }], + })); + + const recovered = await recoverStaleJournals(stateDir, [ws], []); + + expect(recovered[0]?.report.restored).toEqual([path.join(ws, 'a.txt')]); + expect(read('a.txt')).toBe('a0\n'); + expect(existsSync(shared)).toBe(true); + }); + it('restores a journal whose process is gone, and leaves a live one alone', async () => { const crashed = rt.beginTransaction(); if (!(crashed instanceof FileTransaction)) throw new Error('unreachable'); @@ -143,7 +198,7 @@ describe('crash recovery', () => { writeFileSync(path.join(ws, 'live.txt'), 'l0\n'); await write('live.txt', 'l1\n', live); - const recovered = await recoverStaleJournals(stateDir, [ws]); + const recovered = await recoverStaleJournals(stateDir, [ws], []); expect(recovered).toHaveLength(1); const report = recovered[0]?.report; expect([...(report?.restored ?? [])].sort()).toEqual([path.join(ws, 'a.txt'), path.join(ws, 'new.txt')]); @@ -162,7 +217,7 @@ describe('crash recovery', () => { await write('a.txt', 'a1\n', tx); const moved = abandon(tx); // Another workspace: nothing happens. - expect(await recoverStaleJournals(stateDir, [outside])).toEqual([]); + expect(await recoverStaleJournals(stateDir, [outside], [])).toEqual([]); expect(read('a.txt')).toBe('a1\n'); // A tampered record pointing outside the roots is not followed. @@ -172,16 +227,62 @@ describe('crash recovery', () => { const first = manifest.entries[0]; if (first) first.path = path.join(outside, 'victim.txt'); writeFileSync(manifestPath, JSON.stringify(manifest)); - const recovered = await recoverStaleJournals(stateDir, [ws]); + const recovered = await recoverStaleJournals(stateDir, [ws], []); expect(recovered[0]?.report.restored).toEqual([]); expect(recovered[0]?.report.skipped[0]?.reason).toBe('error'); expect(readFileSync(path.join(outside, 'victim.txt'), 'utf8')).toBe('victim\n'); + // A record with a file it could not handle is kept for a later pass. + expect(readdirSync(journalRoot(stateDir))).toHaveLength(1); + }); + + it('undoes writes newest first across journals, whatever order the runs started in', async () => { + const first = rt.beginTransaction(); + const second = rt.beginTransaction(); + if (!(first instanceof FileTransaction) || !(second instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'second\n', second); + await new Promise((r) => setTimeout(r, 5)); + await write('a.txt', 'first\n', first); + abandon(first); + abandon(second); + await recoverStaleJournals(stateDir, [ws], []); + expect(read('a.txt')).toBe('a0\n'); + }); + + it('never restores a protected path', async () => { + const tx = rt.beginTransaction(); + if (!(tx instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'a1\n', tx); + abandon(tx); + const recovered = await recoverStaleJournals(stateDir, [ws], [path.join(ws, 'a.txt')]); + expect(recovered[0]?.report.skipped).toEqual([{ path: path.join(ws, 'a.txt'), reason: 'error', detail: expect.stringContaining('protected') }]); + expect(read('a.txt')).toBe('a1\n'); + }); + + it.skipIf(IS_WINDOWS)('reads and deletes nothing in a journal directory other users can write', async () => { + const tx = rt.beginTransaction(); + if (!(tx instanceof FileTransaction)) throw new Error('unreachable'); + await write('a.txt', 'a1\n', tx); + abandon(tx); + mkdirSync(path.join(journalRoot(stateDir), `zz-1-abcd${COMMITTED}`)); + chmodSync(journalRoot(stateDir), 0o777); + expect(await recoverStaleJournals(stateDir, [ws], [])).toEqual([]); + expect(read('a.txt')).toBe('a1\n'); + expect(readdirSync(journalRoot(stateDir))).toHaveLength(2); + }); + + it('deletes only finalized transaction directories', async () => { + const root = journalRoot(stateDir); + mkdirSync(root, { recursive: true, mode: 0o700 }); + mkdirSync(path.join(root, `notes${COMMITTED}`)); + mkdirSync(path.join(root, `zz-1-abcd${COMMITTED}`)); + await recoverStaleJournals(stateDir, [ws], []); + expect(readdirSync(root)).toEqual([`notes${COMMITTED}`]); }); it('skips a malformed record', async () => { mkdirSync(path.join(journalRoot(stateDir), 'zz-1-abcd'), { recursive: true }); writeFileSync(path.join(journalRoot(stateDir), 'zz-1-abcd', 'manifest.json'), '{"version":1,"entries":"nope"}'); - expect(await recoverStaleJournals(stateDir, [ws])).toEqual([]); + expect(await recoverStaleJournals(stateDir, [ws], [])).toEqual([]); }); }); @@ -198,7 +299,7 @@ describe('finalization', () => { expect(existsSync(tx.dir)).toBe(false); expect(existsSync(path.join(`${tx.dir}${COMMITTED}`, 'manifest.json'))).toBe(true); - expect(await recoverStaleJournals(stateDir, [ws])).toEqual([]); + expect(await recoverStaleJournals(stateDir, [ws], [])).toEqual([]); expect(read('a.txt')).toBe('a1\n'); expect(read('new.txt')).toBe('n1\n'); // Recovery deletes what a finalized run left behind. @@ -206,14 +307,16 @@ describe('finalization', () => { }); it('reports a committed but not flushed journal and never rolls it back', async () => { + let failing = false; const io: JournalIo = { syncDir: async () => { - throw new Error('EIO: flush failed'); + if (failing) throw new Error('EIO: flush failed'); }, removeDir: held, }; const tx = new FileTransaction(stateDir, io); await write('a.txt', 'a1\n', tx); + failing = true; const err = await tx.dispose().then( () => undefined, (e: unknown) => e, @@ -221,12 +324,25 @@ describe('finalization', () => { expect(err).toBeInstanceOf(TransactionFinalizeError); expect(err).toMatchObject({ committed: true }); expect(String(err)).toMatch(/durability is not guaranteed/); + // Asked again, finalization settles the same way. + await expect(tx.dispose()).rejects.toBe(err); expect(existsSync(path.join(`${tx.dir}${COMMITTED}`, 'manifest.json'))).toBe(true); expect(await tx.rollback()).toEqual({ restored: [], skipped: [] }); - expect(await recoverStaleJournals(stateDir, [ws])).toEqual([]); + expect(await recoverStaleJournals(stateDir, [ws], [])).toEqual([]); expect(read('a.txt')).toBe('a1\n'); }); + it('refuses the write when its journal record cannot be flushed', async () => { + const tx = new FileTransaction(stateDir, { + syncDir: async () => { + throw new Error('EIO: flush failed'); + }, + removeDir: held, + }); + await expect(write('a.txt', 'a1\n', tx)).rejects.toThrow(/EIO/); + expect(read('a.txt')).toBe('a0\n'); + }); + it('keeps the journal open for a rollback when the commit rename fails', async () => { const tx = rt.beginTransaction(); if (!(tx instanceof FileTransaction)) throw new Error('unreachable'); diff --git a/src/tools/journal.ts b/src/tools/journal.ts index 28ca080..5876aa9 100644 --- a/src/tools/journal.ts +++ b/src/tools/journal.ts @@ -23,11 +23,11 @@ import { removeEmptyDirInside, removeRegularFile, sha256, - syncDir, syncDirStrict, writeDurable, } from './fs-ops.js'; -import { isInsideDir, isInsideGitDir } from './jail.js'; +import { findMatchingPattern } from '../core/paths.js'; +import { expandTilde, isInsideDir, isInsideGitDir } from './jail.js'; /** Above this many bytes of originals a transaction refuses further writes. */ export const MAX_JOURNAL_BYTES = 64 * 1024 * 1024; @@ -52,6 +52,8 @@ const EntrySchema = z.object({ blob: z.string().regex(/^[0-9]+\.bin$/).nullable(), /** Hashes this transaction wrote (or was about to write) to the file, oldest first. */ written: z.array(z.string()), + /** Wall-clock time (ms) of the latest write to the file; recovery undoes writes newest first across journals. */ + at: z.number().optional(), }); const ManifestSchema = z.object({ @@ -89,6 +91,26 @@ const defaultIo: JournalIo = { /** Ids of transactions this process still has open; a recovery pass leaves them alone. */ const openTransactions = new Set(); +const TXID = /^[0-9a-z]+-\d+-[0-9a-f]+$/; + +function writeTime(): number { + return performance.timeOrigin + performance.now(); +} + +/** + * Throws unless `dir` is a real directory (not a link) that only this user + * can write: journals are restored from and deleted in it. + */ +async function assertPrivateDir(dir: string): Promise { + const st = await fs.lstat(dir); + if (st.isSymbolicLink() || !st.isDirectory()) throw new ToolError('tool-error', `journal directory ${dir} is not a real directory`); + if (process.platform === 'win32') return; + const uid = process.getuid?.(); + if ((uid !== undefined && st.uid !== uid) || (st.mode & 0o022) !== 0) { + throw new ToolError('tool-error', `journal directory ${dir} is not private to this user (owner ${st.uid}, mode ${(st.mode & 0o777).toString(8)})`); + } +} + interface LiveEntry { readonly entry: Entry; /** Original bytes, kept in memory for the in-process rollback. */ @@ -97,6 +119,9 @@ interface LiveEntry { last: string | null; } +/** How finalization ended, once it did. */ +type Finalized = { readonly durable: true } | { readonly durable: false; readonly error: TransactionFinalizeError }; + /** * A per-run journal. The first write to a file snapshots its original bytes * (or "absent") in memory and durably under `/journal//` @@ -109,9 +134,12 @@ export class FileTransaction implements Transaction { readonly #startedAt = Date.now(); readonly #entries = new Map(); readonly #dirs: string[] = []; + /** Directories this transaction's writes really created; only those are removed by the in-process rollback. */ + readonly #ownDirs = new Set(); #bytes = 0; #created = false; #closed = false; + #finalized: Finalized | undefined; #queue: Promise = Promise.resolve(); readonly #io: JournalIo; @@ -145,16 +173,21 @@ export class FileTransaction implements Transaction { }; } + /** Writes the manifest; once it resolves, the record survives a crash (where directories can be flushed). */ async #persist(): Promise { if (!this.#created) { - await fs.mkdir(path.dirname(this.dir), { recursive: true, mode: 0o700 }); + const root = path.dirname(this.dir); + await fs.mkdir(root, { recursive: true, mode: 0o700 }); + await assertPrivateDir(root); + await this.#io.syncDir(path.dirname(root)); await fs.mkdir(this.dir, { mode: 0o700 }); this.#created = true; + await this.#io.syncDir(root); } const next = path.join(this.dir, `${MANIFEST}.next`); await writeDurable(next, JSON.stringify(this.#manifest())); await fs.rename(next, path.join(this.dir, MANIFEST)); - await syncDir(this.dir); + await this.#io.syncDir(this.dir); } /** @@ -174,7 +207,15 @@ export class FileTransaction implements Transaction { if (!this.#roots.includes(root)) this.#roots.push(root); const existing = this.#entries.get(absPath); if (existing) { + // Another writer changed the file since this transaction last wrote it: restoring the + // original later would discard that change, so the write is refused. + const current = before ? sha256(before.bytes) : null; + const ours = existing.last ?? (existing.entry.existed ? existing.entry.original : null); + if (current !== ours) { + throw new ToolError('stale', `${absPath} was changed by another writer since this transaction last wrote it`); + } existing.entry.written.push(nextHash); + existing.entry.at = writeTime(); await this.#persist(); return; } @@ -201,6 +242,7 @@ export class FileTransaction implements Transaction { mode: before?.mode ?? null, blob, written: [nextHash], + at: writeTime(), }, bytes: before?.bytes ?? null, last: null, @@ -209,10 +251,11 @@ export class FileTransaction implements Transaction { }); } - /** Called after a successful write. */ - written(absPath: string, hash: string): void { + /** Called after a successful write, with the directories it created. */ + written(absPath: string, hash: string, createdDirs: readonly string[] = []): void { const live = this.#entries.get(absPath); if (live) live.last = hash; + for (const d of createdDirs) this.#ownDirs.add(d); } rollback(): Promise { @@ -239,8 +282,13 @@ export class FileTransaction implements Transaction { skipped.push({ path: entry.path, reason: 'error', detail: errorMessage(err) }); } } - await removeCreatedDirs(this.#dirs, this.#roots); - await this.#removeRecord(); + await removeCreatedDirs( + this.#dirs.filter((d) => this.#ownDirs.has(d)), + this.#roots, + ); + // A file whose restore failed keeps the record, so a recovery pass can still restore it. + if (skipped.some((s) => s.reason === 'error')) await this.#flushRecord(); + else await this.#removeRecord(); return { restored, skipped }; }); } @@ -251,13 +299,19 @@ export class FileTransaction implements Transaction { * durable. The recursive delete of the renamed directory runs afterwards * and is not awaited. Rejects with `TransactionFinalizeError`: not * committed when the rename failed (the journal stays open for a - * rollback), committed when only the fsync failed. + * rollback), committed when only the fsync failed. Called again, it + * settles the same way. */ dispose(): Promise { return this.#serial(async () => { + if (this.#finalized) { + if (this.#finalized.durable) return; + throw this.#finalized.error; + } if (this.#closed) return; if (!this.#created) { this.#closed = true; + this.#finalized = { durable: true }; openTransactions.delete(this.id); return; } @@ -273,16 +327,26 @@ export class FileTransaction implements Transaction { try { await this.#io.syncDir(path.dirname(this.dir)); } catch (err) { - throw new TransactionFinalizeError( + // The committed record stays: recovery deletes it without undoing anything. + const error = new TransactionFinalizeError( true, `the transaction journal was finalized, but flushing it to disk failed (${errorMessage(err)}); the changes are on disk, but their durability is not guaranteed`, ); - } finally { - void this.#io.removeDir(committed).catch(() => undefined); + this.#finalized = { durable: false, error }; + throw error; } + this.#finalized = { durable: true }; + void this.#io.removeDir(committed).catch(() => undefined); }); } + /** Keeps the record on disk for a recovery pass and stops tracking it here. */ + async #flushRecord(): Promise { + if (!this.#created) return; + await this.#persist().catch(() => undefined); + this.#created = false; + } + async #removeRecord(): Promise { if (!this.#created) return; await fs.rm(this.dir, { recursive: true, force: true }); @@ -360,39 +424,46 @@ async function readOriginal(dir: string, entry: Entry): Promise { return fs.readFile(path.join(dir, entry.blob)); } -async function undoRecord(manifest: Manifest, dir: string, roots: readonly string[]): Promise { - const restored: string[] = []; - const skipped: { path: string; reason: 'changed-externally' | 'error'; detail?: string }[] = []; - for (const entry of [...manifest.entries].reverse()) { - try { - // The record is data on disk: each path is checked like a tool argument. - if (!path.isAbsolute(entry.path) || !roots.some((root) => isInsideDir(root, entry.path))) { - skipped.push({ path: entry.path, reason: 'error', detail: 'outside the workspace roots; not touched' }); - continue; - } - if (!manifest.roots.some((root) => isInsideDir(root, entry.path))) { - skipped.push({ path: entry.path, reason: 'error', detail: 'outside the roots the journal was written for; not touched' }); - continue; - } - const current = await currentContent(entry.path); - const currentHash = current ? sha256(current.bytes) : null; - const originalHash = entry.existed ? entry.original : null; - if (currentHash === originalHash) continue; - if (currentHash === null || !entry.written.includes(currentHash)) { - skipped.push({ path: entry.path, reason: 'changed-externally', detail: 'the file no longer holds what the crashed run wrote' }); - continue; - } - const bytes = await readOriginal(dir, entry); - await restoreEntry(entry, bytes, currentHash); - restored.push(entry.path); - } catch (err) { - skipped.push({ path: entry.path, reason: 'error', detail: errorMessage(err) }); +/** A claimed stale journal and what undoing it has done so far. */ +interface Claimed { + readonly id: string; + readonly dir: string; + readonly manifest: Manifest; + readonly restored: string[]; + readonly skipped: { path: string; reason: 'changed-externally' | 'error'; detail?: string }[]; +} + +async function undoEntry(record: Claimed, entry: Entry, roots: readonly string[], protectedPaths: readonly string[]): Promise { + const { manifest, dir, restored, skipped } = record; + try { + // The record is data on disk: each path is checked like a tool argument. + if (!path.isAbsolute(entry.path) || !roots.some((root) => isInsideDir(root, entry.path))) { + skipped.push({ path: entry.path, reason: 'error', detail: 'outside the workspace roots; not touched' }); + return; + } + if (!manifest.roots.some((root) => isInsideDir(root, entry.path))) { + skipped.push({ path: entry.path, reason: 'error', detail: 'outside the roots the journal was written for; not touched' }); + return; + } + const hit = findMatchingPattern(entry.path, protectedPaths); + if (hit !== undefined) { + skipped.push({ path: entry.path, reason: 'error', detail: `a protected host policy path (${hit}); not touched` }); + return; } + const current = await currentContent(entry.path); + const currentHash = current ? sha256(current.bytes) : null; + const originalHash = entry.existed ? entry.original : null; + if (currentHash === originalHash) return; + if (currentHash === null || !entry.written.includes(currentHash)) { + skipped.push({ path: entry.path, reason: 'changed-externally', detail: 'the file no longer holds what the crashed run wrote' }); + return; + } + const bytes = await readOriginal(dir, entry); + await restoreEntry(entry, bytes, currentHash); + restored.push(entry.path); + } catch (err) { + skipped.push({ path: entry.path, reason: 'error', detail: errorMessage(err) }); } - // Only directories inside both the given roots and the roots the journal was written for. - const dirs = manifest.dirs.filter((d) => manifest.roots.some((root) => isInsideDir(root, d))); - await removeCreatedDirs(dirs, roots); - return { restored, skipped }; } function isCommitted(name: string): boolean { @@ -401,32 +472,46 @@ function isCommitted(name: string): boolean { /** * Restores every journal left by a server process that is gone and that - * touched one of `roots` (newest first, so two cut-off runs that changed the - * same file unwind in order). Files are restored only when they still hold - * what that run wrote; anything else is reported in `skipped`. Never throws. + * touched one of `roots`. Writes are undone newest first across journals, so + * two cut-off runs that changed the same file unwind in order. Files are + * restored only when they still hold what that run wrote and are not + * protected by `protectedPaths` (host policy patterns, `~` expanded); + * anything else is reported in `skipped`. A journal with a file that could not + * be handled is kept for a later pass. Nothing is read or deleted unless the + * journal directory is private to this user. Never throws. */ -export async function recoverStaleJournals(stateDir: string, roots: readonly string[]): Promise { +export async function recoverStaleJournals( + stateDir: string, + roots: readonly string[], + protectedPaths: readonly string[], +): Promise { const base = journalRoot(stateDir); let names: string[]; try { + await assertPrivateDir(base); names = await fs.readdir(base); } catch { return []; } const realRoots = await Promise.all(roots.filter((r) => path.isAbsolute(r)).map(realOrSelf)); + const patterns = protectedPaths.map((p) => expandTilde(p)); // A finalized run is never undone, whatever its directory still holds; it is only deleted. for (const name of names.filter(isCommitted)) { - await fs.rm(path.join(base, name), { recursive: true, force: true }).catch(() => undefined); + if (!TXID.test(name.slice(0, -COMMITTED.length))) continue; + const dir = path.join(base, name); + const st = await fs.lstat(dir).catch(() => null); + if (st?.isDirectory()) await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined); } // The id pattern below also rejects `.committed`, so a finalized run is never read as pending. const records = names .map((name) => ({ name, id: name.includes(RECOVERING) ? name.slice(0, name.indexOf(RECOVERING)) : name })) - .filter((r) => /^[0-9a-z]+-\d+-[0-9a-f]+$/.test(r.id)) - .sort((a, b) => parseInt(b.id.split('-')[0] ?? '0', 36) - parseInt(a.id.split('-')[0] ?? '0', 36)); - const out: RecoveredJournal[] = []; + .filter((r) => TXID.test(r.id)); + const claimed: Claimed[] = []; for (const record of records) { const dir = path.join(base, record.name); try { + const st = await fs.lstat(dir); + if (st.isSymbolicLink() || !st.isDirectory()) continue; const raw: unknown = JSON.parse(await fs.readFile(path.join(dir, MANIFEST), 'utf8')); const parsed = ManifestSchema.safeParse(raw); if (!parsed.success) continue; @@ -439,17 +524,30 @@ export async function recoverStaleJournals(stateDir: string, roots: readonly str } else if (!ownerGone(manifest, openTransactions, record.id)) { continue; } - const claimed = path.join(base, `${record.id}${RECOVERING}${process.pid}`); - if (claimed !== dir) { + const target = path.join(base, `${record.id}${RECOVERING}${process.pid}`); + if (target !== dir) { try { - await fs.rename(dir, claimed); + await fs.rename(dir, target); } catch { continue; } } - const report = await undoRecord(manifest, claimed, realRoots); - await fs.rm(claimed, { recursive: true, force: true }); - out.push({ id: record.id, report }); + claimed.push({ id: record.id, dir: target, manifest, restored: [], skipped: [] }); + } catch { + // One bad record must not stop the others. + } + } + const writes = claimed + .flatMap((record) => record.manifest.entries.map((entry) => ({ record, entry }))) + .sort((a, b) => (b.entry.at ?? b.record.manifest.startedAt) - (a.entry.at ?? a.record.manifest.startedAt)); + for (const { record, entry } of writes) await undoEntry(record, entry, realRoots, patterns); + const out: RecoveredJournal[] = []; + for (const record of claimed) { + try { + // The journal contains planned directory names and cannot establish ownership after a crash. + // A file that could not be handled keeps the record for a later pass. + if (!record.skipped.some((s) => s.reason === 'error')) await fs.rm(record.dir, { recursive: true, force: true }); + out.push({ id: record.id, report: { restored: record.restored, skipped: record.skipped } }); } catch { // One bad record must not stop the others. } diff --git a/src/tools/runtime.test.ts b/src/tools/runtime.test.ts index 95cb68d..877ea0e 100644 --- a/src/tools/runtime.test.ts +++ b/src/tools/runtime.test.ts @@ -1,3 +1,4 @@ +import { spawnSync } from 'node:child_process'; import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; @@ -375,7 +376,7 @@ describe.skipIf(IS_WINDOWS)('bash cwd', () => { const prepared = await prep('bash', { command: 'pwd', cwd: "it's here" }); if (prepared.tool !== 'bash') throw new Error('unreachable'); expect(prepared.effect.cwd).toBe(ws); - expect(prepared.effect.command).toBe(`cd -- '${ws}/it'\\''s here' && pwd`); + expect(prepared.effect.command).toBe(`cd -- '${ws}/it'\\''s here' || exit 1\npwd`); expect(prepared.args.command).toBe(prepared.effect.command); expect(prepared.effect.timeoutMs).toBe(120_000); const result = await rt.commit(prepared, new AbortController().signal); @@ -383,4 +384,124 @@ describe.skipIf(IS_WINDOWS)('bash cwd', () => { const same = await prep('bash', { command: 'pwd', cwd: '.' }); expect(same.tool === 'bash' && same.effect.command).toBe('pwd'); }); + + it('runs nothing of the command when its cwd is gone at commit', async () => { + mkdirSync(path.join(ws, 'gone')); + const prepared = await prep('bash', { command: 'echo first; echo second', cwd: 'gone' }); + rmSync(path.join(ws, 'gone'), { recursive: true }); + const result = await rt.commit(prepared, new AbortController().signal); + expect('exitCode' in result && [result.exitCode, result.stdout]).toEqual([1, '']); + }); +}); + +describe('protected paths and policy metadata', () => { + it('refuses a write that would create a protected directory', async () => { + policy = { ...policy, protectedPaths: [path.join(ws, 'locked')] }; + expect(await code(prep('write', { path: 'locked/inner/x.txt', content: 'x' }))).toBe('protected-path'); + expect(existsSync(path.join(ws, 'locked'))).toBe(false); + }); + + it.skipIf(IS_WINDOWS)('protects the target of a protected literal path that is a link', async () => { + writeFileSync(path.join(ws, 'real.json'), '{}'); + link(path.join(ws, 'real.json'), path.join(ws, 'config.json')); + policy = { ...policy, protectedPaths: [path.join(ws, 'config.json')] }; + expect(await code(prep('write', { path: 'real.json', content: 'x' }))).toBe('protected-path'); + }); + + it('refuses to commit a call it did not prepare', async () => { + const prepared = await prep('grep', { pattern: 'x' }); + await rt.commit(prepared, new AbortController().signal); + expect(await code(rt.commit(prepared, new AbortController().signal))).toBe('tool-error'); + }); + + it('refuses a sandboxed bash when a protected pattern has no directory the sandbox can deny', async () => { + policy = { + ...policy, + protectedPaths: ['**/.env'], + bashContainment: { mode: 'sandbox', readOnly: false, writableRoots: [ws], network: false }, + }; + await expect(prep('bash', { command: 'true' })).rejects.toMatchObject({ code: 'containment-unavailable', message: expect.stringContaining('**/.env') }); + }); +}); + +describe('file names', () => { + it('keeps leading spaces as part of the name', async () => { + await run('write', { path: ' spaced.txt', content: 'x' }); + expect(readFileSync(path.join(ws, ' spaced.txt'), 'utf8')).toBe('x'); + expect(existsSync(path.join(ws, 'spaced.txt'))).toBe(false); + }); + + it.skipIf(IS_WINDOWS)('writes a file whose name is close to the length limit', async () => { + const name = `${'n'.repeat(250)}.txt`; + await run('write', { path: name, content: 'x' }); + expect(readFileSync(path.join(ws, name), 'utf8')).toBe('x'); + }); + + it.skipIf(IS_WINDOWS)('refuses to search through a link given as the search path', async () => { + mkdirSync(path.join(ws, 'dir')); + link(path.join(ws, 'dir'), path.join(ws, 'alias')); + expect(await code(prep('grep', { pattern: 'x', path: 'alias' }))).toBe('invalid-args'); + expect(await code(prep('glob', { pattern: '*', path: 'alias' }))).toBe('invalid-args'); + }); + + it('shows none of the file when an edit does not match', async () => { + writeFileSync(path.join(ws, 'code.ts'), 'const token = "abc123";\nexport default token;\n'); + const err = await prep('edit', { path: 'code.ts', oldString: 'const token = "abc124";', newString: 'x' }).then( + () => undefined, + (e: unknown) => e, + ); + expect(err).toMatchObject({ code: 'not-found' }); + expect(String(err)).not.toContain('abc123'); + }); +}); + +describe('search filters', () => { + const grepFiles = async (args: ToolArgsMap['grep']): Promise => { + const r = await run('grep', args); + return 'matches' in r ? r.matches.map((m) => path.relative(ws, m.file)) : []; + }; + + it('applies gitignore rules to names that begin with two dots', async () => { + writeFileSync(path.join(ws, '.gitignore'), '..cache\n'); + writeFileSync(path.join(ws, '..cache'), 'hit\n'); + writeFileSync(path.join(ws, 'kept.txt'), 'hit\n'); + expect(await grepFiles({ pattern: 'hit' })).toEqual(['kept.txt']); + }); + + it('keeps ignoring files a directory negation does not re-include', async () => { + mkdirSync(path.join(ws, 'logs')); + writeFileSync(path.join(ws, 'logs', '.gitignore'), '*.log\n!sub/\n'); + mkdirSync(path.join(ws, 'logs', 'sub')); + writeFileSync(path.join(ws, 'logs', 'sub', 'x.log'), 'hit\n'); + writeFileSync(path.join(ws, 'logs', 'sub', 'x.txt'), 'hit\n'); + expect(await grepFiles({ pattern: 'hit' })).toEqual([path.join('logs', 'sub', 'x.txt')]); + }); + + it('skips a .git file of a worktree', async () => { + writeFileSync(path.join(ws, '.git'), 'gitdir: hit\n'); + writeFileSync(path.join(ws, 'a.txt'), 'hit\n'); + expect(await grepFiles({ pattern: 'hit' })).toEqual(['a.txt']); + const r = await run('glob', { pattern: '*' }); + expect('files' in r && r.files).toEqual([path.join(ws, 'a.txt')]); + }); + + it('applies the glob filter to a file given as the path', async () => { + writeFileSync(path.join(ws, 'a.txt'), 'hit\n'); + expect(await grepFiles({ pattern: 'hit', path: 'a.txt', glob: '*.ts' })).toEqual([]); + expect(await grepFiles({ pattern: 'hit', path: 'a.txt', glob: '*.txt' })).toEqual(['a.txt']); + }); + + it('skips files that are not valid UTF-8', async () => { + writeFileSync(path.join(ws, 'latin1.txt'), Buffer.from([0x68, 0x69, 0x74, 0x0a, 0xe9, 0xff, 0x0a])); + writeFileSync(path.join(ws, 'utf8.txt'), 'hit\n'); + expect(await grepFiles({ pattern: 'hit' })).toEqual(['utf8.txt']); + }); + + it.skipIf(IS_WINDOWS || spawnSync('mkfifo', ['--help']).error !== undefined)('does not wait on a FIFO named .gitignore or written to', async () => { + spawnSync('mkfifo', [path.join(ws, '.gitignore')]); + spawnSync('mkfifo', [path.join(ws, 'pipe')]); + writeFileSync(path.join(ws, 'a.txt'), 'hit\n'); + expect(await grepFiles({ pattern: 'hit' })).toEqual(['a.txt']); + expect(await code(prep('write', { path: 'pipe', content: 'x' }))).toBe('invalid-args'); + }); }); diff --git a/src/tools/runtime.ts b/src/tools/runtime.ts index bbcca54..670e22d 100644 --- a/src/tools/runtime.ts +++ b/src/tools/runtime.ts @@ -14,13 +14,12 @@ import type { ToolRuntime, Transaction, } from '../core/types.js'; -import { DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS, findBash, runBash, shellQuote } from './bash.js'; +import { DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS, runBash, shellQuote } from './bash.js'; import { binaryDiff, unifiedDiff } from './diff.js'; import { applySearchReplace, type MatchHow } from './edit-match.js'; import { type PathIdentity, type RegularFile, assertDirUnchanged, atomicWrite, captureIdentity, decodeText, errnoCode, isBinary, readRegularFile, sha256 } from './fs-ops.js'; import { FileTransaction } from './journal.js'; import { Jail } from './jail.js'; -import { containmentUnavailableReason } from './sandbox.js'; import { DEFAULT_GLOB_MAX_RESULTS, DEFAULT_GREP_MAX_RESULTS, compileGrep, normalizeGlob, runGlob, runGrep } from './search.js'; /** Default number of lines `read` returns. */ @@ -96,14 +95,23 @@ class MetaStore { } /** - * Literal paths from protected patterns that the OS sandbox can enforce: - * patterns without wildcards, and `dir/**` patterns as `dir`. + * Paths the OS sandbox denies writing, covering every protected pattern: + * a literal pattern as itself, `dir/**` as `dir`, and any other wildcard + * pattern as the directory its literal prefix names (more than the pattern + * protects, never less). Throws `containment-unavailable` for a pattern with + * no absolute directory prefix, rather than running a command that could + * write what the pattern protects. */ function sandboxDenyWrite(patterns: readonly string[]): string[] { const out: string[] = []; for (const p of patterns) { const base = p.endsWith('/**') ? p.slice(0, -3) : p; - if (!/[*?[]/.test(base) && path.isAbsolute(base)) out.push(base); + const wild = base.search(/[*?[]/); + const literal = wild === -1 ? base : base.slice(0, base.lastIndexOf('/', wild)); + if (!path.isAbsolute(literal) || path.dirname(literal) === literal) { + throw new ToolError('containment-unavailable', `the bash sandbox cannot enforce the protected path pattern ${p}`); + } + if (!out.includes(literal)) out.push(literal); } return out; } @@ -171,9 +179,6 @@ export class NodeToolRuntime implements ToolRuntime { ): Promise { switch (call.tool) { case 'bash': { - if (findBash() === null) { - throw new ToolError('tool-error', process.platform === 'win32' ? 'bash requires Git Bash, which was not found' : 'bash was not found'); - } let cwd = jail.cwd; if (call.args.cwd !== undefined) { cwd = await jail.resolve(call.args.cwd); @@ -182,21 +187,19 @@ export class NodeToolRuntime implements ToolRuntime { if (!st.isDirectory()) throw new ToolError('invalid-args', `bash cwd ${call.args.cwd} is not a directory`); } // What hooks see is exactly what runs: another cwd becomes part of the command. - const command = cwd === jail.cwd ? call.args.command : `cd -- ${shellQuote(cwd)} && ${call.args.command}`; + // A cd that fails ends the whole command, whatever operators the command uses. + const command = cwd === jail.cwd ? call.args.command : `cd -- ${shellQuote(cwd)} || exit 1\n${call.args.command}`; const timeoutMs = Math.min(call.args.timeoutMs ?? DEFAULT_BASH_TIMEOUT_MS, MAX_BASH_TIMEOUT_MS); const containment = policy.bashContainment; assertContainmentShape(containment); - if (containment.mode === 'sandbox') { - const reason = await containmentUnavailableReason(); - if (reason !== null) throw new ToolError('containment-unavailable', reason); - } + const denyWrite = containment.mode === 'sandbox' && !containment.readOnly ? sandboxDenyWrite(jail.protectedPaths) : []; const prepared: PreparedCallOf<'bash'> = { id: call.id, tool: 'bash', args: { command, timeoutMs }, effect: { command, cwd: jail.cwd, timeoutMs, containment }, }; - this.#meta.put(prepared, meta(jail.cwd, sandboxDenyWrite(jail.protectedPaths))); + this.#meta.put(prepared, meta(jail.cwd, denyWrite)); return prepared; } case 'read': { @@ -244,10 +247,13 @@ export class NodeToolRuntime implements ToolRuntime { if (call.args.oldString === call.args.newString) { throw new ToolError('invalid-args', 'oldString and newString are the same; the edit would change nothing'); } - const outcome = applySearchReplace(text, call.args.oldString, call.args.newString, call.args.replaceAll === true); + const outcome = applySearchReplace(text, call.args.oldString, call.args.newString, call.args.replaceAll === true, MAX_FILE_BYTES); if (!outcome.ok) { - const code = outcome.kind === 'not-found' ? 'not-found' : 'invalid-args'; - throw new ToolError(code, `${m.display}: ${outcome.message}`); + // Nothing of the file's content is shown: the call is not authorized yet. + if (outcome.kind === 'not-found') { + throw new ToolError('not-found', `${m.display}: search text not found; read the file and write oldString from what is there`); + } + throw new ToolError(outcome.kind === 'too-large' ? 'tool-error' : 'invalid-args', `${m.display}: ${outcome.message}`); } const prepared: PreparedCallOf<'edit'> = { id: call.id, @@ -267,7 +273,7 @@ export class NodeToolRuntime implements ToolRuntime { return prepared; } case 'grep': { - const absRoot = await jail.resolve(call.args.path ?? '.'); + const absRoot = await jail.resolveSearchRoot(call.args.path ?? '.'); await this.#assertExists(absRoot, call.args.path ?? '.'); const ignoreCase = call.args.ignoreCase ?? false; compileGrep(call.args.pattern, ignoreCase); @@ -283,7 +289,7 @@ export class NodeToolRuntime implements ToolRuntime { return prepared; } case 'glob': { - const absRoot = await jail.resolve(call.args.path ?? '.'); + const absRoot = await jail.resolveSearchRoot(call.args.path ?? '.'); const st = await this.#assertExists(absRoot, call.args.path ?? '.'); if (!st.isDirectory()) throw new ToolError('invalid-args', `glob path ${call.args.path ?? '.'} is not a directory`); normalizeGlob(call.args.pattern, absRoot); @@ -316,8 +322,13 @@ export class NodeToolRuntime implements ToolRuntime { return readRegularFile(abs, MAX_FILE_BYTES); } - #metaOf(prepared: PreparedCall, fallbackPath: string): CallMeta { - return this.#meta.take(prepared) ?? { root: path.dirname(fallbackPath), display: fallbackPath, denyWrite: [] }; + /** What prepare recorded for the call; a call this runtime did not prepare (or already committed) is refused. */ + #metaOf(prepared: PreparedCall): CallMeta { + const meta = this.#meta.take(prepared); + if (meta === undefined) { + throw new ToolError('tool-error', `this ${prepared.tool} call was not prepared by this tool runtime (or was already committed); prepare it again`); + } + return meta; } async commit(prepared: PreparedCall, signal: AbortSignal, tx?: Transaction): Promise { @@ -332,24 +343,27 @@ export class NodeToolRuntime implements ToolRuntime { if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before commit'); switch (prepared.tool) { case 'bash': { - const m = this.#metaOf(prepared, prepared.effect.cwd); + const m = this.#metaOf(prepared); return runBash(prepared.effect, signal, { ...(this.#opts.bashOutputCapBytes !== undefined ? { outputCapBytes: this.#opts.bashOutputCapBytes } : {}), denyWrite: m.denyWrite, }); } case 'read': + this.#metaOf(prepared); return this.#commitRead(prepared); case 'write': case 'edit': return this.#commitWrite(prepared, signal, tx); case 'grep': { + const { root } = this.#metaOf(prepared); await assertDirUnchanged(prepared.effect.absRoot); - return runGrep(prepared.effect, this.#metaOf(prepared, prepared.effect.absRoot).root, signal, this.#opts.grepFileBudgetMs); + return runGrep(prepared.effect, root, signal, this.#opts.grepFileBudgetMs); } case 'glob': { + const { root } = this.#metaOf(prepared); await assertDirUnchanged(prepared.effect.absRoot); - return runGlob(prepared.effect, this.#metaOf(prepared, prepared.effect.absRoot).root, signal); + return runGlob(prepared.effect, root, signal); } } } @@ -399,7 +413,7 @@ export class NodeToolRuntime implements ToolRuntime { identity: m.identity, ...(tx ? { beforeWrite: (before: RegularFile | null, createdDirs: readonly string[]) => tx.record(absPath, m.root, before, nextHash, createdDirs) } : {}), }); - tx?.written(absPath, nextHash); + tx?.written(absPath, nextHash, outcome.createdDirs); if (prepared.tool === 'write') return { path: absPath, created: outcome.before === null, diff: prepared.effect.diff }; return { path: absPath, diff --git a/src/tools/sandbox.ts b/src/tools/sandbox.ts index f09c201..72a1b20 100644 --- a/src/tools/sandbox.ts +++ b/src/tools/sandbox.ts @@ -1,5 +1,6 @@ import { ToolError, errorMessage } from '../core/errors.js'; import type { BashContainment } from '../core/types.js'; +import { bootstrapEnv, spawnAndWait } from './bash.js'; /** * OS containment for `bash` through `@anthropic-ai/sandbox-runtime` @@ -24,6 +25,7 @@ type Manager = SandboxModule['SandboxManager']; let loading: Promise | undefined; let networkOpen = false; let tail: Promise = Promise.resolve(); +let probed = false; /** Why containment is unavailable on this machine, or null when it is available. */ let availability: Promise | undefined; @@ -33,7 +35,7 @@ async function loadManager(): Promise { return mod.SandboxManager; } -/** Returns null when OS containment can be enforced here, else the reason. Cached. */ +/** Checks and caches the platform and dependencies before a sandboxed commit can run. */ export function containmentUnavailableReason(): Promise { availability ??= (async () => { if (process.platform !== 'linux' && process.platform !== 'darwin') { @@ -52,6 +54,32 @@ export function containmentUnavailableReason(): Promise { return availability; } +/** Most time the probe command may take. */ +const PROBE_TIMEOUT_MS = 15_000; + +/** + * Runs `true` in the sandbox once: present dependencies do not prove the + * sandbox can start here (user namespaces may be disabled), and a sandbox + * that cannot start would otherwise look like the command's own exit. + */ +async function probe(m: Manager, shell: string, signal: AbortSignal): Promise { + try { + const wrapped = await m.wrapWithSandboxArgv('true', shell, { filesystem: { denyRead: [], allowWrite: [], denyWrite: [] } }); + const env = bootstrapEnv({ ...process.env, ...wrapped.env }); + const r = await spawnAndWait(wrapped.argv, env, process.cwd(), PROBE_TIMEOUT_MS, signal, 4096); + if (r.exitCode === 0) return; + const how = r.timedOut ? `no exit within ${PROBE_TIMEOUT_MS} ms` : `exit ${r.exitCode ?? r.signal}`; + const first = r.stderr.trim().split('\n')[0] ?? ''; + throw new Error(`the sandbox could not start a command (${how}${first ? `: ${first}` : ''})`); + } finally { + try { + m.cleanupAfterCommand(); + } catch { + // Cleanup is best effort. + } + } +} + async function manager(): Promise { loading ??= (async () => { const m = await loadManager(); @@ -86,15 +114,23 @@ export function withSandbox( cwd: string, containment: Extract, denyWrite: readonly string[], + signal: AbortSignal, fn: (wrapped: WrappedCommand) => Promise, ): Promise { const run = async (): Promise => { const reason = await containmentUnavailableReason(); if (reason !== null) throw new ToolError('containment-unavailable', reason); + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before bash started'); let m: Manager; try { m = await manager(); + if (signal.aborted) throw new ToolError('cancelled', 'the run was stopped before bash started'); + if (!probed) { + await probe(m, shell, signal); + probed = true; + } } catch (err) { + if (err instanceof ToolError && err.code === 'cancelled') throw err; throw new ToolError('containment-unavailable', `sandbox runtime failed to start: ${errorMessage(err)}`); } let wrapped: WrappedCommand; diff --git a/src/tools/search.ts b/src/tools/search.ts index 684a56a..1aecee5 100644 --- a/src/tools/search.ts +++ b/src/tools/search.ts @@ -5,7 +5,7 @@ import fs from 'node:fs/promises'; import path from 'node:path'; import { ToolError } from '../core/errors.js'; import { DEFAULT_CASE_INSENSITIVE, matchesPathPattern } from '../core/paths.js'; -import { readFileInside } from './fs-ops.js'; +import { isBinary, readFileInside } from './fs-ops.js'; import type { GlobEffect, GlobResult, GrepEffect, GrepMatch, GrepResult } from '../core/types.js'; /** Default `grep` result count. */ @@ -111,9 +111,12 @@ interface IgnoreLayer { function isIgnored(layers: readonly IgnoreLayer[], abs: string, isDir: boolean): boolean { let ignored = false; + // Directory rules decide about a file's parents apart from the rules about the file itself, + // so `!dir/` re-includes the directory without clearing what `*.log` says about its files. + let parentIgnored = false; for (const layer of layers) { const rel = path.relative(layer.base, abs).split(path.sep).join('/'); - if (rel === '' || rel.startsWith('..')) continue; + if (rel === '' || rel === '..' || rel.startsWith('../') || path.isAbsolute(rel)) continue; for (const rule of layer.rules) { if (rule.dirOnly && !isDir) { // `dir/` also ignores what is below it: test the parents. @@ -123,18 +126,19 @@ function isIgnored(layers: readonly IgnoreLayer[], abs: string, isDir: boolean): for (let i = parts.length; i > 0 && !matchedParent; i--) { if (rule.re.test(parts.slice(0, i).join('/'))) matchedParent = true; } - if (matchedParent) ignored = !rule.negate; + if (matchedParent) parentIgnored = !rule.negate; continue; } if (rule.re.test(rel)) ignored = !rule.negate; } } - return ignored; + return ignored || parentIgnored; } async function loadIgnore(dir: string): Promise { try { - const handle = await fs.open(path.join(dir, '.gitignore'), FS.O_RDONLY | (FS.O_NOFOLLOW ?? 0)); + // Non-blocking, so a FIFO named .gitignore cannot stall the open before the type check. + const handle = await fs.open(path.join(dir, '.gitignore'), FS.O_RDONLY | (FS.O_NOFOLLOW ?? 0) | (FS.O_NONBLOCK ?? 0)); try { const st = await handle.stat(); if (!st.isFile() || st.size > 1024 * 1024) return null; @@ -213,8 +217,9 @@ async function* walkFiles(absRoot: string, jailRoot: string, signal: AbortSignal if (++visited > MAX_VISITED) throw new ToolError('tool-error', `too many files under ${absRoot} (more than ${MAX_VISITED}); narrow the path`); const abs = path.join(dir, entry.name); if (entry.isSymbolicLink()) continue; + // `.git` is also a file, in worktrees and submodules. + if (ALWAYS_IGNORED.has(entry.name)) continue; if (entry.isDirectory()) { - if (ALWAYS_IGNORED.has(entry.name)) continue; if (isIgnored(here, abs, true)) continue; subdirs.push(abs); } else if (entry.isFile()) { @@ -403,11 +408,12 @@ export async function runGrep( const worker = new MatchWorker(effect.pattern, effect.ignoreCase ? 'i' : ''); try { for await (const file of walkFiles(effect.absRoot, jailRoot, signal)) { - if (globs && file !== effect.absRoot && !matchesFileGlob(toRel(effect.absRoot, file), globs)) continue; + const rel = file === effect.absRoot ? path.basename(file) : toRel(effect.absRoot, file); + if (globs && !matchesFileGlob(rel, globs)) continue; // Opened without following links and checked to be the file at this path, // so a directory swapped for a link mid-walk cannot lead outside. const bytes = await readFileInside(file, MAX_GREP_FILE_BYTES); - if (bytes === null || bytes.subarray(0, 8192).includes(0)) continue; + if (bytes === null || isBinary(bytes)) continue; const room = effect.maxResults - matches.length; const found = await worker.match(file, bytes.toString('utf8'), room, fileBudgetMs, signal); for (const [line, text] of found.hits) matches.push({ file, line, text }); @@ -430,4 +436,3 @@ export async function runGlob(effect: GlobEffect, jailRoot: string, signal: Abor all.sort(); return { files: all.slice(0, effect.maxResults), truncated: all.length > effect.maxResults }; } -