Repository navigation
Expand file tree
/
Copy pathtools_def.py
More file actions
executable file
·88 lines (76 loc) · 3.84 KB
/
Copy pathtools_def.py
File metadata and controls
executable file
·88 lines (76 loc) · 3.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""opencode 风格工具集:定义(OpenAI schema)+ 真实执行器
工具在沙盒工作区真实执行(read/bash/edit/write),路径限定 AGENT_ROOT 内防逃逸。
"""
from __future__ import annotations
import json
import os
import subprocess
AGENT_ROOT = os.getenv("AGENT_ROOT", "/sandbox/workspace/agent_ws")
TOOLS_SCHEMA = [
{"type": "function", "function": {
"name": "read", "description": "读取文件内容(UTF-8 文本)",
"parameters": {"type": "object", "properties": {
"path": {"type": "string", "description": "相对工作区的文件路径"}},
"required": ["path"]}}},
{"type": "function", "function": {
"name": "bash", "description": "在工作区目录执行 shell 命令并返回 stdout/stderr",
"parameters": {"type": "object", "properties": {
"command": {"type": "string", "description": "要执行的命令"}},
"required": ["command"]}}},
{"type": "function", "function": {
"name": "edit", "description": "精确替换编辑文件:old_text 必须与文件内容唯一匹配",
"parameters": {"type": "object", "properties": {
"path": {"type": "string"},
"old_text": {"type": "string", "description": "要替换的原文(必须唯一匹配)"},
"new_text": {"type": "string", "description": "替换后的内容"}},
"required": ["path", "old_text", "new_text"]}}},
{"type": "function", "function": {
"name": "write", "description": "写入(覆盖)文件",
"parameters": {"type": "object", "properties": {
"path": {"type": "string"}, "content": {"type": "string"}},
"required": ["path", "content"]}}},
]
def _safe(path: str) -> str:
"""路径限定在 AGENT_ROOT 内"""
p = os.path.realpath(os.path.join(AGENT_ROOT, path.lstrip("/")))
if not p.startswith(os.path.realpath(AGENT_ROOT)):
raise ValueError(f"路径越界: {path}")
return p
def execute_tool(name: str, arguments: str | dict) -> str:
"""执行工具,返回文本结果(作为 role=tool 消息内容)"""
try:
args = json.loads(arguments) if isinstance(arguments, str) else (arguments or {})
except json.JSONDecodeError as e:
return f"ERROR: arguments 不是合法 JSON: {e}"
try:
if name == "read":
p = _safe(args["path"])
with open(p, encoding="utf-8") as f:
return f.read()[:8000] or "(空文件)"
if name == "write":
p = _safe(args["path"])
os.makedirs(os.path.dirname(p) or AGENT_ROOT, exist_ok=True)
with open(p, "w", encoding="utf-8") as f:
f.write(args["content"])
return f"OK: 已写入 {args['path']} ({len(args['content'])} 字符)"
if name == "edit":
p = _safe(args["path"])
src = open(p, encoding="utf-8").read()
old, new = args["old_text"], args["new_text"]
n = src.count(old)
if n == 0:
return f"ERROR: old_text 在 {args['path']} 中未找到"
if n > 1:
return f"ERROR: old_text 匹配 {n} 处,需唯一"
open(p, "w", encoding="utf-8").write(src.replace(old, new, 1))
return f"OK: 已编辑 {args['path']}"
if name == "bash":
r = subprocess.run(args["command"], shell=True, cwd=AGENT_ROOT,
capture_output=True, text=True, timeout=30)
out = (r.stdout or "") + (f"\n[stderr]\n{r.stderr}" if r.stderr else "")
return f"exit={r.returncode}\n{out.strip()[:6000] or '(无输出)'}"
return f"ERROR: 未知工具 {name}"
except FileNotFoundError as e:
return f"ERROR: 文件不存在 {e}"
except Exception as e: # 模型可从错误中恢复
return f"ERROR: {type(e).__name__}: {e}"