diff --git a/src/core/api/adapters/__tests__/adapters.test.ts b/src/core/api/adapters/__tests__/adapters.test.ts
new file mode 100644
index 00000000..7f77c4e6
--- /dev/null
+++ b/src/core/api/adapters/__tests__/adapters.test.ts
@@ -0,0 +1,1102 @@
+import { describe, it } from "mocha"
+import "should"
+import { Anthropic } from "@anthropic-ai/sdk"
+import { ClineStorageMessage } from "@/shared/messages/content"
+import { ClineDefaultTool } from "@/shared/tools"
+import { transformToolCallMessages } from ".."
+
+describe("transformToolCallMessages", () => {
+ describe("apply_patch conversion", () => {
+ const testCases: Array<{
+ name: string
+ input: ClineStorageMessage[]
+ expected: {
+ toolName: string
+ inputPath?: string
+ inputContent?: string
+ inputDiff?: string
+ }[]
+ }> = [
+ {
+ name: "should convert apply_patch Add operation to write_to_file",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_123",
+ name: "apply_patch",
+ input: {
+ input: `apply_patch <<"EOF"
+*** Begin Patch
+*** Add File: src/new-file.ts
+@@
++export function newFunction() {
++ return "hello world"
++}
+*** End Patch
+EOF`,
+ },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "write_to_file",
+ inputPath: "src/new-file.ts",
+ inputContent: `export function newFunction() {
+ return "hello world"
+}`,
+ },
+ ],
+ },
+ {
+ name: "should convert apply_patch Update operation to replace_in_file",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_456",
+ name: "apply_patch",
+ input: {
+ input: 'apply_patch <<"EOF"\n*** Begin Patch\n*** Update File: src/existing-file.ts\n@@\nfunction oldFunction() {\n-\treturn "old"\n+\treturn "new"\n}\n*** End Patch\nEOF',
+ },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "replace_in_file",
+ inputPath: "src/existing-file.ts",
+ inputDiff:
+ '------- SEARCH\n\nfunction oldFunction() {\n\treturn "old"\n}\n=======\n\nfunction oldFunction() {\n\treturn "new"\n}\n+++++++ REPLACE',
+ },
+ ],
+ },
+ {
+ name: "should handle multiple tool_use blocks in same message",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ { type: "text", text: "Making changes..." },
+ {
+ type: "tool_use",
+ id: "toolu_001",
+ name: "apply_patch",
+ input: {
+ input: `apply_patch <<"EOF"
+*** Begin Patch
+*** Add File: file1.ts
+@@
++const x = 1
+*** End Patch
+EOF`,
+ },
+ },
+ {
+ type: "tool_use",
+ id: "toolu_002",
+ name: "apply_patch",
+ input: {
+ input: `apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: file2.ts
+@@1
+2
+3
+4
+- old line
++ new line
+6
+7
+8
+*** End Patch
+EOF`,
+ },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "write_to_file",
+ inputPath: "file1.ts",
+ inputContent: "const x = 1",
+ },
+ {
+ toolName: "replace_in_file",
+ inputPath: "file2.ts",
+ inputDiff: `------- SEARCH
+1
+2
+3
+4
+old line
+6
+7
+8
+=======
+1
+2
+3
+4
+new line
+6
+7
+8
++++++++ REPLACE`,
+ },
+ ],
+ },
+ {
+ name: "should preserve non-apply_patch tool calls",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_999",
+ name: "read_file",
+ input: { path: "some-file.ts" },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "read_file",
+ },
+ ],
+ },
+ {
+ name: "should handle apply_patch with @@ context markers",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_777",
+ name: "apply_patch",
+ input: {
+ input: 'apply_patch <<"EOF"\n*** Begin Patch\n*** Update File: src/class.ts\n@@class MyClass\n@@\t\tmethod():\n-\t\t\treturn false\n+\t\t\treturn true\n*** End Patch\nEOF',
+ },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "replace_in_file",
+ inputPath: "src/class.ts",
+ inputDiff:
+ "------- SEARCH\nclass MyClass\n\t\tmethod():\n\t\t\treturn false\n=======\nclass MyClass\n\t\tmethod():\n\t\t\treturn true\n+++++++ REPLACE",
+ },
+ ],
+ },
+ {
+ name: "should handle Delete operation as replace_in_file",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_888",
+ name: "apply_patch",
+ input: {
+ input: `apply_patch <<"EOF"
+*** Begin Patch
+*** Delete File: src/obsolete.ts
+-function oldCode() {
+- console.log("delete me")
+-}
+*** End Patch
+EOF`,
+ },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "replace_in_file",
+ inputPath: "src/obsolete.ts",
+ inputDiff: `------- SEARCH
+function oldCode() {
+ console.log("delete me")
+}
+=======
+
++++++++ REPLACE`,
+ },
+ ],
+ },
+ {
+ name: "should handle malformed apply_patch by fallback to write_to_file",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_bad",
+ name: "apply_patch",
+ input: {
+ input: "invalid patch format",
+ },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "write_to_file",
+ },
+ ],
+ },
+ {
+ name: "should match tool_result blocks with converted tool_use",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_paired",
+ name: "apply_patch",
+ input: {
+ input: `apply_patch <<"EOF"
+*** Begin Patch
+*** Add File: test.ts
+@@
++ const test = 1
+*** End Patch
+EOF`,
+ },
+ },
+ ],
+ },
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "toolu_paired",
+ content: "File created successfully",
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "write_to_file",
+ inputPath: "test.ts",
+ inputContent: "const test = 1",
+ },
+ ],
+ },
+ {
+ name: "should handle multiple apply_patch operations in one message",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_paired",
+ name: "apply_patch",
+ input: {
+ input: '%%bash\napply_patch <<"EOF"\n*** Begin Patch\n*** Update File: CONTRIBUTING.md\n@@\n-3. Install the necessary dependencies for the extension and webview-gui:\n-\t```bash\n-\tnpm run install:all\n-\t```\n-4. Generate Protocol Buffer files (required before first build):\n-\t```bash\n-\tnpm run protos\n-\t```\n+3. Install the necessary dependencies for the extension and webview-gui:\n+\t```bash\n+\tbun run install:all\n+\t```\n+4. Generate Protocol Buffer files (required before first build):\n+\t```bash\n+\tbun run protos\n+\t```\n@@\n-1. Before creating a PR, generate a changeset entry:\n-\t```bash\n-\tnpm run changeset\n-\t```\n+1. Before creating a PR, generate a changeset entry:\n+\t```bash\n+\tbun run changeset\n+\t```\n@@\n-4. Testing\n-\n-\t- Run `npm run test` to run tests locally. \n-\t- Before submitting PR, run `npm run format:fix` to format your code\n+4. Testing\n+\n+\t- Run `bun run test` to run tests locally. \n+\t- Before submitting PR, run `bun run format:fix` to format your code\n@@\n-2. **Local Development**\n-\t- Run `npm run install:all` to install dependencies\n-\t- Run `npm run protos` to generate Protocol Buffer files (required before first build)\n-\t- Run `npm run test` to run tests locally\n+2. **Local Development**\n+\t- Run `bun run install:all` to install dependencies\n+\t- Run `bun run protos` to generate Protocol Buffer files (required before first build)\n+\t- Run `bun run test` to run tests locally\n*** End Patch\nEOF',
+ },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "replace_in_file",
+ inputPath: "CONTRIBUTING.md",
+
+ inputDiff:
+ "------- SEARCH\n\n3. Install the necessary dependencies for the extension and webview-gui:\n\t```bash\n\tnpm run install:all\n\t```\n4. Generate Protocol Buffer files (required before first build):\n\t```bash\n\tnpm run protos\n\t```\n=======\n\n3. Install the necessary dependencies for the extension and webview-gui:\n\t```bash\n\tbun run install:all\n\t```\n4. Generate Protocol Buffer files (required before first build):\n\t```bash\n\tbun run protos\n\t```\n+++++++ REPLACE\n------- SEARCH\n\n1. Before creating a PR, generate a changeset entry:\n\t```bash\n\tnpm run changeset\n\t```\n=======\n\n1. Before creating a PR, generate a changeset entry:\n\t```bash\n\tbun run changeset\n\t```\n+++++++ REPLACE\n------- SEARCH\n\n4. Testing\n\n\t- Run `npm run test` to run tests locally. \n\t- Before submitting PR, run `npm run format:fix` to format your code\n=======\n\n4. Testing\n\n\t- Run `bun run test` to run tests locally. \n\t- Before submitting PR, run `bun run format:fix` to format your code\n+++++++ REPLACE\n------- SEARCH\n\n2. **Local Development**\n\t- Run `npm run install:all` to install dependencies\n\t- Run `npm run protos` to generate Protocol Buffer files (required before first build)\n\t- Run `npm run test` to run tests locally\n=======\n\n2. **Local Development**\n\t- Run `bun run install:all` to install dependencies\n\t- Run `bun run protos` to generate Protocol Buffer files (required before first build)\n\t- Run `bun run test` to run tests locally\n+++++++ REPLACE",
+ },
+ ],
+ },
+ {
+ name: "should handle context after @@ markers as first line of search block",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_paired",
+ name: "apply_patch",
+ input: {
+ input: `%%bash
+apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: pygorithm/searching/simple.md
+@@[4 line above change]
+[3 line above change]
+[2 line above change]
+[1 line above change]
+-[exact content to find]
++[new content to replace with]
+[1 line below change]
+[2 line below change]
+[3 line below change]
+*** End Patch
+EOF`,
+ },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "replace_in_file",
+ inputPath: "pygorithm/searching/simple.md",
+
+ inputDiff: `------- SEARCH
+[4 line above change]
+[3 line above change]
+[2 line above change]
+[1 line above change]
+[exact content to find]
+[1 line below change]
+[2 line below change]
+[3 line below change]
+=======
+[4 line above change]
+[3 line above change]
+[2 line above change]
+[1 line above change]
+[new content to replace with]
+[1 line below change]
+[2 line below change]
+[3 line below change]
++++++++ REPLACE`,
+ },
+ ],
+ },
+ ]
+
+ testCases.forEach((testCase) => {
+ it(testCase.name, () => {
+ // When native tools are FILE_EDIT/FILE_NEW and messages use apply_patch, convert FROM apply_patch
+ const result = transformToolCallMessages(testCase.input, [ClineDefaultTool.FILE_EDIT, ClineDefaultTool.FILE_NEW])
+ // Find all tool_use blocks in the result
+ const toolUseBlocks: Anthropic.ContentBlock[] = []
+ for (const message of result) {
+ if (Array.isArray(message.content)) {
+ for (const block of message.content) {
+ if (block.type === "tool_use") {
+ toolUseBlocks.push(block)
+ }
+ }
+ }
+ }
+
+ // Verify we have the expected number of tool uses
+ toolUseBlocks.should.have.length(testCase.expected.length)
+
+ // Check each tool use against expectations
+ testCase.expected.forEach((expected, index) => {
+ const toolBlock = toolUseBlocks[index]
+ toolBlock.should.have.property("type", "tool_use")
+
+ if (toolBlock.type === "tool_use") {
+ toolBlock.should.have.property("name", expected.toolName)
+
+ const input = toolBlock.input as any
+
+ if (expected.inputPath) {
+ input.should.have.property("absolutePath", expected.inputPath)
+ }
+
+ if (expected.inputContent !== undefined) {
+ input.should.have.property("content", expected.inputContent)
+ }
+
+ if (expected.inputDiff !== undefined) {
+ if (typeof expected.inputDiff === "string") {
+ input.should.have.property("diff", expected.inputDiff)
+ } else if (expected.inputDiff === true) {
+ input.should.have.property("diff")
+ input.diff.should.be.a.String()
+ input.diff.should.not.be.empty()
+ }
+ }
+ }
+ })
+ })
+ })
+
+ it("should preserve tool_result blocks when tool_use is converted", () => {
+ const input: ClineStorageMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_result_test",
+ name: "apply_patch",
+ input: {
+ input: `apply_patch <<"EOF"
+*** Begin Patch
+*** Add File: result-test.ts
++ export const x = 1
+*** End Patch
+EOF`,
+ },
+ },
+ ],
+ },
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "toolu_result_test",
+ content: "Success",
+ },
+ ],
+ },
+ ]
+
+ // Native tools are FILE_EDIT/FILE_NEW, messages use apply_patch → convert FROM apply_patch
+ // Native tools are FILE_EDIT/FILE_NEW, messages use apply_patch → convert FROM apply_patch
+ const result = transformToolCallMessages(input, [ClineDefaultTool.FILE_EDIT, ClineDefaultTool.FILE_NEW])
+
+ // Find the tool_result block
+ let foundToolResult = false
+ for (const message of result) {
+ if (Array.isArray(message.content)) {
+ for (const block of message.content) {
+ if (block.type === "tool_result" && block.tool_use_id === "toolu_result_test") {
+ foundToolResult = true
+ block.should.have.property("content", "Success")
+ }
+ }
+ }
+ }
+
+ foundToolResult.should.be.true()
+ })
+
+ it("should reconstruct tool_result content with final_file_content for write_to_file", () => {
+ const input: ClineStorageMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_write",
+ name: "apply_patch",
+ input: {
+ input: `apply_patch <<"EOF"
+*** Begin Patch
+*** Add File: new-file.ts
++ export const newVar = 42
+*** End Patch
+EOF`,
+ },
+ },
+ ],
+ },
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "toolu_write",
+ content:
+ "[write_to_file for 'new-file.ts'] Result:\nThe content was successfully saved to new-file.ts.\n\n\nexport const newVar = 42\n\n\nIMPORTANT: For any future changes to this file, use the final_file_content shown above as your reference.",
+ },
+ ],
+ },
+ ]
+
+ // Native tools are FILE_EDIT/FILE_NEW, messages use apply_patch → convert FROM apply_patch
+ const result = transformToolCallMessages(input, [ClineDefaultTool.FILE_EDIT, ClineDefaultTool.FILE_NEW])
+
+ // Find and verify the reconstructed tool_result
+ let reconstructedContent = ""
+ for (const message of result) {
+ if (Array.isArray(message.content)) {
+ for (const block of message.content) {
+ if (block.type === "tool_result" && block.tool_use_id === "toolu_write") {
+ reconstructedContent = typeof block.content === "string" ? block.content : ""
+ }
+ }
+ }
+ }
+
+ reconstructedContent.should.match(/\[apply_patch for 'new-file\.ts'\]/)
+ reconstructedContent.should.match(/successfully saved/)
+ })
+
+ it("should reconstruct tool_result content with final_file_content for replace_in_file", () => {
+ const input: ClineStorageMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_replace",
+ name: "apply_patch",
+ input: {
+ input: `apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: existing.ts
+- const old = 1
++ const new = 2
+*** End Patch
+EOF`,
+ },
+ },
+ ],
+ },
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "toolu_replace",
+ content:
+ "[replace_in_file for 'existing.ts'] Result:\nThe content was successfully saved to existing.ts.\n\n\nconst new = 2\n\n\nIMPORTANT: For any future changes to this file, use the final_file_content shown above as your reference.",
+ },
+ ],
+ },
+ ]
+
+ // Native tools are FILE_EDIT/FILE_NEW, messages use apply_patch → convert FROM apply_patch
+ const result = transformToolCallMessages(input, [ClineDefaultTool.FILE_EDIT, ClineDefaultTool.FILE_NEW])
+
+ // Find and verify the reconstructed tool_result
+ let reconstructedContent = ""
+ for (const message of result) {
+ if (Array.isArray(message.content)) {
+ for (const block of message.content) {
+ if (block.type === "tool_result" && block.tool_use_id === "toolu_replace") {
+ reconstructedContent = typeof block.content === "string" ? block.content : ""
+ }
+ }
+ }
+ }
+
+ reconstructedContent.should.match(/\[apply_patch for 'existing\.ts'\]/)
+ reconstructedContent.should.match(/successfully updated/)
+ reconstructedContent.should.match(/ {
+ const input: ClineStorageMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_no_content",
+ name: "apply_patch",
+ input: {
+ input: `apply_patch <<"EOF"
+*** Begin Patch
+*** Add File: test.ts
++ const x = 1
+*** End Patch
+EOF`,
+ },
+ },
+ ],
+ },
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "toolu_no_content",
+ content: "Simple success message without final_file_content",
+ },
+ ],
+ },
+ ]
+
+ // Native tools are FILE_EDIT/FILE_NEW, messages use apply_patch → convert FROM apply_patch
+ const result = transformToolCallMessages(input, [ClineDefaultTool.FILE_EDIT, ClineDefaultTool.FILE_NEW])
+
+ // Find the tool_result and verify it kept original content
+ let foundContent = ""
+ for (const message of result) {
+ if (Array.isArray(message.content)) {
+ for (const block of message.content) {
+ if (block.type === "tool_result" && block.tool_use_id === "toolu_no_content") {
+ foundContent = typeof block.content === "string" ? block.content : ""
+ }
+ }
+ }
+ }
+
+ foundContent.should.equal("Simple success message without final_file_content")
+ })
+
+ it("should generate valid SEARCH/REPLACE diff format", () => {
+ const input: ClineStorageMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_diff",
+ name: "apply_patch",
+ input: {
+ input: `apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: src/test.ts
+@@
+context line 1
+context line 2
+- old line
++ new line
+context line 3
+*** End Patch
+EOF`,
+ },
+ },
+ ],
+ },
+ ]
+
+ // Native tools are FILE_EDIT/FILE_NEW, messages use apply_patch → convert FROM apply_patch
+ const result = transformToolCallMessages(input, [ClineDefaultTool.FILE_EDIT, ClineDefaultTool.FILE_NEW])
+
+ // Extract the diff from the converted tool
+ let diffContent = ""
+ for (const message of result) {
+ if (Array.isArray(message.content)) {
+ for (const block of message.content) {
+ if (block.type === "tool_use" && block.name === "replace_in_file") {
+ const input = block.input as any
+ diffContent = input.diff
+ }
+ }
+ }
+ }
+
+ // Verify the diff contains the SEARCH/REPLACE markers
+ diffContent.should.match(/------- SEARCH/)
+ diffContent.should.match(/=======/)
+ diffContent.should.match(/\+\+\+\+\+\+\+ REPLACE/)
+ diffContent.should.match(/old line/)
+ diffContent.should.match(/new line/)
+ })
+ })
+
+ describe("write_to_file/replace_in_file to apply_patch conversion", () => {
+ const testCases: Array<{
+ name: string
+ input: ClineStorageMessage[]
+ expected: {
+ toolName: string
+ patchInput?: string
+ }[]
+ }> = [
+ {
+ name: "should convert write_to_file to apply_patch Add operation",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_write",
+ name: "write_to_file",
+ input: {
+ absolutePath: "src/new-file.ts",
+ content: "export const x = 1\nexport const y = 2",
+ },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "apply_patch",
+ patchInput: `apply_patch <<"EOF"
+*** Begin Patch
+*** Add File: src/new-file.ts
+@@
++ export const x = 1
++ export const y = 2
+*** End Patch
+EOF`,
+ },
+ ],
+ },
+ {
+ name: "should convert replace_in_file to apply_patch Update operation",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_replace",
+ name: "replace_in_file",
+ input: {
+ absolutePath: "src/existing.ts",
+ diff: `------- SEARCH
+const old = 1
+=======
+const new = 2
++++++++ REPLACE`,
+ },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "apply_patch",
+ patchInput: `apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: src/existing.ts
+@@
+- const old = 1
++ const new = 2
+*** End Patch
+EOF`,
+ },
+ ],
+ },
+ {
+ name: "should handle multiple write_to_file and replace_in_file in same message",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_1",
+ name: "write_to_file",
+ input: {
+ absolutePath: "file1.ts",
+ content: "const a = 1",
+ },
+ },
+ {
+ type: "tool_use",
+ id: "toolu_2",
+ name: "replace_in_file",
+ input: {
+ absolutePath: "file2.ts",
+ diff: `------- SEARCH
+old
+=======
+new
++++++++ REPLACE`,
+ },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "apply_patch",
+ patchInput: `apply_patch <<"EOF"
+*** Begin Patch
+*** Add File: file1.ts
+@@
++ const a = 1
+*** End Patch
+EOF`,
+ },
+ {
+ toolName: "apply_patch",
+ patchInput: `apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: file2.ts
+@@
+- old
++ new
+*** End Patch
+EOF`,
+ },
+ ],
+ },
+ {
+ name: "should preserve non-write_to_file/replace_in_file tool calls",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_other",
+ name: "read_file",
+ input: { path: "some-file.ts" },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "read_file",
+ },
+ ],
+ },
+ {
+ name: "should convert replace_in_file with context lines to apply_patch",
+ input: [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_context",
+ name: "replace_in_file",
+ input: {
+ absolutePath: "src/test.ts",
+ diff: `------- SEARCH
+function oldFunction() {
+ return "old"
+}
+=======
+function oldFunction() {
+ return "new"
+}
++++++++ REPLACE`,
+ },
+ },
+ ],
+ },
+ ],
+ expected: [
+ {
+ toolName: "apply_patch",
+ patchInput: `apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: src/test.ts
+@@
+function oldFunction() {
+- return "old"
++ return "new"
+}
+*** End Patch
+EOF`,
+ },
+ ],
+ },
+ ]
+
+ testCases.forEach((testCase) => {
+ it(testCase.name, () => {
+ // Native tools are APPLY_PATCH, messages use write_to_file/replace_in_file → convert TO apply_patch
+ const result = transformToolCallMessages(testCase.input, [ClineDefaultTool.APPLY_PATCH])
+
+ // Find all tool_use blocks in the result
+ const toolUseBlocks: Anthropic.ContentBlock[] = []
+ for (const message of result) {
+ if (Array.isArray(message.content)) {
+ for (const block of message.content) {
+ if (block.type === "tool_use") {
+ toolUseBlocks.push(block)
+ }
+ }
+ }
+ }
+
+ // Verify we have the expected number of tool uses
+ toolUseBlocks.should.have.length(testCase.expected.length)
+
+ // Check each tool use against expectations
+ testCase.expected.forEach((expected, index) => {
+ const toolBlock = toolUseBlocks[index]
+ toolBlock.should.have.property("type", "tool_use")
+
+ if (toolBlock.type === "tool_use") {
+ toolBlock.should.have.property("name", expected.toolName)
+
+ if (expected.patchInput !== undefined) {
+ const input = toolBlock.input as any
+ const patchInput = input?.input || ""
+ patchInput.should.equal(expected.patchInput)
+ }
+ }
+ })
+ })
+ })
+
+ it("should use final_file_content to generate apply_patch for write_to_file", () => {
+ const input: ClineStorageMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_write_result",
+ name: "write_to_file",
+ input: {
+ absolutePath: "new.ts",
+ content: "const x = 1\nconst y = 2",
+ },
+ },
+ ],
+ },
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "toolu_write_result",
+ content:
+ "[write_to_file for 'new.ts'] Result:\nThe content was successfully saved to new.ts.\n\n\nconst x = 1\nconst y = 2\n\n\nIMPORTANT: For any future changes to this file, use the final_file_content shown above as your reference.",
+ },
+ ],
+ },
+ ]
+
+ // Native tools are APPLY_PATCH, messages use write_to_file/replace_in_file → convert TO apply_patch
+ const result = transformToolCallMessages(input, [ClineDefaultTool.APPLY_PATCH])
+
+ // Find the tool_use block to verify the generated patch
+ let toolUseBlock: any = null
+ for (const message of result) {
+ if (Array.isArray(message.content)) {
+ for (const block of message.content) {
+ if (block.type === "tool_use" && block.name === "apply_patch") {
+ toolUseBlock = block
+ break
+ }
+ }
+ }
+ }
+
+ toolUseBlock.should.not.be.null()
+ toolUseBlock.name.should.equal("apply_patch")
+ const patchInput = toolUseBlock.input.input
+ patchInput.should.equal(`apply_patch <<"EOF"
+*** Begin Patch
+*** Add File: new.ts
+@@
++ const x = 1
++ const y = 2
+*** End Patch
+EOF`)
+ })
+
+ it("should use final_file_content to generate apply_patch with context for replace_in_file", () => {
+ const input: ClineStorageMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_replace_result",
+ name: "replace_in_file",
+ input: {
+ absolutePath: "foobar.ts",
+ diff: `------- SEARCH
+export function bar(foo: string): string {
+=======
+export function bar(foo: string): Foo {
++++++++ REPLACE`,
+ },
+ },
+ ],
+ },
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "toolu_replace_result",
+ content: `[replace_in_file for 'foobar.ts'] Result:\nThe content was successfully saved to foobar.ts.\n\n\nimport * from "foo"\nexport type Foo = "bar"\nexport function bar(foo: string): Foo {\n\treturn foo as Foo\n}\n\n\nIMPORTANT: For any future changes to this file, use the final_file_content shown above as your reference.`,
+ },
+ ],
+ },
+ ]
+
+ // Native tools are APPLY_PATCH, messages use write_to_file/replace_in_file → convert TO apply_patch
+ const result = transformToolCallMessages(input, [ClineDefaultTool.APPLY_PATCH])
+
+ // Find the tool_use block to verify the generated patch
+ let toolUseBlock: any = null
+ for (const message of result) {
+ if (Array.isArray(message.content)) {
+ for (const block of message.content) {
+ if (block.type === "tool_use" && block.name === "apply_patch") {
+ toolUseBlock = block
+ break
+ }
+ }
+ }
+ }
+
+ toolUseBlock.should.not.be.null()
+ toolUseBlock.name.should.equal("apply_patch")
+ const patchInput = toolUseBlock.input.input
+
+ // Verify the exact patch format
+ const expectedPatch = `apply_patch <<"EOF"\n*** Begin Patch\n*** Update File: foobar.ts\n@@\nimport * from "foo"\nexport type Foo = "bar"\n- export function bar(foo: string): string {\n+ export function bar(foo: string): Foo {\n\treturn foo as Foo\n}\n*** End Patch\nEOF`
+ patchInput.should.equal(expectedPatch)
+ })
+
+ it("should handle tool_result without final_file_content gracefully", () => {
+ const input: ClineStorageMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ {
+ type: "tool_use",
+ id: "toolu_no_final",
+ name: "write_to_file",
+ input: {
+ absolutePath: "test.ts",
+ content: "test",
+ },
+ },
+ ],
+ },
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "toolu_no_final",
+ content: "Success without final_file_content",
+ },
+ ],
+ },
+ ]
+
+ // Native tools are APPLY_PATCH, messages use write_to_file/replace_in_file → convert TO apply_patch
+ const result = transformToolCallMessages(input, [ClineDefaultTool.APPLY_PATCH])
+
+ // Find the tool_result
+ let foundContent = ""
+ for (const message of result) {
+ if (Array.isArray(message.content)) {
+ for (const block of message.content) {
+ if (block.type === "tool_result" && block.tool_use_id === "toolu_no_final") {
+ foundContent = typeof block.content === "string" ? block.content : ""
+ }
+ }
+ }
+ }
+
+ foundContent.should.match(/\[apply_patch for 'test\.ts'\]/)
+ foundContent.should.match(/successfully/)
+ })
+ })
+})
diff --git a/src/core/api/adapters/diff-editors.ts b/src/core/api/adapters/diff-editors.ts
new file mode 100644
index 00000000..68e7e2e7
--- /dev/null
+++ b/src/core/api/adapters/diff-editors.ts
@@ -0,0 +1,606 @@
+import { ClineStorageMessage } from "@/shared/messages/content"
+
+const APPLY_PATCH_PATCH_REGEX = /\*\*\* Begin Patch\s+([\s\S]*?)\s+\*\*\* End Patch/m
+
+/**
+ * Convert apply_patch tool calls to write_to_file and replace_in_file format
+ */
+export function convertApplyPatchToolCalls(messages: Array): Array {
+ // Map to track tool_use_id to converted tool info and original input
+ const toolUseIdMap = new Map()
+
+ return messages.map((message) => {
+ if (!Array.isArray(message.content)) {
+ return message
+ }
+
+ const convertedContent = message.content.map((block) => {
+ // Handle tool_use blocks
+ if (block.type === "tool_use" && block.name === "apply_patch") {
+ const converted = convertApplyPatchToToolCalls(block.input)
+ // Store the conversion with original input for matching tool_result
+ toolUseIdMap.set(block.id, { ...converted, originalInput: block.input })
+
+ return {
+ ...block,
+ name: converted.name,
+ input: converted.input,
+ }
+ }
+
+ // Handle tool_result blocks
+ if (block.type === "tool_result") {
+ const conversion = toolUseIdMap.get(block.tool_use_id)
+ if (conversion) {
+ // Reconstruct the tool_result content to match apply_patch format
+ const reconstructedContent = reconstructApplyPatchResult(
+ block,
+ conversion.name,
+ conversion.input,
+ conversion.originalInput,
+ )
+ return {
+ ...block,
+ content: reconstructedContent,
+ }
+ }
+ }
+
+ return block
+ })
+
+ return {
+ ...message,
+ content: convertedContent,
+ }
+ })
+}
+
+interface ConvertedTool {
+ name: string
+ input: any
+}
+
+/**
+ * Parse apply_patch input and convert to write_to_file or replace_in_file format
+ */
+function convertApplyPatchToToolCalls(input: any): ConvertedTool {
+ const patchInput = typeof input === "string" ? input : input?.input || ""
+
+ // Parse the patch format
+ const patchMatch = patchInput.match(APPLY_PATCH_PATCH_REGEX)
+ if (!patchMatch) {
+ // If we can't parse it, return as-is with write_to_file
+ return {
+ name: "write_to_file",
+ input: input,
+ }
+ }
+
+ const patchContent = patchMatch[1]
+
+ // Extract file operation (Add, Update, or Delete)
+ const fileMatch = patchContent.match(/\*\*\* (Add|Update|Delete) File: (.+?)(?:\n|$)/m)
+ if (!fileMatch) {
+ return {
+ name: "write_to_file",
+ input: input,
+ }
+ }
+
+ const action = fileMatch[1]
+ const filePath = fileMatch[2].trim()
+
+ // If it's an Add operation, convert to write_to_file
+ if (action === "Add") {
+ // Extract the content after the file line
+ const contentAfterFile = patchContent.substring(fileMatch.index! + fileMatch[0].length)
+ return {
+ name: "write_to_file",
+ input: {
+ absolutePath: filePath,
+ content: extractNewContentFromPatch(contentAfterFile),
+ },
+ }
+ }
+
+ // If it's Update or Delete, convert to replace_in_file
+ if (action === "Update" || action === "Delete") {
+ const diff = convertPatchToDiff(patchContent.substring(fileMatch.index! + fileMatch[0].length))
+ return {
+ name: "replace_in_file",
+ input: {
+ absolutePath: filePath,
+ diff: diff,
+ },
+ }
+ }
+
+ // Fallback
+ return {
+ name: "write_to_file",
+ input: input,
+ }
+}
+
+/**
+ * Extract new content from add operation patch
+ */
+function extractNewContentFromPatch(patchContent: string): string {
+ // For Add operations, the patch should contain lines starting with +
+ const lines = patchContent.split("\n")
+ const contentLines: string[] = []
+
+ for (const line of lines) {
+ if (line.startsWith("+")) {
+ // Remove the + prefix and exactly ONE space if present (but not if it's a tab)
+ let content = line.substring(1)
+ if (content.startsWith(" ") && !content.startsWith("\t")) {
+ content = content.substring(1)
+ }
+ contentLines.push(content)
+ }
+ }
+
+ return contentLines.join("\n")
+}
+
+/**
+ * Convert V4A patch format to SEARCH/REPLACE format
+ */
+function convertPatchToDiff(patchContent: string): string {
+ const diffBlocks: string[] = []
+ const lines = patchContent.split("\n")
+
+ let i = 0
+ while (i < lines.length) {
+ const line = lines[i]
+
+ // Skip empty lines at the start
+ if (!line.trim() && i === 0) {
+ i++
+ continue
+ }
+
+ // Check if this is the start of a hunk (@@) or a direct change line
+ if (line.trim().startsWith("@@") || line.startsWith("-") || line.startsWith("+")) {
+ const currentSearch: string[] = []
+ const currentReplace: string[] = []
+
+ // Collect @@ context marker lines
+ // @@ prefix marks context lines. If @@something, then "something" is context.
+ // If just @@, then it's an empty context line.
+ while (i < lines.length && lines[i].trim().startsWith("@@")) {
+ const trimmedLine = lines[i].trim()
+ // Extract the actual context content after @@
+ const contextLine = trimmedLine.substring(2)
+ // Always add the context line (even if empty)
+ currentSearch.push(contextLine)
+ currentReplace.push(contextLine)
+ i++
+ }
+
+ if (i >= lines.length) {
+ break
+ }
+
+ // Collect all remaining lines in this hunk until we hit end of content or next @@
+ const hunkLines: string[] = []
+ while (i < lines.length) {
+ // Check if this is a new hunk (starts with @@)
+ if (lines[i].trim().startsWith("@@")) {
+ break
+ }
+ hunkLines.push(lines[i])
+ i++
+ }
+
+ // Now process the hunk to build SEARCH/REPLACE
+ let hasChanges = false
+ for (let j = 0; j < hunkLines.length; j++) {
+ const hunkLine = hunkLines[j]
+
+ if (hunkLine.startsWith("-")) {
+ hasChanges = true
+ // Strip the - prefix and exactly ONE space if present (but not if it's a tab)
+ let content = hunkLine.substring(1)
+ if (content.startsWith(" ") && !content.startsWith(" \t")) {
+ content = content.substring(1)
+ }
+ currentSearch.push(content)
+ } else if (hunkLine.startsWith("+")) {
+ hasChanges = true
+ // Strip the + prefix and exactly ONE space if present (but not if it's a tab)
+ let content = hunkLine.substring(1)
+ if (content.startsWith(" ") && !content.startsWith(" \t")) {
+ content = content.substring(1)
+ }
+ currentReplace.push(content)
+ } else {
+ // Context line without @@ prefix - add to both sides
+ currentSearch.push(hunkLine)
+ currentReplace.push(hunkLine)
+ }
+ }
+
+ // Create the diff block if we have changes
+ if (hasChanges && (currentSearch.length > 0 || currentReplace.length > 0)) {
+ diffBlocks.push(
+ "------- SEARCH\n" +
+ currentSearch.join("\n") +
+ "\n=======\n" +
+ currentReplace.join("\n") +
+ "\n+++++++ REPLACE",
+ )
+ }
+ } else {
+ i++
+ }
+ }
+
+ return diffBlocks.join("\n")
+}
+
+/**
+ * Reconstruct tool_result content to match apply_patch format by extracting
+ * the final file content and converting it back to V4A patch format
+ */
+function reconstructApplyPatchResult(
+ block: any,
+ convertedToolName: string,
+ _convertedInput: any,
+ originalInput: any,
+): string | any[] {
+ // Extract the content from the tool_result
+ const content = typeof block.content === "string" ? block.content : ""
+
+ // Try to extract the final_file_content
+ const finalContentMatch = content.match(/\s*([\s\S]*?)\s*<\/final_file_content>/)
+
+ if (!finalContentMatch) {
+ // If no final_file_content found, return original content
+ return block.content
+ }
+
+ const filePath = finalContentMatch[1]
+ const finalContent = finalContentMatch[2]
+
+ // Reconstruct the result message based on the converted tool type
+ if (convertedToolName === "write_to_file") {
+ // For write_to_file, we just need to confirm the file was created/written
+ return `[apply_patch for '${filePath}'] Result:\nThe content was successfully saved to ${filePath}.\n\nThe file has been created/updated with the new content.`
+ }
+
+ if (convertedToolName === "replace_in_file") {
+ // For replace_in_file, we need to reconstruct the V4A patch format result
+ // Try to parse the original patch to get the action and build context
+ const patchInput = typeof originalInput === "string" ? originalInput : originalInput?.input || ""
+ const patchMatch = patchInput.match(APPLY_PATCH_PATCH_REGEX)
+
+ if (patchMatch) {
+ const patchContent = patchMatch[1]
+ const fileMatch = patchContent.match(/\*\*\* (Add|Update|Delete) File: (.+?)(?:\n|$)/m)
+
+ if (fileMatch) {
+ const action = fileMatch[1]
+ return `[apply_patch for '${filePath}'] Result:\nThe content was successfully updated in ${filePath}.\n\nThe file has been modified using ${action} operation.\n\n\n${finalContent}\n\n\nIMPORTANT: For any future changes to this file, use the final_file_content shown above as your reference.`
+ }
+ }
+
+ // Fallback for replace_in_file
+ return `[apply_patch for '${filePath}'] Result:\nThe content was successfully updated in ${filePath}.\n\n\n${finalContent}\n\n\nIMPORTANT: For any future changes to this file, use the final_file_content shown above as your reference.`
+ }
+
+ // Default fallback
+ return block.content
+}
+
+/**
+ * Convert write_to_file and replace_in_file tool calls to apply_patch format
+ */
+export function convertWriteToFileToolCalls(messages: Array): Array {
+ // Map to track tool_use_id to converted tool info and original input
+ const toolUseIdMap = new Map()
+
+ // First pass: collect tool_use blocks
+ for (const message of messages) {
+ if (!Array.isArray(message.content)) {
+ continue
+ }
+ for (const block of message.content) {
+ if (block.type === "tool_use" && (block.name === "write_to_file" || block.name === "replace_in_file")) {
+ toolUseIdMap.set(block.id, {
+ originalName: block.name,
+ originalInput: block.input,
+ })
+ }
+ }
+ }
+
+ // Second pass: find tool_results and extract final content to build proper patches
+ const finalContentMap = new Map()
+ for (const message of messages) {
+ if (!Array.isArray(message.content)) {
+ continue
+ }
+ for (const block of message.content) {
+ if (block.type === "tool_result" && toolUseIdMap.has(block.tool_use_id)) {
+ const content = typeof block.content === "string" ? block.content : ""
+ const finalContentMatch = content.match(
+ /\s*([\s\S]*?)\s*<\/final_file_content>/,
+ )
+ if (finalContentMatch) {
+ finalContentMap.set(block.tool_use_id, finalContentMatch[2])
+ }
+ }
+ }
+ }
+
+ // Third pass: convert messages
+ return messages.map((message) => {
+ if (!Array.isArray(message.content)) {
+ return message
+ }
+
+ const convertedContent = message.content.map((block) => {
+ // Handle tool_use blocks for write_to_file and replace_in_file
+ if (block.type === "tool_use" && (block.name === "write_to_file" || block.name === "replace_in_file")) {
+ const finalContent = finalContentMap.get(block.id)
+ const patchInput = convertToPatchFormat(block.name, block.input, finalContent)
+
+ // Update the map with the generated patch
+ const existingEntry = toolUseIdMap.get(block.id)
+ if (existingEntry) {
+ existingEntry.patchInput = patchInput
+ }
+
+ return {
+ ...block,
+ name: "apply_patch",
+ input: {
+ input: patchInput,
+ },
+ }
+ }
+
+ // Handle tool_result blocks
+ if (block.type === "tool_result") {
+ const conversion = toolUseIdMap.get(block.tool_use_id)
+ if (conversion) {
+ // Reconstruct the tool_result content to match apply_patch format
+ const reconstructedContent = reconstructWriteToFileResult(
+ block,
+ conversion.originalName,
+ conversion.originalInput,
+ )
+ return {
+ ...block,
+ content: reconstructedContent,
+ }
+ }
+ }
+
+ return block
+ })
+
+ return {
+ ...message,
+ content: convertedContent,
+ }
+ })
+}
+
+/**
+ * Convert write_to_file or replace_in_file input to apply_patch format
+ */
+function convertToPatchFormat(toolName: string, input: any, finalContent?: string): string {
+ const filePath = input.absolutePath || input.path || ""
+
+ if (toolName === "write_to_file") {
+ // Convert write_to_file to Add operation
+ const content = input.content || ""
+ const lines = content.split("\n")
+ const patchLines = ["@@"]
+ patchLines.push(...lines.map((line: string) => `+ ${line}`))
+
+ return `apply_patch <<"EOF"
+*** Begin Patch
+*** Add File: ${filePath}
+${patchLines.join("\n")}
+*** End Patch
+EOF`
+ }
+
+ if (toolName === "replace_in_file") {
+ // Convert replace_in_file to Update operation
+ const diff = input.diff || ""
+
+ // Parse SEARCH/REPLACE blocks and convert to V4A format with context
+ const patchContent = convertDiffToPatchWithContext(diff, finalContent)
+
+ return `apply_patch <<"EOF"
+*** Begin Patch
+*** Update File: ${filePath}
+${patchContent}
+*** End Patch
+EOF`
+ }
+
+ return ""
+}
+
+/**
+ * Convert SEARCH/REPLACE diff format to V4A patch format with additional context from final content
+ */
+function convertDiffToPatchWithContext(diff: string, finalContent?: string): string {
+ const patchLines: string[] = []
+
+ // Match all SEARCH/REPLACE blocks
+ const blockRegex = /------- SEARCH\s*\n([\s\S]*?)\n=======\s*\n([\s\S]*?)\n\+{7} REPLACE/g
+ let match
+
+ while ((match = blockRegex.exec(diff)) !== null) {
+ const searchContent = match[1]
+ const replaceContent = match[2]
+
+ const searchLines = searchContent.split("\n")
+ const replaceLines = replaceContent.split("\n")
+
+ // Find common prefix and suffix between search and replace
+ let prefixEnd = 0
+ while (
+ prefixEnd < searchLines.length &&
+ prefixEnd < replaceLines.length &&
+ searchLines[prefixEnd] === replaceLines[prefixEnd]
+ ) {
+ prefixEnd++
+ }
+
+ let suffixStart = searchLines.length
+ let replaceSuffixStart = replaceLines.length
+ while (
+ suffixStart > prefixEnd &&
+ replaceSuffixStart > prefixEnd &&
+ searchLines[suffixStart - 1] === replaceLines[replaceSuffixStart - 1]
+ ) {
+ suffixStart--
+ replaceSuffixStart--
+ }
+
+ // If we have finalContent, extract additional context from it
+ if (finalContent) {
+ const finalLines = finalContent.split("\n")
+
+ // Find where the replaced content appears in the final file
+ let matchIndex = -1
+ for (let i = 0; i < finalLines.length; i++) {
+ // Try to match the first replace line
+ if (replaceLines.length > 0 && finalLines[i] === replaceLines[0]) {
+ // Check if subsequent lines also match
+ let allMatch = true
+ for (let j = 1; j < replaceLines.length && i + j < finalLines.length; j++) {
+ if (finalLines[i + j] !== replaceLines[j]) {
+ allMatch = false
+ break
+ }
+ }
+ if (allMatch) {
+ matchIndex = i
+ break
+ }
+ }
+ }
+
+ if (matchIndex >= 0) {
+ // Extract up to 3 lines before as context
+ const contextStart = Math.max(0, matchIndex - 3)
+ const contextLines: string[] = []
+ for (let i = contextStart; i < matchIndex; i++) {
+ contextLines.push(finalLines[i])
+ }
+
+ // Pad to 3 lines if needed (with empty strings)
+ while (contextLines.length < 3) {
+ contextLines.unshift("")
+ }
+
+ // Add @@ marker with the first context line
+ if (contextLines[0] === "") {
+ patchLines.push("@@")
+ } else {
+ patchLines.push(`@@${contextLines[0]}`)
+ }
+
+ // Add remaining context lines (without @@ marker)
+ for (let i = 1; i < contextLines.length; i++) {
+ patchLines.push(contextLines[i])
+ }
+
+ // Add common prefix lines (without +/- markers)
+ for (let i = 0; i < prefixEnd; i++) {
+ patchLines.push(searchLines[i])
+ }
+
+ // Add the actual changes (lines that differ)
+ for (let i = prefixEnd; i < suffixStart; i++) {
+ patchLines.push(`- ${searchLines[i]}`)
+ }
+ for (let i = prefixEnd; i < replaceSuffixStart; i++) {
+ patchLines.push(`+ ${replaceLines[i]}`)
+ }
+
+ // Add common suffix lines (without +/- markers)
+ for (let i = suffixStart; i < searchLines.length; i++) {
+ patchLines.push(searchLines[i])
+ }
+
+ // Extract up to 3 lines after as trailing context (without @@ markers)
+ const contextEnd = Math.min(finalLines.length, matchIndex + replaceLines.length + 3)
+ for (let i = matchIndex + replaceLines.length; i < contextEnd; i++) {
+ patchLines.push(finalLines[i])
+ }
+
+ continue
+ }
+ }
+
+ // Fallback: if no finalContent or couldn't find match, use the prefix/suffix from SEARCH/REPLACE
+ patchLines.push("@@")
+
+ // Add common prefix lines (without +/- markers)
+ for (let i = 0; i < prefixEnd; i++) {
+ patchLines.push(searchLines[i])
+ }
+
+ // Add the actual changes (lines that differ)
+ for (let i = prefixEnd; i < suffixStart; i++) {
+ patchLines.push(`- ${searchLines[i]}`)
+ }
+ for (let i = prefixEnd; i < replaceSuffixStart; i++) {
+ patchLines.push(`+ ${replaceLines[i]}`)
+ }
+
+ // Add common suffix lines (without +/- markers)
+ for (let i = suffixStart; i < searchLines.length; i++) {
+ patchLines.push(searchLines[i])
+ }
+ }
+
+ return patchLines.join("\n")
+}
+
+/**
+ * Reconstruct tool_result content to match apply_patch result format
+ */
+function reconstructWriteToFileResult(block: any, originalToolName: string, originalInput: any): string | any[] {
+ // Extract the content from the tool_result
+ const content = typeof block.content === "string" ? block.content : ""
+
+ // Try to extract the final_file_content
+ const finalContentMatch = content.match(/\s*([\s\S]*?)\s*<\/final_file_content>/)
+
+ const filePath = originalInput.absolutePath || originalInput.path || ""
+
+ if (!finalContentMatch) {
+ // If no final_file_content found, create a simple success message
+ if (originalToolName === "write_to_file") {
+ return `[apply_patch for '${filePath}'] Result:\nThe content was successfully saved to ${filePath}.\n\nThe file has been created/updated with the new content.`
+ } else {
+ return `[apply_patch for '${filePath}'] Result:\nThe content was successfully updated in ${filePath}.\n\nThe file has been modified.`
+ }
+ }
+
+ const finalContent = finalContentMatch[2]
+
+ // Reconstruct the result message based on the original tool type
+ if (originalToolName === "write_to_file") {
+ return `[apply_patch for '${filePath}'] Result:\nThe content was successfully saved to ${filePath}.\n\nThe file has been created/updated with the new content.`
+ }
+
+ if (originalToolName === "replace_in_file") {
+ return `[apply_patch for '${filePath}'] Result:\nThe content was successfully updated in ${filePath}.\n\nThe file has been modified using Update operation.\n\n\n${finalContent}\n\n\nIMPORTANT: For any future changes to this file, use the final_file_content shown above as your reference.`
+ }
+
+ // Default fallback
+ return block.content
+}
diff --git a/src/core/api/adapters/index.ts b/src/core/api/adapters/index.ts
new file mode 100644
index 00000000..53011340
--- /dev/null
+++ b/src/core/api/adapters/index.ts
@@ -0,0 +1,60 @@
+import { ClineStorageMessage } from "@/shared/messages/content"
+import { ClineDefaultTool } from "@/shared/tools"
+import { convertApplyPatchToolCalls, convertWriteToFileToolCalls } from "./diff-editors"
+
+/**
+ * Transforms tool call messages between different tool formats based on native tool support.
+ * Converts between apply_patch and write_to_file/replace_in_file formats as needed.
+ *
+ * @param clineMessages - Array of messages containing tool calls to transform
+ * @param nativeTools - Array of tools natively supported by the current provider
+ * @returns Transformed messages array, or original if no transformation needed
+ */
+export function transformToolCallMessages(
+ clineMessages: ClineStorageMessage[],
+ nativeTools?: ClineDefaultTool[],
+): ClineStorageMessage[] {
+ // Early return if no messages or native tools provided
+ if (!clineMessages?.length || !nativeTools?.length) {
+ return clineMessages
+ }
+
+ // Create Sets for O(1) lookup performance
+ const nativeToolSet = new Set(nativeTools)
+ const usedToolSet = new Set()
+
+ // Single pass: collect all tools used in assistant messages
+ for (const msg of clineMessages) {
+ if (msg.role === "assistant" && Array.isArray(msg.content)) {
+ for (const block of msg.content) {
+ if (block.type === "tool_use" && block.name) {
+ usedToolSet.add(block.name)
+ }
+ }
+ }
+ }
+
+ // Early return if no tools were used
+ if (usedToolSet.size === 0) {
+ return clineMessages
+ }
+
+ // Determine which conversion to apply
+ const hasApplyPatchNative = nativeToolSet.has(ClineDefaultTool.APPLY_PATCH)
+ const hasFileEditNative = nativeToolSet.has(ClineDefaultTool.FILE_EDIT) || nativeToolSet.has(ClineDefaultTool.FILE_NEW)
+
+ const hasApplyPatchUsed = usedToolSet.has(ClineDefaultTool.APPLY_PATCH)
+ const hasFileEditUsed = usedToolSet.has(ClineDefaultTool.FILE_EDIT) || usedToolSet.has(ClineDefaultTool.FILE_NEW)
+
+ // Convert write_to_file/replace_in_file → apply_patch
+ if (hasApplyPatchNative && hasFileEditUsed) {
+ return convertWriteToFileToolCalls(clineMessages)
+ }
+
+ // Convert apply_patch → write_to_file/replace_in_file
+ if (hasFileEditNative && hasApplyPatchUsed) {
+ return convertApplyPatchToolCalls(clineMessages)
+ }
+
+ return clineMessages
+}