Compare commits

...

38 Commits

Author SHA1 Message Date
Agus Zubiaga
0df3dea08d 0.1.11 2025-09-02 23:13:44 -03:00
Agus Zubiaga
182a40ccae Add backticks around glob tool label 2025-09-02 23:12:08 -03:00
Agus Zubiaga
55c61986e8 0.1.10 2025-09-02 20:03:22 -03:00
Agus Zubiaga
46f643b9f4 Improve background terminal output 2025-09-02 20:03:14 -03:00
Agus Zubiaga
07316e2eb0 Redirect console.log et al to stderr 2025-09-02 19:46:30 -03:00
Agus Zubiaga
9dc15bd190 0.1.9 2025-09-02 19:26:40 -03:00
Agus Zubiaga
df04c41d5a Only include relevant files 2025-09-02 19:14:05 -03:00
Agus Zubiaga
a3038d383f Setup linter (#12)
Fixes basic issues. For now, we're still allowing `any`, but it'd be
nice to move away from it.
2025-09-02 19:06:32 -03:00
Agus Zubiaga
28f36d7474 Format README 2025-09-02 18:24:51 -03:00
Agus Zubiaga
a07f132a9a Improve "Other clients" section 2025-09-02 18:23:05 -03:00
Agus Zubiaga
7d969fd9ff Update README.md 2025-09-02 18:17:17 -03:00
Conrad Irwin
a4e8ba0b14 Remove more unsupported /slash commands 2025-09-02 13:18:13 -07:00
Conrad Irwin
532daf0e7e v0.1.8 2025-09-02 12:33:40 -07:00
Conrad Irwin
d6e5910631 Fix load errors when SDK is busted 2025-09-02 12:33:11 -07:00
Agus Zubiaga
0d5e78f1ac Fix info for builtin tools (#11) 2025-09-02 15:50:21 -03:00
Agus Zubiaga
02fac67f52 Do not send tool_call_update for TodoWrite (#10)
When we receive a `TodoWrite` tool use, we send a plan update instead of
a tool call. However, we were still trying to send a tool call update
when we received the `TodoWrite` tool result, which caused an ACP error.

Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>
2025-09-02 11:53:54 -03:00
Agus Zubiaga
1ef3ba327d Unpin SDK now that entrypoint is fixed (#9)
Co-authored-by: Bennet <bennet@zed.dev>
2025-09-02 11:38:45 -03:00
Agus Zubiaga
617233d693 0.1.7 2025-09-02 11:25:56 -03:00
Bennet Bo Fenner
0dc5a4b366 Add support for slash commands (#7)
Co-authored-by: Antonio Scandurra <me@as-cii.com>
Co-authored-by: Agus Zubiaga <agus@zed.dev>
2025-09-02 10:29:45 +02:00
Agus Zubiaga
6d1711cfa4 Use ACP terminal support when available (#8)
When the `terminal` client capability is available, we'll now replace
Claude Code's bash tools with our own that go over ACP. This includes
support for background terminals.

---------

Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>
Co-authored-by: Bennet <bennet@zed.dev>
2025-09-01 12:01:50 -03:00
Ben Brandt
f79a121c9c Remove provenance flag 2025-08-29 12:18:27 -07:00
Ben Brandt
ace8b0b5e5 0.1.6 2025-08-29 12:13:56 -07:00
Ben Brandt
1d14d35779 Add publish step on tags (#6) 2025-08-29 21:13:27 +02:00
Ben Brandt
d39c2adb21 Add CI workflow and Prettier formatting (#5) 2025-08-29 20:35:31 +02:00
Conrad Irwin
48a31df673 v0.1.5 2025-08-29 10:01:57 -06:00
Conrad Irwin
63d243deef Add a bin field 2025-08-29 10:01:45 -06:00
Conrad Irwin
048d5c562c Add bin 2025-08-29 09:57:27 -06:00
Bennet Bo Fenner
d6b805a77b Update tests to reflect new behavior 2025-08-29 10:36:42 +02:00
Conrad Irwin
b83c250f17 Only enable read/write tools if supported by the client 2025-08-28 23:02:59 -06:00
Conrad Irwin
d7511ac542 v0.1.4 2025-08-28 22:42:48 -06:00
Conrad Irwin
f18bfeaf8d Render read files in code blocks 2025-08-28 22:34:56 -06:00
Cole Miller
c4674e901a Change the format of LS tool's title to match Zed agent (#4) 2025-08-29 00:20:51 -04:00
Ben Brandt
dd088b39e3 Cleanup tool updates a bit 2025-08-28 20:01:34 -07:00
Conrad Irwin
a066b838a2 v0.1.3 2025-08-28 20:59:09 -06:00
Conrad Irwin
b875e24ad5 Fix showing of diffs in permission prompts 2025-08-28 20:58:45 -06:00
Conrad Irwin
77f667c619 Fix publishing 2025-08-28 19:33:14 -06:00
Conrad Irwin
1f2953a4ce v0.1.1 2025-08-28 18:20:21 -06:00
Ben Brandt
ce0e1a30ac Only overwrite content if we have something 2025-08-28 16:48:30 -07:00
17 changed files with 1935 additions and 598 deletions

6
.eslintignore Normal file
View File

@@ -0,0 +1,6 @@
node_modules/
dist/
coverage/
*.min.js
*.config.js
.github/

33
.eslintrc.json Normal file
View File

@@ -0,0 +1,33 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module",
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint"],
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
"env": {
"node": true,
"es2020": true
},
"rules": {
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{
"argsIgnorePattern": "^_"
}
],
"no-console": "off",
"no-constant-condition": "off",
"default-case": "error",
"prefer-const": "error",
"no-var": "error",
"eqeqeq": ["error", "always"],
"curly": ["error", "all"]
},
"ignorePatterns": ["dist", "node_modules", "*.js"]
}

45
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,45 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: "ci-${{ github.ref }}"
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
build:
name: Build
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8
- name: Use Node.js
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version: latest
cache: "npm"
- name: Install dependencies
run: npm ci
- name: Check formatting
run: npm run format:check
- name: Run linter
run: npm run lint
- name: Build
run: npm run build
- name: Run tests
run: npm run test:run

23
.github/workflows/publish.yml vendored Normal file
View File

@@ -0,0 +1,23 @@
name: Publish Package to npmjs
on:
push:
tags:
- "v*.*.*"
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8
# Setup .npmrc file to publish to npm
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version: "lts/*"
registry-url: "https://registry.npmjs.org"
- run: npm ci
# Add back provenance once repo is public
- run: npm publish # --provenance --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

4
.prettierrc.json Normal file
View File

@@ -0,0 +1,4 @@
{
"printWidth": 100,
"tabWidth": 2
}

View File

@@ -1,3 +1,51 @@
An ACP-compatible coding agent powered by the Claude Code SDK # ACP adapter for Claude Code
This wrapper lets you use the real version of Claude Code from the IDE of your choice. Use [Claude Code](https://www.anthropic.com/claude-code) from [ACP-compatible](https://agentclientprotocol.com) clients such as [Zed](https://zed.dev)!
This tool implements an ACP agent by using the official [Claude Code SDK](https://docs.anthropic.com/en/docs/claude-code/sdk/sdk-overview), supporting:
- Context @-mentions
- Images
- Tool calls
- Following
- Edit review
- TODO lists
- Interactive (and background) terminals
- Custom [Slash commands](https://docs.anthropic.com/en/docs/claude-code/slash-commands)
- Client MCP servers
Learn more about the [Agent Client Protocol](https://agentclientprotocol.com/).
## How to use
### Zed
The latest version of Zed can already use this adapter out of the box.
To use Claude Code, open the Agent Panel and click "New Claude Code Thread" from the `+` button menu in the top-right:
https://github.com/user-attachments/assets/ddce66c7-79ac-47a3-ad59-4a6a3ca74903
[Read the docs](https://zed.dev/docs/ai/external-agents) on External Agent support.
### Other clients
Setup instructions for other clients are coming soon. Feel free to [submit a PR](https://github.com/zed-industries/claude-code-acp/pulls) to add yours!
#### Installation
Install the adapter from `npm`:
```bash
$ npm install @zed-industries/claude-code-acp
```
You can then use `claude-code-acp` as a regular ACP agent:
```
$ ANTHROPIC_API_KEY=sk-... claude-code-acp
```
## License
Apache-2.0

571
package-lock.json generated
View File

@@ -1,37 +1,44 @@
{ {
"name": "@zed-industries/claude-code-acp", "name": "@zed-industries/claude-code-acp",
"version": "0.1.0", "version": "0.1.11",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@zed-industries/claude-code-acp", "name": "@zed-industries/claude-code-acp",
"version": "0.1.0", "version": "0.1.11",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@anthropic-ai/claude-code": "^1.0.96", "@anthropic-ai/claude-code": "^1.0.100",
"@modelcontextprotocol/sdk": "^1.17.4", "@modelcontextprotocol/sdk": "^1.17.4",
"@types/express": "^5.0.3", "@types/express": "^5.0.3",
"@zed-industries/agent-client-protocol": "0.1.2", "@zed-industries/agent-client-protocol": "0.2.0-alpha.4",
"express": "^5.1.0", "express": "^5.1.0",
"minimist": "^1.2.8", "minimist": "^1.2.8",
"uuid": "11.1.0" "uuid": "11.1.0"
}, },
"bin": {
"claude-code-acp": "dist/index.js"
},
"devDependencies": { "devDependencies": {
"@types/minimist": "^1.2.5", "@types/minimist": "^1.2.5",
"@types/node": "^24.3.0", "@types/node": "^24.3.0",
"@types/uuid": "^10.0.0", "@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^8.42.0",
"@typescript-eslint/parser": "^8.42.0",
"@vitest/ui": "^3.2.4", "@vitest/ui": "^3.2.4",
"eslint": "^8.56.0", "eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"prettier": "^3.6.2",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"typescript": "^5.4.0", "typescript": "^5.4.0",
"vitest": "^3.2.4" "vitest": "^3.2.4"
} }
}, },
"node_modules/@anthropic-ai/claude-code": { "node_modules/@anthropic-ai/claude-code": {
"version": "1.0.96", "version": "1.0.100",
"resolved": "https://registry.npmjs.org/@anthropic-ai/claude-code/-/claude-code-1.0.96.tgz", "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-code/-/claude-code-1.0.100.tgz",
"integrity": "sha512-xnxhYzuh6PYlMcw56REMQiGMW20WaLLOvG8L8TObq70zhNKs3dro7nhYwHRe1c2ubTr20oIJK0aSkyD2BpO8nA==", "integrity": "sha512-b4FRo3t46kPawzE8pT7nxtDc9NdYPTFaPoGGns/ZNqsqRu2jKMiSjjt5DiFvfaBZA8Tnt2qXbv4nd1vqR9Ru8Q==",
"license": "SEE LICENSE IN README.md", "license": "SEE LICENSE IN README.md",
"bin": { "bin": {
"claude": "cli.js" "claude": "cli.js"
@@ -556,6 +563,30 @@
"url": "https://opencollective.com/eslint" "url": "https://opencollective.com/eslint"
} }
}, },
"node_modules/@eslint/eslintrc/node_modules/brace-expansion": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/@eslint/eslintrc/node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
}
},
"node_modules/@eslint/js": { "node_modules/@eslint/js": {
"version": "8.57.1", "version": "8.57.1",
"resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz",
@@ -582,6 +613,30 @@
"node": ">=10.10.0" "node": ">=10.10.0"
} }
}, },
"node_modules/@humanwhocodes/config-array/node_modules/brace-expansion": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/@humanwhocodes/config-array/node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
}
},
"node_modules/@humanwhocodes/module-importer": { "node_modules/@humanwhocodes/module-importer": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz",
@@ -1351,6 +1406,251 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.42.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.42.0.tgz",
"integrity": "sha512-Aq2dPqsQkxHOLfb2OPv43RnIvfj05nw8v/6n3B2NABIPpHnjQnaLo9QGMTvml+tv4korl/Cjfrb/BYhoL8UUTQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/regexpp": "^4.10.0",
"@typescript-eslint/scope-manager": "8.42.0",
"@typescript-eslint/type-utils": "8.42.0",
"@typescript-eslint/utils": "8.42.0",
"@typescript-eslint/visitor-keys": "8.42.0",
"graphemer": "^1.4.0",
"ignore": "^7.0.0",
"natural-compare": "^1.4.0",
"ts-api-utils": "^2.1.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"@typescript-eslint/parser": "^8.42.0",
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
"version": "7.0.5",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",
"integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/@typescript-eslint/parser": {
"version": "8.42.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.42.0.tgz",
"integrity": "sha512-r1XG74QgShUgXph1BYseJ+KZd17bKQib/yF3SR+demvytiRXrwd12Blnz5eYGm8tXaeRdd4x88MlfwldHoudGg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/scope-manager": "8.42.0",
"@typescript-eslint/types": "8.42.0",
"@typescript-eslint/typescript-estree": "8.42.0",
"@typescript-eslint/visitor-keys": "8.42.0",
"debug": "^4.3.4"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/project-service": {
"version": "8.42.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.42.0.tgz",
"integrity": "sha512-vfVpLHAhbPjilrabtOSNcUDmBboQNrJUiNAGoImkZKnMjs2TIcWG33s4Ds0wY3/50aZmTMqJa6PiwkwezaAklg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/tsconfig-utils": "^8.42.0",
"@typescript-eslint/types": "^8.42.0",
"debug": "^4.3.4"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/scope-manager": {
"version": "8.42.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.42.0.tgz",
"integrity": "sha512-51+x9o78NBAVgQzOPd17DkNTnIzJ8T/O2dmMBLoK9qbY0Gm52XJcdJcCl18ExBMiHo6jPMErUQWUv5RLE51zJw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.42.0",
"@typescript-eslint/visitor-keys": "8.42.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@typescript-eslint/tsconfig-utils": {
"version": "8.42.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.42.0.tgz",
"integrity": "sha512-kHeFUOdwAJfUmYKjR3CLgZSglGHjbNTi1H8sTYRYV2xX6eNz4RyJ2LIgsDLKf8Yi0/GL1WZAC/DgZBeBft8QAQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/type-utils": {
"version": "8.42.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.42.0.tgz",
"integrity": "sha512-9KChw92sbPTYVFw3JLRH1ockhyR3zqqn9lQXol3/YbI6jVxzWoGcT3AsAW0mu1MY0gYtsXnUGV/AKpkAj5tVlQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.42.0",
"@typescript-eslint/typescript-estree": "8.42.0",
"@typescript-eslint/utils": "8.42.0",
"debug": "^4.3.4",
"ts-api-utils": "^2.1.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/types": {
"version": "8.42.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.42.0.tgz",
"integrity": "sha512-LdtAWMiFmbRLNP7JNeY0SqEtJvGMYSzfiWBSmx+VSZ1CH+1zyl8Mmw1TT39OrtsRvIYShjJWzTDMPWZJCpwBlw==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@typescript-eslint/typescript-estree": {
"version": "8.42.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.42.0.tgz",
"integrity": "sha512-ku/uYtT4QXY8sl9EDJETD27o3Ewdi72hcXg1ah/kkUgBvAYHLwj2ofswFFNXS+FL5G+AGkxBtvGt8pFBHKlHsQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/project-service": "8.42.0",
"@typescript-eslint/tsconfig-utils": "8.42.0",
"@typescript-eslint/types": "8.42.0",
"@typescript-eslint/visitor-keys": "8.42.0",
"debug": "^4.3.4",
"fast-glob": "^3.3.2",
"is-glob": "^4.0.3",
"minimatch": "^9.0.4",
"semver": "^7.6.0",
"ts-api-utils": "^2.1.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/utils": {
"version": "8.42.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.42.0.tgz",
"integrity": "sha512-JnIzu7H3RH5BrKC4NoZqRfmjqCIS1u3hGZltDYJgkVdqAezl4L9d1ZLw+36huCujtSBSAirGINF/S4UxOcR+/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/eslint-utils": "^4.7.0",
"@typescript-eslint/scope-manager": "8.42.0",
"@typescript-eslint/types": "8.42.0",
"@typescript-eslint/typescript-estree": "8.42.0"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^8.57.0 || ^9.0.0",
"typescript": ">=4.8.4 <6.0.0"
}
},
"node_modules/@typescript-eslint/visitor-keys": {
"version": "8.42.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.42.0.tgz",
"integrity": "sha512-3WbiuzoEowaEn8RSnhJBrxSwX8ULYE9CXaPepS2C2W3NSA5NNIvBaslpBSBElPq0UGr0xVJlXFWOAKIkyylydQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.42.0",
"eslint-visitor-keys": "^4.2.1"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",
"integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"url": "https://opencollective.com/eslint"
}
},
"node_modules/@ungap/structured-clone": { "node_modules/@ungap/structured-clone": {
"version": "1.3.0", "version": "1.3.0",
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
@@ -1496,9 +1796,9 @@
} }
}, },
"node_modules/@zed-industries/agent-client-protocol": { "node_modules/@zed-industries/agent-client-protocol": {
"version": "0.1.2", "version": "0.2.0-alpha.4",
"resolved": "https://registry.npmjs.org/@zed-industries/agent-client-protocol/-/agent-client-protocol-0.1.2.tgz", "resolved": "https://registry.npmjs.org/@zed-industries/agent-client-protocol/-/agent-client-protocol-0.2.0-alpha.4.tgz",
"integrity": "sha512-A1RCN7Uf09vngbhBVLiZENenKYOYD2OGiILLGXPaSBloDbem8xmLaDmrKQuYl0kjLJ1DcWmVaHUv97n1l5vJ6w==", "integrity": "sha512-l/MdK0MrvEb55/U3wAtAN/MC04YK+N6vNyakNgLsK2JTcmG54n45gXa0OZ08lYUmEvLe0shdu1dDtzlOV/Luxw==",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"zod": "^3.0.0" "zod": "^3.0.0"
@@ -1647,14 +1947,26 @@
} }
}, },
"node_modules/brace-expansion": { "node_modules/brace-expansion": {
"version": "1.1.12", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"balanced-match": "^1.0.0", "balanced-match": "^1.0.0"
"concat-map": "0.0.1" }
},
"node_modules/braces": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
"dev": true,
"license": "MIT",
"dependencies": {
"fill-range": "^7.1.1"
},
"engines": {
"node": ">=8"
} }
}, },
"node_modules/bytes": { "node_modules/bytes": {
@@ -2109,6 +2421,19 @@
"url": "https://opencollective.com/eslint" "url": "https://opencollective.com/eslint"
} }
}, },
"node_modules/eslint-config-prettier": {
"version": "9.1.2",
"resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.2.tgz",
"integrity": "sha512-iI1f+D2ViGn+uvv5HuHVUamg8ll4tN+JRHGc6IJi4TP9Kl976C57fzPXgseXNs8v0iA8aSJpHsTWjDb9QJamGQ==",
"dev": true,
"license": "MIT",
"bin": {
"eslint-config-prettier": "bin/cli.js"
},
"peerDependencies": {
"eslint": ">=7.0.0"
}
},
"node_modules/eslint-scope": { "node_modules/eslint-scope": {
"version": "7.2.2", "version": "7.2.2",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz",
@@ -2139,6 +2464,30 @@
"url": "https://opencollective.com/eslint" "url": "https://opencollective.com/eslint"
} }
}, },
"node_modules/eslint/node_modules/brace-expansion": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/eslint/node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
}
},
"node_modules/espree": { "node_modules/espree": {
"version": "9.6.1", "version": "9.6.1",
"resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz",
@@ -2235,12 +2584,12 @@
} }
}, },
"node_modules/eventsource-parser": { "node_modules/eventsource-parser": {
"version": "3.0.5", "version": "3.0.6",
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.5.tgz", "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz",
"integrity": "sha512-bSRG85ZrMdmWtm7qkF9He9TNRzc/Bm99gEJMaQoHJ9E6Kv9QBbsldh2oMj7iXmYNEAVvNgvv5vPorG6W+XtBhQ==", "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=20.0.0" "node": ">=18.0.0"
} }
}, },
"node_modules/expect-type": { "node_modules/expect-type": {
@@ -2316,6 +2665,36 @@
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/fast-glob": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
"integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@nodelib/fs.stat": "^2.0.2",
"@nodelib/fs.walk": "^1.2.3",
"glob-parent": "^5.1.2",
"merge2": "^1.3.0",
"micromatch": "^4.0.8"
},
"engines": {
"node": ">=8.6.0"
}
},
"node_modules/fast-glob/node_modules/glob-parent": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
"dev": true,
"license": "ISC",
"dependencies": {
"is-glob": "^4.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/fast-json-stable-stringify": { "node_modules/fast-json-stable-stringify": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
@@ -2377,6 +2756,19 @@
"node": "^10.12.0 || >=12.0.0" "node": "^10.12.0 || >=12.0.0"
} }
}, },
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
"dev": true,
"license": "MIT",
"dependencies": {
"to-regex-range": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/finalhandler": { "node_modules/finalhandler": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz",
@@ -2554,6 +2946,30 @@
"node": ">=10.13.0" "node": ">=10.13.0"
} }
}, },
"node_modules/glob/node_modules/brace-expansion": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/glob/node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
}
},
"node_modules/globals": { "node_modules/globals": {
"version": "13.24.0", "version": "13.24.0",
"resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz",
@@ -2747,6 +3163,16 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/is-number": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.12.0"
}
},
"node_modules/is-path-inside": { "node_modules/is-path-inside": {
"version": "3.0.3", "version": "3.0.3",
"resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz",
@@ -2910,6 +3336,43 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/merge2": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
"integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 8"
}
},
"node_modules/micromatch": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
"dev": true,
"license": "MIT",
"dependencies": {
"braces": "^3.0.3",
"picomatch": "^2.3.1"
},
"engines": {
"node": ">=8.6"
}
},
"node_modules/micromatch/node_modules/picomatch": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8.6"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/mime-db": { "node_modules/mime-db": {
"version": "1.54.0", "version": "1.54.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
@@ -2932,16 +3395,19 @@
} }
}, },
"node_modules/minimatch": { "node_modules/minimatch": {
"version": "3.1.2", "version": "9.0.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==",
"dev": true, "dev": true,
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"brace-expansion": "^1.1.7" "brace-expansion": "^2.0.1"
}, },
"engines": { "engines": {
"node": "*" "node": ">=16 || 14 >=14.17"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
} }
}, },
"node_modules/minimist": { "node_modules/minimist": {
@@ -3241,6 +3707,22 @@
"node": ">= 0.8.0" "node": ">= 0.8.0"
} }
}, },
"node_modules/prettier": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz",
"integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==",
"dev": true,
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/proxy-addr": { "node_modules/proxy-addr": {
"version": "2.0.7", "version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
@@ -3467,6 +3949,19 @@
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/semver": {
"version": "7.7.2",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
"integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/send": { "node_modules/send": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz",
@@ -3778,6 +4273,19 @@
"node": ">=14.0.0" "node": ">=14.0.0"
} }
}, },
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-number": "^7.0.0"
},
"engines": {
"node": ">=8.0"
}
},
"node_modules/toidentifier": { "node_modules/toidentifier": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
@@ -3797,6 +4305,19 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/ts-api-utils": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz",
"integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18.12"
},
"peerDependencies": {
"typescript": ">=4.8.4"
}
},
"node_modules/ts-node": { "node_modules/ts-node": {
"version": "10.9.2", "version": "10.9.2",
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",

View File

@@ -3,19 +3,33 @@
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
}, },
"version": "0.1.0", "bin": {
"claude-code-acp": "./dist/index.js"
},
"version": "0.1.11",
"description": "An ACP-compatible coding agent powered by the Claude Code SDK (TypeScript)", "description": "An ACP-compatible coding agent powered by the Claude Code SDK (TypeScript)",
"main": "dist/acp-agent.js", "main": "dist/index.js",
"type": "module", "type": "module",
"files": [
"dist/",
"README.md",
"LICENSE",
"package.json"
],
"scripts": { "scripts": {
"build": "tsc", "build": "tsc",
"start": "node dist/index.js", "start": "node dist/index.js",
"dev": "npm run build && npm run start", "dev": "npm run build && npm run start",
"lint": "eslint src --ext .ts", "lint": "eslint src --ext .ts",
"lint:fix": "eslint src --ext .ts --fix",
"format": "prettier --write .",
"format:check": "prettier --check .",
"check": "npm run lint && npm run format:check",
"test": "vitest", "test": "vitest",
"test:integration": "RUN_INTEGRATION_TESTS=true vitest run", "test:integration": "RUN_INTEGRATION_TESTS=true vitest run",
"test:run": "vitest run", "test:run": "vitest run",
"test:coverage": "vitest run --coverage" "test:coverage": "vitest run --coverage",
"prepublishOnly": "npm run build"
}, },
"keywords": [ "keywords": [
"claude", "claude",
@@ -29,10 +43,10 @@
"author": "Zed Industries", "author": "Zed Industries",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@anthropic-ai/claude-code": "^1.0.96", "@anthropic-ai/claude-code": "^1.0.100",
"@modelcontextprotocol/sdk": "^1.17.4", "@modelcontextprotocol/sdk": "^1.17.4",
"@types/express": "^5.0.3", "@types/express": "^5.0.3",
"@zed-industries/agent-client-protocol": "0.1.2", "@zed-industries/agent-client-protocol": "0.2.0-alpha.4",
"express": "^5.1.0", "express": "^5.1.0",
"minimist": "^1.2.8", "minimist": "^1.2.8",
"uuid": "11.1.0" "uuid": "11.1.0"
@@ -41,8 +55,12 @@
"@types/minimist": "^1.2.5", "@types/minimist": "^1.2.5",
"@types/node": "^24.3.0", "@types/node": "^24.3.0",
"@types/uuid": "^10.0.0", "@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^8.42.0",
"@typescript-eslint/parser": "^8.42.0",
"@vitest/ui": "^3.2.4", "@vitest/ui": "^3.2.4",
"eslint": "^8.56.0", "eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"prettier": "^3.6.2",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"typescript": "^5.4.0", "typescript": "^5.4.0",
"vitest": "^3.2.4" "vitest": "^3.2.4"

View File

@@ -2,44 +2,40 @@ import {
Agent, Agent,
AgentSideConnection, AgentSideConnection,
AuthenticateRequest, AuthenticateRequest,
AvailableCommand,
CancelNotification, CancelNotification,
Client, ClientCapabilities,
InitializeRequest, InitializeRequest,
InitializeResponse, InitializeResponse,
LoadSessionRequest,
NewSessionRequest, NewSessionRequest,
NewSessionResponse, NewSessionResponse,
PromptRequest, PromptRequest,
PromptResponse, PromptResponse,
ReadTextFileRequest,
ReadTextFileResponse,
RequestError, RequestError,
ToolCallContent, TerminalHandle,
ToolKind, TerminalOutputResponse,
WriteTextFileRequest,
WriteTextFileResponse,
} from "@zed-industries/agent-client-protocol"; } from "@zed-industries/agent-client-protocol";
import { import {
McpServerConfig, McpServerConfig,
Options,
Query, Query,
query, query,
SDKAssistantMessage, SDKAssistantMessage,
SDKMessage,
SDKUserMessage, SDKUserMessage,
} from "@anthropic-ai/claude-code"; } from "@anthropic-ai/claude-code";
import * as readline from "node:readline"; import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
import { v7 as uuidv7 } from "uuid"; import { v7 as uuidv7 } from "uuid";
import { import { nodeToWebReadable, nodeToWebWritable, Pushable, sleep, unreachable } from "./utils.js";
nodeToWebReadable,
nodeToWebWritable,
Pushable,
unreachable,
} from "./utils.js";
import { ContentBlock } from "@zed-industries/agent-client-protocol";
import { SessionNotification } from "@zed-industries/agent-client-protocol"; import { SessionNotification } from "@zed-industries/agent-client-protocol";
import { createMcpServer } from "./mcp-server.js"; import { createMcpServer } from "./mcp-server.js";
import { AddressInfo } from "node:net"; import { AddressInfo } from "node:net";
import { import { toolInfoFromToolUse, planEntries, toolUpdateFromToolResult } from "./tools.js";
toolInfoFromToolUse,
planEntries,
toolUpdateFromToolResult,
} from "./tools.js";
type Session = { type Session = {
query: Query; query: Query;
@@ -47,25 +43,49 @@ type Session = {
cancelled: boolean; cancelled: boolean;
}; };
type BackgroundTerminal =
| {
handle: TerminalHandle;
status: "started";
lastOutput: TerminalOutputResponse | null;
}
| {
status: "aborted" | "exited" | "killed" | "timedOut";
pendingOutput: TerminalOutputResponse;
};
type ToolUseCache = {
[key: string]: { type: "tool_use"; id: string; name: string; input: any };
};
// Implement the ACP Agent interface // Implement the ACP Agent interface
export class ClaudeAcpAgent implements Agent { export class ClaudeAcpAgent implements Agent {
sessions: { sessions: {
[key: string]: Session; [key: string]: Session;
}; };
client: Client; client: AgentSideConnection;
toolUseCache: { [key: string]: any }; toolUseCache: ToolUseCache;
fileContentCache: { [key: string]: string };
backgroundTerminals: { [key: string]: BackgroundTerminal } = {};
clientCapabilities?: ClientCapabilities;
constructor(client: Client) { constructor(client: AgentSideConnection) {
this.sessions = {}; this.sessions = {};
this.client = client; this.client = client;
this.toolUseCache = {}; this.toolUseCache = {};
this.fileContentCache = {};
} }
async initialize(params: InitializeRequest): Promise<InitializeResponse> {
async initialize(request: InitializeRequest): Promise<InitializeResponse> {
this.clientCapabilities = request.clientCapabilities;
return { return {
protocolVersion: 1, protocolVersion: 1,
// todo!() // todo!()
agentCapabilities: { agentCapabilities: {
promptCapabilities: { image: true, embeddedContext: true }, promptCapabilities: {
image: true,
embeddedContext: true,
},
}, },
authMethods: [ authMethods: [
{ {
@@ -82,8 +102,8 @@ export class ClaudeAcpAgent implements Agent {
}; };
} }
async newSession(params: NewSessionRequest): Promise<NewSessionResponse> { async newSession(params: NewSessionRequest): Promise<NewSessionResponse> {
let sessionId = uuidv7(); const sessionId = uuidv7();
let input = new Pushable<SDKUserMessage>(); const input = new Pushable<SDKUserMessage>();
const mcpServers: Record<string, McpServerConfig> = {}; const mcpServers: Record<string, McpServerConfig> = {};
if (Array.isArray(params.mcpServers)) { if (Array.isArray(params.mcpServers)) {
@@ -99,9 +119,8 @@ export class ClaudeAcpAgent implements Agent {
} }
} }
// todo!() auth const server = await createMcpServer(this, sessionId, this.clientCapabilities);
let server = await createMcpServer(this, sessionId); const address = server.address() as AddressInfo;
let address = server.address() as AddressInfo;
mcpServers["acp"] = { mcpServers["acp"] = {
type: "http", type: "http",
url: "http://127.0.0.1:" + address.port + "/mcp", url: "http://127.0.0.1:" + address.port + "/mcp",
@@ -110,17 +129,38 @@ export class ClaudeAcpAgent implements Agent {
}, },
}; };
let q = query({ const options: Options = {
cwd: params.cwd,
mcpServers,
permissionPromptToolName: "mcp__acp__permission",
stderr: (err) => console.error(err),
};
const allowedTools = [];
const disallowedTools = [];
if (this.clientCapabilities?.fs?.readTextFile) {
allowedTools.push("mcp__acp__read");
disallowedTools.push("Read");
}
if (this.clientCapabilities?.fs?.writeTextFile) {
allowedTools.push("mcp__acp__write");
disallowedTools.push("Write", "Edit", "MultiEdit");
}
if (this.clientCapabilities?.terminal) {
allowedTools.push("mcp__acp__BashOutput", "mcp__acp__KillBash");
disallowedTools.push("Bash", "BashOutput", "KillBash");
}
if (allowedTools.length > 0) {
options.allowedTools = allowedTools;
}
if (disallowedTools.length > 0) {
options.disallowedTools = disallowedTools;
}
const q = query({
prompt: input, prompt: input,
options: { options,
cwd: params.cwd,
mcpServers,
allowedTools: ["mcp__acp__read"],
disallowedTools: ["Read", "Write", "Edit", "MultiEdit"],
strictMcpConfig: true,
permissionPromptToolName: "mcp__acp__permission",
stderr: (err) => console.error(err),
},
}); });
this.sessions[sessionId] = { this.sessions[sessionId] = {
query: q, query: q,
@@ -128,12 +168,14 @@ export class ClaudeAcpAgent implements Agent {
cancelled: false, cancelled: false,
}; };
const availableCommands = await availableSlashCommands(q);
return { return {
sessionId, sessionId,
availableCommands,
}; };
} }
async authenticate(params: AuthenticateRequest): Promise<void> { async authenticate(_params: AuthenticateRequest): Promise<void> {
throw new Error("Method not implemented."); throw new Error("Method not implemented.");
} }
@@ -148,7 +190,7 @@ export class ClaudeAcpAgent implements Agent {
input.push(promptToClaude(params)); input.push(promptToClaude(params));
while (true) { while (true) {
let { value: message, done } = await query.next(); const { value: message, done } = await query.next();
if (done || !message) { if (done || !message) {
if (this.sessions[params.sessionId].cancelled) { if (this.sessions[params.sessionId].cancelled) {
return { stopReason: "cancelled" }; return { stopReason: "cancelled" };
@@ -186,8 +228,8 @@ export class ClaudeAcpAgent implements Agent {
} }
if ( if (
message.message.model == "<synthetic>" && message.message.model === "<synthetic>" &&
message.message.content.length == 1 && message.message.content.length === 1 &&
message.message.content[0].text.includes("Please run /login") message.message.content[0].text.includes("Please run /login")
) { ) {
throw RequestError.authRequired(); throw RequestError.authRequired();
@@ -196,6 +238,7 @@ export class ClaudeAcpAgent implements Agent {
message, message,
params.sessionId, params.sessionId,
this.toolUseCache, this.toolUseCache,
this.fileContentCache,
)) { )) {
await this.client.sessionUpdate(notification); await this.client.sessionUpdate(notification);
} }
@@ -215,6 +258,86 @@ export class ClaudeAcpAgent implements Agent {
this.sessions[params.sessionId].cancelled = true; this.sessions[params.sessionId].cancelled = true;
await this.sessions[params.sessionId].query.interrupt(); await this.sessions[params.sessionId].query.interrupt();
} }
async readTextFile(params: ReadTextFileRequest): Promise<ReadTextFileResponse> {
const response = await this.client.readTextFile(params);
if (!params.limit && !params.line) {
this.fileContentCache[params.path] = response.content;
}
return response;
}
async writeTextFile(params: WriteTextFileRequest): Promise<WriteTextFileResponse> {
const response = await this.client.writeTextFile(params);
this.fileContentCache[params.path] = params.content;
return response;
}
}
async function availableSlashCommands(query: Query): Promise<AvailableCommand[]> {
const UNSUPPORTED_COMMANDS = [
"add-dir",
"agents", // Modal
"bashes", // Modal
"bug", // Modal
"clear", // Escape Codes
"compact", // Not supported via SDK?
"config", // Modal
"context", // Escape Codes
"cost", // Escape Codes
"doctor", // Escape Codes
"exit",
"export", // Modal
"help", // Modal
"hooks", // Modal
"ide", // Modal
"install-github-app", // Modal
"login",
"logout",
"memory",
"mcp",
"migrate-installer", // Modal
"model", // Not supported via SDK?
"output-style", // Modal
"output-style:new", // Modal
"permissions", // Modal
"privacy-settings",
"release-notes", // Escape Codes
"resume",
"status", // Not supported via SDK?
"statusline", // Not needed
"terminal-setup", // Not needed
"todos", // Escape Codes
"vim", // Not needed
];
const commands = await Promise.race([
//todo: Do not use `as any` once `supportedCommands` is exposed via the typescript interface
(query as any).supportedCommands(),
sleep(5000).then(() => {
if (
fs.existsSync(path.resolve(os.homedir(), ".claude.json.backup")) &&
!fs.existsSync(path.resolve(os.homedir(), ".claude.json"))
) {
throw RequestError.authRequired();
}
throw new Error("can't load supported slash commands");
}),
]);
return commands
.map((command: { name: string; description: string; argumentHint: string }) => {
const input = command.argumentHint ? { hint: command.argumentHint } : null;
return {
name: command.name,
description: command.description || "",
input,
};
})
.filter(
(command: AvailableCommand) =>
!(command.name.match(/\(MCP\)/) || UNSUPPORTED_COMMANDS.includes(command.name)),
);
} }
function formatUriAsLink(uri: string): string { function formatUriAsLink(uri: string): string {
@@ -312,13 +435,14 @@ function promptToClaude(prompt: PromptRequest): SDKUserMessage {
export function toAcpNotifications( export function toAcpNotifications(
message: SDKAssistantMessage | SDKUserMessage, message: SDKAssistantMessage | SDKUserMessage,
sessionId: string, sessionId: string,
toolUseCache: { [key: string]: any }, toolUseCache: ToolUseCache,
fileContentCache: { [key: string]: string },
): SessionNotification[] { ): SessionNotification[] {
let chunks = message.message.content as ContentChunk[]; const chunks = message.message.content as ContentChunk[];
let output = []; const output = [];
// Only handle the first chunk for streaming; extend as needed for batching // Only handle the first chunk for streaming; extend as needed for batching
for (const chunk of chunks) { for (const chunk of chunks) {
let update: SessionNotification["update"]; let update: SessionNotification["update"] | null = null;
switch (chunk.type) { switch (chunk.type) {
case "text": case "text":
update = { update = {
@@ -335,8 +459,7 @@ export function toAcpNotifications(
content: { content: {
type: "image", type: "image",
data: chunk.source.type === "base64" ? chunk.source.data : "", data: chunk.source.type === "base64" ? chunk.source.data : "",
mimeType: mimeType: chunk.source.type === "base64" ? chunk.source.media_type : "",
chunk.source.type === "base64" ? chunk.source.media_type : "",
uri: chunk.source.type === "url" ? chunk.source.url : undefined, uri: chunk.source.type === "url" ? chunk.source.url : undefined,
}, },
}; };
@@ -352,7 +475,7 @@ export function toAcpNotifications(
break; break;
case "tool_use": case "tool_use":
toolUseCache[chunk.id] = chunk; toolUseCache[chunk.id] = chunk;
if (chunk.name == "TodoWrite") { if (chunk.name === "TodoWrite") {
update = { update = {
sessionUpdate: "plan", sessionUpdate: "plan",
entries: planEntries(chunk.input), entries: planEntries(chunk.input),
@@ -363,24 +486,37 @@ export function toAcpNotifications(
sessionUpdate: "tool_call", sessionUpdate: "tool_call",
rawInput: chunk.input, rawInput: chunk.input,
status: "pending", status: "pending",
...toolInfoFromToolUse(chunk), ...toolInfoFromToolUse(chunk, fileContentCache),
}; };
} }
break; break;
case "tool_result": case "tool_result": {
update = { const toolUse = toolUseCache[chunk.tool_use_id];
toolCallId: chunk.tool_use_id, if (!toolUse) {
sessionUpdate: "tool_call_update", console.error(
status: chunk.is_error ? "failed" : "completed", `[claude-code-acp] Got a tool result for tool use that wasn't tracked: ${chunk.tool_use_id}`,
...toolUpdateFromToolResult(chunk, toolUseCache[chunk.tool_use_id]), );
}; break;
}
if (toolUse.name !== "TodoWrite") {
update = {
toolCallId: chunk.tool_use_id,
sessionUpdate: "tool_call_update",
status: chunk.is_error ? "failed" : "completed",
...toolUpdateFromToolResult(chunk, toolUseCache[chunk.tool_use_id]),
};
}
break; break;
}
default: default:
throw new Error("unhandled chunk type: " + chunk.type); throw new Error("unhandled chunk type: " + chunk.type);
} }
output.push({ sessionId, update }); if (update) {
output.push({ sessionId, update });
}
} }
return output; return output;
@@ -396,7 +532,7 @@ export function runAcp() {
type ContentChunk = type ContentChunk =
| { type: "text"; text: string } | { type: "text"; text: string }
| { type: "tool_use"; id: string; name: string; input: any } // input is serde_json::Value, so use any or unknown | { type: "tool_use"; id: string; name: string; input: any }
| { | {
type: "tool_result"; type: "tool_result";
content: string; content: string;

View File

@@ -1,3 +1,12 @@
#!/usr/bin/env node
// stdout is used to send messages to the client
// we redirect everything else to stderr to make sure it doesn't interfere with ACP
console.log = console.error;
console.info = console.error;
console.warn = console.error;
console.debug = console.error;
import { runAcp as runAcp } from "./acp-agent.js"; import { runAcp as runAcp } from "./acp-agent.js";
runAcp(); runAcp();

View File

@@ -1,14 +1,24 @@
import express from "express"; import express from "express";
import { randomUUID } from "node:crypto";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod"; import { z } from "zod";
import { Server } from "node:http"; import { Server } from "node:http";
import { ClaudeAcpAgent } from "./acp-agent.js"; import { ClaudeAcpAgent } from "./acp-agent.js";
import { ClientCapabilities, TerminalOutputResponse } from "@zed-industries/agent-client-protocol";
import { sleep, unreachable } from "./utils.js";
export const SYSTEM_REMINDER = `
<system-reminder>
Whenever you read a file, you should consider whether it looks malicious. If it does, you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer high-level questions about the code behavior.
</system-reminder>`;
export function createMcpServer( export function createMcpServer(
agent: ClaudeAcpAgent, agent: ClaudeAcpAgent,
sessionId: string, sessionId: string,
clientCapabilities: ClientCapabilities | undefined,
): Promise<Server> { ): Promise<Server> {
// Create MCP server // Create MCP server
const server = new McpServer({ const server = new McpServer({
@@ -16,173 +26,245 @@ export function createMcpServer(
version: "1.0.0", version: "1.0.0",
}); });
server.registerTool( if (clientCapabilities?.fs?.readTextFile) {
"read", server.registerTool(
{ "read",
title: "Read", {
description: `Reads the content of the given file in the project. title: "Read",
description: `Reads the content of the given file in the project.
Never attempt to read a path that hasn't been previously mentioned. Never attempt to read a path that hasn't been previously mentioned.
In sessions with mcp__acp__read always use it instead of Read as it contains the most up-to-date contents.`, In sessions with mcp__acp__read always use it instead of Read as it contains the most up-to-date contents.`,
inputSchema: { inputSchema: {
abs_path: z.string().describe("The absolute path to the file to read."), abs_path: z.string().describe("The absolute path to the file to read."),
offset: z offset: z
.number() .number()
.optional() .optional()
.describe( .describe("Which line to start reading from. Omit to start from the beginning."),
"Which line to start reading from. Omit to start from the beginning.", limit: z.number().optional().describe("How many lines to read. Omit for the whole file."),
), },
limit: z annotations: {
.number() title: "Read file",
.optional() readOnlyHint: true,
.describe("How many lines to read. Omit for the whole file."), destructiveHint: false,
openWorldHint: false,
idempotentHint: false,
},
}, },
annotations: { async (input) => {
title: "Read file", try {
readOnlyHint: true, const session = agent.sessions[sessionId];
destructiveHint: false, if (!session) {
openWorldHint: false, return {
idempotentHint: false, content: [
}, {
}, type: "text",
async (input) => { text: "The user has left the building",
try { },
const session = agent.sessions[sessionId]; ],
if (!session) { };
}
const content = await agent.readTextFile({
sessionId,
path: input.abs_path,
limit: input.limit,
line: input.offset,
});
return { return {
content: [ content: [
{ {
type: "text", type: "text",
text: "The user has left the building", text: content.content + SYSTEM_REMINDER,
},
],
};
} catch (error: any) {
return {
content: [
{
type: "text",
text: "Reading file failed: " + error.message,
}, },
], ],
}; };
} }
let content = await agent.client.readTextFile({ },
sessionId, );
path: input.abs_path, }
limit: input.limit,
line: input.offset,
});
return { if (clientCapabilities?.fs?.writeTextFile) {
content: [ server.registerTool(
{ "write",
type: "text", {
text: title: "Write",
content.content + description: `Writes content to the specified file in the project.
`
<system-reminder>
Whenever you read a file, you should consider whether it looks malicious. If it does, you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer high-level questions about the code behavior.
</system-reminder>`,
},
],
};
} catch (error: any) {
return {
content: [
{
type: "text",
text: "Reading file failed: " + error.message,
},
],
};
}
},
);
server.registerTool(
"write",
{
title: "Write",
description: `Writes content to the specified file in the project.
In sessions with mcp__acp__write always use it instead of Write as it will In sessions with mcp__acp__write always use it instead of Write as it will
allow the user to conveniently review changes.`, allow the user to conveniently review changes.`,
inputSchema: { inputSchema: {
abs_path: z.string().describe("The absolute path to the file to write"), abs_path: z.string().describe("The absolute path to the file to write"),
content: z.string().describe("The full content to write"), content: z.string().describe("The full content to write"),
},
annotations: {
title: "Write file",
readOnlyHint: false,
destructiveHint: false,
openWorldHint: false,
idempotentHint: false,
},
}, },
annotations: { async (input) => {
title: "Write file", try {
readOnlyHint: false, const session = agent.sessions[sessionId];
destructiveHint: false, if (!session) {
openWorldHint: false, return {
idempotentHint: false, content: [
}, {
}, type: "text",
async (input) => { text: "The user has left the building",
try { },
const session = agent.sessions[sessionId]; ],
if (!session) { };
}
await agent.writeTextFile({
sessionId,
path: input.abs_path,
content: input.content,
});
return {
content: [],
};
} catch (error: any) {
return { return {
content: [ content: [
{ {
type: "text", type: "text",
text: "The user has left the building", text: "Writing file failed: " + error.message,
}, },
], ],
}; };
} }
let content = await agent.client.writeTextFile({ },
sessionId, );
path: input.abs_path,
content: input.content,
});
return { server.registerTool(
content: [], "edit",
}; {
} catch (error: any) { title: "Edit",
return { description: `Edit a file.
content: [
{
type: "text",
text: "Writing file failed: " + error.message,
},
],
};
}
},
);
server.registerTool(
"edit",
{
title: "Edit",
description: `Edit a file.
In sessions with mcp__acp__edit always use it instead of Edit as it will In sessions with mcp__acp__edit always use it instead of Edit as it will
allow the user to conveniently review changes. allow the user to conveniently review changes.
File editing instructions: File editing instructions:
- The \`old_text\` param must match existing file content, including indentation. - The \`old_string\` param must match existing file content, including indentation.
- The \`old_text\` param must come from the actual file, not an outline. - The \`old_string\` param must come from the actual file, not an outline.
- The \`old_text\` section must not be empty. - The \`old_string\` section must not be empty.
- Be minimal with replacements: - Be minimal with replacements:
- For unique lines, include only those lines. - For unique lines, include only those lines.
- For non-unique lines, include enough context to identify them. - For non-unique lines, include enough context to identify them.
- Do not escape quotes, newlines, or other characters. - Do not escape quotes, newlines, or other characters.
- Only edit the specified file.`, - Only edit the specified file.`,
inputSchema: { inputSchema: {
abs_path: z.string().describe("The absolute path to the file to read."), abs_path: z.string().describe("The absolute path to the file to read."),
old_text: z old_string: z.string().describe("The old text to replace (must be unique in the file)"),
.string() new_string: z.string().describe("The new text."),
.describe("The old text to replace (must be unique in the file)"), },
new_text: z.string().describe("The new text."), annotations: {
title: "Edit file",
readOnlyHint: false,
destructiveHint: false,
openWorldHint: false,
idempotentHint: false,
},
}, },
annotations: { async (input) => {
title: "Edit file", try {
readOnlyHint: false, const session = agent.sessions[sessionId];
destructiveHint: false, if (!session) {
openWorldHint: false, return {
idempotentHint: false, content: [
{
type: "text",
text: "The user has left the building",
},
],
};
}
const { content } = await agent.readTextFile({
sessionId,
path: input.abs_path,
});
const { newContent, lineNumbers } = replaceAndCalculateLocation(content, [
{
oldText: input.old_string,
newText: input.new_string,
replaceAll: false,
},
]);
await agent.writeTextFile({
sessionId,
path: input.abs_path,
content: newContent,
});
return {
content: [
{
type: "text",
text: JSON.stringify({ lineNumbers }),
},
],
};
} catch (error: any) {
return {
content: [
{
type: "text",
text: "Editing file failed: " + error.message,
},
],
};
}
}, },
}, );
async (input) => {
try { server.registerTool(
"multi-edit",
{
title: "Multi Edit",
description: `Edit a file with multiple sequential edits.`,
inputSchema: {
file_path: z.string().describe("The absolute path to the file to modify"),
edits: z
.array(
z.object({
old_string: z.string().describe("The text to replace"),
new_string: z.string().describe("The text to replace it with"),
replace_all: z
.boolean()
.optional()
.describe("Replace all occurrences of old_string (default false)"),
}),
)
.min(1)
.describe("Array of edit operations to perform sequentially on the file"),
},
annotations: {
title: "Multi Edit file",
readOnlyHint: false,
destructiveHint: false,
openWorldHint: false,
idempotentHint: false,
},
},
async (input) => {
const session = agent.sessions[sessionId]; const session = agent.sessions[sessionId];
if (!session) { if (!session) {
return { return {
@@ -195,25 +277,23 @@ File editing instructions:
}; };
} }
let { content } = await agent.client.readTextFile({ const { content } = await agent.readTextFile({
sessionId, sessionId,
path: input.abs_path, path: input.file_path,
}); });
const { newContent, lineNumbers } = replaceAndCalculateLocation( const { newContent, lineNumbers } = replaceAndCalculateLocation(
content, content,
[ input.edits.map((edit) => ({
{ oldText: edit.old_string,
oldText: input.old_text, newText: edit.new_string,
newText: input.new_text, replaceAll: edit.replace_all ?? false,
replaceAll: false, })),
},
],
); );
await agent.client.writeTextFile({ await agent.writeTextFile({
sessionId, sessionId,
path: input.abs_path, path: input.file_path,
content: newContent, content: newContent,
}); });
@@ -225,99 +305,257 @@ File editing instructions:
}, },
], ],
}; };
} catch (error: any) {
return {
content: [
{
type: "text",
text: "Editing file failed: " + error.message,
},
],
};
}
},
);
server.registerTool(
"multi-edit",
{
title: "Multi Edit",
description: `Edit a file with multiple sequential edits.`,
inputSchema: {
file_path: z
.string()
.describe("The absolute path to the file to modify"),
edits: z
.array(
z.object({
old_string: z.string().describe("The text to replace"),
new_string: z.string().describe("The text to replace it with"),
replace_all: z
.boolean()
.optional()
.describe(
"Replace all occurrences of old_string (default false)",
),
}),
)
.min(1)
.describe(
"Array of edit operations to perform sequentially on the file",
),
}, },
annotations: { );
title: "Multi Edit file", }
readOnlyHint: false,
destructiveHint: false, if (agent.clientCapabilities?.terminal) {
openWorldHint: false, server.registerTool(
idempotentHint: false, "Bash",
{
title: "Bash",
description: "Executes a bash command",
inputSchema: {
command: z.string().describe("The bash command to execute as a one-liner"),
timeout_ms: z
.number()
.default(2 * 60 * 1000)
.describe("Optional timeout in milliseconds"),
run_in_background: z
.boolean()
.default(false)
.describe(
"When set to true, the command is started in the background. The tool returns an `id` that can be used with the `mcp__acp__BashOutput` tool to retrieve the current output, or the `mcp__acp__KillBash` tool to stop it early.",
),
},
}, },
}, async (input, extra) => {
async (input) => { const session = agent.sessions[sessionId];
const session = agent.sessions[sessionId]; if (!session) {
if (!session) { return {
return { content: [
content: [ {
{ type: "text",
type: "text", text: "The user has left the building",
text: "The user has left the building", },
}, ],
], };
}; }
}
let { content } = await agent.client.readTextFile({ const toolCallId = extra._meta?.["claudecode/toolUseId"];
sessionId,
path: input.file_path,
});
const { newContent, lineNumbers } = replaceAndCalculateLocation( if (typeof toolCallId !== "string") {
content, throw new Error("No tool call ID found");
input.edits.map((edit) => ({ }
oldText: edit.old_string,
newText: edit.new_string,
replaceAll: edit.replace_all ?? false,
})),
);
await agent.client.writeTextFile({ if (!agent.clientCapabilities?.terminal || !agent.client.createTerminal) {
sessionId, throw new Error("unreachable");
path: input.file_path, }
content: newContent,
});
return { const handle = await agent.client.createTerminal({
content: [ command: input.command,
{ sessionId,
type: "text", outputByteLimit: 32_000,
text: JSON.stringify({ lineNumbers }), });
await agent.client.sessionUpdate({
sessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
status: "in_progress",
content: [{ type: "terminal", terminalId: handle.id }],
}, },
], });
};
},
);
let alwaysAllowedTools: { [key: string]: boolean } = {}; const abortPromise = new Promise((resolve) => {
if (extra.signal.aborted) {
resolve(null);
} else {
extra.signal.addEventListener("abort", () => {
resolve(null);
});
}
});
const statusPromise = Promise.race([
handle.waitForExit().then((exitStatus) => ({ status: "exited" as const, exitStatus })),
abortPromise.then(() => ({ status: "aborted" as const, exitStatus: null })),
sleep(input.timeout_ms).then(async () => {
if (agent.backgroundTerminals[handle.id]?.status === "started") {
await handle.kill();
}
return { status: "timedOut" as const, exitStatus: null };
}),
]);
if (input.run_in_background) {
agent.backgroundTerminals[handle.id] = {
handle,
lastOutput: null,
status: "started",
};
statusPromise.then(async ({ status, exitStatus }) => {
const bgTerm = agent.backgroundTerminals[handle.id];
if (bgTerm.status !== "started") {
return;
}
const currentOutput = await handle.currentOutput();
agent.backgroundTerminals[handle.id] = {
status,
pendingOutput: {
...currentOutput,
output: stripCommonPrefix(bgTerm.lastOutput?.output ?? "", currentOutput.output),
exitStatus: exitStatus ?? currentOutput.exitStatus,
},
};
return handle.release();
});
return {
content: [
{
type: "text",
text: `Command started in background with id: ${handle.id}`,
},
],
};
}
await using terminal = handle;
const { status } = await statusPromise;
if (status === "aborted") {
return {
content: [{ type: "text", text: "Tool cancelled by user" }],
};
}
const output = await terminal.currentOutput();
return {
content: [{ type: "text", text: toolCommandOutput(status, output) }],
};
},
);
server.registerTool(
"BashOutput",
{
title: "BashOutput",
description:
"Returns the current output and exit status of a background bash command by its id. Includes only new output since last invocation.",
inputSchema: {
id: z
.string()
.describe("The id of the background bash command as returned by `mcp__acp__Bash`"),
},
},
async (input) => {
const bgTerm = agent.backgroundTerminals[input.id];
if (!bgTerm) {
throw new Error(`Unknown shell ${input.id}`);
}
if (bgTerm.status === "started") {
const newOutput = await bgTerm.handle.currentOutput();
const strippedOutput = stripCommonPrefix(
bgTerm.lastOutput?.output ?? "",
newOutput.output,
);
bgTerm.lastOutput = newOutput;
return {
content: [
{
type: "text",
text: toolCommandOutput(bgTerm.status, {
...newOutput,
output: strippedOutput,
}),
},
],
};
} else {
return {
content: [
{
type: "text",
text: toolCommandOutput(bgTerm.status, bgTerm.pendingOutput),
},
],
};
}
},
);
server.registerTool(
"KillBash",
{
title: "KillBash",
description: "Stops a background command by its id",
inputSchema: {
id: z
.string()
.describe("The id of the background bash command as returned by `mcp__acp__Bash`"),
},
},
async (input) => {
const bgTerm = agent.backgroundTerminals[input.id];
if (!bgTerm) {
throw new Error(`Unknown shell ${input.id}`);
}
switch (bgTerm.status) {
case "started": {
await bgTerm.handle.kill();
const currentOutput = await bgTerm.handle.currentOutput();
agent.backgroundTerminals[bgTerm.handle.id] = {
status: "killed",
pendingOutput: {
...currentOutput,
output: stripCommonPrefix(bgTerm.lastOutput?.output ?? "", currentOutput.output),
},
};
await bgTerm.handle.release();
return {
content: [{ type: "text", text: "Command killed successfully." }],
};
}
case "aborted":
return {
content: [{ type: "text", text: "Command aborted by user." }],
};
case "exited":
return {
content: [{ type: "text", text: "Command had already exited." }],
};
case "killed":
return {
content: [{ type: "text", text: "Command was already killed." }],
};
case "timedOut":
return {
content: [{ type: "text", text: "Command killed by timeout." }],
};
default: {
return unreachable(bgTerm);
}
}
},
);
}
const alwaysAllowedTools: { [key: string]: boolean } = {};
server.registerTool( server.registerTool(
"permission", "permission",
{ {
@@ -357,7 +595,7 @@ File editing instructions:
], ],
}; };
} }
let response = await agent.client.requestPermission({ const response = await agent.client.requestPermission({
options: [ options: [
{ {
kind: "allow_always", kind: "allow_always",
@@ -374,11 +612,10 @@ File editing instructions:
}, },
}); });
if ( if (
response.outcome?.outcome == "selected" && response.outcome?.outcome === "selected" &&
(response.outcome.optionId == "allow" || (response.outcome.optionId === "allow" || response.outcome.optionId === "allow_always")
response.outcome.optionId == "allow_always")
) { ) {
if (response.outcome.optionId == "allow_always") { if (response.outcome.optionId === "allow_always") {
alwaysAllowedTools[input.tool_name] = true; alwaysAllowedTools[input.tool_name] = true;
} }
return { return {
@@ -413,10 +650,9 @@ File editing instructions:
app.post("/mcp", async (req, res) => { app.post("/mcp", async (req, res) => {
try { try {
const transport: StreamableHTTPServerTransport = const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({
new StreamableHTTPServerTransport({ sessionIdGenerator: undefined,
sessionIdGenerator: undefined, });
});
res.on("close", () => { res.on("close", () => {
transport.close(); transport.close();
server.close(); server.close();
@@ -429,7 +665,7 @@ File editing instructions:
jsonrpc: "2.0", jsonrpc: "2.0",
error: { error: {
code: -32603, code: -32603,
message: "Internal server error", message: `Internal server error: ${error}`,
}, },
id: null, id: null,
}); });
@@ -448,6 +684,67 @@ File editing instructions:
}); });
} }
function stripCommonPrefix(a: string, b: string): string {
let i = 0;
while (i < a.length && i < b.length && a[i] === b[i]) {
i++;
}
return b.slice(i);
}
function toolCommandOutput(
status: "started" | "aborted" | "exited" | "killed" | "timedOut",
output: TerminalOutputResponse,
): string {
const { exitStatus, output: commandOutput, truncated } = output;
let toolOutput = "";
switch (status) {
case "started":
case "exited": {
if (exitStatus && (exitStatus.exitCode ?? null) === null) {
toolOutput += `Interrupted by the user. `;
}
break;
}
case "killed":
toolOutput += `Killed. `;
break;
case "timedOut":
toolOutput += `Timed out. `;
break;
case "aborted":
break;
default: {
const unreachable: never = status;
return unreachable;
}
}
if (exitStatus) {
if (typeof exitStatus.exitCode === "number") {
toolOutput += `Exited with code ${exitStatus.exitCode}.`;
}
if (typeof exitStatus.signal === "string") {
toolOutput += `Signal \`${exitStatus.signal}\`. `;
}
toolOutput += "Final output:\n\n";
} else {
toolOutput += "New output:\n\n";
}
toolOutput += commandOutput;
if (truncated) {
toolOutput += `\n\nCommand output was too long, so it was truncated to ${commandOutput.length} bytes.`;
}
return toolOutput;
}
/** /**
* Replace text in a file and calculate the line numbers where the edits occurred. * Replace text in a file and calculate the line numbers where the edits occurred.
* *
@@ -485,7 +782,9 @@ export function replaceAndCalculateLocation(
while (true) { while (true) {
const index = currentContent.indexOf(edit.oldText, searchIndex); const index = currentContent.indexOf(edit.oldText, searchIndex);
if (index === -1) break; if (index === -1) {
break;
}
// Add content before the match // Add content before the match
parts.push(currentContent.substring(lastIndex, index)); parts.push(currentContent.substring(lastIndex, index));

View File

@@ -0,0 +1,5 @@
---
description: 10 * 3 = 30
---
What is 10 \* 3. Only respond with the number.

View File

@@ -0,0 +1,6 @@
---
description: Say hello
argument-hint: [name]
---
Respond with "Hello $1" and nothing else.

View File

@@ -4,6 +4,7 @@ import {
Agent, Agent,
Client, Client,
ClientSideConnection, ClientSideConnection,
NewSessionResponse,
ReadTextFileRequest, ReadTextFileRequest,
ReadTextFileResponse, ReadTextFileResponse,
RequestPermissionRequest, RequestPermissionRequest,
@@ -13,89 +14,168 @@ import {
WriteTextFileResponse, WriteTextFileResponse,
} from "@zed-industries/agent-client-protocol"; } from "@zed-industries/agent-client-protocol";
import { nodeToWebWritable, nodeToWebReadable } from "../utils.js"; import { nodeToWebWritable, nodeToWebReadable } from "../utils.js";
import { toolInfoFromToolUse, toolUpdateFromToolResult } from "../tools.js"; import { markdownEscape, toolInfoFromToolUse, toolUpdateFromToolResult } from "../tools.js";
import { toAcpNotifications } from "../acp-agent.js"; import { toAcpNotifications } from "../acp-agent.js";
import { SDKAssistantMessage } from "@anthropic-ai/claude-code"; import { SDKAssistantMessage } from "@anthropic-ai/claude-code";
describe.skipIf(!process.env.RUN_INTEGRATION_TESTS)( describe.skipIf(!process.env.RUN_INTEGRATION_TESTS)("ACP subprocess integration", () => {
"ACP subprocess integration", let child: ReturnType<typeof spawn>;
() => {
let child: ReturnType<typeof spawn>;
beforeAll(async () => { beforeAll(async () => {
let valid = spawnSync("tsc", { stdio: "inherit" }); const valid = spawnSync("tsc", { stdio: "inherit" });
if (valid.status) { if (valid.status) {
throw new Error("failed to compile"); throw new Error("failed to compile");
} }
// Start the subprocess // Start the subprocess
child = spawn("npm", ["run", "--silent", "dev"], { child = spawn("npm", ["run", "--silent", "dev"], {
stdio: ["pipe", "pipe", "inherit"], stdio: ["pipe", "pipe", "inherit"],
env: process.env, env: process.env,
});
child.on("error", (error) => {
console.error("Error starting subprocess:", error);
});
child.on("exit", (exit) => {
console.error("Exited with", exit);
});
}); });
child.on("error", (error) => {
afterAll(() => { console.error("Error starting subprocess:", error);
child.kill();
}); });
child.on("exit", (exit) => {
console.error("Exited with", exit);
});
});
class TestClient implements Client { afterAll(() => {
agent: Agent; child.kill();
});
constructor(agent: Agent) { class TestClient implements Client {
this.agent = agent; agent: Agent;
} files: Map<string, string> = new Map();
requestPermission( receivedText: string = "";
params: RequestPermissionRequest,
): Promise<RequestPermissionResponse> { constructor(agent: Agent) {
throw new Error("Method not implemented."); this.agent = agent;
} }
async sessionUpdate(params: SessionNotification): Promise<void> {
console.error("RECEVIED", params); takeReceivedText() {
} const text = this.receivedText;
writeTextFile( this.receivedText = "";
params: WriteTextFileRequest, return text;
): Promise<WriteTextFileResponse> { }
throw new Error("Method not implemented.");
} async requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse> {
async readTextFile( const optionId = params.options.find((p) => p.kind === "allow_once")!.optionId;
params: ReadTextFileRequest,
): Promise<ReadTextFileResponse> { return { outcome: { outcome: "selected", optionId } };
return { }
content:
"This project attempts to take over the world by solving the Goldbach conjecture.", async sessionUpdate(params: SessionNotification): Promise<void> {
}; console.error("RECEIVED", JSON.stringify(params, null, 4));
if (
params.update.sessionUpdate === "agent_message_chunk" &&
params.update.content.type === "text"
) {
this.receivedText += params.update.content.text;
} }
} }
it("should connect to the ACP subprocess", async () => { async writeTextFile(params: WriteTextFileRequest): Promise<WriteTextFileResponse> {
const connection = new ClientSideConnection( this.files.set(params.path, params.content);
(agent) => { return null;
return new TestClient(agent); }
},
nodeToWebWritable(child.stdin!),
nodeToWebReadable(child.stdout!),
);
let session = await connection.newSession({ cwd: "./", mcpServers: [] }); async readTextFile(params: ReadTextFileRequest): Promise<ReadTextFileResponse> {
await connection.prompt({ const content = this.files.get(params.path) ?? "";
prompt: [ return {
{ content,
type: "text", };
text: "What does this project do? Read the README.md file.", }
}, }
],
sessionId: session.sessionId, async function setupTestSession(cwd: string): Promise<{
}); client: TestClient;
console.log("DONE AWAITING"); connection: ClientSideConnection;
}, 20000); newSessionResponse: NewSessionResponse;
}, }> {
); let client;
const connection = new ClientSideConnection(
(agent) => {
client = new TestClient(agent);
return client;
},
nodeToWebWritable(child.stdin!),
nodeToWebReadable(child.stdout!),
);
await connection.initialize({
protocolVersion: 1,
clientCapabilities: {
fs: {
readTextFile: true,
writeTextFile: true,
},
},
});
const newSessionResponse = await connection.newSession({
cwd,
mcpServers: [],
});
return { client: client!, connection, newSessionResponse };
}
it("should connect to the ACP subprocess", async () => {
const { client, connection, newSessionResponse } = await setupTestSession("./");
await connection.prompt({
prompt: [
{
type: "text",
text: "Hello",
},
],
sessionId: newSessionResponse.sessionId,
});
expect(client.takeReceivedText()).not.toEqual("");
}, 30000);
it("should include available commands", async () => {
const { client, connection, newSessionResponse } = await setupTestSession(__dirname);
expect(newSessionResponse.availableCommands).toContainEqual({
name: "quick-math",
description: "10 * 3 = 30 (project)",
input: null,
});
expect(newSessionResponse.availableCommands).toContainEqual({
name: "say-hello",
description: "Say hello (project)",
input: { hint: "[name]" },
});
await connection.prompt({
prompt: [
{
type: "text",
text: "/quick-math",
},
],
sessionId: newSessionResponse.sessionId,
});
expect(client.takeReceivedText()).toContain("30");
await connection.prompt({
prompt: [
{
type: "text",
text: "/say-hello GPT-5",
},
],
sessionId: newSessionResponse.sessionId,
});
expect(client.takeReceivedText()).toContain("Hello GPT-5");
}, 30000);
});
describe("tool conversions", () => { describe("tool conversions", () => {
it("should handle Bash nicely", () => { it("should handle Bash nicely", () => {
@@ -109,7 +189,7 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "execute", kind: "execute",
title: "`rm README.md.rm`", title: "`rm README.md.rm`",
content: [ content: [
@@ -134,9 +214,9 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "search", kind: "search",
title: "Find */**.ts", title: "Find `*/**.ts`",
content: [], content: [],
locations: [], locations: [],
}); });
@@ -155,7 +235,7 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "think", kind: "think",
title: "Handle user's work request", title: "Handle user's work request",
content: [ content: [
@@ -176,15 +256,15 @@ describe("tool conversions", () => {
id: "toolu_01EEqsX7Eb9hpx87KAHVPTey", id: "toolu_01EEqsX7Eb9hpx87KAHVPTey",
name: "LS", name: "LS",
input: { input: {
path: "/Users/benbrandt/github/claude-code-acp", path: "/Users/test/github/claude-code-acp",
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "search", kind: "search",
title: "/Users/benbrandt/github/claude-code-acp", title: "List the `/Users/test/github/claude-code-acp` directory's contents",
content: [], content: [],
locations: [{ path: "/Users/benbrandt/github/claude-code-acp" }], locations: [],
}); });
}); });
@@ -198,7 +278,7 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "search", kind: "search",
title: 'grep ".*"', title: 'grep ".*"',
content: [], content: [],
@@ -211,12 +291,12 @@ describe("tool conversions", () => {
id: "toolu_01ABC123XYZ789", id: "toolu_01ABC123XYZ789",
name: "Write", name: "Write",
input: { input: {
abs_path: "/Users/test/project/example.txt", file_path: "/Users/test/project/example.txt",
content: "Hello, World!\nThis is test content.", content: "Hello, World!\nThis is test content.",
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "edit", kind: "edit",
title: "Write /Users/test/project/example.txt", title: "Write /Users/test/project/example.txt",
content: [ content: [
@@ -242,7 +322,7 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "edit", kind: "edit",
title: "Write /Users/test/project/config.json", title: "Write /Users/test/project/config.json",
content: [ content: [
@@ -263,19 +343,14 @@ describe("tool conversions", () => {
id: "toolu_01MNO456PQR789", id: "toolu_01MNO456PQR789",
name: "Read", name: "Read",
input: { input: {
abs_path: "/Users/test/project/readme.md", file_path: "/Users/test/project/readme.md",
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "read", kind: "read",
title: "Read File", title: "Read File",
content: [ content: [],
{
type: "content",
content: { type: "text", text: "/Users/test/project/readme.md" },
},
],
locations: [{ path: "/Users/test/project/readme.md", line: 0 }], locations: [{ path: "/Users/test/project/readme.md", line: 0 }],
}); });
}); });
@@ -290,7 +365,7 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "read", kind: "read",
title: "Read /Users/test/project/data.json", title: "Read /Users/test/project/data.json",
content: [], content: [],
@@ -309,7 +384,7 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "read", kind: "read",
title: "Read /Users/test/project/large.txt (1 - 100)", title: "Read /Users/test/project/large.txt (1 - 100)",
content: [], content: [],
@@ -329,7 +404,7 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "read", kind: "read",
title: "Read /Users/test/project/large.txt (51 - 150)", title: "Read /Users/test/project/large.txt (51 - 150)",
content: [], content: [],
@@ -348,7 +423,7 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "read", kind: "read",
title: "Read /Users/test/project/large.txt (from line 201)", title: "Read /Users/test/project/large.txt (from line 201)",
content: [], content: [],
@@ -368,7 +443,7 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "fetch", kind: "fetch",
title: "Fetch https://agentclientprotocol.com", title: "Fetch https://agentclientprotocol.com",
content: [ content: [
@@ -393,7 +468,7 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "fetch", kind: "fetch",
title: '"agentclientprotocol.com"', title: '"agentclientprotocol.com"',
content: [], content: [],
@@ -401,7 +476,7 @@ describe("tool conversions", () => {
}); });
it("should handle KillBash entries", () => { it("should handle KillBash entries", () => {
let tool_use = { const tool_use = {
type: "tool_use", type: "tool_use",
id: "toolu_01PhLms5fuvmdjy2bb6dfUKT", id: "toolu_01PhLms5fuvmdjy2bb6dfUKT",
name: "KillBash", name: "KillBash",
@@ -410,7 +485,7 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "execute", kind: "execute",
title: `Kill Process`, title: `Kill Process`,
content: [], content: [],
@@ -418,7 +493,7 @@ describe("tool conversions", () => {
}); });
it("should handle BashOutput entries", () => { it("should handle BashOutput entries", () => {
let tool_use = { const tool_use = {
type: "tool_use", type: "tool_use",
id: "toolu_01SJUWPtj1QspgANgtpqGPuN", id: "toolu_01SJUWPtj1QspgANgtpqGPuN",
name: "BashOutput", name: "BashOutput",
@@ -427,7 +502,7 @@ describe("tool conversions", () => {
}, },
}; };
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({ expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "execute", kind: "execute",
title: `Tail Logs`, title: `Tail Logs`,
content: [], content: [],
@@ -475,8 +550,7 @@ describe("tool conversions", () => {
activeForm: "Adding concurrent access tests", activeForm: "Adding concurrent access tests",
}, },
{ {
content: content: "Add tests for Each function with various data types",
"Add tests for Each function with various data types",
status: "pending", status: "pending",
activeForm: "Adding Each function tests", activeForm: "Adding Each function tests",
}, },
@@ -512,7 +586,7 @@ describe("tool conversions", () => {
session_id: "d056596f-e328-41e9-badd-b07122ae5227", session_id: "d056596f-e328-41e9-badd-b07122ae5227",
uuid: "b7c3330c-de8f-4bba-ac53-68c7f76ffeb5", uuid: "b7c3330c-de8f-4bba-ac53-68c7f76ffeb5",
}; };
expect(toAcpNotifications(received, "test", {})).toStrictEqual([ expect(toAcpNotifications(received, "test", {}, {})).toStrictEqual([
{ {
sessionId: "test", sessionId: "test",
update: { update: {
@@ -571,8 +645,8 @@ describe("tool conversions", () => {
name: "edit", name: "edit",
input: { input: {
abs_path: "/Users/test/project/example.txt", abs_path: "/Users/test/project/example.txt",
old_text: "old content", old_string: "old content",
new_text: "new content", new_string: "new content",
}, },
}; };
@@ -594,6 +668,66 @@ describe("tool conversions", () => {
]); ]);
}); });
it("should show full diff for multi edit tool", () => {
const toolUse = {
type: "tool_use",
id: "toolu_01DEF456",
name: "mcp__acp__multi-edit",
input: {
file_path: "/Users/test/project/config.json",
edits: [
{
old_string: 'version": 1',
new_string: 'version": 2',
replace_all: false,
},
{
old_string: 'enabled": false',
new_string: 'enabled": true',
replace_all: true,
},
],
},
};
const fileCache: { [key: string]: string } = {
"/Users/test/project/config.json": JSON.stringify(
{
version: 1,
filler: "filler",
enabled: false,
},
null,
4,
),
};
expect(toolInfoFromToolUse(toolUse, fileCache)).toEqual({
content: [
{
newText: `{
"version": 2,
"filler": "filler",
"enabled": true
}`,
oldText: `{
"version": 1,
"filler": "filler",
"enabled": false
}`,
path: "/Users/test/project/config.json",
type: "diff",
},
],
kind: "edit",
locations: [
{
path: "/Users/test/project/config.json",
},
],
title: "Edit /Users/test/project/config.json",
});
});
it("should extract locations from multi-edit tool results", () => { it("should extract locations from multi-edit tool results", () => {
const toolUse = { const toolUse = {
type: "tool_use", type: "tool_use",
@@ -642,8 +776,8 @@ describe("tool conversions", () => {
name: "mcp__acp__edit", name: "mcp__acp__edit",
input: { input: {
abs_path: "/Users/test/project/main.py", abs_path: "/Users/test/project/main.py",
old_text: "def hello():", old_string: "def hello():",
new_text: "def hello_world():", new_string: "def hello_world():",
}, },
}; };
@@ -658,9 +792,7 @@ describe("tool conversions", () => {
const update = toolUpdateFromToolResult(toolResult, toolUse); const update = toolUpdateFromToolResult(toolResult, toolUse);
expect(update.locations).toEqual([ expect(update.locations).toEqual([{ path: "/Users/test/project/main.py", line: 42 }]);
{ path: "/Users/test/project/main.py", line: 42 },
]);
}); });
it("should handle empty locations from edit tools", () => { it("should handle empty locations from edit tools", () => {
@@ -670,8 +802,8 @@ describe("tool conversions", () => {
name: "edit", name: "edit",
input: { input: {
abs_path: "/Users/test/project/notfound.txt", abs_path: "/Users/test/project/notfound.txt",
old_text: "nonexistent", old_string: "nonexistent",
new_text: "replacement", new_string: "replacement",
}, },
}; };
@@ -696,8 +828,8 @@ describe("tool conversions", () => {
name: "edit", name: "edit",
input: { input: {
abs_path: "/Users/test/project/test.txt", abs_path: "/Users/test/project/test.txt",
old_text: "old", old_string: "old",
new_text: "new", new_string: "new",
}, },
}; };
@@ -716,3 +848,15 @@ describe("tool conversions", () => {
expect(update).toEqual({}); expect(update).toEqual({});
}); });
}); });
describe("escape markdown", () => {
it("should escape markdown characters", () => {
let text = "Hello *world*!";
let escaped = markdownEscape(text);
expect(escaped).toEqual("```\nHello *world*!\n```");
text = "for example:\n```markdown\nHello *world*!\n```\n";
escaped = markdownEscape(text);
expect(escaped).toEqual("````\nfor example:\n```markdown\nHello *world*!\n```\n````");
});
});

View File

@@ -4,13 +4,9 @@ import { replaceAndCalculateLocation } from "../mcp-server.js";
describe("replaceAndCalculateLocation", () => { describe("replaceAndCalculateLocation", () => {
it("should replace first occurrence and return correct line number", () => { it("should replace first occurrence and return correct line number", () => {
const content = "line 1\nline 2 with text\nline 3 with text\nline 4"; const content = "line 1\nline 2 with text\nline 3 with text\nline 4";
const result = replaceAndCalculateLocation(content, [ const result = replaceAndCalculateLocation(content, [{ oldText: "text", newText: "replaced" }]);
{ oldText: "text", newText: "replaced" },
]);
expect(result.newContent).toBe( expect(result.newContent).toBe("line 1\nline 2 with replaced\nline 3 with text\nline 4");
"line 1\nline 2 with replaced\nline 3 with text\nline 4",
);
expect(result.lineNumbers).toEqual([1]); // Line 2 (0-based indexing) expect(result.lineNumbers).toEqual([1]); // Line 2 (0-based indexing)
}); });
@@ -20,9 +16,7 @@ describe("replaceAndCalculateLocation", () => {
{ oldText: "text", newText: "replaced", replaceAll: true }, { oldText: "text", newText: "replaced", replaceAll: true },
]); ]);
expect(result.newContent).toBe( expect(result.newContent).toBe("line 1\nline 2 with replaced\nline 3 with replaced\nline 4");
"line 1\nline 2 with replaced\nline 3 with replaced\nline 4",
);
expect(result.lineNumbers).toEqual([1, 2]); // Lines 2 and 3 (0-based) expect(result.lineNumbers).toEqual([1, 2]); // Lines 2 and 3 (0-based)
}); });
@@ -54,9 +48,7 @@ describe("replaceAndCalculateLocation", () => {
{ oldText: "text", newText: "replaced", replaceAll: true }, { oldText: "text", newText: "replaced", replaceAll: true },
]); ]);
expect(result.newContent).toBe( expect(result.newContent).toBe("line 1\rline 2 with replaced\rline 3 with replaced\rline 4");
"line 1\rline 2 with replaced\rline 3 with replaced\rline 4",
);
expect(result.lineNumbers).toEqual([1, 2]); expect(result.lineNumbers).toEqual([1, 2]);
}); });
@@ -66,17 +58,13 @@ describe("replaceAndCalculateLocation", () => {
{ oldText: "text", newText: "replaced", replaceAll: true }, { oldText: "text", newText: "replaced", replaceAll: true },
]); ]);
expect(result.newContent).toBe( expect(result.newContent).toBe("line 1\nline 2 with replaced\r\nline 3 with replaced\rline 4");
"line 1\nline 2 with replaced\r\nline 3 with replaced\rline 4",
);
expect(result.lineNumbers).toEqual([1, 2]); expect(result.lineNumbers).toEqual([1, 2]);
}); });
it("should handle text at the beginning of file", () => { it("should handle text at the beginning of file", () => {
const content = "text at start\nline 2\nline 3"; const content = "text at start\nline 2\nline 3";
const result = replaceAndCalculateLocation(content, [ const result = replaceAndCalculateLocation(content, [{ oldText: "text", newText: "replaced" }]);
{ oldText: "text", newText: "replaced" },
]);
expect(result.newContent).toBe("replaced at start\nline 2\nline 3"); expect(result.newContent).toBe("replaced at start\nline 2\nline 3");
expect(result.lineNumbers).toEqual([0]); // First line (0-based) expect(result.lineNumbers).toEqual([0]); // First line (0-based)
@@ -84,9 +72,7 @@ describe("replaceAndCalculateLocation", () => {
it("should handle text at the end of file", () => { it("should handle text at the end of file", () => {
const content = "line 1\nline 2\nlast line with text"; const content = "line 1\nline 2\nlast line with text";
const result = replaceAndCalculateLocation(content, [ const result = replaceAndCalculateLocation(content, [{ oldText: "text", newText: "replaced" }]);
{ oldText: "text", newText: "replaced" },
]);
expect(result.newContent).toBe("line 1\nline 2\nlast line with replaced"); expect(result.newContent).toBe("line 1\nline 2\nlast line with replaced");
expect(result.lineNumbers).toEqual([2]); // Last line (0-based) expect(result.lineNumbers).toEqual([2]); // Last line (0-based)
@@ -98,17 +84,13 @@ describe("replaceAndCalculateLocation", () => {
{ oldText: "text", newText: "replaced", replaceAll: true }, { oldText: "text", newText: "replaced", replaceAll: true },
]); ]);
expect(result.newContent).toBe( expect(result.newContent).toBe("line 1\nreplaced replaced replaced\nline 3");
"line 1\nreplaced replaced replaced\nline 3",
);
expect(result.lineNumbers).toEqual([1]); // All on line 2 (0-based), deduplicated expect(result.lineNumbers).toEqual([1]); // All on line 2 (0-based), deduplicated
}); });
it("should handle empty file content", () => { it("should handle empty file content", () => {
const content = ""; const content = "";
const result = replaceAndCalculateLocation(content, [ const result = replaceAndCalculateLocation(content, [{ oldText: "text", newText: "replaced" }]);
{ oldText: "text", newText: "replaced" },
]);
expect(result.newContent).toBe(""); expect(result.newContent).toBe("");
expect(result.lineNumbers).toEqual([]); expect(result.lineNumbers).toEqual([]);
@@ -117,9 +99,7 @@ describe("replaceAndCalculateLocation", () => {
it("should handle empty search text", () => { it("should handle empty search text", () => {
// Test with replaceAll false (default) // Test with replaceAll false (default)
const content1 = "line 1\nline 2\nline 3"; const content1 = "line 1\nline 2\nline 3";
const result1 = replaceAndCalculateLocation(content1, [ const result1 = replaceAndCalculateLocation(content1, [{ oldText: "", newText: "replaced" }]);
{ oldText: "", newText: "replaced" },
]);
expect(result1.newContent).toBe(content1); expect(result1.newContent).toBe(content1);
expect(result1.lineNumbers).toEqual([]); expect(result1.lineNumbers).toEqual([]);
@@ -142,9 +122,7 @@ describe("replaceAndCalculateLocation", () => {
it("should handle single line content", () => { it("should handle single line content", () => {
const content = "single line with text here"; const content = "single line with text here";
const result = replaceAndCalculateLocation(content, [ const result = replaceAndCalculateLocation(content, [{ oldText: "text", newText: "replaced" }]);
{ oldText: "text", newText: "replaced" },
]);
expect(result.newContent).toBe("single line with replaced here"); expect(result.newContent).toBe("single line with replaced here");
expect(result.lineNumbers).toEqual([0]); // Line 1 (0-based) expect(result.lineNumbers).toEqual([0]); // Line 1 (0-based)
@@ -183,9 +161,7 @@ describe("replaceAndCalculateLocation", () => {
it("should handle very long lines", () => { it("should handle very long lines", () => {
const longLine = "a".repeat(10000) + "text" + "b".repeat(10000); const longLine = "a".repeat(10000) + "text" + "b".repeat(10000);
const content = `line 1\n${longLine}\nline 3`; const content = `line 1\n${longLine}\nline 3`;
const result = replaceAndCalculateLocation(content, [ const result = replaceAndCalculateLocation(content, [{ oldText: "text", newText: "replaced" }]);
{ oldText: "text", newText: "replaced" },
]);
expect(result.newContent).toBe( expect(result.newContent).toBe(
`line 1\n${"a".repeat(10000)}replaced${"b".repeat(10000)}\nline 3`, `line 1\n${"a".repeat(10000)}replaced${"b".repeat(10000)}\nline 3`,
@@ -198,9 +174,7 @@ describe("replaceAndCalculateLocation", () => {
lines[500] = "line with text"; lines[500] = "line with text";
const content = lines.join("\n"); const content = lines.join("\n");
const result = replaceAndCalculateLocation(content, [ const result = replaceAndCalculateLocation(content, [{ oldText: "text", newText: "replaced" }]);
{ oldText: "text", newText: "replaced" },
]);
expect(result.lineNumbers).toEqual([500]); expect(result.lineNumbers).toEqual([500]);
expect(result.newContent).includes("line with replaced"); expect(result.newContent).includes("line with replaced");
@@ -224,9 +198,7 @@ describe("replaceAndCalculateLocation", () => {
const result1 = replaceAndCalculateLocation(content, [ const result1 = replaceAndCalculateLocation(content, [
{ oldText: "short", newText: "very very long text" }, { oldText: "short", newText: "very very long text" },
]); ]);
expect(result1.newContent).toBe( expect(result1.newContent).toBe("very very long text\nmedium line\nlong line here");
"very very long text\nmedium line\nlong line here",
);
expect(result1.lineNumbers).toEqual([0]); expect(result1.lineNumbers).toEqual([0]);
// Replacing with shorter text // Replacing with shorter text
@@ -260,9 +232,7 @@ describe("replaceAndCalculateLocation", () => {
it("should handle replacement at exact end of line", () => { it("should handle replacement at exact end of line", () => {
const content = "line ends with text\nnext line"; const content = "line ends with text\nnext line";
const result = replaceAndCalculateLocation(content, [ const result = replaceAndCalculateLocation(content, [{ oldText: "text", newText: "replaced" }]);
{ oldText: "text", newText: "replaced" },
]);
expect(result.newContent).toBe("line ends with replaced\nnext line"); expect(result.newContent).toBe("line ends with replaced\nnext line");
expect(result.lineNumbers).toEqual([0]); expect(result.lineNumbers).toEqual([0]);
@@ -302,9 +272,7 @@ describe("replaceAndCalculateLocation", () => {
// - All "foo" occurrences (lines 1, 3, 5 in original) // - All "foo" occurrences (lines 1, 3, 5 in original)
// - First "bar" occurrence (line 1 after first edit) // - First "bar" occurrence (line 1 after first edit)
// - "line 3" (line 2 after previous edits) // - "line 3" (line 2 after previous edits)
expect(result.newContent).toBe( expect(result.newContent).toBe("line 1\nFOO BAR\nLINE THREE\nFOO baz\nline 5\nbar FOO\nline 7");
"line 1\nFOO BAR\nLINE THREE\nFOO baz\nline 5\nbar FOO\nline 7",
);
// Line numbers reflect position in final content, deduplicated and sorted // Line numbers reflect position in final content, deduplicated and sorted
expect(result.lineNumbers).toEqual([ expect(result.lineNumbers).toEqual([
@@ -326,9 +294,7 @@ describe("replaceAndCalculateLocation", () => {
// First edit replaces first "hello" only // First edit replaces first "hello" only
// Second edit replaces all "world" in the modified content // Second edit replaces all "world" in the modified content
// Third edit replaces remaining "hello"s in the modified content // Third edit replaces remaining "hello"s in the modified content
expect(result.newContent).toBe( expect(result.newContent).toBe("hi earth\ngreetings greetings\nearth greetings earth");
"hi earth\ngreetings greetings\nearth greetings earth",
);
// Line numbers reflect position in final content, deduplicated and sorted // Line numbers reflect position in final content, deduplicated and sorted
expect(result.lineNumbers).toEqual([ expect(result.lineNumbers).toEqual([
@@ -340,17 +306,14 @@ describe("replaceAndCalculateLocation", () => {
it("should handle complex scenarios with marker-like text", () => { it("should handle complex scenarios with marker-like text", () => {
// Test that our marker approach doesn't get confused by similar text // Test that our marker approach doesn't get confused by similar text
const content = const content = "line 1\n__MARKER__text\nline 3\n__REPLACE_MARKER_abc__\nline 5";
"line 1\n__MARKER__text\nline 3\n__REPLACE_MARKER_abc__\nline 5";
const result = replaceAndCalculateLocation(content, [ const result = replaceAndCalculateLocation(content, [
{ oldText: "__MARKER__", newText: "REPLACED", replaceAll: true }, { oldText: "__MARKER__", newText: "REPLACED", replaceAll: true },
{ oldText: "text", newText: "content" }, { oldText: "text", newText: "content" },
{ oldText: "__REPLACE_MARKER_abc__", newText: "DONE" }, { oldText: "__REPLACE_MARKER_abc__", newText: "DONE" },
]); ]);
expect(result.newContent).toBe( expect(result.newContent).toBe("line 1\nREPLACEDcontent\nline 3\nDONE\nline 5");
"line 1\nREPLACEDcontent\nline 3\nDONE\nline 5",
);
// Line numbers should be correct even with marker-like text // Line numbers should be correct even with marker-like text
expect(result.lineNumbers).toEqual([ expect(result.lineNumbers).toEqual([

View File

@@ -1,10 +1,10 @@
import { ContentBlock } from "@modelcontextprotocol/sdk/types.js";
import { import {
PlanEntry, PlanEntry,
ToolCallContent, ToolCallContent,
ToolCallLocation, ToolCallLocation,
ToolKind, ToolKind,
} from "@zed-industries/agent-client-protocol"; } from "@zed-industries/agent-client-protocol";
import { replaceAndCalculateLocation, SYSTEM_REMINDER } from "./mcp-server.js";
interface ToolInfo { interface ToolInfo {
title: string; title: string;
@@ -19,7 +19,10 @@ interface ToolUpdate {
locations?: ToolCallLocation[]; locations?: ToolCallLocation[];
} }
export function toolInfoFromToolUse(toolUse: any): ToolInfo { export function toolInfoFromToolUse(
toolUse: any,
cachedFileContent: { [key: string]: string },
): ToolInfo {
const name = toolUse.name; const name = toolUse.name;
const input = toolUse.input; const input = toolUse.input;
@@ -41,30 +44,15 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
case "NotebookRead": case "NotebookRead":
return { return {
title: input?.notebook_path title: input?.notebook_path ? `Read Notebook ${input.notebook_path}` : "Read Notebook",
? `Read Notebook ${input.notebook_path}`
: "Read Notebook",
kind: "read", kind: "read",
content: content: [],
input && input.notebook_path
? [
{
type: "content",
content: {
type: "text",
text: input.notebook_path.toString(),
},
},
]
: [],
locations: input?.notebook_path ? [{ path: input.notebook_path }] : [], locations: input?.notebook_path ? [{ path: input.notebook_path }] : [],
}; };
case "NotebookEdit": case "NotebookEdit":
return { return {
title: input?.notebook_path title: input?.notebook_path ? `Edit Notebook ${input.notebook_path}` : "Edit Notebook",
? `Edit Notebook ${input.notebook_path}`
: "Edit Notebook",
kind: "edit", kind: "edit",
content: content:
input && input.new_source input && input.new_source
@@ -79,13 +67,12 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
}; };
case "Bash": case "Bash":
case "mcp__acp__Bash":
return { return {
title: input?.command title: input?.command ? "`" + input.command.replaceAll("`", "\\`") + "`" : "Terminal",
? "`" + input.command.replaceAll("`", "\\`") + "`"
: "Terminal",
kind: "execute", kind: "execute",
content: content:
input && input.command input && input.description
? [ ? [
{ {
type: "content", type: "content",
@@ -96,6 +83,7 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
}; };
case "BashOutput": case "BashOutput":
case "mcp__acp__BashOutput":
return { return {
title: "Tail Logs", title: "Tail Logs",
kind: "execute", kind: "execute",
@@ -103,6 +91,7 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
}; };
case "KillBash": case "KillBash":
case "mcp__acp__KillBash":
return { return {
title: "Kill Process", title: "Kill Process",
kind: "execute", kind: "execute",
@@ -113,11 +102,7 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
let limit = ""; let limit = "";
if (input.limit) { if (input.limit) {
limit = limit =
" (" + " (" + ((input.offset ?? 0) + 1) + " - " + ((input.offset ?? 0) + input.limit) + ")";
((input.offset ?? 0) + 1) +
" - " +
((input.offset ?? 0) + input.limit) +
")";
} else if (input.offset) { } else if (input.offset) {
limit = " (from line " + (input.offset + 1) + ")"; limit = " (from line " + (input.offset + 1) + ")";
} }
@@ -138,65 +123,108 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
return { return {
title: "Read File", title: "Read File",
kind: "read", kind: "read",
content: content: [],
input && input.abs_path locations: [{ path: input.file_path, line: input.offset ?? 0 }],
? [
{
type: "content",
content: { type: "text", text: input.abs_path.toString() },
},
]
: [],
locations: [{ path: input.abs_path, line: input.offset ?? 0 }],
}; };
case "LS": case "LS":
return { return {
title: input?.path ? input.path : "Current Directory", title: `List the ${input?.path ? "`" + input.path + "`" : "current"} directory's contents`,
kind: "search", kind: "search",
content: [], content: [],
locations: input?.path ? [{ path: input.path }] : [], locations: [],
}; };
case "mcp__acp__edit": case "mcp__acp__edit":
case "Edit": case "Edit": {
const path = input?.abs_path ?? input?.file_path;
let oldText = input.old_string ?? null;
let newText = input.new_string ?? "";
let line = null;
if (path && input.old_text) {
try {
const oldContent = cachedFileContent[path] || "";
const newContent = replaceAndCalculateLocation(oldContent, [
{
oldText: input.old_string,
newText: input.new_string,
replaceAll: false,
},
]);
oldText = oldContent;
newText = newContent.newContent;
line = newContent.lineNumbers[0];
} catch (e) {
console.error(e);
}
}
return { return {
title: input?.abs_path ? `Edit ${input.abs_path}` : "Edit", title: path ? `Edit \`${path}\`` : "Edit",
kind: "edit", kind: "edit",
content: content:
input && input.abs_path input && path
? [ ? [
{ {
type: "diff", type: "diff",
path: input.abs_path, path,
oldText: input.old_text || null, oldText,
newText: input.new_text, newText,
}, },
] ]
: [], : [],
locations: input?.abs_path ? [{ path: input.abs_path }] : [], locations: path ? [{ path, line }] : [],
}; };
}
case "mcp__acp__multi-edit": case "mcp__acp__multi-edit":
case "MultiEdit": case "MultiEdit": {
const multiInput = input as {
file_path: string;
edits: {
old_string: string;
new_string: string;
replace_all?: boolean;
}[];
};
let oldTextMulti = multiInput.edits.map((edit: any) => edit.old_string).join("\n");
let newTextMulti = multiInput.edits.map((edit: any) => edit.new_string).join("\n");
try {
if (multiInput.edits && multiInput.file_path) {
const oldContent =
cachedFileContent[multiInput.file_path] ||
multiInput.edits.map((edit: any) => edit.oldText).join("\n");
const newContent = replaceAndCalculateLocation(
oldContent,
multiInput.edits.map((edit) => ({
oldText: edit.old_string,
newText: edit.new_string,
replaceAll: edit.replace_all,
})),
);
oldTextMulti = oldContent;
newTextMulti = newContent.newContent;
}
} catch (e) {
console.error(e);
}
// Display it as a normal edit, because end users don't care about // Display it as a normal edit, because end users don't care about
// the distinction between edits and multi-edits. // the distinction between edits and multi-edits.
return { return {
title: input?.file_path ? `Edit ${input.file_path}` : "Edit", title: input?.file_path ? `Edit ${input.file_path}` : "Edit",
kind: "edit", kind: "edit",
content: content: [
input && input.edits && input.edits.length > 0 {
? input.edits.map((edit: any) => ({ type: "diff" as const,
type: "diff" as const, path: input.file_path,
path: input.file_path, oldText: oldTextMulti,
oldText: edit.old_string || null, newText: newTextMulti,
newText: edit.new_string, },
})) ],
: [],
locations: input?.file_path ? [{ path: input.file_path }] : [], locations: input?.file_path ? [{ path: input.file_path }] : [],
}; };
}
case "mcp__acp__write": case "mcp__acp__write": {
let content: ToolCallContent[] = []; let content: ToolCallContent[] = [];
if (input && input.abs_path) { if (input && input.abs_path) {
content = [ content = [
@@ -221,32 +249,33 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
content, content,
locations: input?.abs_path ? [{ path: input.abs_path }] : [], locations: input?.abs_path ? [{ path: input.abs_path }] : [],
}; };
}
case "Write": case "Write":
return { return {
title: input?.abs_path ? `Write ${input.abs_path}` : "Write", title: input?.file_path ? `Write ${input.file_path}` : "Write",
kind: "edit", kind: "edit",
content: content:
input && input.abs_path input && input.file_path
? [ ? [
{ {
type: "diff", type: "diff",
path: input.abs_path, path: input.file_path,
oldText: null, oldText: null,
newText: input.content, newText: input.content,
}, },
] ]
: [], : [],
locations: input?.abs_path ? [{ path: input.abs_path }] : [], locations: input?.file_path ? [{ path: input.file_path }] : [],
}; };
case "Glob": { case "Glob": {
let label = "Find"; let label = "Find";
if (input.path) { if (input.path) {
label += ` ${input.path}`; label += ` \`${input.path}\``;
} }
if (input.pattern) { if (input.pattern) {
label += ` ${input.pattern}`; label += ` \`${input.pattern}\``;
} }
return { return {
title: label, title: label,
@@ -285,6 +314,7 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
label += " -c"; label += " -c";
break; break;
case "Content": case "Content":
default:
break; break;
} }
} }
@@ -394,10 +424,7 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
} }
} }
export function toolUpdateFromToolResult( export function toolUpdateFromToolResult(toolResult: any, toolUse: any | undefined): ToolUpdate {
toolResult: any,
toolUse: any | undefined,
): ToolUpdate {
switch (toolUse?.name) { switch (toolUse?.name) {
case "mcp__acp__edit": case "mcp__acp__edit":
case "edit": case "edit":
@@ -408,15 +435,14 @@ export function toolUpdateFromToolResult(
const firstContent = toolResult.content[0]; const firstContent = toolResult.content[0];
const data = JSON.parse(firstContent.text || firstContent); const data = JSON.parse(firstContent.text || firstContent);
if (data.lineNumbers && Array.isArray(data.lineNumbers)) { if (data.lineNumbers && Array.isArray(data.lineNumbers)) {
const locations: ToolCallLocation[] = data.lineNumbers.map( const locations: ToolCallLocation[] = data.lineNumbers.map((line: number) => ({
(line: number) => ({ path: toolUse?.input?.abs_path || toolUse?.input?.file_path,
path: toolUse?.input?.abs_path || toolUse?.input?.file_path, line: line,
line: line, }));
}),
);
return { locations }; return { locations };
} }
} catch (e) { } catch (error) {
console.error(`Error parsing edit tool result: ${error}`);
// If parsing fails, return empty object // If parsing fails, return empty object
return {}; return {};
} }
@@ -432,26 +458,63 @@ export function toolUpdateFromToolResult(
const firstContent = toolResult.content[0]; const firstContent = toolResult.content[0];
const data = JSON.parse(firstContent.text || firstContent); const data = JSON.parse(firstContent.text || firstContent);
if (data.lineNumbers && Array.isArray(data.lineNumbers)) { if (data.lineNumbers && Array.isArray(data.lineNumbers)) {
const locations: ToolCallLocation[] = data.lineNumbers.map( const locations: ToolCallLocation[] = data.lineNumbers.map((line: number) => ({
(line: number) => ({ path: toolUse?.input?.file_path || toolUse?.input?.abs_path,
path: toolUse?.input?.file_path || toolUse?.input?.abs_path, line: line,
line: line, }));
}),
);
return { locations }; return { locations };
} }
} catch (e) { } catch (error) {
console.error(`Error parsing edit tool result: ${error}`);
// If parsing fails, return empty object // If parsing fails, return empty object
return {}; return {};
} }
} }
return {}; return {};
} }
case "mcp__acp__write":
case "Write":
return {};
case "Read":
case "mcp__acp__read":
if (Array.isArray(toolResult.content) && toolResult.content.length > 0) {
return {
content: toolResult.content.map((content: any) => ({
type: "content",
content:
content.type === "text"
? {
type: "text",
text: markdownEscape(content.text.replace(SYSTEM_REMINDER, "")),
}
: content,
})),
};
} else if (typeof toolResult.content === "string" && toolResult.content.length > 0) {
return {
content: [
{
type: "content",
content: {
type: "text",
text: markdownEscape(toolResult.content.replace(SYSTEM_REMINDER, "")),
},
},
],
};
}
return {};
case "mcp__acp__Bash":
// The bash tool already embeds a terminal
return {};
case "Task": case "Task":
case "NotebookEdit": case "NotebookEdit":
case "NotebookRead": case "NotebookRead":
case "mcp__acp__write":
case "Write":
case "TodoWrite": case "TodoWrite":
case "exit_plan_mode": case "exit_plan_mode":
case "Bash": case "Bash":
@@ -464,21 +527,22 @@ export function toolUpdateFromToolResult(
case "WebSearch": case "WebSearch":
case "Other": case "Other":
default: { default: {
// This happens for the mcp__acp__read tool, if (Array.isArray(toolResult.content) && toolResult.content.length > 0) {
// but may also for others...
if (Array.isArray(toolResult.content)) {
return { return {
content: toolResult.content.map((content: any) => ({ content: toolResult.content.map((content: any) => ({
type: "content", type: "content",
content, content,
})), })),
}; };
} else if (typeof toolResult.content === "string") { } else if (typeof toolResult.content === "string" && toolResult.content.length > 0) {
return { return {
content: [ content: [
{ {
type: "content", type: "content",
content: { type: "text", text: toolResult.content }, content: {
type: "text",
text: toolResult.content,
},
}, },
], ],
}; };
@@ -501,3 +565,13 @@ export function planEntries(input: { todos: ClaudePlanEntry[] }): PlanEntry[] {
priority: "medium", priority: "medium",
})); }));
} }
export function markdownEscape(text: string): string {
let escape = "```";
for (const [m] of text.matchAll(/^```+/gm)) {
while (m.length >= escape.length) {
escape += "`";
}
}
return escape + "\n" + text + (text.endsWith("\n") ? "" : "\n") + escape;
}

View File

@@ -45,24 +45,23 @@ export class Pushable<T> implements AsyncIterable<T> {
} }
// Helper to convert Node.js streams to Web Streams // Helper to convert Node.js streams to Web Streams
export function nodeToWebWritable( export function nodeToWebWritable(nodeStream: Writable): WritableStream<Uint8Array> {
nodeStream: Writable,
): WritableStream<Uint8Array> {
return new WritableStream<Uint8Array>({ return new WritableStream<Uint8Array>({
write(chunk) { write(chunk) {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
nodeStream.write(Buffer.from(chunk), (err) => { nodeStream.write(Buffer.from(chunk), (err) => {
if (err) reject(err); if (err) {
else resolve(); reject(err);
} else {
resolve();
}
}); });
}); });
}, },
}); });
} }
export function nodeToWebReadable( export function nodeToWebReadable(nodeStream: Readable): ReadableStream<Uint8Array> {
nodeStream: Readable,
): ReadableStream<Uint8Array> {
return new ReadableStream<Uint8Array>({ return new ReadableStream<Uint8Array>({
start(controller) { start(controller) {
nodeStream.on("data", (chunk: Buffer) => { nodeStream.on("data", (chunk: Buffer) => {
@@ -77,3 +76,7 @@ export function nodeToWebReadable(
export function unreachable(value: never): never { export function unreachable(value: never): never {
throw new Error(`Unexpected case: ${value}`); throw new Error(`Unexpected case: ${value}`);
} }
export function sleep(time: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, time));
}