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/web/server.py ADDED
@@ -0,0 +1,321 @@
1
+ """Live Web UI for Aether: watch the agent plan, act and report in real time.
2
+
3
+ Run with: python -m aether.web --workspace <dir> [--provider mock]
4
+ Then open: http://127.0.0.1:5000
5
+
6
+ The server is a local dashboard (binds to 127.0.0.1 by default). It is meant
7
+ for one user on their own machine; do not expose it to the public internet.
8
+ Set AETHER_WEB_TOKEN to require a shared token on every API call.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import threading
16
+ import time
17
+ import uuid
18
+ from dataclasses import dataclass, field, replace
19
+ from pathlib import Path
20
+
21
+ from flask import Flask, Response, jsonify, request, send_from_directory
22
+
23
+ from ..agent import Agent
24
+ from ..config import Config, load_config
25
+ from ..llm import LLMClient
26
+ from ..memory import Memory
27
+ from ..tools import build_default_tools
28
+
29
+ STATIC_DIR = Path(__file__).parent / "static"
30
+
31
+ # Tool results longer than this are trimmed before reaching the browser.
32
+ EVENT_RESULT_LIMIT = 6000
33
+
34
+
35
+ @dataclass
36
+ class RunState:
37
+ run_id: str
38
+ task: str
39
+ status: str = "running" # running | done | stopped | error
40
+ created_at: float = field(default_factory=time.time)
41
+ events: list[dict] = field(default_factory=list)
42
+ result: str = ""
43
+ error: str = ""
44
+ agent: Agent | None = None
45
+ cond: threading.Condition = field(default_factory=threading.Condition)
46
+
47
+ def emit(self, event: dict) -> None:
48
+ with self.cond:
49
+ self.events.append(event)
50
+ self.cond.notify_all()
51
+
52
+ def finish(self, status: str, *, result: str = "", error: str = "") -> None:
53
+ with self.cond:
54
+ self.status = status
55
+ self.result = result or self.result
56
+ self.error = error
57
+ self.cond.notify_all()
58
+
59
+
60
+ class RunManager:
61
+ """Owns every run started through the Web UI (one thread per run)."""
62
+
63
+ def __init__(self, base_config: Config, keep_last: int = 200):
64
+ self.base = base_config
65
+ self.keep_last = keep_last
66
+ self.runs: dict[str, RunState] = {}
67
+ self.order: list[str] = []
68
+ self.lock = threading.Lock()
69
+
70
+ # ------------------------------------------------------------------ start
71
+ def start(self, task: str, overrides: dict | None = None) -> str:
72
+ overrides = {k: v for k, v in (overrides or {}).items() if v not in (None, "")}
73
+ cfg = replace(self.base, **overrides) if overrides else self.base
74
+
75
+ state = RunState(run_id=uuid.uuid4().hex[:12], task=task)
76
+ # NOTE: no run_start event here - Agent.run() emits it once the
77
+ # thread is up; emitting twice would duplicate the task card in the UI.
78
+
79
+ with self.lock:
80
+ self.runs[state.run_id] = state
81
+ self.order.append(state.run_id)
82
+ # Prune old finished runs so the process stays small.
83
+ while len(self.order) > self.keep_last:
84
+ old_id = self.order[0]
85
+ old = self.runs.get(old_id)
86
+ if old is not None and old.status == "running":
87
+ break
88
+ self.order.pop(0)
89
+ self.runs.pop(old_id, None)
90
+
91
+ threading.Thread(
92
+ target=self._execute,
93
+ args=(state, cfg),
94
+ daemon=True,
95
+ name=f"aether-{state.run_id}",
96
+ ).start()
97
+ return state.run_id
98
+
99
+ # ---------------------------------------------------------------- execute
100
+ def _execute(self, state: RunState, cfg: Config) -> None:
101
+ try:
102
+ llm = LLMClient(cfg)
103
+ memory = Memory(cfg.resolved_memory_dir())
104
+ registry = build_default_tools(cfg, memory)
105
+ agent = Agent(cfg, llm, registry, memory, color=False, on_event=state.emit)
106
+ state.agent = agent
107
+
108
+ result = agent.run(state.task)
109
+ status = "stopped" if agent.stop_flag.is_set() else "done"
110
+ state.finish(status, result=result)
111
+ except Exception as exc: # noqa: BLE001 - report the failure to the browser
112
+ message = f"{exc.__class__.__name__}: {exc}"
113
+ state.emit({"type": "run_error", "message": message})
114
+ state.finish("error", error=message)
115
+
116
+ # ------------------------------------------------------------------- stop
117
+ def stop(self, run_id: str) -> bool:
118
+ state = self.runs.get(run_id)
119
+ if state is None or state.agent is None or state.status != "running":
120
+ return False
121
+ state.agent.request_stop()
122
+ return True
123
+
124
+ # ------------------------------------------------------------------ query
125
+ def get(self, run_id: str) -> RunState | None:
126
+ return self.runs.get(run_id)
127
+
128
+ def summary(self) -> list[dict]:
129
+ with self.lock:
130
+ states = [self.runs[r] for r in reversed(self.order) if r in self.runs]
131
+ return [
132
+ {
133
+ "run_id": s.run_id,
134
+ "task": s.task,
135
+ "status": s.status,
136
+ "created_at": s.created_at,
137
+ "event_count": len(s.events),
138
+ }
139
+ for s in states
140
+ ]
141
+
142
+
143
+ # ---------------------------------------------------------------- trimming
144
+ def _trim(event: dict) -> dict:
145
+ """Cap oversized tool results before they reach the browser."""
146
+ if event.get("type") == "tool_result" and len(event.get("result", "")) > EVENT_RESULT_LIMIT:
147
+ event = dict(event)
148
+ dropped = len(event["result"]) - EVENT_RESULT_LIMIT
149
+ event["result"] = (
150
+ event["result"][:EVENT_RESULT_LIMIT] + f"\n... [{dropped} chars trimmed for display]"
151
+ )
152
+ return event
153
+
154
+
155
+ # --------------------------------------------------------------- SSE stream
156
+ def _sse_stream(state: RunState) -> Response:
157
+ def generate():
158
+ idx = 0 # late subscribers replay everything that already happened
159
+ while True:
160
+ with state.cond:
161
+ while idx >= len(state.events) and state.status == "running":
162
+ state.cond.wait(timeout=15)
163
+ if idx >= len(state.events):
164
+ yield ": keep-alive\n\n"
165
+ fresh = state.events[idx:]
166
+ idx = len(state.events)
167
+ finished = state.status != "running"
168
+
169
+ for event in fresh:
170
+ yield f"data: {json.dumps(_trim(event), ensure_ascii=False)}\n\n"
171
+
172
+ if finished:
173
+ tail = {"status": state.status}
174
+ if state.error:
175
+ tail["error"] = state.error
176
+ yield f"event: end\ndata: {json.dumps(tail)}\n\n"
177
+ return
178
+
179
+ return Response(
180
+ generate(),
181
+ mimetype="text/event-stream",
182
+ headers={
183
+ "Cache-Control": "no-cache",
184
+ "X-Accel-Buffering": "no",
185
+ "Connection": "keep-alive",
186
+ },
187
+ )
188
+
189
+
190
+ # ------------------------------------------------------------ Flask factory
191
+ def create_app(config_path: str | None = None, **config_overrides) -> Flask:
192
+ base = load_config(config_path, **config_overrides)
193
+ manager = RunManager(base)
194
+ token = os.environ.get("AETHER_WEB_TOKEN", "")
195
+
196
+ app = Flask("aether", static_folder=None)
197
+
198
+ def authorized() -> bool:
199
+ """When AETHER_WEB_TOKEN is set, every call must present it."""
200
+ if not token:
201
+ return True
202
+ supplied = request.headers.get("X-Aether-Token") or request.args.get("token")
203
+ if not supplied and request.is_json:
204
+ supplied = (request.get_json(silent=True) or {}).get("token")
205
+ return supplied == token
206
+
207
+ def guard():
208
+ if not authorized():
209
+ return (
210
+ jsonify(
211
+ {
212
+ "error": "unauthorized: present AETHER_WEB_TOKEN "
213
+ "as ?token=, X-Aether-Token header, or token field"
214
+ }
215
+ ),
216
+ 401,
217
+ )
218
+ return None
219
+
220
+ # ------------------------------------------------------------------ pages
221
+ @app.get("/")
222
+ def index():
223
+ return send_from_directory(STATIC_DIR, "index.html")
224
+
225
+ @app.get("/static/<path:filename>")
226
+ def static_files(filename: str):
227
+ return send_from_directory(STATIC_DIR, filename)
228
+
229
+ # -------------------------------------------------------------------- API
230
+ @app.get("/api/health")
231
+ def health():
232
+ blocked = guard()
233
+ if blocked:
234
+ return blocked
235
+ from .. import __version__
236
+
237
+ return jsonify(
238
+ {
239
+ "ok": True,
240
+ "version": __version__,
241
+ "provider": base.provider,
242
+ "model": base.model,
243
+ "workspace": str(base.resolved_workspace()),
244
+ "secured": bool(token),
245
+ }
246
+ )
247
+
248
+ @app.get("/api/tools")
249
+ def tools():
250
+ blocked = guard()
251
+ if blocked:
252
+ return blocked
253
+ memory = Memory(base.resolved_memory_dir())
254
+ registry = build_default_tools(base, memory)
255
+ return jsonify(registry.schemas())
256
+
257
+ @app.post("/api/runs")
258
+ def create_run():
259
+ blocked = guard()
260
+ if blocked:
261
+ return blocked
262
+ body = request.get_json(silent=True) or {}
263
+ task = str(body.get("task", "")).strip()
264
+ if not task:
265
+ return jsonify({"error": "task is required"}), 400
266
+ if len(task) > 20_000:
267
+ return jsonify({"error": "task is too long (max 20000 chars)"}), 400
268
+ overrides = {
269
+ key: body.get(key)
270
+ for key in ("provider", "base_url", "model", "max_iterations", "temperature")
271
+ }
272
+ run_id = manager.start(task, overrides)
273
+ return jsonify({"run_id": run_id, "status": "running"}), 201
274
+
275
+ @app.get("/api/runs")
276
+ def list_runs():
277
+ blocked = guard()
278
+ if blocked:
279
+ return blocked
280
+ return jsonify({"runs": manager.summary()})
281
+
282
+ @app.get("/api/runs/<run_id>")
283
+ def get_run(run_id: str):
284
+ blocked = guard()
285
+ if blocked:
286
+ return blocked
287
+ state = manager.get(run_id)
288
+ if state is None:
289
+ return jsonify({"error": "unknown run"}), 404
290
+ with state.cond:
291
+ return jsonify(
292
+ {
293
+ "run_id": state.run_id,
294
+ "task": state.task,
295
+ "status": state.status,
296
+ "created_at": state.created_at,
297
+ "result": state.result,
298
+ "error": state.error,
299
+ "events": [_trim(e) for e in state.events],
300
+ }
301
+ )
302
+
303
+ @app.post("/api/runs/<run_id>/stop")
304
+ def stop_run(run_id: str):
305
+ blocked = guard()
306
+ if blocked:
307
+ return blocked
308
+ ok = manager.stop(run_id)
309
+ return jsonify({"ok": ok}), (200 if ok else 409)
310
+
311
+ @app.get("/api/stream/<run_id>")
312
+ def stream(run_id: str):
313
+ blocked = guard()
314
+ if blocked:
315
+ return blocked
316
+ state = manager.get(run_id)
317
+ if state is None:
318
+ return jsonify({"error": "unknown run"}), 404
319
+ return _sse_stream(state)
320
+
321
+ return app