aether-agent-framework 1.3.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.
- aether/__init__.py +9 -0
- aether/__main__.py +4 -0
- aether/agent.py +222 -0
- aether/cli.py +118 -0
- aether/config.py +98 -0
- aether/llm.py +227 -0
- aether/memory.py +45 -0
- aether/planner.py +31 -0
- aether/tools/__init__.py +101 -0
- aether/tools/base.py +72 -0
- aether/tools/data.py +199 -0
- aether/tools/delegate.py +163 -0
- aether/tools/files.py +150 -0
- aether/tools/knowledge.py +247 -0
- aether/tools/loader.py +85 -0
- aether/tools/net.py +141 -0
- aether/tools/productivity.py +250 -0
- aether/tools/python_exec.py +59 -0
- aether/tools/shell.py +121 -0
- aether/tools/web.py +113 -0
- aether/web/__init__.py +18 -0
- aether/web/__main__.py +62 -0
- aether/web/server.py +321 -0
- aether/web/static/index.html +470 -0
- aether_agent_framework-1.3.0.dist-info/METADATA +254 -0
- aether_agent_framework-1.3.0.dist-info/RECORD +30 -0
- aether_agent_framework-1.3.0.dist-info/WHEEL +5 -0
- aether_agent_framework-1.3.0.dist-info/entry_points.txt +3 -0
- aether_agent_framework-1.3.0.dist-info/licenses/LICENSE +21 -0
- aether_agent_framework-1.3.0.dist-info/top_level.txt +1 -0
aether/tools/files.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""File tools, sandboxed to the workspace directory."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from .base import Tool
|
|
8
|
+
|
|
9
|
+
IGNORE_PARTS = {
|
|
10
|
+
".git", "__pycache__", "node_modules", ".venv", "venv",
|
|
11
|
+
".aether", ".idea", ".vscode",
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _looks_binary(chunk: bytes) -> bool:
|
|
16
|
+
return b"\0" in chunk
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _WorkspaceTool(Tool):
|
|
20
|
+
def __init__(self, workspace: Path, allow_outside: bool = False):
|
|
21
|
+
self.workspace = Path(workspace).resolve()
|
|
22
|
+
self.allow_outside = allow_outside
|
|
23
|
+
|
|
24
|
+
def _resolve(self, raw: str) -> Path:
|
|
25
|
+
p = Path(raw).expanduser()
|
|
26
|
+
if not p.is_absolute():
|
|
27
|
+
p = self.workspace / p
|
|
28
|
+
p = p.resolve()
|
|
29
|
+
if not self.allow_outside and not p.is_relative_to(self.workspace):
|
|
30
|
+
raise ValueError(
|
|
31
|
+
f"Path '{raw}' is outside the workspace ({self.workspace}). "
|
|
32
|
+
"Use paths inside the workspace."
|
|
33
|
+
)
|
|
34
|
+
return p
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ReadFile(_WorkspaceTool):
|
|
38
|
+
name = "read_file"
|
|
39
|
+
description = "Read a text file. Optionally limit to a line range."
|
|
40
|
+
parameters = {
|
|
41
|
+
"type": "object",
|
|
42
|
+
"properties": {
|
|
43
|
+
"path": {"type": "string"},
|
|
44
|
+
"start_line": {"type": "integer"},
|
|
45
|
+
"end_line": {"type": "integer"},
|
|
46
|
+
},
|
|
47
|
+
"required": ["path"],
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
def run(self, args: dict) -> str:
|
|
51
|
+
path = self._resolve(str(args["path"]))
|
|
52
|
+
if not path.exists():
|
|
53
|
+
return f"ERROR: {path} does not exist."
|
|
54
|
+
data = path.read_bytes()[:1_000_000]
|
|
55
|
+
if _looks_binary(data[:2048]):
|
|
56
|
+
return f"ERROR: {path} looks binary ({path.stat().st_size} bytes); not reading."
|
|
57
|
+
text = data.decode("utf-8", errors="replace")
|
|
58
|
+
lines = text.splitlines()
|
|
59
|
+
start = max(int(args.get("start_line") or 1), 1)
|
|
60
|
+
end = int(args.get("end_line") or len(lines))
|
|
61
|
+
window = lines[start - 1 : end]
|
|
62
|
+
numbered = [f"{start + i:5d}| {ln}" for i, ln in enumerate(window)]
|
|
63
|
+
return f"{path} ({len(lines)} lines)\n" + "\n".join(numbered)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class WriteFile(_WorkspaceTool):
|
|
67
|
+
name = "write_file"
|
|
68
|
+
description = (
|
|
69
|
+
"Create or overwrite a file with the given content. "
|
|
70
|
+
"Parent directories are created automatically."
|
|
71
|
+
)
|
|
72
|
+
parameters = {
|
|
73
|
+
"type": "object",
|
|
74
|
+
"properties": {
|
|
75
|
+
"path": {"type": "string"},
|
|
76
|
+
"content": {"type": "string"},
|
|
77
|
+
},
|
|
78
|
+
"required": ["path", "content"],
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
def run(self, args: dict) -> str:
|
|
82
|
+
path = self._resolve(str(args["path"]))
|
|
83
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
84
|
+
path.write_text(str(args.get("content", "")), encoding="utf-8")
|
|
85
|
+
return f"Wrote {path} ({path.stat().st_size} bytes)."
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class EditFile(_WorkspaceTool):
|
|
89
|
+
name = "edit_file"
|
|
90
|
+
description = (
|
|
91
|
+
"Replace an exact snippet in a file. old_text must appear exactly once; "
|
|
92
|
+
"include enough surrounding context to make it unique."
|
|
93
|
+
)
|
|
94
|
+
parameters = {
|
|
95
|
+
"type": "object",
|
|
96
|
+
"properties": {
|
|
97
|
+
"path": {"type": "string"},
|
|
98
|
+
"old_text": {"type": "string"},
|
|
99
|
+
"new_text": {"type": "string"},
|
|
100
|
+
},
|
|
101
|
+
"required": ["path", "old_text", "new_text"],
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
def run(self, args: dict) -> str:
|
|
105
|
+
path = self._resolve(str(args["path"]))
|
|
106
|
+
if not path.exists():
|
|
107
|
+
return f"ERROR: {path} does not exist."
|
|
108
|
+
text = path.read_text(encoding="utf-8")
|
|
109
|
+
old = str(args["old_text"])
|
|
110
|
+
new = str(args["new_text"])
|
|
111
|
+
count = text.count(old)
|
|
112
|
+
if count == 0:
|
|
113
|
+
return "ERROR: old_text not found (check whitespace and indentation)."
|
|
114
|
+
if count > 1:
|
|
115
|
+
return f"ERROR: old_text appears {count} times; make it unique or use write_file."
|
|
116
|
+
path.write_text(text.replace(old, new, 1), encoding="utf-8")
|
|
117
|
+
return f"Edited {path}."
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class ListDir(_WorkspaceTool):
|
|
121
|
+
name = "list_dir"
|
|
122
|
+
description = "List files and folders under a path (defaults to the workspace root)."
|
|
123
|
+
parameters = {
|
|
124
|
+
"type": "object",
|
|
125
|
+
"properties": {
|
|
126
|
+
"path": {"type": "string"},
|
|
127
|
+
"depth": {"type": "integer", "description": "Recursion depth (default 2, max 5)."},
|
|
128
|
+
},
|
|
129
|
+
"required": [],
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
def run(self, args: dict) -> str:
|
|
133
|
+
root = self._resolve(str(args.get("path") or "."))
|
|
134
|
+
if not root.exists():
|
|
135
|
+
return f"ERROR: {root} does not exist."
|
|
136
|
+
depth = min(int(args.get("depth") or 2), 5)
|
|
137
|
+
out: list[str] = []
|
|
138
|
+
for path in sorted(root.rglob("*")):
|
|
139
|
+
rel = path.relative_to(root)
|
|
140
|
+
if any(part in IGNORE_PARTS for part in rel.parts):
|
|
141
|
+
continue
|
|
142
|
+
if len(rel.parts) > depth:
|
|
143
|
+
continue
|
|
144
|
+
kind = "dir " if path.is_dir() else "file"
|
|
145
|
+
size = f" ({path.stat().st_size}B)" if path.is_file() else "/"
|
|
146
|
+
out.append(f"{kind} {rel}{size}")
|
|
147
|
+
if len(out) >= 500:
|
|
148
|
+
out.append("... [listing truncated]")
|
|
149
|
+
break
|
|
150
|
+
return "\n".join(out) or "(empty)"
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Keyless knowledge sources: Wikipedia, arXiv and GitHub public APIs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import xml.etree.ElementTree as ET
|
|
7
|
+
from urllib.parse import quote
|
|
8
|
+
|
|
9
|
+
import requests
|
|
10
|
+
|
|
11
|
+
from .base import Tool
|
|
12
|
+
from .web import HEADERS
|
|
13
|
+
|
|
14
|
+
# Wikimedia's robot policy asks automated clients for a descriptive User-Agent.
|
|
15
|
+
WIKI_HEADERS = {
|
|
16
|
+
**HEADERS,
|
|
17
|
+
"User-Agent": "AetherAgent/1.0 (autonomous agent framework; +https://github.com/Atikur-rahman-ar/Localrepo)",
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class SearchWikipedia(Tool):
|
|
22
|
+
name = "search_wikipedia"
|
|
23
|
+
description = (
|
|
24
|
+
"Search Wikipedia for article titles, snippets and URLs. "
|
|
25
|
+
"Set full_page=true to also pull the plain-text article extract of "
|
|
26
|
+
"the top hit. No API key."
|
|
27
|
+
)
|
|
28
|
+
parameters = {
|
|
29
|
+
"type": "object",
|
|
30
|
+
"properties": {
|
|
31
|
+
"query": {"type": "string"},
|
|
32
|
+
"language": {
|
|
33
|
+
"type": "string",
|
|
34
|
+
"description": "Wikipedia language code (default 'en', e.g. 'de', 'bn', 'zh').",
|
|
35
|
+
},
|
|
36
|
+
"full_page": {
|
|
37
|
+
"type": "boolean",
|
|
38
|
+
"description": "Also return the extracted plain text of the top result (default false).",
|
|
39
|
+
},
|
|
40
|
+
"max_results": {"type": "integer", "description": "Default 5, max 10."},
|
|
41
|
+
},
|
|
42
|
+
"required": ["query"],
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
def run(self, args: dict) -> str:
|
|
46
|
+
query = str(args.get("query", "")).strip()
|
|
47
|
+
if not query:
|
|
48
|
+
return "ERROR: 'query' is required."
|
|
49
|
+
lang = re.sub(r"[^a-z-]", "", str(args.get("language") or "en").lower()) or "en"
|
|
50
|
+
limit = min(int(args.get("max_results") or 5), 10)
|
|
51
|
+
api = f"https://{lang}.wikipedia.org/w/api.php"
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
resp = requests.get(
|
|
55
|
+
api,
|
|
56
|
+
params={
|
|
57
|
+
"action": "query",
|
|
58
|
+
"list": "search",
|
|
59
|
+
"srsearch": query,
|
|
60
|
+
"srlimit": limit,
|
|
61
|
+
"format": "json",
|
|
62
|
+
},
|
|
63
|
+
headers=WIKI_HEADERS,
|
|
64
|
+
timeout=30,
|
|
65
|
+
)
|
|
66
|
+
except requests.RequestException as exc:
|
|
67
|
+
return f"ERROR: Wikipedia search failed: {exc}"
|
|
68
|
+
|
|
69
|
+
if resp.status_code == 429:
|
|
70
|
+
return (
|
|
71
|
+
"ERROR: Wikipedia is throttling automated requests from this "
|
|
72
|
+
"network. Wait a minute and retry, or use web_search/fetch_url."
|
|
73
|
+
)
|
|
74
|
+
if not resp.ok:
|
|
75
|
+
return f"ERROR: Wikipedia API returned HTTP {resp.status_code}."
|
|
76
|
+
|
|
77
|
+
hits = resp.json().get("query", {}).get("search", [])
|
|
78
|
+
|
|
79
|
+
if not hits:
|
|
80
|
+
return f"No Wikipedia results for '{query}'."
|
|
81
|
+
|
|
82
|
+
lines = [
|
|
83
|
+
f"- {h.get('title', '')}\n"
|
|
84
|
+
f" https://{lang}.wikipedia.org/wiki/{quote(str(h.get('title', '')).replace(' ', '_'))}\n"
|
|
85
|
+
f" {re.sub(r'<[^>]+>', '', str(h.get('snippet', '')))}"
|
|
86
|
+
for h in hits
|
|
87
|
+
]
|
|
88
|
+
out = "\n".join(lines)
|
|
89
|
+
|
|
90
|
+
if args.get("full_page"):
|
|
91
|
+
try:
|
|
92
|
+
ext = requests.get(
|
|
93
|
+
api,
|
|
94
|
+
params={
|
|
95
|
+
"action": "query",
|
|
96
|
+
"prop": "extracts",
|
|
97
|
+
"explaintext": 1,
|
|
98
|
+
"format": "json",
|
|
99
|
+
"titles": hits[0].get("title", ""),
|
|
100
|
+
},
|
|
101
|
+
headers=WIKI_HEADERS,
|
|
102
|
+
timeout=30,
|
|
103
|
+
).json()
|
|
104
|
+
for page in ext.get("query", {}).get("pages", {}).values():
|
|
105
|
+
extract = str(page.get("extract", "")).strip()
|
|
106
|
+
out += (
|
|
107
|
+
f"\n\n--- Full text of '{page.get('title')}' "
|
|
108
|
+
f"(truncated) ---\n{extract[:6000]}"
|
|
109
|
+
)
|
|
110
|
+
break
|
|
111
|
+
except requests.RequestException as exc:
|
|
112
|
+
out += f"\n\n(full-page extract failed: {exc})"
|
|
113
|
+
return out
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class SearchArxiv(Tool):
|
|
117
|
+
name = "search_arxiv"
|
|
118
|
+
description = (
|
|
119
|
+
"Search arXiv for papers: titles, authors, dates, abstracts and PDF "
|
|
120
|
+
"links. Query can use arXiv syntax like 'cat:cs.LG AND attention'. "
|
|
121
|
+
"No API key."
|
|
122
|
+
)
|
|
123
|
+
parameters = {
|
|
124
|
+
"type": "object",
|
|
125
|
+
"properties": {
|
|
126
|
+
"query": {"type": "string"},
|
|
127
|
+
"max_results": {"type": "integer", "description": "Default 5, max 20."},
|
|
128
|
+
},
|
|
129
|
+
"required": ["query"],
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
NS = {"a": "http://www.w3.org/2005/Atom"}
|
|
133
|
+
|
|
134
|
+
def run(self, args: dict) -> str:
|
|
135
|
+
query = str(args.get("query", "")).strip()
|
|
136
|
+
if not query:
|
|
137
|
+
return "ERROR: 'query' is required."
|
|
138
|
+
limit = min(int(args.get("max_results") or 5), 20)
|
|
139
|
+
search = query if ":" in query.split()[0] else f"all:{query}"
|
|
140
|
+
|
|
141
|
+
try:
|
|
142
|
+
resp = requests.get(
|
|
143
|
+
"https://export.arxiv.org/api/query",
|
|
144
|
+
params={"search_query": search, "max_results": limit, "sortBy": "relevance"},
|
|
145
|
+
headers=HEADERS,
|
|
146
|
+
timeout=30,
|
|
147
|
+
)
|
|
148
|
+
resp.raise_for_status()
|
|
149
|
+
entries = ET.fromstring(resp.text).findall("a:entry", self.NS)
|
|
150
|
+
except (requests.RequestException, ET.ParseError) as exc:
|
|
151
|
+
return f"ERROR: arXiv search failed: {exc}"
|
|
152
|
+
|
|
153
|
+
if not entries:
|
|
154
|
+
return f"No arXiv results for '{query}'."
|
|
155
|
+
|
|
156
|
+
lines = []
|
|
157
|
+
for e in entries:
|
|
158
|
+
title = " ".join(e.findtext("a:title", default="", namespaces=self.NS).split())
|
|
159
|
+
summary = " ".join(
|
|
160
|
+
e.findtext("a:summary", default="", namespaces=self.NS).split()
|
|
161
|
+
)[:400]
|
|
162
|
+
authors = [
|
|
163
|
+
a.findtext("a:name", default="", namespaces=self.NS)
|
|
164
|
+
for a in e.findall("a:author", self.NS)
|
|
165
|
+
][:4]
|
|
166
|
+
pdf = next(
|
|
167
|
+
(
|
|
168
|
+
l.get("href")
|
|
169
|
+
for l in e.findall("a:link", self.NS)
|
|
170
|
+
if l.get("type") == "application/pdf"
|
|
171
|
+
),
|
|
172
|
+
e.findtext("a:id", default="", namespaces=self.NS),
|
|
173
|
+
)
|
|
174
|
+
date = e.findtext("a:published", default="", namespaces=self.NS)[:10]
|
|
175
|
+
lines.append(
|
|
176
|
+
f"- {title} ({date})\n"
|
|
177
|
+
f" {', '.join(a for a in authors if a)}\n"
|
|
178
|
+
f" PDF: {pdf}\n"
|
|
179
|
+
f" {summary}"
|
|
180
|
+
)
|
|
181
|
+
return "\n\n".join(lines)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class SearchGitHub(Tool):
|
|
185
|
+
name = "search_github"
|
|
186
|
+
description = (
|
|
187
|
+
"Search GitHub for repositories, issues or users through the public "
|
|
188
|
+
"API with full search syntax (e.g. 'agent framework language:python "
|
|
189
|
+
"stars:>500'). No API key; anonymous search is rate-limited to ~10 "
|
|
190
|
+
"requests/minute."
|
|
191
|
+
)
|
|
192
|
+
parameters = {
|
|
193
|
+
"type": "object",
|
|
194
|
+
"properties": {
|
|
195
|
+
"query": {"type": "string"},
|
|
196
|
+
"kind": {"type": "string", "description": "'repos' (default), 'issues' or 'users'."},
|
|
197
|
+
"max_results": {"type": "integer", "description": "Default 5, max 20."},
|
|
198
|
+
},
|
|
199
|
+
"required": ["query"],
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
def run(self, args: dict) -> str:
|
|
203
|
+
query = str(args.get("query", "")).strip()
|
|
204
|
+
if not query:
|
|
205
|
+
return "ERROR: 'query' is required."
|
|
206
|
+
kind = str(args.get("kind") or "repos").lower()
|
|
207
|
+
if kind not in ("repos", "issues", "users"):
|
|
208
|
+
return "ERROR: 'kind' must be repos, issues or users."
|
|
209
|
+
endpoint = {"repos": "repositories", "issues": "issues", "users": "users"}[kind]
|
|
210
|
+
limit = min(int(args.get("max_results") or 5), 20)
|
|
211
|
+
|
|
212
|
+
try:
|
|
213
|
+
resp = requests.get(
|
|
214
|
+
f"https://api.github.com/search/{endpoint}",
|
|
215
|
+
params={"q": query, "per_page": limit},
|
|
216
|
+
headers=HEADERS,
|
|
217
|
+
timeout=30,
|
|
218
|
+
)
|
|
219
|
+
except requests.RequestException as exc:
|
|
220
|
+
return f"ERROR: GitHub search failed: {exc}"
|
|
221
|
+
|
|
222
|
+
if resp.status_code == 403 or resp.status_code == 429:
|
|
223
|
+
return "ERROR: GitHub anonymous rate limit hit (~10 searches/min). Wait a minute and retry."
|
|
224
|
+
if resp.status_code == 422:
|
|
225
|
+
return "ERROR: GitHub rejected the query syntax."
|
|
226
|
+
resp.raise_for_status()
|
|
227
|
+
|
|
228
|
+
items = resp.json().get("items", [])
|
|
229
|
+
if not items:
|
|
230
|
+
return f"No GitHub {kind} matching '{query}'."
|
|
231
|
+
|
|
232
|
+
lines = []
|
|
233
|
+
for it in items:
|
|
234
|
+
if kind == "repos":
|
|
235
|
+
lines.append(
|
|
236
|
+
f"- {it.get('full_name')} (stars: {it.get('stargazers_count', 0)})\n"
|
|
237
|
+
f" {it.get('html_url')}\n"
|
|
238
|
+
f" {str(it.get('description') or '')[:200]}"
|
|
239
|
+
)
|
|
240
|
+
elif kind == "issues":
|
|
241
|
+
lines.append(
|
|
242
|
+
f"- [#{it.get('number')}] {it.get('title')} (state: {it.get('state')})\n"
|
|
243
|
+
f" {it.get('html_url')}"
|
|
244
|
+
)
|
|
245
|
+
else:
|
|
246
|
+
lines.append(f"- {it.get('login')} ({it.get('type')})\n {it.get('html_url')}")
|
|
247
|
+
return "\n".join(lines)
|
aether/tools/loader.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Auto-load user-defined tools from a folder of plain Python files.
|
|
2
|
+
|
|
3
|
+
Point ``custom_tools_dir`` (or the AETHER_CUSTOM_TOOLS environment variable)
|
|
4
|
+
at a directory; every ``*.py`` file in it is imported and any ``Tool``
|
|
5
|
+
subclass found at module level is instantiated and registered. This lets you
|
|
6
|
+
drop a new capability into the folder without touching Aether's source.
|
|
7
|
+
|
|
8
|
+
Example ``my_tools.py``:
|
|
9
|
+
|
|
10
|
+
from aether.tools.base import Tool
|
|
11
|
+
|
|
12
|
+
class Shout(Tool):
|
|
13
|
+
name = "shout"
|
|
14
|
+
description = "Repeat a message in capital letters."
|
|
15
|
+
parameters = {
|
|
16
|
+
"type": "object",
|
|
17
|
+
"properties": {"text": {"type": "string"}},
|
|
18
|
+
"required": ["text"],
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
def run(self, args: dict) -> str:
|
|
22
|
+
return args["text"].upper() + "!"
|
|
23
|
+
|
|
24
|
+
Notes:
|
|
25
|
+
- Files whose name starts with ``_`` are skipped.
|
|
26
|
+
- A tool whose ``name`` collides with an existing one replaces it
|
|
27
|
+
(handy for overriding built-ins deliberately).
|
|
28
|
+
- A class failing to instantiate is reported and skipped; the rest still load.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import importlib.util
|
|
34
|
+
import sys
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from typing import List
|
|
37
|
+
|
|
38
|
+
from .base import Tool, ToolRegistry
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def load_tools_from_dir(directory: str | Path, registry: ToolRegistry) -> List[str]:
|
|
42
|
+
"""Import every plugin file in ``directory`` and register the tools found.
|
|
43
|
+
|
|
44
|
+
Returns the names of tools that were actually registered.
|
|
45
|
+
"""
|
|
46
|
+
folder = Path(directory).expanduser()
|
|
47
|
+
if not folder.is_dir():
|
|
48
|
+
print(f"[aether] custom tools dir not found: {folder}", file=sys.stderr)
|
|
49
|
+
return []
|
|
50
|
+
|
|
51
|
+
registered: List[str] = []
|
|
52
|
+
for path in sorted(folder.glob("*.py")):
|
|
53
|
+
if path.name.startswith("_"):
|
|
54
|
+
continue
|
|
55
|
+
module_name = f"aether_plugins_{path.stem}"
|
|
56
|
+
try:
|
|
57
|
+
spec = importlib.util.spec_from_file_location(module_name, path)
|
|
58
|
+
if spec is None or spec.loader is None:
|
|
59
|
+
raise ImportError(f"cannot load {path.name}")
|
|
60
|
+
module = importlib.util.module_from_spec(spec)
|
|
61
|
+
sys.modules[module_name] = module # allow plugin-internal imports
|
|
62
|
+
spec.loader.exec_module(module)
|
|
63
|
+
except Exception as exc: # noqa: BLE001 - one bad file must not kill startup
|
|
64
|
+
print(f"[aether] skipped plugin {path.name}: {exc}", file=sys.stderr)
|
|
65
|
+
continue
|
|
66
|
+
|
|
67
|
+
for attr in dir(module):
|
|
68
|
+
obj = getattr(module, attr)
|
|
69
|
+
if (
|
|
70
|
+
isinstance(obj, type)
|
|
71
|
+
and issubclass(obj, Tool)
|
|
72
|
+
and obj.__module__ == module_name # only classes defined here
|
|
73
|
+
):
|
|
74
|
+
try:
|
|
75
|
+
instance = obj()
|
|
76
|
+
if not instance.name or instance.name == "tool":
|
|
77
|
+
raise ValueError("tool has no usable 'name'")
|
|
78
|
+
registry.register(instance)
|
|
79
|
+
registered.append(instance.name)
|
|
80
|
+
except Exception as exc: # noqa: BLE001
|
|
81
|
+
print(
|
|
82
|
+
f"[aether] plugin class {obj.__name__} in {path.name} skipped: {exc}",
|
|
83
|
+
file=sys.stderr,
|
|
84
|
+
)
|
|
85
|
+
return registered
|
aether/tools/net.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Network tools: generic HTTP API calls and file downloads. No API keys."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from urllib.parse import unquote, urlparse
|
|
7
|
+
|
|
8
|
+
import requests
|
|
9
|
+
|
|
10
|
+
from .base import Tool
|
|
11
|
+
from .files import _WorkspaceTool
|
|
12
|
+
from .web import HEADERS
|
|
13
|
+
|
|
14
|
+
MAX_DOWNLOAD_BYTES = 200 * 1024 * 1024 # 200 MB safety cap
|
|
15
|
+
_INTERESTING_HEADERS = (
|
|
16
|
+
"content-type", "content-length", "location", "server", "date", "allow",
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class HttpRequest(Tool):
|
|
21
|
+
name = "http_request"
|
|
22
|
+
description = (
|
|
23
|
+
"Call any HTTP(S) API with a chosen method, headers and body; returns "
|
|
24
|
+
"the status code, key response headers and the body. Use this for JSON "
|
|
25
|
+
"REST APIs - fetch_url is only for reading pages as text."
|
|
26
|
+
)
|
|
27
|
+
parameters = {
|
|
28
|
+
"type": "object",
|
|
29
|
+
"properties": {
|
|
30
|
+
"url": {"type": "string"},
|
|
31
|
+
"method": {
|
|
32
|
+
"type": "string",
|
|
33
|
+
"description": "GET (default), POST, PUT, PATCH, DELETE or HEAD.",
|
|
34
|
+
},
|
|
35
|
+
"headers": {"type": "object", "description": "Extra request headers."},
|
|
36
|
+
"body": {"type": "string", "description": "Raw request body."},
|
|
37
|
+
"json": {"type": "object", "description": "JSON body (takes priority over 'body')."},
|
|
38
|
+
"timeout": {"type": "integer", "description": "Seconds (default 30, max 120)."},
|
|
39
|
+
},
|
|
40
|
+
"required": ["url"],
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
def run(self, args: dict) -> str:
|
|
44
|
+
url = str(args.get("url", "")).strip()
|
|
45
|
+
parsed = urlparse(url)
|
|
46
|
+
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
|
47
|
+
return "ERROR: provide a valid http(s) URL."
|
|
48
|
+
|
|
49
|
+
method = str(args.get("method") or "GET").upper()
|
|
50
|
+
if method not in ("GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"):
|
|
51
|
+
return f"ERROR: unsupported method '{method}'."
|
|
52
|
+
|
|
53
|
+
timeout = min(max(int(args.get("timeout") or 30), 1), 120)
|
|
54
|
+
headers = dict(HEADERS)
|
|
55
|
+
headers.update({str(k): str(v) for k, v in (args.get("headers") or {}).items()})
|
|
56
|
+
|
|
57
|
+
json_body = args.get("json")
|
|
58
|
+
if json_body is not None and not isinstance(json_body, dict):
|
|
59
|
+
return "ERROR: 'json' must be an object (key/value map)."
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
resp = requests.request(
|
|
63
|
+
method,
|
|
64
|
+
url,
|
|
65
|
+
headers=headers,
|
|
66
|
+
data=None if json_body is not None else str(args.get("body") or "") or None,
|
|
67
|
+
json=json_body,
|
|
68
|
+
timeout=timeout,
|
|
69
|
+
allow_redirects=True,
|
|
70
|
+
)
|
|
71
|
+
except requests.RequestException as exc:
|
|
72
|
+
return f"ERROR: request failed: {exc}"
|
|
73
|
+
|
|
74
|
+
meta = [f"HTTP {resp.status_code} {resp.reason}", f"final_url: {resp.url}"]
|
|
75
|
+
meta += [
|
|
76
|
+
f"{k}: {v}"
|
|
77
|
+
for k, v in resp.headers.items()
|
|
78
|
+
if k.lower() in _INTERESTING_HEADERS
|
|
79
|
+
]
|
|
80
|
+
payload = resp.content[:200_000].decode("utf-8", errors="replace")
|
|
81
|
+
return "\n".join(meta) + "\n\n" + payload
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class DownloadFile(_WorkspaceTool):
|
|
85
|
+
name = "download_file"
|
|
86
|
+
description = (
|
|
87
|
+
"Download a file from a URL into the workspace - images, PDFs, "
|
|
88
|
+
"archives, datasets, any binary that fetch_url refuses. Returns the "
|
|
89
|
+
"saved path and size. Hard limit 200 MB."
|
|
90
|
+
)
|
|
91
|
+
parameters = {
|
|
92
|
+
"type": "object",
|
|
93
|
+
"properties": {
|
|
94
|
+
"url": {"type": "string"},
|
|
95
|
+
"path": {
|
|
96
|
+
"type": "string",
|
|
97
|
+
"description": "Destination path in the workspace (default: filename from the URL).",
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
"required": ["url"],
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
def run(self, args: dict) -> str:
|
|
104
|
+
url = str(args.get("url", "")).strip()
|
|
105
|
+
parsed = urlparse(url)
|
|
106
|
+
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
|
107
|
+
return "ERROR: provide a valid http(s) URL."
|
|
108
|
+
|
|
109
|
+
default_name = Path(unquote(parsed.path)).name or "download.bin"
|
|
110
|
+
dest = self._resolve(str(args.get("path") or "").strip() or default_name)
|
|
111
|
+
if dest.is_dir():
|
|
112
|
+
return f"ERROR: {dest} is a directory; pick a file path."
|
|
113
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
114
|
+
|
|
115
|
+
written = 0
|
|
116
|
+
try:
|
|
117
|
+
with requests.get(
|
|
118
|
+
url, headers=HEADERS, timeout=60, stream=True, allow_redirects=True
|
|
119
|
+
) as resp:
|
|
120
|
+
resp.raise_for_status()
|
|
121
|
+
declared = int(resp.headers.get("Content-Length") or 0)
|
|
122
|
+
if declared > MAX_DOWNLOAD_BYTES:
|
|
123
|
+
return (
|
|
124
|
+
f"ERROR: file is {declared} bytes; limit is "
|
|
125
|
+
f"{MAX_DOWNLOAD_BYTES}."
|
|
126
|
+
)
|
|
127
|
+
with dest.open("wb") as fh:
|
|
128
|
+
for chunk in resp.iter_content(chunk_size=65536):
|
|
129
|
+
written += len(chunk)
|
|
130
|
+
if written > MAX_DOWNLOAD_BYTES:
|
|
131
|
+
break
|
|
132
|
+
fh.write(chunk)
|
|
133
|
+
except requests.RequestException as exc:
|
|
134
|
+
dest.unlink(missing_ok=True)
|
|
135
|
+
return f"ERROR: download failed: {exc}"
|
|
136
|
+
|
|
137
|
+
if written > MAX_DOWNLOAD_BYTES:
|
|
138
|
+
dest.unlink(missing_ok=True)
|
|
139
|
+
return f"ERROR: download exceeded {MAX_DOWNLOAD_BYTES} bytes; aborted and removed."
|
|
140
|
+
|
|
141
|
+
return f"Saved {dest} ({written} bytes)."
|