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/memory.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Session transcript + long-term notes, stored under the memory directory."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Memory:
|
|
11
|
+
def __init__(self, memory_dir: Path):
|
|
12
|
+
self.dir = Path(memory_dir)
|
|
13
|
+
(self.dir / "sessions").mkdir(parents=True, exist_ok=True)
|
|
14
|
+
stamp = time.strftime("%Y%m%d-%H%M%S")
|
|
15
|
+
self.session_path = self.dir / "sessions" / f"{stamp}.jsonl"
|
|
16
|
+
self.notes_path = self.dir / "notes.md"
|
|
17
|
+
|
|
18
|
+
# ------------------------------------------------------------- transcript
|
|
19
|
+
def log(self, role: str, content: str) -> None:
|
|
20
|
+
entry = {"ts": time.time(), "role": role, "content": content}
|
|
21
|
+
with self.session_path.open("a", encoding="utf-8") as fh:
|
|
22
|
+
fh.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
23
|
+
|
|
24
|
+
# ------------------------------------------------------------------ notes
|
|
25
|
+
def remember(self, fact: str) -> str:
|
|
26
|
+
fact = fact.strip()
|
|
27
|
+
if not fact:
|
|
28
|
+
return "ERROR: empty fact."
|
|
29
|
+
with self.notes_path.open("a", encoding="utf-8") as fh:
|
|
30
|
+
fh.write(f"- [{time.strftime('%Y-%m-%d %H:%M')}] {fact}\n")
|
|
31
|
+
return f"Remembered: {fact}"
|
|
32
|
+
|
|
33
|
+
def recall(self, query: str = "") -> str:
|
|
34
|
+
if not self.notes_path.exists():
|
|
35
|
+
return "No notes stored yet."
|
|
36
|
+
lines = self.notes_path.read_text(encoding="utf-8").splitlines()
|
|
37
|
+
if query:
|
|
38
|
+
needle = query.lower()
|
|
39
|
+
lines = [ln for ln in lines if needle in ln.lower()]
|
|
40
|
+
return "\n".join(lines) if lines else f"No notes matching '{query}'."
|
|
41
|
+
|
|
42
|
+
def load_notes_into_context(self, max_chars: int = 1500) -> str:
|
|
43
|
+
if not self.notes_path.exists():
|
|
44
|
+
return ""
|
|
45
|
+
return self.notes_path.read_text(encoding="utf-8")[-max_chars:]
|
aether/planner.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Optional planning step: decompose a task into an ordered checklist."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
SYSTEM = (
|
|
8
|
+
"You are a planning module inside an autonomous agent. Given a task, output a "
|
|
9
|
+
"concise ordered checklist of concrete steps (max 10). One step per line, "
|
|
10
|
+
"formatted as '1. ...'. No preamble, no explanation."
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def make_plan(llm, task: str) -> list[str]:
|
|
15
|
+
"""Best-effort planning; any failure simply means 'no plan'."""
|
|
16
|
+
try:
|
|
17
|
+
reply = llm.chat(
|
|
18
|
+
[
|
|
19
|
+
{"role": "system", "content": SYSTEM},
|
|
20
|
+
{"role": "user", "content": task},
|
|
21
|
+
]
|
|
22
|
+
)
|
|
23
|
+
except Exception: # noqa: BLE001 - planning must never block execution
|
|
24
|
+
return []
|
|
25
|
+
|
|
26
|
+
steps = []
|
|
27
|
+
for line in (reply.get("content") or "").splitlines():
|
|
28
|
+
match = re.match(r"^\d+[.)]\s*(.+)$", line.strip())
|
|
29
|
+
if match:
|
|
30
|
+
steps.append(match.group(1).strip())
|
|
31
|
+
return steps[:10]
|
aether/tools/__init__.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Default toolbelt assembly."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
from ..config import Config
|
|
8
|
+
from ..memory import Memory
|
|
9
|
+
from .base import Tool, ToolRegistry
|
|
10
|
+
from .data import RenderChart, RunSqlite
|
|
11
|
+
from .files import EditFile, ListDir, ReadFile, WriteFile
|
|
12
|
+
from .knowledge import SearchArxiv, SearchGitHub, SearchWikipedia
|
|
13
|
+
from .loader import load_tools_from_dir
|
|
14
|
+
from .net import DownloadFile, HttpRequest
|
|
15
|
+
from .productivity import CreateCalendarEvent, SendEmail
|
|
16
|
+
from .python_exec import ExecutePython
|
|
17
|
+
from .shell import RunCommand
|
|
18
|
+
from .web import FetchURL, WebSearch
|
|
19
|
+
|
|
20
|
+
__all__ = ["Tool", "ToolRegistry", "build_default_tools", "load_tools_from_dir"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class RememberTool(Tool):
|
|
24
|
+
name = "remember"
|
|
25
|
+
description = "Store a durable fact or preference in long-term notes for future sessions."
|
|
26
|
+
parameters = {
|
|
27
|
+
"type": "object",
|
|
28
|
+
"properties": {"fact": {"type": "string"}},
|
|
29
|
+
"required": ["fact"],
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
def __init__(self, memory: Memory):
|
|
33
|
+
self.memory = memory
|
|
34
|
+
|
|
35
|
+
def run(self, args: dict) -> str:
|
|
36
|
+
return self.memory.remember(str(args.get("fact", "")))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class RecallTool(Tool):
|
|
40
|
+
name = "recall"
|
|
41
|
+
description = "Search your long-term notes. Pass a query to filter, or none to list all."
|
|
42
|
+
parameters = {
|
|
43
|
+
"type": "object",
|
|
44
|
+
"properties": {"query": {"type": "string"}},
|
|
45
|
+
"required": [],
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
def __init__(self, memory: Memory):
|
|
49
|
+
self.memory = memory
|
|
50
|
+
|
|
51
|
+
def run(self, args: dict) -> str:
|
|
52
|
+
return self.memory.recall(str(args.get("query", "")).strip())
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def build_default_tools(config: Config, memory: Memory, delegate_depth: int = 0) -> ToolRegistry:
|
|
56
|
+
"""Instantiate every built-in tool, then any custom tools from
|
|
57
|
+
config.custom_tools_dir (or AETHER_CUSTOM_TOOLS).
|
|
58
|
+
|
|
59
|
+
``delegate_depth`` is the nesting level of the agent this registry is
|
|
60
|
+
built for (0 = top-level). ``delegate_task`` is registered only while
|
|
61
|
+
``delegate_depth < config.max_delegate_depth``, so sub-agents cannot
|
|
62
|
+
delegate beyond the configured limit.
|
|
63
|
+
"""
|
|
64
|
+
registry = ToolRegistry(max_output=config.max_tool_output)
|
|
65
|
+
workspace = config.resolved_workspace()
|
|
66
|
+
|
|
67
|
+
registry.register(RunCommand(workspace, auto_approve=config.auto_approve))
|
|
68
|
+
registry.register(ReadFile(workspace, allow_outside=config.allow_outside_workspace))
|
|
69
|
+
registry.register(WriteFile(workspace, allow_outside=config.allow_outside_workspace))
|
|
70
|
+
registry.register(EditFile(workspace, allow_outside=config.allow_outside_workspace))
|
|
71
|
+
registry.register(ListDir(workspace, allow_outside=config.allow_outside_workspace))
|
|
72
|
+
registry.register(ExecutePython(workspace))
|
|
73
|
+
registry.register(WebSearch())
|
|
74
|
+
registry.register(FetchURL())
|
|
75
|
+
registry.register(HttpRequest())
|
|
76
|
+
registry.register(DownloadFile(workspace, allow_outside=config.allow_outside_workspace))
|
|
77
|
+
registry.register(SearchWikipedia())
|
|
78
|
+
registry.register(SearchArxiv())
|
|
79
|
+
registry.register(SearchGitHub())
|
|
80
|
+
registry.register(RunSqlite(workspace, allow_outside=config.allow_outside_workspace))
|
|
81
|
+
registry.register(RenderChart(workspace, allow_outside=config.allow_outside_workspace))
|
|
82
|
+
registry.register(RememberTool(memory))
|
|
83
|
+
registry.register(RecallTool(memory))
|
|
84
|
+
registry.register(SendEmail())
|
|
85
|
+
registry.register(CreateCalendarEvent(workspace))
|
|
86
|
+
|
|
87
|
+
if config.max_delegate_depth > delegate_depth:
|
|
88
|
+
from .delegate import DelegateTool
|
|
89
|
+
|
|
90
|
+
registry.register(
|
|
91
|
+
DelegateTool(
|
|
92
|
+
config,
|
|
93
|
+
memory,
|
|
94
|
+
depth=delegate_depth + 1,
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
custom_dir = config.custom_tools_dir or os.environ.get("AETHER_CUSTOM_TOOLS", "")
|
|
99
|
+
if custom_dir:
|
|
100
|
+
load_tools_from_dir(custom_dir, registry)
|
|
101
|
+
return registry
|
aether/tools/base.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Tool base class and registry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import traceback
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def truncate(text: str, limit: int) -> str:
|
|
10
|
+
if len(text) <= limit:
|
|
11
|
+
return text
|
|
12
|
+
return text[:limit] + f"\n... [output truncated, {len(text) - limit} chars dropped]"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Tool:
|
|
16
|
+
"""A callable capability exposed to the model.
|
|
17
|
+
|
|
18
|
+
Subclasses define ``name``, ``description``, ``parameters`` (a JSON Schema
|
|
19
|
+
object) and implement ``run(args: dict) -> str``. The returned string is
|
|
20
|
+
what the model sees.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
name: str = "tool"
|
|
24
|
+
description: str = ""
|
|
25
|
+
parameters: dict = {"type": "object", "properties": {}, "required": []}
|
|
26
|
+
|
|
27
|
+
def run(self, args: dict) -> str: # pragma: no cover - overridden
|
|
28
|
+
raise NotImplementedError
|
|
29
|
+
|
|
30
|
+
def bind_agent(self, agent) -> None:
|
|
31
|
+
"""Optional hook: called by Agent.__init__ for every tool in its
|
|
32
|
+
registry. Lets tools that need agent services (stop flag, event
|
|
33
|
+
observer) receive them without the registry builder knowing about
|
|
34
|
+
the agent. Default: no-op."""
|
|
35
|
+
|
|
36
|
+
def schema(self) -> dict:
|
|
37
|
+
return {
|
|
38
|
+
"name": self.name,
|
|
39
|
+
"description": self.description,
|
|
40
|
+
"parameters": self.parameters,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ToolRegistry:
|
|
45
|
+
def __init__(self, max_output: int = 8000):
|
|
46
|
+
self.tools: dict[str, Tool] = {}
|
|
47
|
+
self.max_output = max_output
|
|
48
|
+
|
|
49
|
+
def register(self, tool: Tool) -> None:
|
|
50
|
+
self.tools[tool.name] = tool
|
|
51
|
+
|
|
52
|
+
def schemas(self) -> list[dict]:
|
|
53
|
+
return [t.schema() for t in self.tools.values()]
|
|
54
|
+
|
|
55
|
+
def call(self, name: str, arguments: str | dict) -> str:
|
|
56
|
+
tool = self.tools.get(name)
|
|
57
|
+
if tool is None:
|
|
58
|
+
return f"ERROR: unknown tool '{name}'. Available: {', '.join(self.tools)}"
|
|
59
|
+
|
|
60
|
+
if isinstance(arguments, str):
|
|
61
|
+
try:
|
|
62
|
+
args = json.loads(arguments) if arguments.strip() else {}
|
|
63
|
+
except json.JSONDecodeError as exc:
|
|
64
|
+
return f"ERROR: arguments for '{name}' are not valid JSON: {exc}"
|
|
65
|
+
else:
|
|
66
|
+
args = arguments
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
result = tool.run(args)
|
|
70
|
+
except Exception as exc: # noqa: BLE001 - errors go back to the model
|
|
71
|
+
result = f"ERROR: {exc.__class__.__name__}: {exc}\n{traceback.format_exc(limit=2)}"
|
|
72
|
+
return truncate(str(result), self.max_output)
|
aether/tools/data.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Data tools: local SQLite queries and chart rendering (matplotlib optional)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sqlite3
|
|
6
|
+
|
|
7
|
+
from .base import Tool
|
|
8
|
+
from .files import _WorkspaceTool
|
|
9
|
+
|
|
10
|
+
MAX_ROWS = 50
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class RunSqlite(_WorkspaceTool):
|
|
14
|
+
name = "run_sqlite"
|
|
15
|
+
description = (
|
|
16
|
+
"Execute ONE SQL statement against a local SQLite database file. "
|
|
17
|
+
"Read-only by default; pass mode='write' for INSERT/UPDATE/DELETE/DDL. "
|
|
18
|
+
"SELECT results come back as a Markdown table (first 50 rows)."
|
|
19
|
+
)
|
|
20
|
+
parameters = {
|
|
21
|
+
"type": "object",
|
|
22
|
+
"properties": {
|
|
23
|
+
"path": {"type": "string", "description": "Path to the .db/.sqlite file (inside the workspace)."},
|
|
24
|
+
"sql": {"type": "string", "description": "A single SQL statement."},
|
|
25
|
+
"params": {"type": "array", "description": "Optional positional SQL parameters."},
|
|
26
|
+
"mode": {"type": "string", "description": "'read' (default) or 'write'."},
|
|
27
|
+
},
|
|
28
|
+
"required": ["path", "sql"],
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
def run(self, args: dict) -> str:
|
|
32
|
+
path = self._resolve(str(args.get("path", "")))
|
|
33
|
+
sql = str(args.get("sql", "")).strip()
|
|
34
|
+
if not sql:
|
|
35
|
+
return "ERROR: 'sql' is required."
|
|
36
|
+
if not path.exists():
|
|
37
|
+
return f"ERROR: {path} does not exist (run_sqlite never creates databases)."
|
|
38
|
+
|
|
39
|
+
write = str(args.get("mode") or "read").lower() == "write"
|
|
40
|
+
params = args.get("params")
|
|
41
|
+
if params is not None and not isinstance(params, list):
|
|
42
|
+
return "ERROR: 'params' must be an array of positional values."
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
if write:
|
|
46
|
+
conn = sqlite3.connect(str(path))
|
|
47
|
+
else:
|
|
48
|
+
conn = sqlite3.connect(f"{path.as_uri()}?mode=ro", uri=True)
|
|
49
|
+
conn.row_factory = sqlite3.Row
|
|
50
|
+
try:
|
|
51
|
+
cur = conn.execute(sql, params or [])
|
|
52
|
+
rows = cur.fetchmany(MAX_ROWS + 1)
|
|
53
|
+
if write:
|
|
54
|
+
conn.commit() # default isolation: execute() opens a txn that must be committed
|
|
55
|
+
finally:
|
|
56
|
+
conn.close()
|
|
57
|
+
except sqlite3.Error as exc:
|
|
58
|
+
hint = ""
|
|
59
|
+
if not write and any(
|
|
60
|
+
kw in sql[:12].upper() for kw in ("INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "ALTER")
|
|
61
|
+
):
|
|
62
|
+
hint = " (pass mode='write' to modify the database)"
|
|
63
|
+
return f"ERROR: {exc}{hint}"
|
|
64
|
+
|
|
65
|
+
if cur.description is None: # non-SELECT statement
|
|
66
|
+
return f"OK. Rows affected: {cur.rowcount}."
|
|
67
|
+
|
|
68
|
+
columns = [d[0] for d in cur.description]
|
|
69
|
+
truncated = len(rows) > MAX_ROWS
|
|
70
|
+
rows = rows[:MAX_ROWS]
|
|
71
|
+
|
|
72
|
+
def cell(value) -> str:
|
|
73
|
+
return str(value).replace("|", "\\|").replace("\n", " ")
|
|
74
|
+
|
|
75
|
+
out = ["| " + " | ".join(columns) + " |", "|" + "|".join("---" for _ in columns) + "|"]
|
|
76
|
+
out += ["| " + " | ".join(cell(v) for v in row) + " |" for row in rows]
|
|
77
|
+
note = f"\n({cur.rowcount if cur.rowcount >= 0 else len(rows)} rows"
|
|
78
|
+
note += f", showing first {len(rows)}{'; use LIMIT/OFFSET for more' if truncated else ''})"
|
|
79
|
+
return "\n".join(out) + note
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class RenderChart(_WorkspaceTool):
|
|
83
|
+
name = "render_chart"
|
|
84
|
+
description = (
|
|
85
|
+
"Render a chart (line, bar, scatter, pie or histogram) from arrays of "
|
|
86
|
+
"data and save it as a PNG inside the workspace. Multi-series works by "
|
|
87
|
+
"passing 'y' as an array of arrays plus optional 'series_names'. "
|
|
88
|
+
"Requires matplotlib (pip install matplotlib); a clear error is "
|
|
89
|
+
"returned if it is missing."
|
|
90
|
+
)
|
|
91
|
+
parameters = {
|
|
92
|
+
"type": "object",
|
|
93
|
+
"properties": {
|
|
94
|
+
"type": {"type": "string", "description": "'line' (default), 'bar', 'scatter', 'pie' or 'hist'."},
|
|
95
|
+
"title": {"type": "string"},
|
|
96
|
+
"x": {
|
|
97
|
+
"type": "array",
|
|
98
|
+
"description": "X values, categories or pie labels. Optional for line/hist.",
|
|
99
|
+
},
|
|
100
|
+
"y": {
|
|
101
|
+
"type": "array",
|
|
102
|
+
"description": "Y values; pass an array of arrays for multi-series line/bar/hist.",
|
|
103
|
+
},
|
|
104
|
+
"x_label": {"type": "string"},
|
|
105
|
+
"y_label": {"type": "string"},
|
|
106
|
+
"series_names": {"type": "array", "description": "Legend labels for multi-series charts."},
|
|
107
|
+
"path": {"type": "string", "description": "Output PNG path (default 'chart.png')."},
|
|
108
|
+
},
|
|
109
|
+
"required": ["y"],
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
def run(self, args: dict) -> str:
|
|
113
|
+
try:
|
|
114
|
+
import matplotlib
|
|
115
|
+
except ImportError:
|
|
116
|
+
return (
|
|
117
|
+
"ERROR: matplotlib is not installed. Install it with "
|
|
118
|
+
"'pip install matplotlib' and retry, or use execute_python."
|
|
119
|
+
)
|
|
120
|
+
matplotlib.use("Agg")
|
|
121
|
+
import matplotlib.pyplot as plt
|
|
122
|
+
|
|
123
|
+
chart_type = str(args.get("type") or "line").lower()
|
|
124
|
+
if chart_type not in ("line", "bar", "scatter", "pie", "hist"):
|
|
125
|
+
return f"ERROR: unknown chart type '{chart_type}'."
|
|
126
|
+
|
|
127
|
+
y = args.get("y")
|
|
128
|
+
if not isinstance(y, list) or not y:
|
|
129
|
+
return "ERROR: 'y' must be a non-empty array."
|
|
130
|
+
x = args.get("x") or []
|
|
131
|
+
if not isinstance(x, list):
|
|
132
|
+
return "ERROR: 'x' must be an array."
|
|
133
|
+
|
|
134
|
+
multi = isinstance(y[0], list)
|
|
135
|
+
series = y if multi else [y]
|
|
136
|
+
names = list(args.get("series_names") or []) or [
|
|
137
|
+
f"series {i + 1}" for i in range(len(series))
|
|
138
|
+
]
|
|
139
|
+
|
|
140
|
+
if chart_type in ("scatter", "pie") and multi:
|
|
141
|
+
return f"ERROR: '{chart_type}' supports a single series (pass y as one flat array)."
|
|
142
|
+
if chart_type == "scatter" and (not x or len(x) != len(series[0])):
|
|
143
|
+
return "ERROR: scatter needs 'x' with the same length as 'y'."
|
|
144
|
+
|
|
145
|
+
plt.rcParams["axes.unicode_minus"] = False
|
|
146
|
+
fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
|
|
147
|
+
|
|
148
|
+
if chart_type == "line":
|
|
149
|
+
for ys, nm in zip(series, names):
|
|
150
|
+
xs = x if x and len(x) == len(ys) else range(1, len(ys) + 1)
|
|
151
|
+
ax.plot(xs, ys, marker="o", markersize=3, label=nm)
|
|
152
|
+
if len(series) > 1:
|
|
153
|
+
ax.legend()
|
|
154
|
+
ax.grid(alpha=0.3)
|
|
155
|
+
elif chart_type == "bar":
|
|
156
|
+
n = len(series)
|
|
157
|
+
width = 0.8 / n
|
|
158
|
+
xs = list(range(len(series[0])))
|
|
159
|
+
for i, (ys, nm) in enumerate(zip(series, names)):
|
|
160
|
+
pos = [v + (i - (n - 1) / 2) * width for v in xs]
|
|
161
|
+
ax.bar(pos, ys, width=width, label=nm)
|
|
162
|
+
ax.set_xticks(xs)
|
|
163
|
+
ax.set_xticklabels([str(v) for v in x] if len(x) == len(xs) else xs)
|
|
164
|
+
if len(series) > 1:
|
|
165
|
+
ax.legend()
|
|
166
|
+
ax.grid(alpha=0.3, axis="y")
|
|
167
|
+
elif chart_type == "scatter":
|
|
168
|
+
ax.scatter(x, series[0], s=24)
|
|
169
|
+
ax.grid(alpha=0.3)
|
|
170
|
+
elif chart_type == "pie":
|
|
171
|
+
ax.pie(
|
|
172
|
+
series[0],
|
|
173
|
+
labels=[str(v) for v in x] if x else None,
|
|
174
|
+
autopct="%1.1f%%",
|
|
175
|
+
startangle=90,
|
|
176
|
+
)
|
|
177
|
+
else: # hist
|
|
178
|
+
for ys, nm in zip(series, names):
|
|
179
|
+
ax.hist(ys, bins=min(20, max(5, len(ys) // 2 or 5)), alpha=0.6, label=nm)
|
|
180
|
+
if multi:
|
|
181
|
+
ax.legend()
|
|
182
|
+
ax.grid(alpha=0.3, axis="y")
|
|
183
|
+
|
|
184
|
+
ax.set_title(str(args.get("title") or ""))
|
|
185
|
+
if args.get("x_label") and chart_type != "pie":
|
|
186
|
+
ax.set_xlabel(str(args["x_label"]))
|
|
187
|
+
if args.get("y_label") and chart_type != "pie":
|
|
188
|
+
ax.set_ylabel(str(args["y_label"]))
|
|
189
|
+
|
|
190
|
+
out_raw = str(args.get("path") or "chart.png").strip() or "chart.png"
|
|
191
|
+
out = self._resolve(out_raw)
|
|
192
|
+
if out.suffix.lower() != ".png":
|
|
193
|
+
out = out.with_suffix(".png")
|
|
194
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
195
|
+
fig.savefig(out, dpi=150)
|
|
196
|
+
plt.close(fig)
|
|
197
|
+
|
|
198
|
+
label = f"{len(series)} series" if multi else f"{len(series[0])} points"
|
|
199
|
+
return f"Saved {chart_type} chart ({label}) to {out} ({out.stat().st_size} bytes)."
|
aether/tools/delegate.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Multi-agent handoffs: the agent can delegate subtasks to sub-agents.
|
|
2
|
+
|
|
3
|
+
``delegate_task`` spawns a child :class:`~aether.agent.Agent` with a fresh
|
|
4
|
+
conversation, its own iteration budget and the same toolbelt (minus further
|
|
5
|
+
delegation once the configured depth limit is reached). The child runs to
|
|
6
|
+
completion synchronously; its final answer becomes the tool output the parent
|
|
7
|
+
sees.
|
|
8
|
+
|
|
9
|
+
Guard rails:
|
|
10
|
+
- ``max_delegate_depth`` (default 1): how many nesting levels are allowed.
|
|
11
|
+
0 disables the tool entirely; 1 means the top-level agent may delegate but
|
|
12
|
+
sub-agents may not delegate further.
|
|
13
|
+
- ``delegate_max_iterations`` (default 15): smaller loop budget for children,
|
|
14
|
+
so a delegation can never run longer than the parent itself.
|
|
15
|
+
- The parent's stop flag is shared: stopping a run also stops any in-flight
|
|
16
|
+
sub-agent.
|
|
17
|
+
- Sub-agent events are forwarded to observers (Web UI) as ``delegate_event``
|
|
18
|
+
payloads so delegation stays visible in the dashboard.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from dataclasses import replace
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from .base import Tool
|
|
27
|
+
|
|
28
|
+
_PROVIDER_LABEL = {
|
|
29
|
+
"openai_compatible": "openai-compatible",
|
|
30
|
+
"ollama": "ollama",
|
|
31
|
+
"mock": "mock",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class DelegateTool(Tool):
|
|
36
|
+
"""Run a self-contained subtask in a fresh sub-agent and return its result."""
|
|
37
|
+
|
|
38
|
+
name = "delegate_task"
|
|
39
|
+
description = (
|
|
40
|
+
"Spawn a sub-agent to complete a self-contained subtask with its own fresh "
|
|
41
|
+
"context and toolbelt. Ideal for focused pieces of work you can hand off "
|
|
42
|
+
"completely - e.g. 'research X and summarise it', 'draft file Y', 'fix the "
|
|
43
|
+
"failing tests in module Z'. Give a crisp, complete task description plus any "
|
|
44
|
+
"background the sub-agent cannot see (it does NOT share your conversation). "
|
|
45
|
+
"The sub-agent's final report is returned as the tool result."
|
|
46
|
+
)
|
|
47
|
+
parameters = {
|
|
48
|
+
"type": "object",
|
|
49
|
+
"properties": {
|
|
50
|
+
"task": {
|
|
51
|
+
"type": "string",
|
|
52
|
+
"description": "Complete, self-contained description of the subtask.",
|
|
53
|
+
},
|
|
54
|
+
"context": {
|
|
55
|
+
"type": "string",
|
|
56
|
+
"description": "Optional background facts, file paths or constraints "
|
|
57
|
+
"the sub-agent needs but cannot discover on its own.",
|
|
58
|
+
},
|
|
59
|
+
"use_plan": {
|
|
60
|
+
"type": "boolean",
|
|
61
|
+
"description": "Let the sub-agent make an explicit plan first "
|
|
62
|
+
"(default false; usually not needed for focused subtasks).",
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
"required": ["task"],
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
def __init__(
|
|
69
|
+
self,
|
|
70
|
+
config, # aether.config.Config
|
|
71
|
+
memory, # aether.memory.Memory (shared with the parent)
|
|
72
|
+
depth: int = 1, # this tool's children will run at this depth
|
|
73
|
+
parent_stop_flag=None, # threading.Event from the parent agent
|
|
74
|
+
parent_on_event=None, # observer callable from the parent agent
|
|
75
|
+
):
|
|
76
|
+
self.config = config
|
|
77
|
+
self.memory = memory
|
|
78
|
+
self.depth = depth
|
|
79
|
+
self._stop_flag = parent_stop_flag
|
|
80
|
+
self._on_event = parent_on_event
|
|
81
|
+
|
|
82
|
+
# ------------------------------------------------------------------ events
|
|
83
|
+
def bind_agent(self, agent) -> None:
|
|
84
|
+
"""Called by Agent.__init__: receive the owning agent's stop flag and
|
|
85
|
+
event observer so sub-agents stream into the same dashboard and stop
|
|
86
|
+
together with the parent."""
|
|
87
|
+
self._stop_flag = agent.stop_flag
|
|
88
|
+
self._on_event = agent.on_event
|
|
89
|
+
|
|
90
|
+
def _forward(self, event: dict) -> None:
|
|
91
|
+
if self._on_event is None:
|
|
92
|
+
return
|
|
93
|
+
try:
|
|
94
|
+
self._on_event({"type": "delegate_event", "depth": self.depth, "event": event})
|
|
95
|
+
except Exception: # noqa: BLE001 - observation must not break execution
|
|
96
|
+
pass
|
|
97
|
+
|
|
98
|
+
# ---------------------------------------------------------------- execution
|
|
99
|
+
def run(self, args: dict) -> str:
|
|
100
|
+
task = str(args.get("task", "")).strip()
|
|
101
|
+
if not task:
|
|
102
|
+
return "ERROR: 'task' is required and cannot be empty."
|
|
103
|
+
context = str(args.get("context", "")).strip()
|
|
104
|
+
use_plan = bool(args.get("use_plan", False))
|
|
105
|
+
|
|
106
|
+
# Lazy imports: the tools package imports this module, so importing it
|
|
107
|
+
# at module level would be circular.
|
|
108
|
+
from ..agent import Agent
|
|
109
|
+
from ..config import Config
|
|
110
|
+
from ..llm import LLMClient, LLMError
|
|
111
|
+
from . import build_default_tools
|
|
112
|
+
|
|
113
|
+
if not isinstance(self.config, Config): # pragma: no cover - defensive
|
|
114
|
+
return "ERROR: delegate_task was constructed with an invalid config."
|
|
115
|
+
|
|
116
|
+
sub_config = replace(
|
|
117
|
+
self.config,
|
|
118
|
+
max_iterations=self.config.delegate_max_iterations,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
llm = LLMClient(sub_config)
|
|
122
|
+
registry = build_default_tools(sub_config, self.memory, delegate_depth=self.depth)
|
|
123
|
+
|
|
124
|
+
child = Agent(
|
|
125
|
+
sub_config,
|
|
126
|
+
llm,
|
|
127
|
+
registry,
|
|
128
|
+
self.memory,
|
|
129
|
+
color=False,
|
|
130
|
+
on_event=self._forward,
|
|
131
|
+
)
|
|
132
|
+
# Share the parent's stop flag: stopping the run stops the whole tree.
|
|
133
|
+
if self._stop_flag is not None:
|
|
134
|
+
child.stop_flag = self._stop_flag
|
|
135
|
+
|
|
136
|
+
prompt = task
|
|
137
|
+
if context:
|
|
138
|
+
prompt += f"\n\nBackground from the parent agent:\n{context}"
|
|
139
|
+
|
|
140
|
+
provider = _PROVIDER_LABEL.get(sub_config.provider, sub_config.provider)
|
|
141
|
+
try:
|
|
142
|
+
result = child.run(prompt, use_plan=use_plan)
|
|
143
|
+
except LLMError as exc:
|
|
144
|
+
return (
|
|
145
|
+
f"ERROR: sub-agent could not reach its LLM backend "
|
|
146
|
+
f"(provider={provider}): {exc}"
|
|
147
|
+
)
|
|
148
|
+
except Exception as exc: # noqa: BLE001 - errors go back to the model
|
|
149
|
+
return f"ERROR: sub-agent failed: {exc.__class__.__name__}: {exc}"
|
|
150
|
+
|
|
151
|
+
if child.stop_flag.is_set():
|
|
152
|
+
return (
|
|
153
|
+
f"Sub-agent stopped before finishing (user requested stop). "
|
|
154
|
+
f"Partial report:\n{result}"
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
return f"[sub-agent result, depth {self.depth}]\n{result}"
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def workspace_label(config) -> str:
|
|
161
|
+
"""Human-readable workspace path for prompt/docs use."""
|
|
162
|
+
ws: Path = config.resolved_workspace()
|
|
163
|
+
return str(ws)
|