-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmesh.py
More file actions
189 lines (167 loc) · 6.11 KB
/
mesh.py
File metadata and controls
189 lines (167 loc) · 6.11 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""Agent Mesh module - heartbeat, health monitoring, metrics reporting."""
from __future__ import annotations
import threading
import time
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING:
from .client import AxmeClient
class MeshClient:
"""Mesh operations for an AxmeClient instance."""
def __init__(self, client: AxmeClient) -> None:
self._client = client
self._heartbeat_thread: threading.Thread | None = None
self._heartbeat_stop = threading.Event()
self._metrics_buffer: dict[str, Any] = {}
# ── Heartbeat ────────────────────────────────────────────────────
def heartbeat(
self,
*,
metrics: dict[str, Any] | None = None,
trace_id: str | None = None,
) -> dict[str, Any]:
"""Send a single heartbeat to the mesh. Optionally include metrics."""
body: dict[str, Any] = {}
if metrics:
body["metrics"] = metrics
return self._client._request_json(
"POST",
"/v1/mesh/heartbeat",
json_body=body if body else None,
retryable=True,
trace_id=trace_id,
)
def start_heartbeat(
self,
*,
interval_seconds: float = 30.0,
include_metrics: bool = True,
) -> None:
"""Start a background thread that sends heartbeats at regular intervals.
Args:
interval_seconds: Seconds between heartbeats (default 30).
include_metrics: Whether to include buffered metrics with each heartbeat.
"""
if self._heartbeat_thread is not None and self._heartbeat_thread.is_alive():
return # Already running
self._heartbeat_stop.clear()
def _loop() -> None:
while not self._heartbeat_stop.wait(timeout=interval_seconds):
try:
metrics = self._flush_metrics() if include_metrics else None
self.heartbeat(metrics=metrics)
except Exception:
pass # Heartbeat failures are non-fatal
self._heartbeat_thread = threading.Thread(
target=_loop, daemon=True, name="axme-mesh-heartbeat",
)
self._heartbeat_thread.start()
def stop_heartbeat(self) -> None:
"""Stop the background heartbeat thread."""
self._heartbeat_stop.set()
if self._heartbeat_thread is not None:
self._heartbeat_thread.join(timeout=5.0)
self._heartbeat_thread = None
# ── Metrics ──────────────────────────────────────────────────────
def report_metric(
self,
*,
success: bool = True,
latency_ms: float | None = None,
cost_usd: float | None = None,
) -> None:
"""Buffer a metric observation. Flushed with next heartbeat."""
buf = self._metrics_buffer
buf["intents_total"] = buf.get("intents_total", 0) + 1
if success:
buf["intents_succeeded"] = buf.get("intents_succeeded", 0) + 1
else:
buf["intents_failed"] = buf.get("intents_failed", 0) + 1
if latency_ms is not None:
# Running average
count = buf["intents_total"]
prev_avg = buf.get("avg_latency_ms", 0.0)
buf["avg_latency_ms"] = prev_avg + (latency_ms - prev_avg) / count
if cost_usd is not None:
buf["cost_usd"] = buf.get("cost_usd", 0.0) + cost_usd
def _flush_metrics(self) -> dict[str, Any] | None:
if not self._metrics_buffer:
return None
metrics = self._metrics_buffer.copy()
self._metrics_buffer.clear()
return metrics
# ── Agent management ─────────────────────────────────────────────
def list_agents(
self,
*,
limit: int = 100,
health: str | None = None,
trace_id: str | None = None,
) -> dict[str, Any]:
"""List all agents in workspace with health status."""
params: dict[str, str] = {"limit": str(limit)}
if health:
params["health"] = health
return self._client._request_json(
"GET",
"/v1/mesh/agents",
params=params,
retryable=True,
trace_id=trace_id,
)
def get_agent(
self,
address_id: str,
*,
trace_id: str | None = None,
) -> dict[str, Any]:
"""Get single agent detail with metrics and events."""
return self._client._request_json(
"GET",
f"/v1/mesh/agents/{address_id}",
retryable=True,
trace_id=trace_id,
)
def kill(
self,
address_id: str,
*,
trace_id: str | None = None,
) -> dict[str, Any]:
"""Kill an agent - block all intents to and from it."""
return self._client._request_json(
"POST",
f"/v1/mesh/agents/{address_id}/kill",
retryable=False,
trace_id=trace_id,
)
def resume(
self,
address_id: str,
*,
trace_id: str | None = None,
) -> dict[str, Any]:
"""Resume a killed agent."""
return self._client._request_json(
"POST",
f"/v1/mesh/agents/{address_id}/resume",
retryable=False,
trace_id=trace_id,
)
def list_events(
self,
*,
limit: int = 50,
event_type: str | None = None,
trace_id: str | None = None,
) -> dict[str, Any]:
"""List recent mesh events (kills, resumes, health changes)."""
params: dict[str, str] = {"limit": str(limit)}
if event_type:
params["event_type"] = event_type
return self._client._request_json(
"GET",
"/v1/mesh/events",
params=params,
retryable=True,
trace_id=trace_id,
)