ether-core 0.1.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.
- ether/__init__.py +32 -0
- ether/assets/wordlists/common_dirs.txt.gz +0 -0
- ether/assets/wordlists/common_params.txt.gz +0 -0
- ether/assets/wordlists/common_passwords.txt.gz +0 -0
- ether/assets/wordlists/common_usernames.txt.gz +0 -0
- ether/assets/wordlists/subdomains_500.txt.gz +0 -0
- ether/cli/__init__.py +5 -0
- ether/cli/__main__.py +8 -0
- ether/cli/commands/__init__.py +1 -0
- ether/cli/commands/doctor.py +21 -0
- ether/cli/commands/graph.py +311 -0
- ether/cli/commands/logs.py +45 -0
- ether/cli/commands/mcp.py +49 -0
- ether/cli/commands/run.py +146 -0
- ether/cli/commands/session.py +61 -0
- ether/cli/commands/telemetry.py +51 -0
- ether/cli/commands/tool.py +131 -0
- ether/cli/context.py +71 -0
- ether/cli/formatters.py +39 -0
- ether/cli/router.py +368 -0
- ether/common/__init__.py +201 -0
- ether/common/algorithms.py +407 -0
- ether/common/canonicalize.py +93 -0
- ether/common/context.py +25 -0
- ether/common/crypto.py +183 -0
- ether/common/embeddings.py +93 -0
- ether/common/exceptions.py +13 -0
- ether/common/logging.py +386 -0
- ether/common/secure_memory.py +159 -0
- ether/common/ssrf.py +93 -0
- ether/core/__init__.py +25 -0
- ether/core/diagnostics.py +368 -0
- ether/core/executor.py +296 -0
- ether/core/sandbox.py +118 -0
- ether/core/session.py +956 -0
- ether/gateway/__init__.py +21 -0
- ether/gateway/gate.py +392 -0
- ether/gateway/network.py +98 -0
- ether/gateway/preflight.py +802 -0
- ether/graph/__init__.py +13 -0
- ether/graph/analytics.py +334 -0
- ether/graph/store.py +1615 -0
- ether/graph/telemetry.py +334 -0
- ether/graph/timeline.py +185 -0
- ether/mcp/__init__.py +5 -0
- ether/mcp/server.py +382 -0
- ether/paths.py +176 -0
- ether/py.typed +0 -0
- ether/registry/__init__.py +7 -0
- ether/registry/adapter.py +194 -0
- ether/registry/manifest.py +53 -0
- ether/registry/registry.py +150 -0
- ether/registry/wordlists.py +156 -0
- ether/schemas/__init__.py +50 -0
- ether/schemas/base.py +122 -0
- ether/schemas/credential.py +50 -0
- ether/schemas/dns.py +116 -0
- ether/schemas/host_internal.py +58 -0
- ether/schemas/network.py +142 -0
- ether/schemas/power.py +68 -0
- ether/schemas/vulnerability.py +221 -0
- ether/schemas/web.py +172 -0
- ether_core-0.1.0.dist-info/METADATA +440 -0
- ether_core-0.1.0.dist-info/RECORD +104 -0
- ether_core-0.1.0.dist-info/WHEEL +4 -0
- ether_core-0.1.0.dist-info/entry_points.txt +2 -0
- ether_core-0.1.0.dist-info/licenses/LICENSE +21 -0
- tools/__init__.py +0 -0
- tools/dnspython/__init__.py +1 -0
- tools/dnspython/adapter.py +302 -0
- tools/dnspython/cli.py +202 -0
- tools/dnspython/manifest.toml +138 -0
- tools/ffuf/__init__.py +1 -0
- tools/ffuf/adapter.py +183 -0
- tools/ffuf/manifest.toml +121 -0
- tools/gobuster/__init__.py +0 -0
- tools/gobuster/adapter.py +90 -0
- tools/gobuster/manifest.toml +104 -0
- tools/http_probe/adapter.py +256 -0
- tools/http_probe/manifest.toml +40 -0
- tools/netexec/__init__.py +1 -0
- tools/netexec/adapter.py +163 -0
- tools/netexec/manifest.toml +83 -0
- tools/nikto/__init__.py +0 -0
- tools/nikto/adapter.py +145 -0
- tools/nikto/manifest.toml +108 -0
- tools/nmap/__init__.py +0 -0
- tools/nmap/adapter.py +97 -0
- tools/nmap/manifest.toml +159 -0
- tools/nuclei/__init__.py +1 -0
- tools/nuclei/adapter.py +171 -0
- tools/nuclei/manifest.toml +117 -0
- tools/searchsploit/__init__.py +1 -0
- tools/searchsploit/adapter.py +139 -0
- tools/searchsploit/manifest.toml +103 -0
- tools/sqlmap/__init__.py +1 -0
- tools/sqlmap/adapter.py +214 -0
- tools/sqlmap/manifest.toml +89 -0
- tools/subfinder/__init__.py +0 -0
- tools/subfinder/adapter.py +71 -0
- tools/subfinder/manifest.toml +104 -0
- tools/whois/__init__.py +0 -0
- tools/whois/adapter.py +80 -0
- tools/whois/manifest.toml +95 -0
ether/graph/telemetry.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"""Agent Telemetry & Context Compiler for Ether.
|
|
2
|
+
|
|
3
|
+
Compiles deterministic, token-budgeted graph snapshots and zero-token semantic diffs
|
|
4
|
+
for autonomous agents, fulfilling Epoch 2 (Agent Telemetry Protocol).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from typing import Any, Callable, Dict, List, Optional, Union
|
|
10
|
+
|
|
11
|
+
from ether.common.algorithms import knapsack_01
|
|
12
|
+
from ether.graph.analytics import GraphAnalyticsEngine
|
|
13
|
+
from ether.graph.store import GraphStore
|
|
14
|
+
from ether.schemas.base import BaseFinding
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _parse_timestamp(val: Any) -> float:
|
|
18
|
+
"""Parse float, integer, ISO string, or SQLite timestamp into float epoch seconds."""
|
|
19
|
+
if val is None:
|
|
20
|
+
return 0.0
|
|
21
|
+
if isinstance(val, (int, float)):
|
|
22
|
+
return float(val)
|
|
23
|
+
if isinstance(val, datetime):
|
|
24
|
+
return val.timestamp()
|
|
25
|
+
if isinstance(val, str):
|
|
26
|
+
val = val.strip()
|
|
27
|
+
try:
|
|
28
|
+
return datetime.fromisoformat(val).timestamp()
|
|
29
|
+
except Exception:
|
|
30
|
+
pass
|
|
31
|
+
try:
|
|
32
|
+
return (
|
|
33
|
+
datetime.strptime(val, "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc).timestamp()
|
|
34
|
+
)
|
|
35
|
+
except Exception:
|
|
36
|
+
pass
|
|
37
|
+
return 0.0
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class GraphTelemetryCompiler:
|
|
41
|
+
"""Compiles point-in-time graph state snapshots and semantic diffs for AI agents.
|
|
42
|
+
|
|
43
|
+
Uses dynamic programming 0/1 knapsack to fit the highest-utility findings into a strict
|
|
44
|
+
token window and produces zero-token graph diffs for incremental agent reasoning loops.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
store: GraphStore,
|
|
50
|
+
session_id: str,
|
|
51
|
+
execution_session: Optional[Any] = None,
|
|
52
|
+
) -> None:
|
|
53
|
+
self.store = store
|
|
54
|
+
self.session_id = session_id
|
|
55
|
+
self.execution_session = execution_session
|
|
56
|
+
|
|
57
|
+
@staticmethod
|
|
58
|
+
def budget_findings(
|
|
59
|
+
findings: List[BaseFinding],
|
|
60
|
+
max_tokens: int = 4000,
|
|
61
|
+
chars_per_token: float = 4.0,
|
|
62
|
+
) -> List[BaseFinding]:
|
|
63
|
+
"""Select optimal subset of findings using 0/1 knapsack dynamic programming.
|
|
64
|
+
|
|
65
|
+
Maximizes information utility under the target token window while prioritizing
|
|
66
|
+
exploitable vulnerabilities, discovered credentials, and critical network assets.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def _estimate_weight(f: BaseFinding) -> int:
|
|
70
|
+
raw_len = len(f.model_dump_json())
|
|
71
|
+
return max(1, int(raw_len / chars_per_token))
|
|
72
|
+
|
|
73
|
+
def _estimate_utility(f: BaseFinding) -> float:
|
|
74
|
+
score = 10.0
|
|
75
|
+
st = str(f.schema_type).lower()
|
|
76
|
+
if "vulnerability" in st or "exploit" in st:
|
|
77
|
+
score += 50.0
|
|
78
|
+
elif "credential" in st:
|
|
79
|
+
score += 80.0
|
|
80
|
+
elif "service" in st:
|
|
81
|
+
score += 20.0
|
|
82
|
+
elif "host" in st:
|
|
83
|
+
score += 15.0
|
|
84
|
+
|
|
85
|
+
if getattr(f, "data", None) and isinstance(f.data, dict):
|
|
86
|
+
sev = str(f.data.get("severity", "")).lower()
|
|
87
|
+
if "crit" in sev:
|
|
88
|
+
score += 60.0
|
|
89
|
+
elif "high" in sev:
|
|
90
|
+
score += 40.0
|
|
91
|
+
elif "med" in sev:
|
|
92
|
+
score += 20.0
|
|
93
|
+
elif "low" in sev:
|
|
94
|
+
score += 10.0
|
|
95
|
+
return score
|
|
96
|
+
|
|
97
|
+
return knapsack_01(findings, max_tokens, _estimate_weight, _estimate_utility)
|
|
98
|
+
|
|
99
|
+
@staticmethod
|
|
100
|
+
def resolve_entity_variables(pik: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
101
|
+
"""Extract investigation variables from primary identity key dictionary."""
|
|
102
|
+
resolved: Dict[str, Any] = {}
|
|
103
|
+
if pik:
|
|
104
|
+
target = pik.get("ip") or pik.get("domain") or pik.get("host_ip")
|
|
105
|
+
if target:
|
|
106
|
+
resolved["TARGET"] = target
|
|
107
|
+
if "port" in pik:
|
|
108
|
+
resolved["PORT"] = pik["port"]
|
|
109
|
+
if "service" in pik or "service_name" in pik:
|
|
110
|
+
resolved["SERVICE"] = pik.get("service") or pik.get("service_name")
|
|
111
|
+
if "protocol" in pik:
|
|
112
|
+
resolved["PROTOCOL"] = pik["protocol"]
|
|
113
|
+
return resolved
|
|
114
|
+
|
|
115
|
+
async def compile_telemetry_snapshot(
|
|
116
|
+
self,
|
|
117
|
+
selected_entity_id: Optional[str] = None,
|
|
118
|
+
max_tokens: int = 4000,
|
|
119
|
+
variable_resolver: Optional[Callable[[Optional[Dict[str, Any]]], Dict[str, Any]]] = None,
|
|
120
|
+
objective: Optional[str] = None,
|
|
121
|
+
) -> Dict[str, Any]:
|
|
122
|
+
"""Compile a point-in-time state snapshot of the active investigation session."""
|
|
123
|
+
session_data = await self.store.get_session(self.session_id)
|
|
124
|
+
if not session_data:
|
|
125
|
+
raise ValueError(f"Session '{self.session_id}' not found.")
|
|
126
|
+
|
|
127
|
+
# 1. Resolve selected entity
|
|
128
|
+
selected_entity: Optional[BaseFinding] = None
|
|
129
|
+
resolved_vars: Dict[str, Any] = {}
|
|
130
|
+
resolver = variable_resolver or self.resolve_entity_variables
|
|
131
|
+
|
|
132
|
+
if selected_entity_id:
|
|
133
|
+
node_data = await self.store.get_node(self.session_id, selected_entity_id)
|
|
134
|
+
if node_data:
|
|
135
|
+
pik = json.loads(node_data["pik_json"])
|
|
136
|
+
selected_entity = BaseFinding(
|
|
137
|
+
schema_type=node_data["schema_type"],
|
|
138
|
+
pik=pik,
|
|
139
|
+
data=json.loads(node_data["data_json"]),
|
|
140
|
+
status=node_data.get("status", "confirmed"),
|
|
141
|
+
)
|
|
142
|
+
resolved_vars = resolver(pik)
|
|
143
|
+
|
|
144
|
+
# 2. Ingest all session findings and apply knapsack budgeting
|
|
145
|
+
raw_nodes = await self.store.get_all_nodes(self.session_id)
|
|
146
|
+
raw_edges = await self.store.get_all_edges(self.session_id)
|
|
147
|
+
findings: List[BaseFinding] = []
|
|
148
|
+
for n in raw_nodes:
|
|
149
|
+
try:
|
|
150
|
+
findings.append(
|
|
151
|
+
BaseFinding(
|
|
152
|
+
schema_type=n["schema_type"],
|
|
153
|
+
pik=json.loads(n["pik_json"]),
|
|
154
|
+
data=json.loads(n["data_json"]),
|
|
155
|
+
status=n.get("status", "confirmed"),
|
|
156
|
+
)
|
|
157
|
+
)
|
|
158
|
+
except Exception:
|
|
159
|
+
continue
|
|
160
|
+
|
|
161
|
+
budgeted = self.budget_findings(findings, max_tokens=max_tokens)
|
|
162
|
+
stats = await self.store.get_stats(self.session_id)
|
|
163
|
+
|
|
164
|
+
# 2.5 Offline Vector RAG Retrieval for Objective
|
|
165
|
+
rag_findings = []
|
|
166
|
+
if objective and hasattr(self.store, "semantic_search"):
|
|
167
|
+
try:
|
|
168
|
+
rag_findings = await self.store.semantic_search(
|
|
169
|
+
session_id=self.session_id,
|
|
170
|
+
query=objective,
|
|
171
|
+
limit=5,
|
|
172
|
+
)
|
|
173
|
+
except Exception:
|
|
174
|
+
rag_findings = []
|
|
175
|
+
|
|
176
|
+
# 3. Graph analytics summary
|
|
177
|
+
critical_count = 0
|
|
178
|
+
if raw_nodes:
|
|
179
|
+
analytics = GraphAnalyticsEngine(raw_nodes, raw_edges)
|
|
180
|
+
critical_count = len(analytics.identify_critical_assets())
|
|
181
|
+
|
|
182
|
+
# 4. Resolve active jobs from supervisor if attached
|
|
183
|
+
active_jobs = []
|
|
184
|
+
if self.execution_session and hasattr(self.execution_session, "get_active_jobs"):
|
|
185
|
+
for job in self.execution_session.get_active_jobs():
|
|
186
|
+
if str(getattr(job, "session_id", "")) == self.session_id:
|
|
187
|
+
active_jobs.append(job.to_dict() if hasattr(job, "to_dict") else vars(job))
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
"session_id": self.session_id,
|
|
191
|
+
"session_name": session_data.get("name", "Default"),
|
|
192
|
+
"selected_entity": (
|
|
193
|
+
selected_entity.model_dump(mode="json") if selected_entity else None
|
|
194
|
+
),
|
|
195
|
+
"resolved_vars": resolved_vars,
|
|
196
|
+
"entity_counts": stats,
|
|
197
|
+
"budgeted_findings": [f.model_dump(mode="json") for f in budgeted],
|
|
198
|
+
"rag_findings": rag_findings,
|
|
199
|
+
"active_jobs": active_jobs,
|
|
200
|
+
"graph_summary": {
|
|
201
|
+
"total_nodes": len(raw_nodes),
|
|
202
|
+
"total_edges": len(raw_edges),
|
|
203
|
+
"critical_assets": critical_count,
|
|
204
|
+
},
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async def compute_graph_diff(
|
|
208
|
+
self,
|
|
209
|
+
baseline_timestamp: Optional[Union[float, str, datetime]] = None,
|
|
210
|
+
action_id: Optional[str] = None,
|
|
211
|
+
) -> Dict[str, Any]:
|
|
212
|
+
"""Compute the set-theoretic graph delta: Δ = S_(t+1) \\ S_t.
|
|
213
|
+
|
|
214
|
+
Can be queried by exact `action_id` (action-scoped diff) or `baseline_timestamp`.
|
|
215
|
+
"""
|
|
216
|
+
# 1. Reconcile state decay deterministically before computing delta
|
|
217
|
+
decay_info = await self.store.reconcile_state_decay(self.session_id)
|
|
218
|
+
status_counts = decay_info.get("status_breakdown") or decay_info.get("status_counts", {})
|
|
219
|
+
status_breakdown = {
|
|
220
|
+
"confirmed": status_counts.get("confirmed", 0),
|
|
221
|
+
"flapping": status_counts.get("flapping", 0),
|
|
222
|
+
"stale": status_counts.get("stale", 0),
|
|
223
|
+
}
|
|
224
|
+
transitions = decay_info.get("transitions", [])
|
|
225
|
+
transition_map = {t["id"]: t for t in transitions}
|
|
226
|
+
|
|
227
|
+
nodes = await self.store.get_all_nodes(self.session_id, include_stale=True)
|
|
228
|
+
edges = await self.store.get_all_edges(self.session_id)
|
|
229
|
+
node_map = {n["id"]: n for n in nodes}
|
|
230
|
+
|
|
231
|
+
added_nodes = []
|
|
232
|
+
updated_nodes = []
|
|
233
|
+
added_edges = []
|
|
234
|
+
|
|
235
|
+
if action_id:
|
|
236
|
+
for n in nodes:
|
|
237
|
+
if n.get("action_id") == action_id:
|
|
238
|
+
node_item = {
|
|
239
|
+
"id": n["id"],
|
|
240
|
+
"schema_type": n["schema_type"],
|
|
241
|
+
"pik": json.loads(n["pik_json"]),
|
|
242
|
+
"data": json.loads(n["data_json"]),
|
|
243
|
+
"status": n.get("status", "confirmed"),
|
|
244
|
+
}
|
|
245
|
+
if n["id"] in transition_map:
|
|
246
|
+
t = transition_map[n["id"]]
|
|
247
|
+
node_item["new_attributes"] = {"status": t["to"]}
|
|
248
|
+
node_item["previous_attributes"] = {"status": t["from"]}
|
|
249
|
+
if n.get("created_action_id") == action_id:
|
|
250
|
+
added_nodes.append(node_item)
|
|
251
|
+
else:
|
|
252
|
+
updated_nodes.append(node_item)
|
|
253
|
+
|
|
254
|
+
for e in edges:
|
|
255
|
+
if e.get("action_id") == action_id:
|
|
256
|
+
added_edges.append(
|
|
257
|
+
{
|
|
258
|
+
"session_id": e.get("session_id", self.session_id),
|
|
259
|
+
"source_id": e["source_id"],
|
|
260
|
+
"target_id": e["target_id"],
|
|
261
|
+
"relation_type": e.get("relation_type", "relates_to"),
|
|
262
|
+
}
|
|
263
|
+
)
|
|
264
|
+
elif baseline_timestamp is not None:
|
|
265
|
+
baseline_ts = _parse_timestamp(baseline_timestamp)
|
|
266
|
+
for n in nodes:
|
|
267
|
+
created_at = _parse_timestamp(n.get("created_at"))
|
|
268
|
+
updated_at = _parse_timestamp(n.get("updated_at"))
|
|
269
|
+
node_item = {
|
|
270
|
+
"id": n["id"],
|
|
271
|
+
"schema_type": n["schema_type"],
|
|
272
|
+
"pik": json.loads(n["pik_json"]),
|
|
273
|
+
"data": json.loads(n["data_json"]),
|
|
274
|
+
"status": n.get("status", "confirmed"),
|
|
275
|
+
}
|
|
276
|
+
if n["id"] in transition_map:
|
|
277
|
+
t = transition_map[n["id"]]
|
|
278
|
+
node_item["new_attributes"] = {"status": t["to"]}
|
|
279
|
+
node_item["previous_attributes"] = {"status": t["from"]}
|
|
280
|
+
if created_at > baseline_ts:
|
|
281
|
+
added_nodes.append(node_item)
|
|
282
|
+
elif updated_at > baseline_ts:
|
|
283
|
+
updated_nodes.append(node_item)
|
|
284
|
+
|
|
285
|
+
for e in edges:
|
|
286
|
+
edge_ts = _parse_timestamp(e.get("created_at") or e.get("updated_at"))
|
|
287
|
+
if edge_ts > baseline_ts:
|
|
288
|
+
added_edges.append(
|
|
289
|
+
{
|
|
290
|
+
"session_id": e.get("session_id", self.session_id),
|
|
291
|
+
"source_id": e["source_id"],
|
|
292
|
+
"target_id": e["target_id"],
|
|
293
|
+
"relation_type": e.get("relation_type", "relates_to"),
|
|
294
|
+
}
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
# Include nodes that underwent state transitions during this diff run
|
|
298
|
+
seen_ids = {n["id"] for n in added_nodes} | {n["id"] for n in updated_nodes}
|
|
299
|
+
for t in transitions:
|
|
300
|
+
nid = t["id"]
|
|
301
|
+
if nid not in seen_ids and nid in node_map:
|
|
302
|
+
n = node_map[nid]
|
|
303
|
+
updated_nodes.append(
|
|
304
|
+
{
|
|
305
|
+
"id": nid,
|
|
306
|
+
"schema_type": n["schema_type"],
|
|
307
|
+
"pik": json.loads(n["pik_json"]),
|
|
308
|
+
"data": json.loads(n["data_json"]),
|
|
309
|
+
"status": t["to"],
|
|
310
|
+
"new_attributes": {"status": t["to"]},
|
|
311
|
+
"previous_attributes": {"status": t["from"]},
|
|
312
|
+
}
|
|
313
|
+
)
|
|
314
|
+
seen_ids.add(nid)
|
|
315
|
+
|
|
316
|
+
anchored_migrations = await self.store.get_anchored_migrations(
|
|
317
|
+
self.session_id, action_id=action_id
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
total_delta_count = (
|
|
321
|
+
len(added_nodes) + len(updated_nodes) + len(added_edges) + len(anchored_migrations)
|
|
322
|
+
)
|
|
323
|
+
return {
|
|
324
|
+
"session_id": self.session_id,
|
|
325
|
+
"action_id": action_id,
|
|
326
|
+
"baseline_timestamp": baseline_timestamp,
|
|
327
|
+
"added_nodes": added_nodes,
|
|
328
|
+
"updated_nodes": updated_nodes,
|
|
329
|
+
"added_edges": added_edges,
|
|
330
|
+
"status_breakdown": status_breakdown,
|
|
331
|
+
"anchored_migrations": anchored_migrations,
|
|
332
|
+
"total_delta_count": total_delta_count,
|
|
333
|
+
"tokens_consumed": 0,
|
|
334
|
+
}
|
ether/graph/timeline.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Deep module managing session action timeline, execution audit trails, and event lifecycle."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional
|
|
7
|
+
|
|
8
|
+
import aiosqlite
|
|
9
|
+
|
|
10
|
+
from ether.schemas.power import ActionRequest
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from ether.graph.store import GraphStore
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ActionTimelineRepository:
|
|
17
|
+
"""The deep module managing persistent event logging, audit trails,
|
|
18
|
+
|
|
19
|
+
and active/closed tab status for investigation sessions.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, store: GraphStore):
|
|
23
|
+
self.store = store
|
|
24
|
+
|
|
25
|
+
async def append_event(
|
|
26
|
+
self,
|
|
27
|
+
session_id: str,
|
|
28
|
+
action: ActionRequest,
|
|
29
|
+
result: Dict[str, Any],
|
|
30
|
+
message: str,
|
|
31
|
+
) -> None:
|
|
32
|
+
"""Append a structured action/result event to the session event log."""
|
|
33
|
+
async with self.store.connection() as db:
|
|
34
|
+
await db.execute(
|
|
35
|
+
"""INSERT INTO event_log (session_id, action_payload, result_payload, human_readable, schema_type, finding_json)
|
|
36
|
+
VALUES (?, ?, ?, ?, ?, ?)""",
|
|
37
|
+
(
|
|
38
|
+
session_id,
|
|
39
|
+
action.model_dump_json(),
|
|
40
|
+
json.dumps(result),
|
|
41
|
+
message,
|
|
42
|
+
"system.event",
|
|
43
|
+
"{}",
|
|
44
|
+
),
|
|
45
|
+
)
|
|
46
|
+
await db.commit()
|
|
47
|
+
|
|
48
|
+
async def log_audit_event(
|
|
49
|
+
self, session_id: str, action_name: str, message: str, status: str
|
|
50
|
+
) -> None:
|
|
51
|
+
"""Append an audit lifecycle event (e.g. session closed/reopened) to event_log."""
|
|
52
|
+
async with self.store.connection() as db:
|
|
53
|
+
await db.execute(
|
|
54
|
+
"""INSERT INTO event_log (session_id, action_payload, result_payload, human_readable, schema_type, finding_json)
|
|
55
|
+
VALUES (?, ?, ?, ?, ?, ?)""",
|
|
56
|
+
(
|
|
57
|
+
session_id,
|
|
58
|
+
json.dumps({"action": action_name}),
|
|
59
|
+
json.dumps({"status": status}),
|
|
60
|
+
message,
|
|
61
|
+
f"system.{action_name}",
|
|
62
|
+
"{}",
|
|
63
|
+
),
|
|
64
|
+
)
|
|
65
|
+
await db.commit()
|
|
66
|
+
|
|
67
|
+
async def get_event_log(self, session_id: str) -> List[Dict[str, Any]]:
|
|
68
|
+
"""Fetch all non-closed events for a session in chronological order."""
|
|
69
|
+
async with self.store.connection() as db:
|
|
70
|
+
db.row_factory = aiosqlite.Row
|
|
71
|
+
cursor = await db.execute(
|
|
72
|
+
"SELECT * FROM event_log WHERE session_id = ? AND (closed IS NULL OR closed = 0) ORDER BY timestamp ASC, id ASC",
|
|
73
|
+
(session_id,),
|
|
74
|
+
)
|
|
75
|
+
rows = await cursor.fetchall()
|
|
76
|
+
return [dict(r) for r in rows]
|
|
77
|
+
|
|
78
|
+
async def mark_event_closed(self, action_id: str, session_id: Optional[str] = None) -> None:
|
|
79
|
+
"""Mark an event log entry as closed/deleted from the active view."""
|
|
80
|
+
async with self.store.connection() as db:
|
|
81
|
+
if session_id:
|
|
82
|
+
await db.execute(
|
|
83
|
+
"UPDATE event_log SET closed = 1 WHERE session_id = ? AND (json_extract(action_payload, '$.action_id') = ? OR action_payload LIKE ?)",
|
|
84
|
+
(session_id, action_id, f'%"{action_id}"%'),
|
|
85
|
+
)
|
|
86
|
+
else:
|
|
87
|
+
await db.execute(
|
|
88
|
+
"UPDATE event_log SET closed = 1 WHERE json_extract(action_payload, '$.action_id') = ? OR action_payload LIKE ?",
|
|
89
|
+
(action_id, f'%"{action_id}"%'),
|
|
90
|
+
)
|
|
91
|
+
await db.commit()
|
|
92
|
+
|
|
93
|
+
async def get_closed_events_count(self, session_id: str) -> int:
|
|
94
|
+
"""Get the count of closed events/tabs for a session."""
|
|
95
|
+
async with self.store.connection() as db:
|
|
96
|
+
cursor = await db.execute(
|
|
97
|
+
"SELECT COUNT(*) FROM event_log WHERE session_id = ? AND closed = 1",
|
|
98
|
+
(session_id,),
|
|
99
|
+
)
|
|
100
|
+
row = await cursor.fetchone()
|
|
101
|
+
return row[0] if row else 0
|
|
102
|
+
|
|
103
|
+
async def compact_timeline(self, session_id: str, keep_closed_events: int = 500) -> int:
|
|
104
|
+
"""Prune older closed event logs to prevent unbounded timeline table growth."""
|
|
105
|
+
async with self.store.connection() as db:
|
|
106
|
+
cursor = await db.execute(
|
|
107
|
+
"SELECT id FROM event_log WHERE session_id = ? AND closed = 1 ORDER BY timestamp DESC, id DESC",
|
|
108
|
+
(session_id,),
|
|
109
|
+
)
|
|
110
|
+
rows = await cursor.fetchall()
|
|
111
|
+
if len(rows) > keep_closed_events:
|
|
112
|
+
if keep_closed_events == 0:
|
|
113
|
+
cursor_del = await db.execute(
|
|
114
|
+
"DELETE FROM event_log WHERE session_id = ? AND closed = 1",
|
|
115
|
+
(session_id,),
|
|
116
|
+
)
|
|
117
|
+
else:
|
|
118
|
+
cutoff_id = rows[keep_closed_events][0]
|
|
119
|
+
cursor_del = await db.execute(
|
|
120
|
+
"DELETE FROM event_log WHERE session_id = ? AND closed = 1 AND id <= ?",
|
|
121
|
+
(session_id, cutoff_id),
|
|
122
|
+
)
|
|
123
|
+
await db.commit()
|
|
124
|
+
return cursor_del.rowcount
|
|
125
|
+
return 0
|
|
126
|
+
|
|
127
|
+
async def query_timeline(
|
|
128
|
+
self,
|
|
129
|
+
session_id: str,
|
|
130
|
+
schema_type: Optional[str] = None,
|
|
131
|
+
keyword: Optional[str] = None,
|
|
132
|
+
limit: int = 100,
|
|
133
|
+
) -> List[Dict[str, Any]]:
|
|
134
|
+
"""Query chronological timeline events with optional schema and keyword filters."""
|
|
135
|
+
query = "SELECT * FROM event_log WHERE session_id = ? AND (closed IS NULL OR closed = 0)"
|
|
136
|
+
params: List[Any] = [session_id]
|
|
137
|
+
|
|
138
|
+
if schema_type:
|
|
139
|
+
query += " AND schema_type = ?"
|
|
140
|
+
params.append(schema_type)
|
|
141
|
+
|
|
142
|
+
if keyword:
|
|
143
|
+
query += (
|
|
144
|
+
" AND (human_readable LIKE ? OR action_payload LIKE ? OR result_payload LIKE ?)"
|
|
145
|
+
)
|
|
146
|
+
like_kw = f"%{keyword}%"
|
|
147
|
+
params.extend([like_kw, like_kw, like_kw])
|
|
148
|
+
|
|
149
|
+
query += " ORDER BY timestamp ASC, id ASC LIMIT ?"
|
|
150
|
+
params.append(limit)
|
|
151
|
+
|
|
152
|
+
async with self.store.connection() as db:
|
|
153
|
+
db.row_factory = aiosqlite.Row
|
|
154
|
+
cursor = await db.execute(query, tuple(params))
|
|
155
|
+
rows = await cursor.fetchall()
|
|
156
|
+
return [dict(r) for r in rows]
|
|
157
|
+
|
|
158
|
+
async def replay_session_history(self, session_id: str) -> List[Dict[str, Any]]:
|
|
159
|
+
"""Replay session timeline history into a normalized, structured event sequence."""
|
|
160
|
+
raw_events = await self.get_event_log(session_id)
|
|
161
|
+
replayed: List[Dict[str, Any]] = []
|
|
162
|
+
|
|
163
|
+
for row in raw_events:
|
|
164
|
+
try:
|
|
165
|
+
action_data = json.loads(row.get("action_payload") or "{}")
|
|
166
|
+
except Exception:
|
|
167
|
+
action_data = {}
|
|
168
|
+
try:
|
|
169
|
+
result_data = json.loads(row.get("result_payload") or "{}")
|
|
170
|
+
except Exception:
|
|
171
|
+
result_data = {}
|
|
172
|
+
|
|
173
|
+
replayed.append(
|
|
174
|
+
{
|
|
175
|
+
"id": row.get("id"),
|
|
176
|
+
"timestamp": row.get("timestamp"),
|
|
177
|
+
"schema_type": row.get("schema_type"),
|
|
178
|
+
"message": row.get("human_readable"),
|
|
179
|
+
"tool_name": action_data.get("tool_name"),
|
|
180
|
+
"action_id": action_data.get("action_id"),
|
|
181
|
+
"status": result_data.get("status") or "completed",
|
|
182
|
+
"details": result_data,
|
|
183
|
+
}
|
|
184
|
+
)
|
|
185
|
+
return replayed
|