txcode-sdk 0.1.0__py3-none-any.whl
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.
- txcode_sdk/__init__.py +49 -0
- txcode_sdk/agent/__init__.py +17 -0
- txcode_sdk/agent/base_agent.py +475 -0
- txcode_sdk/agent/chat/__init__.py +4 -0
- txcode_sdk/agent/chat/agent_tool.py +1 -0
- txcode_sdk/agent/chat/chat_agent.py +26 -0
- txcode_sdk/agent/chat/prompts/role.txt +31 -0
- txcode_sdk/agent/code/__init__.py +4 -0
- txcode_sdk/agent/code/agent_tool.py +1 -0
- txcode_sdk/agent/code/code_agent.py +26 -0
- txcode_sdk/agent/code/prompts/role.txt +51 -0
- txcode_sdk/agent/common/__init__.py +3 -0
- txcode_sdk/agent/common/common_agent.py +23 -0
- txcode_sdk/agent/common/prompt/role.txt +51 -0
- txcode_sdk/agent/mem/__init__.py +3 -0
- txcode_sdk/agent/mem/agent_tool.py +1 -0
- txcode_sdk/agent/mem/mem_agent.py +139 -0
- txcode_sdk/agent/mem/prompts/role.txt +36 -0
- txcode_sdk/agent/summarizer/__init__.py +3 -0
- txcode_sdk/agent/summarizer/prompts/role.txt +31 -0
- txcode_sdk/agent/summarizer/summarizer_agent.py +101 -0
- txcode_sdk/agent/task/__init__.py +4 -0
- txcode_sdk/agent/task/agent_tool.py +1 -0
- txcode_sdk/agent/task/prompts/role.txt +51 -0
- txcode_sdk/agent/task/task_agent.py +26 -0
- txcode_sdk/agent/tool_registry.py +119 -0
- txcode_sdk/client.py +215 -0
- txcode_sdk/compact/__init__.py +3 -0
- txcode_sdk/compact/compressor.py +74 -0
- txcode_sdk/hooks/__init__.py +19 -0
- txcode_sdk/hooks/handlers/__init__.py +4 -0
- txcode_sdk/hooks/handlers/base.py +19 -0
- txcode_sdk/hooks/handlers/memory.py +30 -0
- txcode_sdk/hooks/processor.py +19 -0
- txcode_sdk/hooks/queue.py +29 -0
- txcode_sdk/hooks/types.py +10 -0
- txcode_sdk/provider/__init__.py +6 -0
- txcode_sdk/provider/base.py +34 -0
- txcode_sdk/provider/deepseek_provider.py +60 -0
- txcode_sdk/provider/openai_provider.py +209 -0
- txcode_sdk/provider/router.py +13 -0
- txcode_sdk/session/__init__.py +3 -0
- txcode_sdk/session/manager.py +316 -0
- txcode_sdk/skills/__init__.py +43 -0
- txcode_sdk/specs/__init__.py +132 -0
- txcode_sdk/tools/__init__.py +3 -0
- txcode_sdk/tools/bash.txt +47 -0
- txcode_sdk/tools/bash_tool.py +79 -0
- txcode_sdk/tools/edit_file.py +141 -0
- txcode_sdk/tools/edit_file.txt +13 -0
- txcode_sdk/tools/glob.txt +12 -0
- txcode_sdk/tools/glob_tool.py +67 -0
- txcode_sdk/tools/grep.txt +14 -0
- txcode_sdk/tools/grep_tool.py +76 -0
- txcode_sdk/tools/memory_tool.py +78 -0
- txcode_sdk/tools/read_file.py +75 -0
- txcode_sdk/tools/read_file.txt +17 -0
- txcode_sdk/tools/write_file.py +43 -0
- txcode_sdk/tools/write_file.txt +11 -0
- txcode_sdk/types.py +158 -0
- txcode_sdk-0.1.0.dist-info/METADATA +58 -0
- txcode_sdk-0.1.0.dist-info/RECORD +64 -0
- txcode_sdk-0.1.0.dist-info/WHEEL +4 -0
- txcode_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SpecInjector:
|
|
7
|
+
def __init__(self):
|
|
8
|
+
self._project_specs_path: str | None = None
|
|
9
|
+
|
|
10
|
+
def set_project_path(self, project_path: str | None):
|
|
11
|
+
if project_path:
|
|
12
|
+
self._project_specs_path = str(Path(project_path) / ".txcode" / "specs")
|
|
13
|
+
else:
|
|
14
|
+
self._project_specs_path = None
|
|
15
|
+
|
|
16
|
+
def should_inject(self, message_count: int) -> bool:
|
|
17
|
+
return message_count == 0
|
|
18
|
+
|
|
19
|
+
def build_spec_injection(self) -> str:
|
|
20
|
+
specs = self._load_specs()
|
|
21
|
+
if not specs:
|
|
22
|
+
return ""
|
|
23
|
+
|
|
24
|
+
required = [s for s in specs if s.get("read_mode") == "required"]
|
|
25
|
+
optional = [s for s in specs if s.get("read_mode") != "required"]
|
|
26
|
+
|
|
27
|
+
if not required and not optional:
|
|
28
|
+
return ""
|
|
29
|
+
|
|
30
|
+
injection = "\n\n## 用户问题\n{{原始用户问题}}\n\n## 规范说明\n你来分析一下这个问题是否为一个开发任务,如果是开发任务你必须要先阅读规范,然后严格按照规范开发,如果不是开发任务可以选择不读"
|
|
31
|
+
|
|
32
|
+
if required:
|
|
33
|
+
injection += "\n\n### 必读规范\n<specs>"
|
|
34
|
+
for spec in required:
|
|
35
|
+
spec_path = f"{self._project_specs_path}/{spec['name']}/SPEC.md" if self._project_specs_path else spec.get("file_path", "")
|
|
36
|
+
injection += f"\n <spec>\n <name>{_escape_xml(spec['name'])}</name>\n <description>{_escape_xml(spec['description'])}</description>\n <path>{spec_path}</path>\n </spec>"
|
|
37
|
+
injection += "\n</specs>"
|
|
38
|
+
|
|
39
|
+
if optional:
|
|
40
|
+
injection += "\n\n### 选读规范\n<specs>"
|
|
41
|
+
for spec in optional:
|
|
42
|
+
spec_path = f"{self._project_specs_path}/{spec['name']}/SPEC.md" if self._project_specs_path else spec.get("file_path", "")
|
|
43
|
+
injection += f"\n <spec>\n <name>{_escape_xml(spec['name'])}</name>\n <description>{_escape_xml(spec['description'])}</description>\n <path>{spec_path}</path>\n </spec>"
|
|
44
|
+
injection += "\n</specs>"
|
|
45
|
+
|
|
46
|
+
return injection
|
|
47
|
+
|
|
48
|
+
def inject_into_message(self, message: str, project_path: str | None = None) -> str:
|
|
49
|
+
if project_path:
|
|
50
|
+
self.set_project_path(project_path)
|
|
51
|
+
injection = self.build_spec_injection()
|
|
52
|
+
if not injection:
|
|
53
|
+
return message
|
|
54
|
+
return injection.replace("{{原始用户问题}}", message)
|
|
55
|
+
|
|
56
|
+
def _load_specs(self) -> list[dict]:
|
|
57
|
+
specs: list[dict] = []
|
|
58
|
+
if not self._project_specs_path:
|
|
59
|
+
return specs
|
|
60
|
+
|
|
61
|
+
specs_dir = Path(self._project_specs_path)
|
|
62
|
+
if not specs_dir.exists():
|
|
63
|
+
return specs
|
|
64
|
+
|
|
65
|
+
for entry in sorted(specs_dir.iterdir()):
|
|
66
|
+
if entry.is_dir():
|
|
67
|
+
spec_md = entry / "SPEC.md"
|
|
68
|
+
if spec_md.exists():
|
|
69
|
+
spec = self._parse_spec(spec_md)
|
|
70
|
+
if spec:
|
|
71
|
+
specs.append(spec)
|
|
72
|
+
return specs
|
|
73
|
+
|
|
74
|
+
def _parse_spec(self, file_path: Path) -> dict | None:
|
|
75
|
+
try:
|
|
76
|
+
content = file_path.read_text("utf-8", errors="replace")
|
|
77
|
+
name = file_path.parent.name
|
|
78
|
+
description = ""
|
|
79
|
+
read_mode = "optional"
|
|
80
|
+
|
|
81
|
+
frontmatter_match = _match_frontmatter(content)
|
|
82
|
+
if frontmatter_match:
|
|
83
|
+
frontmatter_str = frontmatter_match[0]
|
|
84
|
+
raw_content = frontmatter_match[1].strip()
|
|
85
|
+
metadata = _parse_yaml_frontmatter(frontmatter_str)
|
|
86
|
+
if metadata:
|
|
87
|
+
name = metadata.get("name", name)
|
|
88
|
+
description = metadata.get("description", "")
|
|
89
|
+
read_mode = metadata.get("read_mode", "optional")
|
|
90
|
+
else:
|
|
91
|
+
raw_content = content
|
|
92
|
+
description = content.strip()[:200]
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
"name": name,
|
|
96
|
+
"description": description,
|
|
97
|
+
"read_mode": read_mode,
|
|
98
|
+
"content": content,
|
|
99
|
+
"raw_content": raw_content,
|
|
100
|
+
"file_path": str(file_path),
|
|
101
|
+
}
|
|
102
|
+
except Exception:
|
|
103
|
+
return None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _match_frontmatter(content: str) -> tuple[str, str] | None:
|
|
107
|
+
import re
|
|
108
|
+
m = re.match(r"^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$", content)
|
|
109
|
+
if m:
|
|
110
|
+
return (m.group(1), m.group(2))
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _parse_yaml_frontmatter(frontmatter_str: str) -> dict | None:
|
|
115
|
+
try:
|
|
116
|
+
result: dict = {}
|
|
117
|
+
for line in frontmatter_str.splitlines():
|
|
118
|
+
line = line.strip()
|
|
119
|
+
if not line or line.startswith("#"):
|
|
120
|
+
continue
|
|
121
|
+
if ":" in line:
|
|
122
|
+
key, _, value = line.partition(":")
|
|
123
|
+
key = key.strip()
|
|
124
|
+
value = value.strip().strip("'\"")
|
|
125
|
+
result[key] = value
|
|
126
|
+
return result if result else None
|
|
127
|
+
except Exception:
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _escape_xml(s: str) -> str:
|
|
132
|
+
return s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """).replace("'", "'")
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
### 工具bash
|
|
2
|
+
在持久化 shell 会话中执行 bash 命令,支持可选超时,确保正确的处理和安全措施。
|
|
3
|
+
|
|
4
|
+
所有命令默认在 ${directory} 执行。如需在其他目录运行命令,使用 `workdir` 参数。**禁止使用 `cd <目录> && <命令>` 模式**,应该使用 `workdir` 参数代替。
|
|
5
|
+
|
|
6
|
+
**重要**:此工具仅用于终端操作如 git、npm、docker 等。**禁止**用于文件操作(读取、写入、编辑、搜索文件)——请使用专用工具。
|
|
7
|
+
|
|
8
|
+
## 执行前验证
|
|
9
|
+
|
|
10
|
+
1. **目录验证**:
|
|
11
|
+
- 如果命令会创建新目录或文件,先用 `ls` 验证父目录存在
|
|
12
|
+
- 例如:运行 "mkdir foo/bar" 前,先用 `ls foo` 确认 "foo" 存在
|
|
13
|
+
|
|
14
|
+
2. **命令执行**:
|
|
15
|
+
- 包含空格的路径必须用双引号包裹
|
|
16
|
+
- 正确示例:`mkdir "/Users/name/My Documents"`
|
|
17
|
+
- 错误示例:`mkdir /Users/name/My Documents`(会失败)
|
|
18
|
+
- 确保正确引用后执行命令
|
|
19
|
+
|
|
20
|
+
## 使用说明
|
|
21
|
+
|
|
22
|
+
- `command` 参数是必需的
|
|
23
|
+
- 可选超时时间(毫秒),默认 120000ms(2分钟)
|
|
24
|
+
- 请用 5-10 个字写清楚命令作用的描述
|
|
25
|
+
- 如果输出超过 2000 行或 51200 字节,会被截断并保存到文件
|
|
26
|
+
- 可以用 Read 的 offset/limit 读取特定部分,或用 grep 搜索全部内容
|
|
27
|
+
- **禁止**使用 `head`、`tail` 等命令限制输出
|
|
28
|
+
|
|
29
|
+
**禁止使用 bash 执行以下操作**,请使用专用工具:
|
|
30
|
+
- 文件搜索:用 glob(不用 find 或 ls)
|
|
31
|
+
- 内容搜索:用 grep(不用 grep 或 rg)
|
|
32
|
+
- 读取文件:用 read_file(不用 cat/head/tail)
|
|
33
|
+
- 编辑文件:用 edit_file(不用 sed/awk)
|
|
34
|
+
- 写入文件:用 write_file(不用 echo >/cat <<EOF)
|
|
35
|
+
- 输出文本:直接输出(不用 echo/printf)
|
|
36
|
+
|
|
37
|
+
**多命令执行**:
|
|
38
|
+
- 独立命令可以并行执行多个 Bash 调用
|
|
39
|
+
- 顺序依赖的命令用 `&&` 链接(如 `git add . && git commit -m "message" && git push`)
|
|
40
|
+
- 不关心前置结果时用 `;` 分隔
|
|
41
|
+
- **禁止**使用换行符分隔命令(在引号字符串中除外)
|
|
42
|
+
|
|
43
|
+
**注意事项**:
|
|
44
|
+
- 禁止使用交互式 git 命令(如 `git rebase -i` 或 `git add -i`)
|
|
45
|
+
- 除非用户明确要求,不要推送到远程
|
|
46
|
+
- 没有变更时不创建空提交
|
|
47
|
+
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from importlib.resources import files
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from ..types import Tool, ToolContext, ToolResult
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _bash_tool_desc() -> str:
|
|
11
|
+
return files("txcode_sdk.tools").joinpath("bash.txt").read_text("utf-8")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
MAX_BYTES = 50 * 1024
|
|
15
|
+
MAX_LINES = 2000
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def _bash(params: dict, ctx: ToolContext) -> ToolResult:
|
|
19
|
+
command = params.get("command", "")
|
|
20
|
+
workdir = params.get("workdir", ctx.work_dir)
|
|
21
|
+
timeout = params.get("timeout", 120000) / 1000
|
|
22
|
+
|
|
23
|
+
if not command.strip():
|
|
24
|
+
return ToolResult(success=False, output="", error="Empty command")
|
|
25
|
+
|
|
26
|
+
work_path = Path(workdir)
|
|
27
|
+
if not work_path.is_absolute():
|
|
28
|
+
work_path = Path(ctx.work_dir) / work_path
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
proc = await asyncio.create_subprocess_shell(
|
|
32
|
+
command,
|
|
33
|
+
stdout=asyncio.subprocess.PIPE,
|
|
34
|
+
stderr=asyncio.subprocess.STDOUT,
|
|
35
|
+
cwd=str(work_path),
|
|
36
|
+
)
|
|
37
|
+
stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
|
38
|
+
raw = stdout.decode("utf-8", errors="replace")
|
|
39
|
+
|
|
40
|
+
lines = raw.splitlines()
|
|
41
|
+
truncated = False
|
|
42
|
+
if len(lines) > MAX_LINES:
|
|
43
|
+
lines = lines[:MAX_LINES]
|
|
44
|
+
raw = "\n".join(lines)
|
|
45
|
+
truncated = True
|
|
46
|
+
if len(raw.encode("utf-8")) > MAX_BYTES:
|
|
47
|
+
raw = raw.encode("utf-8")[:MAX_BYTES].decode("utf-8", errors="replace")
|
|
48
|
+
truncated = True
|
|
49
|
+
|
|
50
|
+
output = raw
|
|
51
|
+
if truncated:
|
|
52
|
+
output += f"\n\n[Output truncated: exceeded {MAX_LINES} lines or {MAX_BYTES} bytes]"
|
|
53
|
+
|
|
54
|
+
return ToolResult(
|
|
55
|
+
success=proc.returncode == 0,
|
|
56
|
+
output=output,
|
|
57
|
+
error=None if proc.returncode == 0 else f"Exit code: {proc.returncode}",
|
|
58
|
+
metadata={"exit_code": proc.returncode},
|
|
59
|
+
)
|
|
60
|
+
except asyncio.TimeoutError:
|
|
61
|
+
return ToolResult(success=False, output="", error=f"Command timed out after {timeout}s")
|
|
62
|
+
except Exception as e:
|
|
63
|
+
return ToolResult(success=False, output="", error=str(e))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
bash_tool = Tool(
|
|
67
|
+
name="bash",
|
|
68
|
+
description=_bash_tool_desc(),
|
|
69
|
+
parameters={
|
|
70
|
+
"type": "object",
|
|
71
|
+
"properties": {
|
|
72
|
+
"command": {"type": "string", "description": "要执行的命令"},
|
|
73
|
+
"workdir": {"type": "string", "description": "工作目录"},
|
|
74
|
+
"timeout": {"type": "integer", "description": "超时时间,毫秒,默认120000"},
|
|
75
|
+
},
|
|
76
|
+
"required": ["command"],
|
|
77
|
+
},
|
|
78
|
+
execute=_bash,
|
|
79
|
+
)
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from importlib.resources import files
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from ..types import Tool, ToolContext, ToolResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _edit_tool_desc() -> str:
|
|
10
|
+
return files("txcode_sdk.tools").joinpath("edit_file.txt").read_text("utf-8")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _match_old_string(content: str, old_string: str) -> list[int]:
|
|
14
|
+
positions: list[int] = []
|
|
15
|
+
start = 0
|
|
16
|
+
while True:
|
|
17
|
+
idx = content.find(old_string, start)
|
|
18
|
+
if idx == -1:
|
|
19
|
+
break
|
|
20
|
+
positions.append(idx)
|
|
21
|
+
start = idx + 1
|
|
22
|
+
return positions
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _try_stripped_match(content: str, old_string: str) -> list[int]:
|
|
26
|
+
old_lines = old_string.splitlines()
|
|
27
|
+
content_lines = content.splitlines()
|
|
28
|
+
old_stripped = [l.rstrip() for l in old_lines]
|
|
29
|
+
content_stripped = [l.rstrip() for l in content_lines]
|
|
30
|
+
|
|
31
|
+
positions: list[int] = []
|
|
32
|
+
for i in range(len(content_stripped) - len(old_stripped) + 1):
|
|
33
|
+
match = True
|
|
34
|
+
for j in range(len(old_stripped)):
|
|
35
|
+
if content_stripped[i + j] != old_stripped[j]:
|
|
36
|
+
match = False
|
|
37
|
+
break
|
|
38
|
+
if match:
|
|
39
|
+
pos = sum(len(l) + 1 for l in content_lines[:i])
|
|
40
|
+
positions.append(pos)
|
|
41
|
+
return positions
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _try_indentation_flexible_match(content: str, old_string: str) -> list[int]:
|
|
45
|
+
old_lines = old_string.splitlines()
|
|
46
|
+
content_lines = content.splitlines()
|
|
47
|
+
old_stripped = [l.strip() for l in old_lines]
|
|
48
|
+
content_stripped = [l.strip() for l in content_lines]
|
|
49
|
+
|
|
50
|
+
positions: list[int] = []
|
|
51
|
+
for i in range(len(content_stripped) - len(old_stripped) + 1):
|
|
52
|
+
match = True
|
|
53
|
+
for j in range(len(old_stripped)):
|
|
54
|
+
if content_stripped[i + j] != old_stripped[j]:
|
|
55
|
+
match = False
|
|
56
|
+
break
|
|
57
|
+
if match:
|
|
58
|
+
pos = sum(len(l) + 1 for l in content_lines[:i])
|
|
59
|
+
positions.append(pos)
|
|
60
|
+
return positions
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _try_whitespace_normalized_match(content: str, old_string: str) -> list[int]:
|
|
64
|
+
def _normalize(s: str) -> str:
|
|
65
|
+
return " ".join(s.split())
|
|
66
|
+
|
|
67
|
+
old_norm = _normalize(old_string)
|
|
68
|
+
content_norm = _normalize(content)
|
|
69
|
+
|
|
70
|
+
positions: list[int] = []
|
|
71
|
+
if old_norm not in content_norm:
|
|
72
|
+
return positions
|
|
73
|
+
|
|
74
|
+
idx = content_norm.find(old_norm)
|
|
75
|
+
while idx != -1:
|
|
76
|
+
positions.append(idx)
|
|
77
|
+
idx = content_norm.find(old_norm, idx + 1)
|
|
78
|
+
|
|
79
|
+
return positions
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
async def _edit_file(params: dict, ctx: ToolContext) -> ToolResult:
|
|
83
|
+
file_path = Path(params.get("file_path", ""))
|
|
84
|
+
if not file_path.is_absolute():
|
|
85
|
+
file_path = Path(ctx.work_dir) / file_path
|
|
86
|
+
|
|
87
|
+
old_string = params.get("old_string", "")
|
|
88
|
+
new_string = params.get("new_string", "")
|
|
89
|
+
replace_all = params.get("replace_all", False)
|
|
90
|
+
|
|
91
|
+
if not file_path.exists():
|
|
92
|
+
return ToolResult(success=False, output="", error=f"File not found: {file_path}")
|
|
93
|
+
|
|
94
|
+
try:
|
|
95
|
+
content = file_path.read_text(encoding="utf-8")
|
|
96
|
+
except Exception as e:
|
|
97
|
+
return ToolResult(success=False, output="", error=str(e))
|
|
98
|
+
|
|
99
|
+
if replace_all:
|
|
100
|
+
if old_string not in content:
|
|
101
|
+
return ToolResult(success=False, output="", error="old_string not found in file")
|
|
102
|
+
count = content.count(old_string)
|
|
103
|
+
new_content = content.replace(old_string, new_string)
|
|
104
|
+
file_path.write_text(new_content, encoding="utf-8")
|
|
105
|
+
return ToolResult(success=True, output=f"Replaced {count} occurrence(s) in {file_path}")
|
|
106
|
+
else:
|
|
107
|
+
positions = _match_old_string(content, old_string)
|
|
108
|
+
if len(positions) == 0:
|
|
109
|
+
positions = _try_stripped_match(content, old_string)
|
|
110
|
+
if len(positions) == 0:
|
|
111
|
+
positions = _try_indentation_flexible_match(content, old_string)
|
|
112
|
+
if len(positions) == 0:
|
|
113
|
+
positions = _try_whitespace_normalized_match(content, old_string)
|
|
114
|
+
if len(positions) == 0:
|
|
115
|
+
return ToolResult(success=False, output="", error="old_string not found in file")
|
|
116
|
+
if len(positions) > 1:
|
|
117
|
+
return ToolResult(
|
|
118
|
+
success=False,
|
|
119
|
+
output="",
|
|
120
|
+
error=f"old_string found {len(positions)} times, please provide more context to make it unique",
|
|
121
|
+
)
|
|
122
|
+
new_content = content[: positions[0]] + new_string + content[positions[0] + len(old_string) :]
|
|
123
|
+
file_path.write_text(new_content, encoding="utf-8")
|
|
124
|
+
return ToolResult(success=True, output=f"File edited: {file_path}")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
edit_file_tool = Tool(
|
|
128
|
+
name="edit_file",
|
|
129
|
+
description=_edit_tool_desc(),
|
|
130
|
+
parameters={
|
|
131
|
+
"type": "object",
|
|
132
|
+
"properties": {
|
|
133
|
+
"file_path": {"type": "string", "description": "文件绝对路径"},
|
|
134
|
+
"old_string": {"type": "string", "description": "要被替换的内容"},
|
|
135
|
+
"new_string": {"type": "string", "description": "替换后的新内容"},
|
|
136
|
+
"replace_all": {"type": "boolean", "description": "是否替换所有匹配项"},
|
|
137
|
+
},
|
|
138
|
+
"required": ["file_path", "old_string", "new_string"],
|
|
139
|
+
},
|
|
140
|
+
execute=_edit_file,
|
|
141
|
+
)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
### 工具edit_file
|
|
2
|
+
对文件执行精确的字符串替换。当文件已经存在时,应该直接调用edit_file工具修改,而不是删除后重新新建,除非客户要求。
|
|
3
|
+
|
|
4
|
+
**功能**:
|
|
5
|
+
- 在编辑前,**必须**至少使用过一次 Read 工具。未读取文件就编辑会报错
|
|
6
|
+
- 从 Read 工具输出编辑文本时,确保保留精确的缩进(空格/制表符)。行号前缀格式是:行号 + 冒号 + 空格(如 `1: `)。`old_string` 和 `new_string` 中**禁止**包含行号前缀的任何部分
|
|
7
|
+
- **优先**编辑现有文件,**禁止**创建新文件除非明确需要
|
|
8
|
+
- 只有用户明确要求时才使用表情符号
|
|
9
|
+
- 如果 `old_string` 在文件中找不到会**失败**
|
|
10
|
+
- 如果 `old_string` 在文件中出现多次会**失败**,可以提供更多上下文使其唯一,或使用 `replace_all` 替换所有匹配项
|
|
11
|
+
- `replace_all` 用于在整个文件中替换和重命名字符串
|
|
12
|
+
|
|
13
|
+
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import glob as _glob_module
|
|
4
|
+
import os
|
|
5
|
+
from importlib.resources import files
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from ..types import Tool, ToolContext, ToolResult
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _glob_tool_desc() -> str:
|
|
12
|
+
return files("txcode_sdk.tools").joinpath("glob.txt").read_text("utf-8")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
IGNORE_DIRS = {"node_modules", ".git", "dist", "build", "__pycache__", ".tox", ".eggs", "*.egg-info", ".mypy_cache", ".pytest_cache", ".ruff_cache", ".venv", "venv", ".txcode"}
|
|
16
|
+
|
|
17
|
+
MAX_RESULTS = 100
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def _glob(params: dict, ctx: ToolContext) -> ToolResult:
|
|
21
|
+
pattern = params.get("pattern", "**/*")
|
|
22
|
+
directory = params.get("directory", ctx.work_dir)
|
|
23
|
+
|
|
24
|
+
base_path = Path(directory)
|
|
25
|
+
if not base_path.is_absolute():
|
|
26
|
+
base_path = Path(ctx.work_dir) / base_path
|
|
27
|
+
|
|
28
|
+
search_pattern = str(base_path / pattern)
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
matches = _glob_module.glob(search_pattern, recursive=True)
|
|
32
|
+
except Exception as e:
|
|
33
|
+
return ToolResult(success=False, output="", error=str(e))
|
|
34
|
+
|
|
35
|
+
filtered: list[str] = []
|
|
36
|
+
for p in matches:
|
|
37
|
+
parts = set(Path(p).parts)
|
|
38
|
+
if parts & IGNORE_DIRS:
|
|
39
|
+
continue
|
|
40
|
+
filtered.append(p)
|
|
41
|
+
|
|
42
|
+
matches_sorted = sorted(filtered, key=lambda p: os.path.getmtime(p), reverse=True)
|
|
43
|
+
|
|
44
|
+
total = len(matches_sorted)
|
|
45
|
+
truncated = total > MAX_RESULTS
|
|
46
|
+
matches_sorted = matches_sorted[:MAX_RESULTS]
|
|
47
|
+
|
|
48
|
+
output = "\n".join(matches_sorted)
|
|
49
|
+
if truncated:
|
|
50
|
+
output += f"\n\n[Results truncated: showing {MAX_RESULTS} of {total} matches]"
|
|
51
|
+
|
|
52
|
+
return ToolResult(success=True, output=output, metadata={"count": total})
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
glob_tool = Tool(
|
|
56
|
+
name="glob",
|
|
57
|
+
description=_glob_tool_desc(),
|
|
58
|
+
parameters={
|
|
59
|
+
"type": "object",
|
|
60
|
+
"properties": {
|
|
61
|
+
"pattern": {"type": "string", "description": "glob 模式,如 '**/*.py'"},
|
|
62
|
+
"directory": {"type": "string", "description": "搜索目录的绝对路径"},
|
|
63
|
+
},
|
|
64
|
+
"required": ["pattern"],
|
|
65
|
+
},
|
|
66
|
+
execute=_glob,
|
|
67
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
### 工具grep
|
|
2
|
+
快速的内容搜索工具,适用于任何规模的代码库。
|
|
3
|
+
|
|
4
|
+
**功能**:
|
|
5
|
+
- 使用正则表达式搜索文件内容
|
|
6
|
+
- 支持完整正则语法(如 "log.*Error", "function\s+\w+" 等)
|
|
7
|
+
- 用 `include` 参数按文件模式过滤(如 "*.js", "*.{ts,tsx}")
|
|
8
|
+
- 返回有匹配的文件路径和行号,按修改时间排序
|
|
9
|
+
- 当你需要查找包含特定模式的文件时使用此工具
|
|
10
|
+
|
|
11
|
+
**注意**:
|
|
12
|
+
- 如果需要识别/统计文件中的匹配数量,直接用 Bash 工具运行 `rg` (ripgrep),**不要**用 Grep
|
|
13
|
+
- 当你需要可能需要多轮搜索的开放式搜索时,使用 Task 工具
|
|
14
|
+
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
from importlib.resources import files
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from ..types import Tool, ToolContext, ToolResult
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _grep_tool_desc() -> str:
|
|
12
|
+
return files("txcode_sdk.tools").joinpath("grep.txt").read_text("utf-8")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
async def _grep(params: dict, ctx: ToolContext) -> ToolResult:
|
|
16
|
+
pattern = params.get("pattern", "")
|
|
17
|
+
directory = params.get("directory", ctx.work_dir)
|
|
18
|
+
include = params.get("include", None)
|
|
19
|
+
|
|
20
|
+
base_path = Path(directory)
|
|
21
|
+
if not base_path.is_absolute():
|
|
22
|
+
base_path = Path(ctx.work_dir) / base_path
|
|
23
|
+
|
|
24
|
+
if not base_path.exists():
|
|
25
|
+
return ToolResult(success=False, output="", error=f"Directory not found: {base_path}")
|
|
26
|
+
|
|
27
|
+
try:
|
|
28
|
+
regex = re.compile(pattern)
|
|
29
|
+
except re.error as e:
|
|
30
|
+
return ToolResult(success=False, output="", error=f"Invalid regex: {e}")
|
|
31
|
+
|
|
32
|
+
results: list[str] = []
|
|
33
|
+
|
|
34
|
+
for root, dirs, files in os.walk(str(base_path)):
|
|
35
|
+
for name in dirs:
|
|
36
|
+
if name.startswith("."):
|
|
37
|
+
dirs.remove(name)
|
|
38
|
+
for filename in files:
|
|
39
|
+
if include:
|
|
40
|
+
if include.startswith("*."):
|
|
41
|
+
ext = include[1:]
|
|
42
|
+
if not filename.endswith(ext):
|
|
43
|
+
continue
|
|
44
|
+
else:
|
|
45
|
+
if not re.match(include.replace("*", ".*").replace("?", "."), filename):
|
|
46
|
+
continue
|
|
47
|
+
|
|
48
|
+
file_path = Path(root) / filename
|
|
49
|
+
try:
|
|
50
|
+
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
|
|
51
|
+
for line_no, line in enumerate(f, 1):
|
|
52
|
+
if regex.search(line):
|
|
53
|
+
results.append(f"{file_path}:{line_no}: {line.rstrip()}")
|
|
54
|
+
except Exception:
|
|
55
|
+
continue
|
|
56
|
+
|
|
57
|
+
output = "\n".join(results[:100])
|
|
58
|
+
if len(results) > 100:
|
|
59
|
+
output += f"\n\n[Results truncated: showing 100 of {len(results)} matches]"
|
|
60
|
+
return ToolResult(success=True, output=output or "(no matches)", metadata={"count": len(results)})
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
grep_tool = Tool(
|
|
64
|
+
name="grep",
|
|
65
|
+
description=_grep_tool_desc(),
|
|
66
|
+
parameters={
|
|
67
|
+
"type": "object",
|
|
68
|
+
"properties": {
|
|
69
|
+
"pattern": {"type": "string", "description": "正则表达式模式"},
|
|
70
|
+
"directory": {"type": "string", "description": "搜索目录"},
|
|
71
|
+
"include": {"type": "string", "description": "文件模式过滤,如 '*.py'"},
|
|
72
|
+
},
|
|
73
|
+
"required": ["pattern"],
|
|
74
|
+
},
|
|
75
|
+
execute=_grep,
|
|
76
|
+
)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from ..types import Tool, ToolContext, ToolResult
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _get_memory_path(work_dir: str) -> Path:
|
|
9
|
+
return Path(work_dir) / ".txcode" / "memory" / "MEMORY.md"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _read_memory(work_dir: str) -> str:
|
|
13
|
+
path = _get_memory_path(work_dir)
|
|
14
|
+
if path.exists():
|
|
15
|
+
return path.read_text("utf-8", errors="replace")
|
|
16
|
+
return ""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _write_memory(work_dir: str, content: str) -> ToolResult:
|
|
20
|
+
path = _get_memory_path(work_dir)
|
|
21
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
22
|
+
path.write_text(content, "utf-8")
|
|
23
|
+
return ToolResult(success=True, output="Memory saved successfully.")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def memory_execute(args: dict, context: ToolContext) -> ToolResult:
|
|
27
|
+
action = args.get("action", "read")
|
|
28
|
+
work_dir = context.work_dir
|
|
29
|
+
|
|
30
|
+
if action == "read":
|
|
31
|
+
content = _read_memory(work_dir)
|
|
32
|
+
if content.strip():
|
|
33
|
+
return ToolResult(success=True, output=content)
|
|
34
|
+
return ToolResult(success=True, output="(No memories recorded yet)")
|
|
35
|
+
|
|
36
|
+
if action == "add":
|
|
37
|
+
entry = args.get("content", "")
|
|
38
|
+
if not entry.strip():
|
|
39
|
+
return ToolResult(success=False, output="", error="No content provided for memory entry.")
|
|
40
|
+
|
|
41
|
+
existing = _read_memory(work_dir)
|
|
42
|
+
new_content = _format_memory_entry(existing, entry)
|
|
43
|
+
return _write_memory(work_dir, new_content)
|
|
44
|
+
|
|
45
|
+
if action == "replace":
|
|
46
|
+
content = args.get("content", "")
|
|
47
|
+
return _write_memory(work_dir, content)
|
|
48
|
+
|
|
49
|
+
return ToolResult(success=False, output="", error=f"Unknown action: {action}")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _format_memory_entry(existing: str, new_entry: str) -> str:
|
|
53
|
+
clean_entry = new_entry.strip()
|
|
54
|
+
if not existing.strip():
|
|
55
|
+
return f"# 记忆条目 1\n\n{clean_entry}"
|
|
56
|
+
return existing.rstrip() + f"\n\n---\n\n{clean_entry}"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
memory_tool = Tool(
|
|
60
|
+
name="memory",
|
|
61
|
+
description="Manage persistent memory. Use 'read' to view all memories, 'add' to append a new memory entry (entries are separated by '---'), 'replace' to overwrite all memories.",
|
|
62
|
+
parameters={
|
|
63
|
+
"type": "object",
|
|
64
|
+
"properties": {
|
|
65
|
+
"action": {
|
|
66
|
+
"type": "string",
|
|
67
|
+
"enum": ["read", "add", "replace"],
|
|
68
|
+
"description": "Action: read to view, add to append, replace to overwrite",
|
|
69
|
+
},
|
|
70
|
+
"content": {
|
|
71
|
+
"type": "string",
|
|
72
|
+
"description": "Memory content (required for add/replace actions)",
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
"required": ["action"],
|
|
76
|
+
},
|
|
77
|
+
execute=memory_execute,
|
|
78
|
+
)
|