Compare commits

...

21 Commits

Author SHA1 Message Date
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
11 changed files with 1173 additions and 1371 deletions

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

@@ -0,0 +1,42 @@
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: 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 }}

1062
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,19 +3,24 @@
"publishConfig": {
"access": "public"
},
"version": "0.1.0",
"bin": {
"claude-code-acp": "./dist/index.js"
},
"version": "0.1.7",
"description": "An ACP-compatible coding agent powered by the Claude Code SDK (TypeScript)",
"main": "dist/acp-agent.js",
"main": "dist/index.js",
"type": "module",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "npm run build && npm run start",
"lint": "eslint src --ext .ts",
"format": "prettier --write .",
"format:check": "prettier --check .",
"test": "vitest",
"test:integration": "RUN_INTEGRATION_TESTS=true vitest run",
"test:run": "vitest run",
"test:coverage": "vitest run --coverage"
"test:coverage": "vitest run --coverage",
"prepublishOnly": "npm run build"
},
"keywords": [
"claude",
@@ -29,10 +34,10 @@
"author": "Zed Industries",
"license": "Apache-2.0",
"dependencies": {
"@anthropic-ai/claude-code": "^1.0.96",
"@anthropic-ai/claude-code": "1.0.96",
"@modelcontextprotocol/sdk": "^1.17.4",
"@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",
"minimist": "^1.2.8",
"uuid": "11.1.0"
@@ -42,7 +47,7 @@
"@types/node": "^24.3.0",
"@types/uuid": "^10.0.0",
"@vitest/ui": "^3.2.4",
"eslint": "^8.56.0",
"prettier": "^3.6.2",
"ts-node": "^10.9.2",
"typescript": "^5.4.0",
"vitest": "^3.2.4"

View File

@@ -2,28 +2,31 @@ import {
Agent,
AgentSideConnection,
AuthenticateRequest,
AvailableCommand,
CancelNotification,
Client,
ClientCapabilities,
InitializeRequest,
InitializeResponse,
LoadSessionRequest,
NewSessionRequest,
NewSessionResponse,
PromptRequest,
PromptResponse,
ReadTextFileRequest,
ReadTextFileResponse,
RequestError,
ToolCallContent,
ToolKind,
TerminalHandle,
TerminalOutputResponse,
WriteTextFileRequest,
WriteTextFileResponse,
} from "@zed-industries/agent-client-protocol";
import {
McpServerConfig,
Options,
Query,
query,
SDKAssistantMessage,
SDKMessage,
SDKUserMessage,
} from "@anthropic-ai/claude-code";
import * as readline from "node:readline";
import { v7 as uuidv7 } from "uuid";
import {
nodeToWebReadable,
@@ -31,7 +34,6 @@ import {
Pushable,
unreachable,
} from "./utils.js";
import { ContentBlock } from "@zed-industries/agent-client-protocol";
import { SessionNotification } from "@zed-industries/agent-client-protocol";
import { createMcpServer } from "./mcp-server.js";
import { AddressInfo } from "node:net";
@@ -47,25 +49,45 @@ type Session = {
cancelled: boolean;
};
type BackgroundTerminal =
| {
handle: TerminalHandle;
status: "started";
lastOutput: TerminalOutputResponse | null;
}
| {
status: "aborted" | "exited" | "killed" | "timedOut";
pendingOutput: TerminalOutputResponse;
};
// Implement the ACP Agent interface
export class ClaudeAcpAgent implements Agent {
sessions: {
[key: string]: Session;
};
client: Client;
client: AgentSideConnection;
toolUseCache: { [key: string]: any };
fileContentCache: { [key: string]: any };
backgroundTerminals: { [key: string]: BackgroundTerminal } = {};
clientCapabilities?: ClientCapabilities;
constructor(client: Client) {
constructor(client: AgentSideConnection) {
this.sessions = {};
this.client = client;
this.toolUseCache = {};
this.fileContentCache = {};
}
async initialize(params: InitializeRequest): Promise<InitializeResponse> {
async initialize(request: InitializeRequest): Promise<InitializeResponse> {
this.clientCapabilities = request.clientCapabilities;
return {
protocolVersion: 1,
// todo!()
agentCapabilities: {
promptCapabilities: { image: true, embeddedContext: true },
promptCapabilities: {
image: true,
embeddedContext: true,
},
},
authMethods: [
{
@@ -99,8 +121,11 @@ export class ClaudeAcpAgent implements Agent {
}
}
// todo!() auth
let server = await createMcpServer(this, sessionId);
let server = await createMcpServer(
this,
sessionId,
this.clientCapabilities,
);
let address = server.address() as AddressInfo;
mcpServers["acp"] = {
type: "http",
@@ -110,17 +135,38 @@ export class ClaudeAcpAgent implements Agent {
},
};
let 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;
}
let q = query({
prompt: input,
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),
},
options,
});
this.sessions[sessionId] = {
query: q,
@@ -128,12 +174,14 @@ export class ClaudeAcpAgent implements Agent {
cancelled: false,
};
const availableCommands = await availableSlashCommands(q);
return {
sessionId,
availableCommands,
};
}
async authenticate(params: AuthenticateRequest): Promise<void> {
async authenticate(_params: AuthenticateRequest): Promise<void> {
throw new Error("Method not implemented.");
}
@@ -196,6 +244,7 @@ export class ClaudeAcpAgent implements Agent {
message,
params.sessionId,
this.toolUseCache,
this.fileContentCache,
)) {
await this.client.sessionUpdate(notification);
}
@@ -215,6 +264,85 @@ export class ClaudeAcpAgent implements Agent {
this.sessions[params.sessionId].cancelled = true;
await this.sessions[params.sessionId].query.interrupt();
}
async readTextFile(
params: ReadTextFileRequest,
): Promise<ReadTextFileResponse> {
let 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> {
let response = await this.client.writeTextFile(params);
this.fileContentCache[params.path] = params.content;
return response;
}
}
async function availableSlashCommands(
query: Query,
): Promise<AvailableCommand[]> {
const UNSUPPORTED_COMMANDS = [
"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",
"mcp",
"migrate-installer", // Modal
"model", // Not supported via SDK?
"output-style", // Modal
"output-style:new", // Modal
"permissions", // Modal
"release-notes", // Escape Codes
"resume",
"status", // Not supported via SDK?
"statusline", // Not needed
"terminal-setup", // Not needed
"todos", // Escape Codes
"vim", // Not needed
];
//todo: Do not use `as any` once `supportedCommands` is exposed via the typescript interface
const commands = await (query as any).supportedCommands();
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) =>
!UNSUPPORTED_COMMANDS.includes(command.name),
);
}
function formatUriAsLink(uri: string): string {
@@ -313,6 +441,7 @@ export function toAcpNotifications(
message: SDKAssistantMessage | SDKUserMessage,
sessionId: string,
toolUseCache: { [key: string]: any },
fileContentCache: { [key: string]: string },
): SessionNotification[] {
let chunks = message.message.content as ContentChunk[];
let output = [];
@@ -363,7 +492,7 @@ export function toAcpNotifications(
sessionUpdate: "tool_call",
rawInput: chunk.input,
status: "pending",
...toolInfoFromToolUse(chunk),
...toolInfoFromToolUse(chunk, fileContentCache),
};
}
break;

View File

@@ -1,3 +1,5 @@
#!/usr/bin/env node
import { runAcp as runAcp } from "./acp-agent.js";
runAcp();

View File

@@ -5,10 +5,22 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
import { z } from "zod";
import { Server } from "node:http";
import { ClaudeAcpAgent } from "./acp-agent.js";
import {
ClientCapabilities,
TerminalOutputResponse,
} from "@zed-industries/agent-client-protocol";
import { tool } from "@anthropic-ai/claude-code";
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(
agent: ClaudeAcpAgent,
sessionId: string,
clientCapabilities: ClientCapabilities | undefined,
): Promise<Server> {
// Create MCP server
const server = new McpServer({
@@ -16,143 +28,144 @@ export function createMcpServer(
version: "1.0.0",
});
server.registerTool(
"read",
{
title: "Read",
description: `Reads the content of the given file in the project.
if (clientCapabilities?.fs?.readTextFile) {
server.registerTool(
"read",
{
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.
In sessions with mcp__acp__read always use it instead of Read as it contains the most up-to-date contents.`,
inputSchema: {
abs_path: z.string().describe("The absolute path to the file to read."),
offset: z
.number()
.optional()
.describe(
"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."),
inputSchema: {
abs_path: z
.string()
.describe("The absolute path to the file to read."),
offset: z
.number()
.optional()
.describe(
"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."),
},
annotations: {
title: "Read file",
readOnlyHint: true,
destructiveHint: false,
openWorldHint: false,
idempotentHint: false,
},
},
annotations: {
title: "Read file",
readOnlyHint: true,
destructiveHint: false,
openWorldHint: false,
idempotentHint: false,
},
},
async (input) => {
try {
const session = agent.sessions[sessionId];
if (!session) {
async (input) => {
try {
const session = agent.sessions[sessionId];
if (!session) {
return {
content: [
{
type: "text",
text: "The user has left the building",
},
],
};
}
let content = await agent.readTextFile({
sessionId,
path: input.abs_path,
limit: input.limit,
line: input.offset,
});
return {
content: [
{
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 {
content: [
{
type: "text",
text:
content.content +
`
<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.
if (clientCapabilities?.fs?.writeTextFile) {
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
allow the user to conveniently review changes.`,
inputSchema: {
abs_path: z.string().describe("The absolute path to the file to write"),
content: z.string().describe("The full content to write"),
inputSchema: {
abs_path: z
.string()
.describe("The absolute path to the file to write"),
content: z.string().describe("The full content to write"),
},
annotations: {
title: "Write file",
readOnlyHint: false,
destructiveHint: false,
openWorldHint: false,
idempotentHint: false,
},
},
annotations: {
title: "Write file",
readOnlyHint: false,
destructiveHint: false,
openWorldHint: false,
idempotentHint: false,
},
},
async (input) => {
try {
const session = agent.sessions[sessionId];
if (!session) {
async (input) => {
try {
const session = agent.sessions[sessionId];
if (!session) {
return {
content: [
{
type: "text",
text: "The user has left the building",
},
],
};
}
let content = await agent.writeTextFile({
sessionId,
path: input.abs_path,
content: input.content,
});
return {
content: [],
};
} catch (error: any) {
return {
content: [
{
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 {
content: [],
};
} catch (error: any) {
return {
content: [
{
type: "text",
text: "Writing file failed: " + error.message,
},
],
};
}
},
);
server.registerTool(
"edit",
{
title: "Edit",
description: `Edit a file.
server.registerTool(
"edit",
{
title: "Edit",
description: `Edit a file.
In sessions with mcp__acp__edit always use it instead of Edit as it will
allow the user to conveniently review changes.
@@ -166,23 +179,116 @@ File editing instructions:
- For non-unique lines, include enough context to identify them.
- Do not escape quotes, newlines, or other characters.
- Only edit the specified file.`,
inputSchema: {
abs_path: z.string().describe("The absolute path to the file to read."),
old_text: z
.string()
.describe("The old text to replace (must be unique in the file)"),
new_text: z.string().describe("The new text."),
inputSchema: {
abs_path: z
.string()
.describe("The absolute path to the file to read."),
old_text: z
.string()
.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: {
title: "Edit file",
readOnlyHint: false,
destructiveHint: false,
openWorldHint: false,
idempotentHint: false,
async (input) => {
try {
const session = agent.sessions[sessionId];
if (!session) {
return {
content: [
{
type: "text",
text: "The user has left the building",
},
],
};
}
let { content } = await agent.readTextFile({
sessionId,
path: input.abs_path,
});
const { newContent, lineNumbers } = replaceAndCalculateLocation(
content,
[
{
oldText: input.old_text,
newText: input.new_text,
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];
if (!session) {
return {
@@ -195,25 +301,23 @@ File editing instructions:
};
}
let { content } = await agent.client.readTextFile({
let { content } = await agent.readTextFile({
sessionId,
path: input.abs_path,
path: input.file_path,
});
const { newContent, lineNumbers } = replaceAndCalculateLocation(
content,
[
{
oldText: input.old_text,
newText: input.new_text,
replaceAll: false,
},
],
input.edits.map((edit) => ({
oldText: edit.old_string,
newText: edit.new_string,
replaceAll: edit.replace_all ?? false,
})),
);
await agent.client.writeTextFile({
await agent.writeTextFile({
sessionId,
path: input.abs_path,
path: input.file_path,
content: newContent,
});
@@ -225,97 +329,327 @@ 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,
openWorldHint: false,
idempotentHint: false,
);
}
if (agent.clientCapabilities?.terminal) {
server.registerTool(
"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) => {
const session = agent.sessions[sessionId];
if (!session) {
return {
content: [
{
type: "text",
text: "The user has left the building",
},
],
};
}
async (input, extra) => {
const session = agent.sessions[sessionId];
if (!session) {
return {
content: [
{
type: "text",
text: "The user has left the building",
},
],
};
}
let { content } = await agent.client.readTextFile({
sessionId,
path: input.file_path,
});
const toolCallId = extra._meta?.["claudecode/toolUseId"];
const { newContent, lineNumbers } = replaceAndCalculateLocation(
content,
input.edits.map((edit) => ({
oldText: edit.old_string,
newText: edit.new_string,
replaceAll: edit.replace_all ?? false,
})),
);
if (typeof toolCallId !== "string") {
throw new Error("No tool call ID found");
}
await agent.client.writeTextFile({
sessionId,
path: input.file_path,
content: newContent,
});
if (
!agent.clientCapabilities?.terminal ||
!agent.client.createTerminal
) {
throw new Error("unreachable");
}
return {
content: [
{
type: "text",
text: JSON.stringify({ lineNumbers }),
const handle = await agent.client.createTerminal({
command: input.command,
sessionId,
outputByteLimit: 32_000,
});
await agent.client.sessionUpdate({
sessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
status: "in_progress",
content: [{ type: "terminal", terminalId: handle.id }],
},
],
};
},
);
});
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(() => ({ status: "exited" as const })),
abortPromise.then(() => ({ status: "aborted" as const })),
sleep(input.timeout_ms).then(async () => {
if (agent.backgroundTerminals[handle.id]?.status === "started") {
await handle.kill();
}
return { status: "timedOut" as const };
}),
]);
if (input.run_in_background) {
agent.backgroundTerminals[handle.id] = {
handle,
lastOutput: null,
status: "started",
};
statusPromise.then(async ({ status }) => {
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,
),
},
};
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: {
const unreachable: never = bgTerm;
return unreachable;
}
}
},
);
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 sleep(time: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, time));
}
function toolCommandOutput(
status: "started" | "aborted" | "exited" | "killed" | "timedOut",
output: TerminalOutputResponse,
): string {
const { exitStatus, output: commandOutput, truncated } = output;
let toolOutput = "";
switch (status) {
case "started": {
if (exitStatus?.exitCode == null) {
toolOutput += `Interrupted. `;
}
break;
}
case "killed":
toolOutput += `Killed. `;
break;
case "timedOut":
toolOutput += `Timed out. `;
break;
case "exited":
case "aborted":
break;
default: {
const unreachable: never = status;
return unreachable;
}
}
if (exitStatus?.exitCode != null && exitStatus.exitCode !== 0) {
toolOutput += `Failed with exit code ${exitStatus.exitCode}.`;
}
if (exitStatus?.signal != null) {
toolOutput += `Signal \`${exitStatus.signal}\`. `;
}
toolOutput += "Output:\n\n";
toolOutput += commandOutput;
if (truncated) {
toolOutput += `\n\nCommand output was too long, so it was truncated to ${commandOutput.length} bytes.`;
}
return toolOutput;
}
}
let alwaysAllowedTools: { [key: string]: boolean } = {};
server.registerTool(

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,
Client,
ClientSideConnection,
NewSessionResponse,
ReadTextFileRequest,
ReadTextFileResponse,
RequestPermissionRequest,
@@ -13,7 +14,11 @@ import {
WriteTextFileResponse,
} from "@zed-industries/agent-client-protocol";
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 { SDKAssistantMessage } from "@anthropic-ai/claude-code";
@@ -46,54 +51,146 @@ describe.skipIf(!process.env.RUN_INTEGRATION_TESTS)(
class TestClient implements Client {
agent: Agent;
files: Map<string, string> = new Map();
receivedText: string = "";
constructor(agent: Agent) {
this.agent = agent;
}
requestPermission(
takeReceivedText() {
const text = this.receivedText;
this.receivedText = "";
return text;
}
async requestPermission(
params: RequestPermissionRequest,
): Promise<RequestPermissionResponse> {
throw new Error("Method not implemented.");
const optionId = params.options.find(
(p) => p.kind === "allow_once",
)!.optionId;
return { outcome: { outcome: "selected", optionId } };
}
async sessionUpdate(params: SessionNotification): Promise<void> {
console.error("RECEVIED", params);
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;
}
}
writeTextFile(
async writeTextFile(
params: WriteTextFileRequest,
): Promise<WriteTextFileResponse> {
throw new Error("Method not implemented.");
this.files.set(params.path, params.content);
return null;
}
async readTextFile(
params: ReadTextFileRequest,
): Promise<ReadTextFileResponse> {
const content = this.files.get(params.path) ?? "";
return {
content:
"This project attempts to take over the world by solving the Goldbach conjecture.",
content,
};
}
}
it("should connect to the ACP subprocess", async () => {
async function setupTestSession(cwd: string): Promise<{
client: TestClient;
connection: ClientSideConnection;
newSessionResponse: NewSessionResponse;
}> {
let client;
const connection = new ClientSideConnection(
(agent) => {
return new TestClient(agent);
client = new TestClient(agent);
return client;
},
nodeToWebWritable(child.stdin!),
nodeToWebReadable(child.stdout!),
);
let session = await connection.newSession({ cwd: "./", mcpServers: [] });
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: "What does this project do? Read the README.md file.",
text: "Hello",
},
],
sessionId: session.sessionId,
sessionId: newSessionResponse.sessionId,
});
console.log("DONE AWAITING");
}, 20000);
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);
},
);
@@ -109,7 +206,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "execute",
title: "`rm README.md.rm`",
content: [
@@ -134,7 +231,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "search",
title: "Find */**.ts",
content: [],
@@ -155,7 +252,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "think",
title: "Handle user's work request",
content: [
@@ -176,15 +273,16 @@ describe("tool conversions", () => {
id: "toolu_01EEqsX7Eb9hpx87KAHVPTey",
name: "LS",
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",
title: "/Users/benbrandt/github/claude-code-acp",
title:
"List the `/Users/test/github/claude-code-acp` directory's contents",
content: [],
locations: [{ path: "/Users/benbrandt/github/claude-code-acp" }],
locations: [],
});
});
@@ -198,7 +296,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "search",
title: 'grep ".*"',
content: [],
@@ -216,7 +314,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "edit",
title: "Write /Users/test/project/example.txt",
content: [
@@ -242,7 +340,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "edit",
title: "Write /Users/test/project/config.json",
content: [
@@ -267,15 +365,10 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "read",
title: "Read File",
content: [
{
type: "content",
content: { type: "text", text: "/Users/test/project/readme.md" },
},
],
content: [],
locations: [{ path: "/Users/test/project/readme.md", line: 0 }],
});
});
@@ -290,7 +383,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "read",
title: "Read /Users/test/project/data.json",
content: [],
@@ -309,7 +402,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "read",
title: "Read /Users/test/project/large.txt (1 - 100)",
content: [],
@@ -329,7 +422,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "read",
title: "Read /Users/test/project/large.txt (51 - 150)",
content: [],
@@ -348,7 +441,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "read",
title: "Read /Users/test/project/large.txt (from line 201)",
content: [],
@@ -368,7 +461,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "fetch",
title: "Fetch https://agentclientprotocol.com",
content: [
@@ -393,7 +486,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "fetch",
title: '"agentclientprotocol.com"',
content: [],
@@ -410,7 +503,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "execute",
title: `Kill Process`,
content: [],
@@ -427,7 +520,7 @@ describe("tool conversions", () => {
},
};
expect(toolInfoFromToolUse(tool_use)).toStrictEqual({
expect(toolInfoFromToolUse(tool_use, {})).toStrictEqual({
kind: "execute",
title: `Tail Logs`,
content: [],
@@ -512,7 +605,7 @@ describe("tool conversions", () => {
session_id: "d056596f-e328-41e9-badd-b07122ae5227",
uuid: "b7c3330c-de8f-4bba-ac53-68c7f76ffeb5",
};
expect(toAcpNotifications(received, "test", {})).toStrictEqual([
expect(toAcpNotifications(received, "test", {}, {})).toStrictEqual([
{
sessionId: "test",
update: {
@@ -594,6 +687,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,
},
],
},
};
let 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", () => {
const toolUse = {
type: "tool_use",
@@ -716,3 +869,17 @@ describe("tool conversions", () => {
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

@@ -1,10 +1,13 @@
import { ContentBlock } from "@modelcontextprotocol/sdk/types.js";
import {
Client,
PlanEntry,
ToolCallContent,
ToolCallLocation,
ToolKind,
} from "@zed-industries/agent-client-protocol";
import { replaceAndCalculateLocation, SYSTEM_REMINDER } from "./mcp-server.js";
import { tool } from "@anthropic-ai/claude-code";
interface ToolInfo {
title: string;
@@ -19,7 +22,10 @@ interface ToolUpdate {
locations?: ToolCallLocation[];
}
export function toolInfoFromToolUse(toolUse: any): ToolInfo {
export function toolInfoFromToolUse(
toolUse: any,
cachedFileContent: { [key: string]: string },
): ToolInfo {
const name = toolUse.name;
const input = toolUse.input;
@@ -45,18 +51,7 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
? `Read Notebook ${input.notebook_path}`
: "Read Notebook",
kind: "read",
content:
input && input.notebook_path
? [
{
type: "content",
content: {
type: "text",
text: input.notebook_path.toString(),
},
},
]
: [],
content: [],
locations: input?.notebook_path ? [{ path: input.notebook_path }] : [],
};
@@ -79,13 +74,14 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
};
case "Bash":
case "mcp__acp__Bash":
return {
title: input?.command
? "`" + input.command.replaceAll("`", "\\`") + "`"
: "Terminal",
kind: "execute",
content:
input && input.command
input && input.description
? [
{
type: "content",
@@ -96,6 +92,7 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
};
case "BashOutput":
case "mcp__acp__BashOutput":
return {
title: "Tail Logs",
kind: "execute",
@@ -103,6 +100,7 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
};
case "KillBash":
case "mcp__acp__KillBash":
return {
title: "Kill Process",
kind: "execute",
@@ -138,28 +136,39 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
return {
title: "Read File",
kind: "read",
content:
input && input.abs_path
? [
{
type: "content",
content: { type: "text", text: input.abs_path.toString() },
},
]
: [],
content: [],
locations: [{ path: input.abs_path, line: input.offset ?? 0 }],
};
case "LS":
return {
title: input?.path ? input.path : "Current Directory",
title: `List the ${input?.path ? "`" + input.path + "`" : "current"} directory's contents`,
kind: "search",
content: [],
locations: input?.path ? [{ path: input.path }] : [],
locations: [],
};
case "mcp__acp__edit":
case "Edit":
let oldText = input.old_text || null;
let newText = input.new_text;
if (input?.abs_path && input.old_text) {
try {
let oldContent = cachedFileContent[input.abs_path] || "";
let newContent = replaceAndCalculateLocation(oldContent, [
{
oldText: input.old_text,
newText: input.new_text,
replaceAll: false,
},
]);
oldText = oldContent;
newText = newContent.newContent;
} catch (e) {
console.error(e);
}
}
return {
title: input?.abs_path ? `Edit ${input.abs_path}` : "Edit",
kind: "edit",
@@ -169,8 +178,8 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
{
type: "diff",
path: input.abs_path,
oldText: input.old_text || null,
newText: input.new_text,
oldText,
newText,
},
]
: [],
@@ -179,20 +188,52 @@ export function toolInfoFromToolUse(toolUse: any): ToolInfo {
case "mcp__acp__multi-edit":
case "MultiEdit":
let 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) {
let oldContent =
cachedFileContent[multiInput.file_path] ||
multiInput.edits.map((edit: any) => edit.oldText).join("\n");
let 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
// the distinction between edits and multi-edits.
return {
title: input?.file_path ? `Edit ${input.file_path}` : "Edit",
kind: "edit",
content:
input && input.edits && input.edits.length > 0
? input.edits.map((edit: any) => ({
type: "diff" as const,
path: input.file_path,
oldText: edit.old_string || null,
newText: edit.new_string,
}))
: [],
content: [
{
type: "diff" as const,
path: input.file_path,
oldText: oldTextMulti,
newText: newTextMulti,
},
],
locations: input?.file_path ? [{ path: input.file_path }] : [],
};
@@ -447,11 +488,55 @@ export function toolUpdateFromToolResult(
}
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 "NotebookEdit":
case "NotebookRead":
case "mcp__acp__write":
case "Write":
case "TodoWrite":
case "exit_plan_mode":
case "Bash":
@@ -464,21 +549,25 @@ export function toolUpdateFromToolResult(
case "WebSearch":
case "Other":
default: {
// This happens for the mcp__acp__read tool,
// but may also for others...
if (Array.isArray(toolResult.content)) {
if (Array.isArray(toolResult.content) && toolResult.content.length > 0) {
return {
content: toolResult.content.map((content: any) => ({
type: "content",
content,
})),
};
} else if (typeof toolResult.content === "string") {
} else if (
typeof toolResult.content === "string" &&
toolResult.content.length > 0
) {
return {
content: [
{
type: "content",
content: { type: "text", text: toolResult.content },
content: {
type: "text",
text: toolResult.content,
},
},
],
};
@@ -501,3 +590,13 @@ export function planEntries(input: { todos: ClaudePlanEntry[] }): PlanEntry[] {
priority: "medium",
}));
}
export function markdownEscape(text: string): string {
let escape = "```";
for (let [m] of text.matchAll(/^```+/gm)) {
while (m.length >= escape.length) {
escape += "`";
}
}
return escape + "\n" + text + (text.endsWith("\n") ? "" : "\n") + escape;
}