@link-assistant/agent 0.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/EXAMPLES.md +383 -0
- package/LICENSE +24 -0
- package/MODELS.md +95 -0
- package/README.md +388 -0
- package/TOOLS.md +134 -0
- package/package.json +89 -0
- package/src/agent/agent.ts +150 -0
- package/src/agent/generate.txt +75 -0
- package/src/auth/index.ts +64 -0
- package/src/bun/index.ts +96 -0
- package/src/bus/global.ts +10 -0
- package/src/bus/index.ts +119 -0
- package/src/cli/bootstrap.js +41 -0
- package/src/cli/bootstrap.ts +17 -0
- package/src/cli/cmd/agent.ts +165 -0
- package/src/cli/cmd/cmd.ts +5 -0
- package/src/cli/cmd/export.ts +88 -0
- package/src/cli/cmd/mcp.ts +80 -0
- package/src/cli/cmd/models.ts +58 -0
- package/src/cli/cmd/run.ts +359 -0
- package/src/cli/cmd/stats.ts +276 -0
- package/src/cli/error.ts +27 -0
- package/src/command/index.ts +73 -0
- package/src/command/template/initialize.txt +10 -0
- package/src/config/config.ts +705 -0
- package/src/config/markdown.ts +41 -0
- package/src/file/ripgrep.ts +391 -0
- package/src/file/time.ts +38 -0
- package/src/file/watcher.ts +75 -0
- package/src/file.ts +6 -0
- package/src/flag/flag.ts +19 -0
- package/src/format/formatter.ts +248 -0
- package/src/format/index.ts +137 -0
- package/src/global/index.ts +52 -0
- package/src/id/id.ts +72 -0
- package/src/index.js +371 -0
- package/src/mcp/index.ts +289 -0
- package/src/patch/index.ts +622 -0
- package/src/project/bootstrap.ts +22 -0
- package/src/project/instance.ts +67 -0
- package/src/project/project.ts +105 -0
- package/src/project/state.ts +65 -0
- package/src/provider/models-macro.ts +11 -0
- package/src/provider/models.ts +98 -0
- package/src/provider/opencode.js +47 -0
- package/src/provider/provider.ts +636 -0
- package/src/provider/transform.ts +241 -0
- package/src/server/project.ts +48 -0
- package/src/server/server.ts +249 -0
- package/src/session/agent.js +204 -0
- package/src/session/compaction.ts +249 -0
- package/src/session/index.ts +380 -0
- package/src/session/message-v2.ts +758 -0
- package/src/session/message.ts +189 -0
- package/src/session/processor.ts +356 -0
- package/src/session/prompt/anthropic-20250930.txt +166 -0
- package/src/session/prompt/anthropic.txt +105 -0
- package/src/session/prompt/anthropic_spoof.txt +1 -0
- package/src/session/prompt/beast.txt +147 -0
- package/src/session/prompt/build-switch.txt +5 -0
- package/src/session/prompt/codex.txt +318 -0
- package/src/session/prompt/copilot-gpt-5.txt +143 -0
- package/src/session/prompt/gemini.txt +155 -0
- package/src/session/prompt/grok-code.txt +1 -0
- package/src/session/prompt/plan.txt +8 -0
- package/src/session/prompt/polaris.txt +107 -0
- package/src/session/prompt/qwen.txt +109 -0
- package/src/session/prompt/summarize-turn.txt +5 -0
- package/src/session/prompt/summarize.txt +10 -0
- package/src/session/prompt/title.txt +25 -0
- package/src/session/prompt.ts +1390 -0
- package/src/session/retry.ts +53 -0
- package/src/session/revert.ts +108 -0
- package/src/session/status.ts +75 -0
- package/src/session/summary.ts +179 -0
- package/src/session/system.ts +138 -0
- package/src/session/todo.ts +36 -0
- package/src/snapshot/index.ts +197 -0
- package/src/storage/storage.ts +226 -0
- package/src/tool/bash.ts +193 -0
- package/src/tool/bash.txt +121 -0
- package/src/tool/batch.ts +173 -0
- package/src/tool/batch.txt +28 -0
- package/src/tool/codesearch.ts +123 -0
- package/src/tool/codesearch.txt +12 -0
- package/src/tool/edit.ts +604 -0
- package/src/tool/edit.txt +10 -0
- package/src/tool/glob.ts +65 -0
- package/src/tool/glob.txt +6 -0
- package/src/tool/grep.ts +116 -0
- package/src/tool/grep.txt +8 -0
- package/src/tool/invalid.ts +17 -0
- package/src/tool/ls.ts +110 -0
- package/src/tool/ls.txt +1 -0
- package/src/tool/multiedit.ts +46 -0
- package/src/tool/multiedit.txt +41 -0
- package/src/tool/patch.ts +188 -0
- package/src/tool/patch.txt +1 -0
- package/src/tool/read.ts +201 -0
- package/src/tool/read.txt +12 -0
- package/src/tool/registry.ts +87 -0
- package/src/tool/task.ts +126 -0
- package/src/tool/task.txt +60 -0
- package/src/tool/todo.ts +39 -0
- package/src/tool/todoread.txt +14 -0
- package/src/tool/todowrite.txt +167 -0
- package/src/tool/tool.ts +66 -0
- package/src/tool/webfetch.ts +171 -0
- package/src/tool/webfetch.txt +14 -0
- package/src/tool/websearch.ts +133 -0
- package/src/tool/websearch.txt +11 -0
- package/src/tool/write.ts +33 -0
- package/src/tool/write.txt +8 -0
- package/src/util/binary.ts +41 -0
- package/src/util/context.ts +25 -0
- package/src/util/defer.ts +12 -0
- package/src/util/error.ts +54 -0
- package/src/util/eventloop.ts +20 -0
- package/src/util/filesystem.ts +69 -0
- package/src/util/fn.ts +11 -0
- package/src/util/iife.ts +3 -0
- package/src/util/keybind.ts +79 -0
- package/src/util/lazy.ts +11 -0
- package/src/util/locale.ts +39 -0
- package/src/util/lock.ts +98 -0
- package/src/util/log.ts +177 -0
- package/src/util/queue.ts +19 -0
- package/src/util/rpc.ts +42 -0
- package/src/util/scrap.ts +10 -0
- package/src/util/signal.ts +12 -0
- package/src/util/timeout.ts +14 -0
- package/src/util/token.ts +7 -0
- package/src/util/wildcard.ts +54 -0
package/src/tool/grep.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import z from "zod"
|
|
2
|
+
import { Tool } from "./tool"
|
|
3
|
+
import { Ripgrep } from "../file/ripgrep"
|
|
4
|
+
|
|
5
|
+
import DESCRIPTION from "./grep.txt"
|
|
6
|
+
import { Instance } from "../project/instance"
|
|
7
|
+
|
|
8
|
+
export const GrepTool = Tool.define("grep", {
|
|
9
|
+
description: DESCRIPTION,
|
|
10
|
+
parameters: z.object({
|
|
11
|
+
pattern: z.string().describe("The regex pattern to search for in file contents"),
|
|
12
|
+
path: z.string().optional().describe("The directory to search in. Defaults to the current working directory."),
|
|
13
|
+
include: z.string().optional().describe('File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")'),
|
|
14
|
+
}),
|
|
15
|
+
async execute(params) {
|
|
16
|
+
if (!params.pattern) {
|
|
17
|
+
throw new Error("pattern is required")
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const searchPath = params.path || Instance.directory
|
|
21
|
+
|
|
22
|
+
const rgPath = await Ripgrep.filepath()
|
|
23
|
+
const args = ["-nH", "--field-match-separator=|", "--regexp", params.pattern]
|
|
24
|
+
if (params.include) {
|
|
25
|
+
args.push("--glob", params.include)
|
|
26
|
+
}
|
|
27
|
+
args.push(searchPath)
|
|
28
|
+
|
|
29
|
+
const proc = Bun.spawn([rgPath, ...args], {
|
|
30
|
+
stdout: "pipe",
|
|
31
|
+
stderr: "pipe",
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
const output = await new Response(proc.stdout).text()
|
|
35
|
+
const errorOutput = await new Response(proc.stderr).text()
|
|
36
|
+
const exitCode = await proc.exited
|
|
37
|
+
|
|
38
|
+
if (exitCode === 1) {
|
|
39
|
+
return {
|
|
40
|
+
title: params.pattern,
|
|
41
|
+
metadata: { matches: 0, truncated: false },
|
|
42
|
+
output: "No files found",
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (exitCode !== 0) {
|
|
47
|
+
throw new Error(`ripgrep failed: ${errorOutput}`)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const lines = output.trim().split("\n")
|
|
51
|
+
const matches = []
|
|
52
|
+
|
|
53
|
+
for (const line of lines) {
|
|
54
|
+
if (!line) continue
|
|
55
|
+
|
|
56
|
+
const [filePath, lineNumStr, ...lineTextParts] = line.split("|")
|
|
57
|
+
if (!filePath || !lineNumStr || lineTextParts.length === 0) continue
|
|
58
|
+
|
|
59
|
+
const lineNum = parseInt(lineNumStr, 10)
|
|
60
|
+
const lineText = lineTextParts.join("|")
|
|
61
|
+
|
|
62
|
+
const file = Bun.file(filePath)
|
|
63
|
+
const stats = await file.stat().catch(() => null)
|
|
64
|
+
if (!stats) continue
|
|
65
|
+
|
|
66
|
+
matches.push({
|
|
67
|
+
path: filePath,
|
|
68
|
+
modTime: stats.mtime.getTime(),
|
|
69
|
+
lineNum,
|
|
70
|
+
lineText,
|
|
71
|
+
})
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
matches.sort((a, b) => b.modTime - a.modTime)
|
|
75
|
+
|
|
76
|
+
const limit = 100
|
|
77
|
+
const truncated = matches.length > limit
|
|
78
|
+
const finalMatches = truncated ? matches.slice(0, limit) : matches
|
|
79
|
+
|
|
80
|
+
if (finalMatches.length === 0) {
|
|
81
|
+
return {
|
|
82
|
+
title: params.pattern,
|
|
83
|
+
metadata: { matches: 0, truncated: false },
|
|
84
|
+
output: "No files found",
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const outputLines = [`Found ${finalMatches.length} matches`]
|
|
89
|
+
|
|
90
|
+
let currentFile = ""
|
|
91
|
+
for (const match of finalMatches) {
|
|
92
|
+
if (currentFile !== match.path) {
|
|
93
|
+
if (currentFile !== "") {
|
|
94
|
+
outputLines.push("")
|
|
95
|
+
}
|
|
96
|
+
currentFile = match.path
|
|
97
|
+
outputLines.push(`${match.path}:`)
|
|
98
|
+
}
|
|
99
|
+
outputLines.push(` Line ${match.lineNum}: ${match.lineText}`)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (truncated) {
|
|
103
|
+
outputLines.push("")
|
|
104
|
+
outputLines.push("(Results are truncated. Consider using a more specific path or pattern.)")
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
title: params.pattern,
|
|
109
|
+
metadata: {
|
|
110
|
+
matches: finalMatches.length,
|
|
111
|
+
truncated,
|
|
112
|
+
},
|
|
113
|
+
output: outputLines.join("\n"),
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
})
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
- Fast content search tool that works with any codebase size
|
|
2
|
+
- Searches file contents using regular expressions
|
|
3
|
+
- Supports full regex syntax (eg. "log.*Error", "function\s+\w+", etc.)
|
|
4
|
+
- Filter files by pattern with the include parameter (eg. "*.js", "*.{ts,tsx}")
|
|
5
|
+
- Returns file paths with at least one match sorted by modification time
|
|
6
|
+
- Use this tool when you need to find files containing specific patterns
|
|
7
|
+
- If you need to identify/count the number of matches within files, use the Bash tool with `rg` (ripgrep) directly. Do NOT use `grep`.
|
|
8
|
+
- When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Task tool instead
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import z from "zod"
|
|
2
|
+
import { Tool } from "./tool"
|
|
3
|
+
|
|
4
|
+
export const InvalidTool = Tool.define("invalid", {
|
|
5
|
+
description: "Do not use",
|
|
6
|
+
parameters: z.object({
|
|
7
|
+
tool: z.string(),
|
|
8
|
+
error: z.string(),
|
|
9
|
+
}),
|
|
10
|
+
async execute(params) {
|
|
11
|
+
return {
|
|
12
|
+
title: "Invalid Tool",
|
|
13
|
+
output: `The arguments provided to the tool are invalid: ${params.error}`,
|
|
14
|
+
metadata: {},
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
})
|
package/src/tool/ls.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import z from "zod"
|
|
2
|
+
import { Tool } from "./tool"
|
|
3
|
+
import * as path from "path"
|
|
4
|
+
import DESCRIPTION from "./ls.txt"
|
|
5
|
+
import { Instance } from "../project/instance"
|
|
6
|
+
import { Ripgrep } from "../file/ripgrep"
|
|
7
|
+
|
|
8
|
+
export const IGNORE_PATTERNS = [
|
|
9
|
+
"node_modules/",
|
|
10
|
+
"__pycache__/",
|
|
11
|
+
".git/",
|
|
12
|
+
"dist/",
|
|
13
|
+
"build/",
|
|
14
|
+
"target/",
|
|
15
|
+
"vendor/",
|
|
16
|
+
"bin/",
|
|
17
|
+
"obj/",
|
|
18
|
+
".idea/",
|
|
19
|
+
".vscode/",
|
|
20
|
+
".zig-cache/",
|
|
21
|
+
"zig-out",
|
|
22
|
+
".coverage",
|
|
23
|
+
"coverage/",
|
|
24
|
+
"vendor/",
|
|
25
|
+
"tmp/",
|
|
26
|
+
"temp/",
|
|
27
|
+
".cache/",
|
|
28
|
+
"cache/",
|
|
29
|
+
"logs/",
|
|
30
|
+
".venv/",
|
|
31
|
+
"venv/",
|
|
32
|
+
"env/",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
const LIMIT = 100
|
|
36
|
+
|
|
37
|
+
export const ListTool = Tool.define("list", {
|
|
38
|
+
description: DESCRIPTION,
|
|
39
|
+
parameters: z.object({
|
|
40
|
+
path: z.string().describe("The absolute path to the directory to list (must be absolute, not relative)").optional(),
|
|
41
|
+
ignore: z.array(z.string()).describe("List of glob patterns to ignore").optional(),
|
|
42
|
+
}),
|
|
43
|
+
async execute(params) {
|
|
44
|
+
const searchPath = path.resolve(Instance.directory, params.path || ".")
|
|
45
|
+
|
|
46
|
+
const ignoreGlobs = IGNORE_PATTERNS.map((p) => `!${p}*`).concat(params.ignore?.map((p) => `!${p}`) || [])
|
|
47
|
+
const files = []
|
|
48
|
+
for await (const file of Ripgrep.files({ cwd: searchPath, glob: ignoreGlobs })) {
|
|
49
|
+
files.push(file)
|
|
50
|
+
if (files.length >= LIMIT) break
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Build directory structure
|
|
54
|
+
const dirs = new Set<string>()
|
|
55
|
+
const filesByDir = new Map<string, string[]>()
|
|
56
|
+
|
|
57
|
+
for (const file of files) {
|
|
58
|
+
const dir = path.dirname(file)
|
|
59
|
+
const parts = dir === "." ? [] : dir.split("/")
|
|
60
|
+
|
|
61
|
+
// Add all parent directories
|
|
62
|
+
for (let i = 0; i <= parts.length; i++) {
|
|
63
|
+
const dirPath = i === 0 ? "." : parts.slice(0, i).join("/")
|
|
64
|
+
dirs.add(dirPath)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Add file to its directory
|
|
68
|
+
if (!filesByDir.has(dir)) filesByDir.set(dir, [])
|
|
69
|
+
filesByDir.get(dir)!.push(path.basename(file))
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function renderDir(dirPath: string, depth: number): string {
|
|
73
|
+
const indent = " ".repeat(depth)
|
|
74
|
+
let output = ""
|
|
75
|
+
|
|
76
|
+
if (depth > 0) {
|
|
77
|
+
output += `${indent}${path.basename(dirPath)}/\n`
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const childIndent = " ".repeat(depth + 1)
|
|
81
|
+
const children = Array.from(dirs)
|
|
82
|
+
.filter((d) => path.dirname(d) === dirPath && d !== dirPath)
|
|
83
|
+
.sort()
|
|
84
|
+
|
|
85
|
+
// Render subdirectories first
|
|
86
|
+
for (const child of children) {
|
|
87
|
+
output += renderDir(child, depth + 1)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Render files
|
|
91
|
+
const files = filesByDir.get(dirPath) || []
|
|
92
|
+
for (const file of files.sort()) {
|
|
93
|
+
output += `${childIndent}${file}\n`
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return output
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const output = `${searchPath}/\n` + renderDir(".", 0)
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
title: path.relative(Instance.worktree, searchPath),
|
|
103
|
+
metadata: {
|
|
104
|
+
count: files.length,
|
|
105
|
+
truncated: files.length >= LIMIT,
|
|
106
|
+
},
|
|
107
|
+
output,
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
})
|
package/src/tool/ls.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Lists files and directories in a given path. The path parameter must be absolute; omit it to use the current workspace directory. You can optionally provide an array of glob patterns to ignore with the ignore parameter. You should generally prefer the Glob and Grep tools, if you know which directories to search.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import z from "zod"
|
|
2
|
+
import { Tool } from "./tool"
|
|
3
|
+
import { EditTool } from "./edit"
|
|
4
|
+
import DESCRIPTION from "./multiedit.txt"
|
|
5
|
+
import path from "path"
|
|
6
|
+
import { Instance } from "../project/instance"
|
|
7
|
+
|
|
8
|
+
export const MultiEditTool = Tool.define("multiedit", {
|
|
9
|
+
description: DESCRIPTION,
|
|
10
|
+
parameters: z.object({
|
|
11
|
+
filePath: z.string().describe("The absolute path to the file to modify"),
|
|
12
|
+
edits: z
|
|
13
|
+
.array(
|
|
14
|
+
z.object({
|
|
15
|
+
filePath: z.string().describe("The absolute path to the file to modify"),
|
|
16
|
+
oldString: z.string().describe("The text to replace"),
|
|
17
|
+
newString: z.string().describe("The text to replace it with (must be different from oldString)"),
|
|
18
|
+
replaceAll: z.boolean().optional().describe("Replace all occurrences of oldString (default false)"),
|
|
19
|
+
}),
|
|
20
|
+
)
|
|
21
|
+
.describe("Array of edit operations to perform sequentially on the file"),
|
|
22
|
+
}),
|
|
23
|
+
async execute(params, ctx) {
|
|
24
|
+
const tool = await EditTool.init()
|
|
25
|
+
const results = []
|
|
26
|
+
for (const [, edit] of params.edits.entries()) {
|
|
27
|
+
const result = await tool.execute(
|
|
28
|
+
{
|
|
29
|
+
filePath: params.filePath,
|
|
30
|
+
oldString: edit.oldString,
|
|
31
|
+
newString: edit.newString,
|
|
32
|
+
replaceAll: edit.replaceAll,
|
|
33
|
+
},
|
|
34
|
+
ctx,
|
|
35
|
+
)
|
|
36
|
+
results.push(result)
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
title: path.relative(Instance.worktree, params.filePath),
|
|
40
|
+
metadata: {
|
|
41
|
+
results: results.map((r) => r.metadata),
|
|
42
|
+
},
|
|
43
|
+
output: results.at(-1)!.output,
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
})
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
This is a tool for making multiple edits to a single file in one operation. It is built on top of the Edit tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the Edit tool when you need to make multiple edits to the same file.
|
|
2
|
+
|
|
3
|
+
Before using this tool:
|
|
4
|
+
|
|
5
|
+
1. Use the Read tool to understand the file's contents and context
|
|
6
|
+
2. Verify the directory path is correct
|
|
7
|
+
|
|
8
|
+
To make multiple file edits, provide the following:
|
|
9
|
+
1. file_path: The absolute path to the file to modify (must be absolute, not relative)
|
|
10
|
+
2. edits: An array of edit operations to perform, where each edit contains:
|
|
11
|
+
- oldString: The text to replace (must match the file contents exactly, including all whitespace and indentation)
|
|
12
|
+
- newString: The edited text to replace the oldString
|
|
13
|
+
- replaceAll: Replace all occurrences of oldString. This parameter is optional and defaults to false.
|
|
14
|
+
|
|
15
|
+
IMPORTANT:
|
|
16
|
+
- All edits are applied in sequence, in the order they are provided
|
|
17
|
+
- Each edit operates on the result of the previous edit
|
|
18
|
+
- All edits must be valid for the operation to succeed - if any edit fails, none will be applied
|
|
19
|
+
- This tool is ideal when you need to make several changes to different parts of the same file
|
|
20
|
+
|
|
21
|
+
CRITICAL REQUIREMENTS:
|
|
22
|
+
1. All edits follow the same requirements as the single Edit tool
|
|
23
|
+
2. The edits are atomic - either all succeed or none are applied
|
|
24
|
+
3. Plan your edits carefully to avoid conflicts between sequential operations
|
|
25
|
+
|
|
26
|
+
WARNING:
|
|
27
|
+
- The tool will fail if edits.oldString doesn't match the file contents exactly (including whitespace)
|
|
28
|
+
- The tool will fail if edits.oldString and edits.newString are the same
|
|
29
|
+
- Since edits are applied in sequence, ensure that earlier edits don't affect the text that later edits are trying to find
|
|
30
|
+
|
|
31
|
+
When making edits:
|
|
32
|
+
- Ensure all edits result in idiomatic, correct code
|
|
33
|
+
- Do not leave the code in a broken state
|
|
34
|
+
- Always use absolute file paths (starting with /)
|
|
35
|
+
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
|
|
36
|
+
- Use replaceAll for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.
|
|
37
|
+
|
|
38
|
+
If you want to create a new file, use:
|
|
39
|
+
- A new file path, including dir name if needed
|
|
40
|
+
- First edit: empty oldString and the new file's contents as newString
|
|
41
|
+
- Subsequent edits: normal edit operations on the created content
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import z from "zod"
|
|
2
|
+
import * as path from "path"
|
|
3
|
+
import * as fs from "fs/promises"
|
|
4
|
+
import { Tool } from "./tool"
|
|
5
|
+
import { FileTime } from "../file/time"
|
|
6
|
+
import { Bus } from "../bus"
|
|
7
|
+
import { FileWatcher } from "../file/watcher"
|
|
8
|
+
import { Instance } from "../project/instance"
|
|
9
|
+
import { Patch } from "../patch"
|
|
10
|
+
import { Filesystem } from "../util/filesystem"
|
|
11
|
+
import { createTwoFilesPatch } from "diff"
|
|
12
|
+
|
|
13
|
+
const PatchParams = z.object({
|
|
14
|
+
patchText: z.string().describe("The full patch text that describes all changes to be made"),
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
export const PatchTool = Tool.define("patch", {
|
|
18
|
+
description:
|
|
19
|
+
"Apply a patch to modify multiple files. Supports adding, updating, and deleting files with context-aware changes.",
|
|
20
|
+
parameters: PatchParams,
|
|
21
|
+
async execute(params, ctx) {
|
|
22
|
+
if (!params.patchText) {
|
|
23
|
+
throw new Error("patchText is required")
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Parse the patch to get hunks
|
|
27
|
+
let hunks: Patch.Hunk[]
|
|
28
|
+
try {
|
|
29
|
+
const parseResult = Patch.parsePatch(params.patchText)
|
|
30
|
+
hunks = parseResult.hunks
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw new Error(`Failed to parse patch: ${error}`)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (hunks.length === 0) {
|
|
36
|
+
throw new Error("No file changes found in patch")
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// No restrictions - unrestricted patching
|
|
40
|
+
const fileChanges: Array<{
|
|
41
|
+
filePath: string
|
|
42
|
+
oldContent: string
|
|
43
|
+
newContent: string
|
|
44
|
+
type: "add" | "update" | "delete" | "move"
|
|
45
|
+
movePath?: string
|
|
46
|
+
}> = []
|
|
47
|
+
|
|
48
|
+
let totalDiff = ""
|
|
49
|
+
|
|
50
|
+
for (const hunk of hunks) {
|
|
51
|
+
const filePath = path.resolve(Instance.directory, hunk.path)
|
|
52
|
+
|
|
53
|
+
switch (hunk.type) {
|
|
54
|
+
case "add":
|
|
55
|
+
if (hunk.type === "add") {
|
|
56
|
+
const oldContent = ""
|
|
57
|
+
const newContent = hunk.contents
|
|
58
|
+
const diff = createTwoFilesPatch(filePath, filePath, oldContent, newContent)
|
|
59
|
+
|
|
60
|
+
fileChanges.push({
|
|
61
|
+
filePath,
|
|
62
|
+
oldContent,
|
|
63
|
+
newContent,
|
|
64
|
+
type: "add",
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
totalDiff += diff + "\n"
|
|
68
|
+
}
|
|
69
|
+
break
|
|
70
|
+
|
|
71
|
+
case "update":
|
|
72
|
+
// Check if file exists for update
|
|
73
|
+
const stats = await fs.stat(filePath).catch(() => null)
|
|
74
|
+
if (!stats || stats.isDirectory()) {
|
|
75
|
+
throw new Error(`File not found or is directory: ${filePath}`)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Read file and update time tracking (like edit tool does)
|
|
79
|
+
await FileTime.assert(ctx.sessionID, filePath)
|
|
80
|
+
const oldContent = await fs.readFile(filePath, "utf-8")
|
|
81
|
+
let newContent = oldContent
|
|
82
|
+
|
|
83
|
+
// Apply the update chunks to get new content
|
|
84
|
+
try {
|
|
85
|
+
const fileUpdate = Patch.deriveNewContentsFromChunks(filePath, hunk.chunks)
|
|
86
|
+
newContent = fileUpdate.content
|
|
87
|
+
} catch (error) {
|
|
88
|
+
throw new Error(`Failed to apply update to ${filePath}: ${error}`)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const diff = createTwoFilesPatch(filePath, filePath, oldContent, newContent)
|
|
92
|
+
|
|
93
|
+
fileChanges.push({
|
|
94
|
+
filePath,
|
|
95
|
+
oldContent,
|
|
96
|
+
newContent,
|
|
97
|
+
type: hunk.move_path ? "move" : "update",
|
|
98
|
+
movePath: hunk.move_path ? path.resolve(Instance.directory, hunk.move_path) : undefined,
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
totalDiff += diff + "\n"
|
|
102
|
+
break
|
|
103
|
+
|
|
104
|
+
case "delete":
|
|
105
|
+
// Check if file exists for deletion
|
|
106
|
+
await FileTime.assert(ctx.sessionID, filePath)
|
|
107
|
+
const contentToDelete = await fs.readFile(filePath, "utf-8")
|
|
108
|
+
const deleteDiff = createTwoFilesPatch(filePath, filePath, contentToDelete, "")
|
|
109
|
+
|
|
110
|
+
fileChanges.push({
|
|
111
|
+
filePath,
|
|
112
|
+
oldContent: contentToDelete,
|
|
113
|
+
newContent: "",
|
|
114
|
+
type: "delete",
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
totalDiff += deleteDiff + "\n"
|
|
118
|
+
break
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// No restrictions - apply changes directly
|
|
123
|
+
// Apply the changes
|
|
124
|
+
const changedFiles: string[] = []
|
|
125
|
+
|
|
126
|
+
for (const change of fileChanges) {
|
|
127
|
+
switch (change.type) {
|
|
128
|
+
case "add":
|
|
129
|
+
// Create parent directories
|
|
130
|
+
const addDir = path.dirname(change.filePath)
|
|
131
|
+
if (addDir !== "." && addDir !== "/") {
|
|
132
|
+
await fs.mkdir(addDir, { recursive: true })
|
|
133
|
+
}
|
|
134
|
+
await fs.writeFile(change.filePath, change.newContent, "utf-8")
|
|
135
|
+
changedFiles.push(change.filePath)
|
|
136
|
+
break
|
|
137
|
+
|
|
138
|
+
case "update":
|
|
139
|
+
await fs.writeFile(change.filePath, change.newContent, "utf-8")
|
|
140
|
+
changedFiles.push(change.filePath)
|
|
141
|
+
break
|
|
142
|
+
|
|
143
|
+
case "move":
|
|
144
|
+
if (change.movePath) {
|
|
145
|
+
// Create parent directories for destination
|
|
146
|
+
const moveDir = path.dirname(change.movePath)
|
|
147
|
+
if (moveDir !== "." && moveDir !== "/") {
|
|
148
|
+
await fs.mkdir(moveDir, { recursive: true })
|
|
149
|
+
}
|
|
150
|
+
// Write to new location
|
|
151
|
+
await fs.writeFile(change.movePath, change.newContent, "utf-8")
|
|
152
|
+
// Remove original
|
|
153
|
+
await fs.unlink(change.filePath)
|
|
154
|
+
changedFiles.push(change.movePath)
|
|
155
|
+
}
|
|
156
|
+
break
|
|
157
|
+
|
|
158
|
+
case "delete":
|
|
159
|
+
await fs.unlink(change.filePath)
|
|
160
|
+
changedFiles.push(change.filePath)
|
|
161
|
+
break
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Update file time tracking
|
|
165
|
+
FileTime.read(ctx.sessionID, change.filePath)
|
|
166
|
+
if (change.movePath) {
|
|
167
|
+
FileTime.read(ctx.sessionID, change.movePath)
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Publish file change events
|
|
172
|
+
for (const filePath of changedFiles) {
|
|
173
|
+
await Bus.publish(FileWatcher.Event.Updated, { file: filePath, event: "change" })
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Generate output summary
|
|
177
|
+
const relativePaths = changedFiles.map((filePath) => path.relative(Instance.worktree, filePath))
|
|
178
|
+
const summary = `${fileChanges.length} files changed`
|
|
179
|
+
|
|
180
|
+
return {
|
|
181
|
+
title: summary,
|
|
182
|
+
metadata: {
|
|
183
|
+
diff: totalDiff,
|
|
184
|
+
},
|
|
185
|
+
output: `Patch applied successfully. ${summary}:\n${relativePaths.map((p) => ` ${p}`).join("\n")}`,
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
})
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
do not use
|