execweave 1.0.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.
- execweave/__init__.py +3 -0
- execweave/__main__.py +5 -0
- execweave/_conversation_records_core.py +902 -0
- execweave/_dashboard_shell_base.py +148 -0
- execweave/_http_proxy_base.py +565 -0
- execweave/_http_proxy_bounded.py +560 -0
- execweave/_http_proxy_stage.py +509 -0
- execweave/acceptance_output.py +19 -0
- execweave/agent_bootstrap.py +395 -0
- execweave/agent_topology.py +313 -0
- execweave/agent_trace.py +1162 -0
- execweave/agy_preview_sanitize.py +102 -0
- execweave/analysis.py +427 -0
- execweave/anthropic.py +228 -0
- execweave/anthropic_cli.py +171 -0
- execweave/anthropic_full_fidelity.py +385 -0
- execweave/antigravity_adapter.py +112 -0
- execweave/antigravity_adapter_base.py +479 -0
- execweave/antigravity_full_fidelity.py +656 -0
- execweave/antigravity_full_fidelity_base.py +172 -0
- execweave/antigravity_full_fidelity_collaboration_base.py +451 -0
- execweave/antigravity_hook_cli.py +209 -0
- execweave/antigravity_record.py +96 -0
- execweave/antigravity_subagent_linkage.py +449 -0
- execweave/antigravity_trace_capability.py +39 -0
- execweave/auto_specialized.py +547 -0
- execweave/backends.py +102 -0
- execweave/benchmark.py +80 -0
- execweave/claude_adapter.py +517 -0
- execweave/claude_child_transcript.py +314 -0
- execweave/claude_delegation.py +136 -0
- execweave/claude_full_fidelity.py +396 -0
- execweave/claude_hook_cli.py +209 -0
- execweave/claude_hook_contract.py +943 -0
- execweave/claude_model_observer.py +353 -0
- execweave/claude_record.py +106 -0
- execweave/cli.py +629 -0
- execweave/codex_adapter.py +455 -0
- execweave/codex_conversation.py +621 -0
- execweave/codex_full_fidelity.py +287 -0
- execweave/codex_hook_cli.py +301 -0
- execweave/codex_hook_entry.py +207 -0
- execweave/codex_hook_lifecycle.py +363 -0
- execweave/codex_message_diagnostics.py +322 -0
- execweave/codex_message_transport_diagnostics.py +399 -0
- execweave/codex_record.py +199 -0
- execweave/codex_rollout_structures.py +402 -0
- execweave/codex_rollout_trace.py +56 -0
- execweave/codex_rollout_trace_base.py +1509 -0
- execweave/collector.py +768 -0
- execweave/command.py +157 -0
- execweave/command_privacy.py +20 -0
- execweave/content_evidence.py +101 -0
- execweave/content_integrity.py +289 -0
- execweave/content_store.py +273 -0
- execweave/controlled_checks.py +561 -0
- execweave/conversation_archive.py +338 -0
- execweave/conversation_message_identity.py +264 -0
- execweave/conversation_preview.py +66 -0
- execweave/conversation_preview_antigravity.py +32 -0
- execweave/conversation_preview_claude.py +31 -0
- execweave/conversation_preview_codex.py +107 -0
- execweave/conversation_preview_common.py +180 -0
- execweave/conversation_preview_generic.py +188 -0
- execweave/conversation_preview_lines.py +133 -0
- execweave/conversation_preview_transcript.py +121 -0
- execweave/conversation_records.py +349 -0
- execweave/conversation_records_antigravity.py +370 -0
- execweave/conversation_records_codex.py +83 -0
- execweave/conversation_records_common.py +17 -0
- execweave/conversation_records_ollama.py +39 -0
- execweave/correlation.py +818 -0
- execweave/cursor_adapter.py +349 -0
- execweave/cursor_delegation.py +87 -0
- execweave/cursor_delegation_base.py +220 -0
- execweave/cursor_full_fidelity.py +489 -0
- execweave/cursor_hook_cli.py +195 -0
- execweave/cursor_hook_contract.py +439 -0
- execweave/cursor_lifecycle.py +159 -0
- execweave/cursor_record.py +96 -0
- execweave/dashboard_shell.py +283 -0
- execweave/delivery_status.py +94 -0
- execweave/entry.py +98 -0
- execweave/evidence_availability.py +113 -0
- execweave/evidence_grade.py +166 -0
- execweave/fidelity.py +304 -0
- execweave/filesystem.py +327 -0
- execweave/finalization.py +92 -0
- execweave/focus.py +118 -0
- execweave/framework_adapters/__init__.py +34 -0
- execweave/framework_adapters/autogen.py +398 -0
- execweave/framework_adapters/base.py +580 -0
- execweave/framework_adapters/camel.py +270 -0
- execweave/framework_adapters/camel_channel.py +71 -0
- execweave/framework_adapters/metagpt.py +315 -0
- execweave/framework_adapters/metagpt_ollama_compat.py +54 -0
- execweave/framework_adapters/metagpt_recording.py +342 -0
- execweave/framework_adapters/registry.py +90 -0
- execweave/graph.py +590 -0
- execweave/graph_ops.py +472 -0
- execweave/hook_command.py +32 -0
- execweave/hook_delivery.py +32 -0
- execweave/hook_input.py +16 -0
- execweave/http_proxy.py +187 -0
- execweave/http_proxy_cli.py +84 -0
- execweave/inference_gateway.py +476 -0
- execweave/inference_gateway_cli.py +211 -0
- execweave/inference_gateway_full_fidelity.py +613 -0
- execweave/inference_identity.py +76 -0
- execweave/inference_identity_cli.py +60 -0
- execweave/integrity.py +235 -0
- execweave/integrity_cli.py +55 -0
- execweave/investigation_index.py +445 -0
- execweave/litellm_callback.py +211 -0
- execweave/litellm_callback_cli.py +42 -0
- execweave/live.py +445 -0
- execweave/live_core.py +972 -0
- execweave/live_view.py +109 -0
- execweave/live_view_extra_style.py +11 -0
- execweave/live_view_markup.py +29 -0
- execweave/live_view_process_layout.py +650 -0
- execweave/live_view_readability.py +502 -0
- execweave/live_view_script_a.py +59 -0
- execweave/live_view_script_b.py +97 -0
- execweave/live_view_script_c.py +59 -0
- execweave/live_view_script_d.py +40 -0
- execweave/live_view_style.py +34 -0
- execweave/model_runtime.py +560 -0
- execweave/model_runtime_cli.py +265 -0
- execweave/model_runtime_full_fidelity.py +519 -0
- execweave/observation.py +53 -0
- execweave/observation_demo.py +69 -0
- execweave/openai_agents.py +267 -0
- execweave/openai_agents_sdk.py +453 -0
- execweave/openai_compatible.py +239 -0
- execweave/openai_compatible_cli.py +189 -0
- execweave/openai_compatible_full_fidelity.py +438 -0
- execweave/opencode_adapter.py +325 -0
- execweave/opencode_event_contract.py +734 -0
- execweave/opencode_full_fidelity.py +198 -0
- execweave/opencode_hook_cli.py +119 -0
- execweave/opencode_plugin_cli.py +150 -0
- execweave/opencode_record.py +96 -0
- execweave/opencode_task_linkage.py +225 -0
- execweave/overhead_benchmark.py +440 -0
- execweave/privacy.py +84 -0
- execweave/private_io.py +465 -0
- execweave/provider_capability.py +578 -0
- execweave/provider_lifecycle.py +282 -0
- execweave/provider_record.py +290 -0
- execweave/reader_identity.py +13 -0
- execweave/redacted_archive.py +906 -0
- execweave/risk.py +106 -0
- execweave/rule_pack.py +359 -0
- execweave/rule_pack_cli.py +57 -0
- execweave/run_assessment.py +200 -0
- execweave/runtime_endpoint_availability.py +44 -0
- execweave/scalability_benchmark.py +195 -0
- execweave/schema.py +62 -0
- execweave/scope.py +85 -0
- execweave/semantic.py +453 -0
- execweave/session_summary.py +159 -0
- execweave/sink.py +71 -0
- execweave/strace_backend.py +927 -0
- execweave/stream_assembly.py +363 -0
- execweave/task_artifacts.py +192 -0
- execweave/task_validation.py +317 -0
- execweave/theme.py +40 -0
- execweave/top.py +599 -0
- execweave/top_cli.py +150 -0
- execweave/validate.py +196 -0
- execweave/vendor/dagre.min.js +815 -0
- execweave/view_cli.py +49 -0
- execweave/viewer.py +474 -0
- execweave/viewer_agent_panel.py +630 -0
- execweave/viewer_agent_panel_antigravity.py +31 -0
- execweave/viewer_agent_panel_claude.py +9 -0
- execweave/viewer_agent_panel_codex.py +50 -0
- execweave/viewer_agent_panel_cursor.py +9 -0
- execweave/viewer_agent_panel_default.py +79 -0
- execweave/viewer_agent_panel_ollama.py +20 -0
- execweave/viewer_agent_panel_opencode.py +9 -0
- execweave/viewer_agent_panel_registry.py +20 -0
- execweave/viewer_archive_verifier.py +178 -0
- execweave/viewer_background_files.py +86 -0
- execweave/viewer_content_browser.py +307 -0
- execweave/viewer_content_health.py +208 -0
- execweave/viewer_content_inspector.py +309 -0
- execweave/viewer_controlled_checks.py +258 -0
- execweave/viewer_conversation_sync.py +115 -0
- execweave/viewer_dashboard_clean.py +405 -0
- execweave/viewer_dashboard_focus.py +127 -0
- execweave/viewer_dashboard_hardening.py +264 -0
- execweave/viewer_dashboard_hardening_v2.py +62 -0
- execweave/viewer_dashboard_projection.py +261 -0
- execweave/viewer_delivery_status.py +155 -0
- execweave/viewer_edge_decross.py +117 -0
- execweave/viewer_execution_flow.py +611 -0
- execweave/viewer_execution_flow_provider_normalization.py +107 -0
- execweave/viewer_execution_flow_safety.py +349 -0
- execweave/viewer_external_endpoints.py +307 -0
- execweave/viewer_flow_canvas.py +1140 -0
- execweave/viewer_flow_layout.py +922 -0
- execweave/viewer_fold_state.py +31 -0
- execweave/viewer_framework_flow.py +68 -0
- execweave/viewer_framework_model_output.py +133 -0
- execweave/viewer_gif.py +278 -0
- execweave/viewer_history_browser.py +225 -0
- execweave/viewer_investigation.py +268 -0
- execweave/viewer_layout_geometry.py +192 -0
- execweave/viewer_layout_v2.py +429 -0
- execweave/viewer_layout_v2_detached.py +25 -0
- execweave/viewer_limits.py +93 -0
- execweave/viewer_live_layout.py +61 -0
- execweave/viewer_message_handoffs.py +114 -0
- execweave/viewer_projection.py +488 -0
- execweave/viewer_projection_base.py +522 -0
- execweave/viewer_projection_bridges.py +214 -0
- execweave/viewer_recorded_sources.py +146 -0
- execweave/viewer_run_assessment.py +274 -0
- execweave/viewer_run_guide.py +175 -0
- execweave/viewer_runtime_evidence.py +258 -0
- execweave/viewer_semantic_projection.py +641 -0
- execweave/viewer_session_flow.py +491 -0
- execweave/viewer_structure_share.py +132 -0
- execweave/viewer_task_validation.py +241 -0
- execweave/viewer_tool_mirror_identity.py +75 -0
- execweave/viewer_workflow_mode.py +127 -0
- execweave/workflow.py +183 -0
- execweave-1.0.0.dist-info/METADATA +462 -0
- execweave-1.0.0.dist-info/RECORD +234 -0
- execweave-1.0.0.dist-info/WHEEL +4 -0
- execweave-1.0.0.dist-info/entry_points.txt +30 -0
- execweave-1.0.0.dist-info/licenses/LICENSE +16 -0
execweave/top.py
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import shlex
|
|
6
|
+
import shutil
|
|
7
|
+
import stat
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
from collections import deque
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import TextIO
|
|
17
|
+
from urllib.error import HTTPError, URLError
|
|
18
|
+
from urllib.parse import parse_qs, urlsplit, urlunsplit
|
|
19
|
+
from urllib.request import Request, urlopen
|
|
20
|
+
|
|
21
|
+
import psutil
|
|
22
|
+
|
|
23
|
+
from .collector import infer_agent_name
|
|
24
|
+
from .live import LiveResult, run_live
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_ATTACH_TOKEN_PREFIX = "execweave-top-"
|
|
28
|
+
_ATTACH_TOKEN_SUFFIX = ".token"
|
|
29
|
+
_LIVE_TOKEN_HEADER = "X-ExecWeave-Token"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class TerminalState:
|
|
34
|
+
event_count: int = 0
|
|
35
|
+
node_count: int = 0
|
|
36
|
+
edge_count: int = 0
|
|
37
|
+
sequence: int = -1
|
|
38
|
+
finished: bool = False
|
|
39
|
+
compact: bool = False
|
|
40
|
+
connection_status: str = "CONNECTING"
|
|
41
|
+
nodes: dict[str, dict[str, object]] = field(default_factory=dict)
|
|
42
|
+
edges: dict[str, dict[str, object]] = field(default_factory=dict)
|
|
43
|
+
recent: deque[str] = field(default_factory=lambda: deque(maxlen=8))
|
|
44
|
+
|
|
45
|
+
@staticmethod
|
|
46
|
+
def _edge_id(edge: dict[str, object]) -> str:
|
|
47
|
+
value = edge.get("id")
|
|
48
|
+
if isinstance(value, str) and value:
|
|
49
|
+
return value
|
|
50
|
+
return f"{edge.get('source')}:{edge.get('relation')}:{edge.get('target')}"
|
|
51
|
+
|
|
52
|
+
def apply_snapshot(self, payload: dict[str, object], sequence: int) -> None:
|
|
53
|
+
self.sequence = sequence
|
|
54
|
+
self.event_count = int(payload.get("event_count", 0) or 0)
|
|
55
|
+
self.node_count = int(payload.get("node_count", 0) or 0)
|
|
56
|
+
self.edge_count = int(payload.get("edge_count", 0) or 0)
|
|
57
|
+
self.compact = bool(payload.get("live_payload_compact"))
|
|
58
|
+
self.nodes = {
|
|
59
|
+
str(node.get("id")): node
|
|
60
|
+
for node in payload.get("nodes", [])
|
|
61
|
+
if isinstance(node, dict) and node.get("id")
|
|
62
|
+
}
|
|
63
|
+
self.edges = {
|
|
64
|
+
self._edge_id(edge): edge
|
|
65
|
+
for edge in payload.get("edges", [])
|
|
66
|
+
if isinstance(edge, dict)
|
|
67
|
+
}
|
|
68
|
+
self.connection_status = "LIVE"
|
|
69
|
+
|
|
70
|
+
def apply_update(self, update: dict[str, object]) -> None:
|
|
71
|
+
self.sequence = int(update.get("sequence", self.sequence) or self.sequence)
|
|
72
|
+
final_graph = update.get("final_graph")
|
|
73
|
+
if update.get("terminal") and isinstance(final_graph, dict):
|
|
74
|
+
# The web client and Top must consume the same authoritative final
|
|
75
|
+
# entities, including canonical identity replacement, before stopping.
|
|
76
|
+
self.apply_snapshot(final_graph, self.sequence)
|
|
77
|
+
return
|
|
78
|
+
self.event_count = int(update.get("event_count", self.event_count) or 0)
|
|
79
|
+
self.node_count = int(update.get("node_count", self.node_count) or 0)
|
|
80
|
+
self.edge_count = int(update.get("edge_count", self.edge_count) or 0)
|
|
81
|
+
if update.get("live_payload_compact"):
|
|
82
|
+
self.compact = True
|
|
83
|
+
for key in ("nodes_added", "nodes_updated"):
|
|
84
|
+
for node in update.get(key, []):
|
|
85
|
+
if not isinstance(node, dict) or not node.get("id"):
|
|
86
|
+
continue
|
|
87
|
+
self.nodes[str(node["id"])] = node
|
|
88
|
+
self._remember_node(node)
|
|
89
|
+
for key in ("edges_added", "edges_updated"):
|
|
90
|
+
for edge in update.get(key, []):
|
|
91
|
+
if not isinstance(edge, dict):
|
|
92
|
+
continue
|
|
93
|
+
self.edges[self._edge_id(edge)] = edge
|
|
94
|
+
self._remember_edge(edge)
|
|
95
|
+
|
|
96
|
+
def _remember_node(self, node: dict[str, object]) -> None:
|
|
97
|
+
node_type = str(node.get("type") or "node")
|
|
98
|
+
name = str(node.get("name") or node.get("id") or "")
|
|
99
|
+
self.recent.append(f"{node_type:<18} {name}")
|
|
100
|
+
|
|
101
|
+
def _remember_edge(self, edge: dict[str, object]) -> None:
|
|
102
|
+
relation = str(edge.get("relation") or "edge")
|
|
103
|
+
target = str(edge.get("target") or "")
|
|
104
|
+
count = int(edge.get("count", 1) or 1)
|
|
105
|
+
suffix = f" x{count}" if count > 1 else ""
|
|
106
|
+
self.recent.append(f"{relation:<18} {target}{suffix}")
|
|
107
|
+
|
|
108
|
+
def apply_response(self, response: dict[str, object]) -> None:
|
|
109
|
+
kind = response.get("kind")
|
|
110
|
+
if kind == "snapshot":
|
|
111
|
+
graph = response.get("graph")
|
|
112
|
+
if isinstance(graph, dict):
|
|
113
|
+
self.apply_snapshot(graph, int(response.get("sequence", 0) or 0))
|
|
114
|
+
elif kind == "delta":
|
|
115
|
+
base = int(response.get("base_sequence", self.sequence) or 0)
|
|
116
|
+
if self.sequence >= 0 and base != self.sequence:
|
|
117
|
+
self.sequence = -1
|
|
118
|
+
self.connection_status = "RESYNCING"
|
|
119
|
+
return
|
|
120
|
+
for update in response.get("updates", []):
|
|
121
|
+
if isinstance(update, dict):
|
|
122
|
+
expected = self.sequence + 1
|
|
123
|
+
sequence = int(update.get("sequence", expected) or expected)
|
|
124
|
+
if self.sequence >= 0 and sequence != expected:
|
|
125
|
+
self.sequence = -1
|
|
126
|
+
self.connection_status = "RESYNCING"
|
|
127
|
+
return
|
|
128
|
+
self.apply_update(update)
|
|
129
|
+
self.connection_status = "LIVE"
|
|
130
|
+
elif kind == "noop":
|
|
131
|
+
self.sequence = int(response.get("sequence", self.sequence) or self.sequence)
|
|
132
|
+
self.event_count = int(response.get("event_count", self.event_count) or 0)
|
|
133
|
+
self.node_count = int(response.get("node_count", self.node_count) or 0)
|
|
134
|
+
self.edge_count = int(response.get("edge_count", self.edge_count) or 0)
|
|
135
|
+
self.connection_status = "LIVE"
|
|
136
|
+
self.finished = bool(response.get("live_finished"))
|
|
137
|
+
if self.finished:
|
|
138
|
+
self.connection_status = "FINISHED"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _entity_type_count(state: TerminalState, *types: str) -> int | None:
|
|
142
|
+
if state.compact and not state.nodes:
|
|
143
|
+
return None
|
|
144
|
+
wanted = set(types)
|
|
145
|
+
return sum(1 for node in state.nodes.values() if str(node.get("type")) in wanted)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _model_summary(state: TerminalState) -> str:
|
|
149
|
+
names: list[str] = []
|
|
150
|
+
for node in state.nodes.values():
|
|
151
|
+
node_type = str(node.get("type") or "")
|
|
152
|
+
attributes = node.get("attributes") if isinstance(node.get("attributes"), dict) else {}
|
|
153
|
+
if node_type == "model":
|
|
154
|
+
value = node.get("name") or node.get("id")
|
|
155
|
+
if value:
|
|
156
|
+
names.append(str(value))
|
|
157
|
+
for key in ("resolved_model", "requested_model"):
|
|
158
|
+
value = attributes.get(key)
|
|
159
|
+
if isinstance(value, str) and value:
|
|
160
|
+
names.append(value)
|
|
161
|
+
unique = list(dict.fromkeys(names))
|
|
162
|
+
if not unique:
|
|
163
|
+
return "-"
|
|
164
|
+
if len(unique) == 1:
|
|
165
|
+
return unique[0]
|
|
166
|
+
return f"{unique[0]} +{len(unique) - 1}"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _process_metrics(state: TerminalState, cache: dict[int, psutil.Process]) -> tuple[str, str]:
|
|
170
|
+
pids: set[int] = set()
|
|
171
|
+
for node in state.nodes.values():
|
|
172
|
+
if node.get("type") != "process":
|
|
173
|
+
continue
|
|
174
|
+
attributes = node.get("attributes")
|
|
175
|
+
if not isinstance(attributes, dict):
|
|
176
|
+
continue
|
|
177
|
+
pid = attributes.get("pid")
|
|
178
|
+
if isinstance(pid, int) and pid > 0:
|
|
179
|
+
pids.add(pid)
|
|
180
|
+
if not pids:
|
|
181
|
+
return "-", "-"
|
|
182
|
+
cpu = 0.0
|
|
183
|
+
rss = 0
|
|
184
|
+
measured = 0
|
|
185
|
+
for pid in pids:
|
|
186
|
+
try:
|
|
187
|
+
process = cache.get(pid)
|
|
188
|
+
if process is None:
|
|
189
|
+
process = psutil.Process(pid)
|
|
190
|
+
process.cpu_percent(interval=None)
|
|
191
|
+
cache[pid] = process
|
|
192
|
+
cpu += process.cpu_percent(interval=None)
|
|
193
|
+
rss += process.memory_info().rss
|
|
194
|
+
measured += 1
|
|
195
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
|
|
196
|
+
cache.pop(pid, None)
|
|
197
|
+
if not measured:
|
|
198
|
+
return "-", "-"
|
|
199
|
+
rss_mb = rss / (1024 * 1024)
|
|
200
|
+
return f"{cpu:.1f}%", f"{rss_mb:.0f}M"
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _format_count(value: int | None) -> str:
|
|
204
|
+
return "-" if value is None else str(value)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _evidence_summary(state: TerminalState) -> str:
|
|
208
|
+
types = {str(node.get("type") or "") for node in state.nodes.values()}
|
|
209
|
+
semantic = bool(types & {"agent", "tool", "tool_call", "mcp_server", "model", "command"})
|
|
210
|
+
return "runtime+semantic" if semantic else "runtime"
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def format_dashboard(
|
|
214
|
+
state: TerminalState,
|
|
215
|
+
*,
|
|
216
|
+
command: list[str],
|
|
217
|
+
process_cache: dict[int, psutil.Process] | None = None,
|
|
218
|
+
width: int | None = None,
|
|
219
|
+
) -> str:
|
|
220
|
+
cache = process_cache if process_cache is not None else {}
|
|
221
|
+
width = width or shutil.get_terminal_size((120, 30)).columns
|
|
222
|
+
width = max(80, width)
|
|
223
|
+
agent = infer_agent_name(command)
|
|
224
|
+
cpu, rss = _process_metrics(state, cache)
|
|
225
|
+
procs = _entity_type_count(state, "process")
|
|
226
|
+
tools = _entity_type_count(state, "tool_call")
|
|
227
|
+
files = _entity_type_count(state, "file")
|
|
228
|
+
network = _entity_type_count(state, "network_endpoint")
|
|
229
|
+
infer = sum(
|
|
230
|
+
1
|
|
231
|
+
for node in state.nodes.values()
|
|
232
|
+
if "inference" in str(node.get("type") or "").lower()
|
|
233
|
+
)
|
|
234
|
+
if state.compact and not state.nodes:
|
|
235
|
+
infer_value: str = "-"
|
|
236
|
+
else:
|
|
237
|
+
infer_value = str(infer)
|
|
238
|
+
model = _model_summary(state)
|
|
239
|
+
command_text = " ".join(command) or "-"
|
|
240
|
+
max_command = max(12, width - 94)
|
|
241
|
+
if len(command_text) > max_command:
|
|
242
|
+
command_text = command_text[: max(1, max_command - 1)] + "…"
|
|
243
|
+
header = (
|
|
244
|
+
"AGENT CPU RSS PROCS TOOLS FILES NET INFER MODEL "
|
|
245
|
+
"EVENTS TRACE COMMAND"
|
|
246
|
+
)
|
|
247
|
+
row = (
|
|
248
|
+
f"{agent[:15]:<15} {cpu:>6} {rss:>6} {_format_count(procs):>5} "
|
|
249
|
+
f"{_format_count(tools):>5} {_format_count(files):>5} {_format_count(network):>3} "
|
|
250
|
+
f"{infer_value:>5} {model[:21]:<21} {state.event_count:>6} "
|
|
251
|
+
f"{_evidence_summary(state):<17} {command_text}"
|
|
252
|
+
)
|
|
253
|
+
title = (
|
|
254
|
+
f"ExecWeave Top [{state.connection_status}] seq={state.sequence} "
|
|
255
|
+
f"nodes={state.node_count} edges={state.edge_count}"
|
|
256
|
+
)
|
|
257
|
+
lines = [title[:width], "─" * min(width, max(len(title), 80)), header[:width], row[:width]]
|
|
258
|
+
if state.compact:
|
|
259
|
+
lines.extend(
|
|
260
|
+
[
|
|
261
|
+
"",
|
|
262
|
+
"Large-graph protective mode: category details are bounded; "
|
|
263
|
+
"collection and the Web Viewer remain available.",
|
|
264
|
+
]
|
|
265
|
+
)
|
|
266
|
+
if state.recent:
|
|
267
|
+
lines.extend(["", "Recent activity"])
|
|
268
|
+
lines.extend(f" {item}"[:width] for item in reversed(state.recent))
|
|
269
|
+
lines.extend(
|
|
270
|
+
[
|
|
271
|
+
"",
|
|
272
|
+
"This dashboard is attached to the live session; the Agent remains interactive "
|
|
273
|
+
"in the original terminal.",
|
|
274
|
+
]
|
|
275
|
+
)
|
|
276
|
+
return "\n".join(lines)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _split_authenticated_live_url(raw: str) -> tuple[str, str]:
|
|
280
|
+
parsed = urlsplit(raw)
|
|
281
|
+
values = parse_qs(parsed.query).get("t", [])
|
|
282
|
+
if len(values) != 1 or not values[0]:
|
|
283
|
+
raise ValueError("live server did not provide an authentication token")
|
|
284
|
+
base = urlunsplit((parsed.scheme, parsed.netloc, parsed.path or "/", "", ""))
|
|
285
|
+
return base, values[0]
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _create_attach_token_file(token: str) -> Path:
|
|
289
|
+
if not token:
|
|
290
|
+
raise ValueError("live authentication token must not be empty")
|
|
291
|
+
fd, raw_path = tempfile.mkstemp(prefix=_ATTACH_TOKEN_PREFIX, suffix=_ATTACH_TOKEN_SUFFIX)
|
|
292
|
+
path = Path(raw_path)
|
|
293
|
+
try:
|
|
294
|
+
with os.fdopen(fd, "w", encoding="utf-8", newline="") as handle:
|
|
295
|
+
handle.write(token)
|
|
296
|
+
if os.name != "nt":
|
|
297
|
+
os.chmod(path, 0o600)
|
|
298
|
+
except BaseException:
|
|
299
|
+
path.unlink(missing_ok=True)
|
|
300
|
+
raise
|
|
301
|
+
return path
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _consume_attach_token_file(raw_path: str | Path) -> str:
|
|
305
|
+
path = Path(raw_path).expanduser().resolve()
|
|
306
|
+
temp_root = Path(tempfile.gettempdir()).resolve()
|
|
307
|
+
if path.parent != temp_root:
|
|
308
|
+
raise ValueError("detached dashboard token file must be in the system temp directory")
|
|
309
|
+
if not (path.name.startswith(_ATTACH_TOKEN_PREFIX) and path.name.endswith(_ATTACH_TOKEN_SUFFIX)):
|
|
310
|
+
raise ValueError("invalid detached dashboard token file name")
|
|
311
|
+
try:
|
|
312
|
+
info = path.lstat()
|
|
313
|
+
if not stat.S_ISREG(info.st_mode) or info.st_size > 512:
|
|
314
|
+
raise ValueError("invalid detached dashboard token file")
|
|
315
|
+
if os.name != "nt":
|
|
316
|
+
if info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) & 0o077:
|
|
317
|
+
raise ValueError("detached dashboard token file permissions are not private")
|
|
318
|
+
token = path.read_text(encoding="utf-8")
|
|
319
|
+
except OSError as exc:
|
|
320
|
+
raise ValueError("detached dashboard token file is unavailable") from exc
|
|
321
|
+
finally:
|
|
322
|
+
path.unlink(missing_ok=True)
|
|
323
|
+
if not token:
|
|
324
|
+
raise ValueError("detached dashboard token file is empty")
|
|
325
|
+
return token
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
class TerminalTopClient:
|
|
329
|
+
def __init__(
|
|
330
|
+
self,
|
|
331
|
+
*,
|
|
332
|
+
live_url: str,
|
|
333
|
+
token: str,
|
|
334
|
+
command: list[str],
|
|
335
|
+
refresh_seconds: float,
|
|
336
|
+
stream: TextIO,
|
|
337
|
+
stop_event: threading.Event,
|
|
338
|
+
) -> None:
|
|
339
|
+
if not token:
|
|
340
|
+
raise ValueError("live authentication token must not be empty")
|
|
341
|
+
self.live_url = live_url.rstrip("/")
|
|
342
|
+
self.token = token
|
|
343
|
+
self.command = list(command)
|
|
344
|
+
self.refresh_seconds = max(0.1, refresh_seconds)
|
|
345
|
+
self.stream = stream
|
|
346
|
+
self.stop_event = stop_event
|
|
347
|
+
self.state = TerminalState()
|
|
348
|
+
self.process_cache: dict[int, psutil.Process] = {}
|
|
349
|
+
self._interactive = bool(getattr(stream, "isatty", lambda: False)())
|
|
350
|
+
self._last_noninteractive_render = 0.0
|
|
351
|
+
|
|
352
|
+
def _fetch(self) -> dict[str, object]:
|
|
353
|
+
url = f"{self.live_url}/live.json?after={self.state.sequence}"
|
|
354
|
+
request = Request(url, headers={_LIVE_TOKEN_HEADER: self.token})
|
|
355
|
+
with urlopen(request, timeout=max(1.0, self.refresh_seconds * 4)) as response:
|
|
356
|
+
payload = json.loads(response.read().decode("utf-8"))
|
|
357
|
+
if not isinstance(payload, dict):
|
|
358
|
+
raise ValueError("live endpoint returned a non-object payload")
|
|
359
|
+
return payload
|
|
360
|
+
|
|
361
|
+
def _render(self, *, force: bool = False) -> None:
|
|
362
|
+
now = time.monotonic()
|
|
363
|
+
if not self._interactive and not force and now - self._last_noninteractive_render < 5.0:
|
|
364
|
+
return
|
|
365
|
+
self._last_noninteractive_render = now
|
|
366
|
+
dashboard = format_dashboard(
|
|
367
|
+
self.state,
|
|
368
|
+
command=self.command,
|
|
369
|
+
process_cache=self.process_cache,
|
|
370
|
+
)
|
|
371
|
+
if self._interactive:
|
|
372
|
+
self.stream.write("\x1b]0;ExecWeave Top\x07")
|
|
373
|
+
self.stream.write("\x1b[2J\x1b[H")
|
|
374
|
+
self.stream.write(dashboard + "\n")
|
|
375
|
+
self.stream.flush()
|
|
376
|
+
|
|
377
|
+
def run(self) -> None:
|
|
378
|
+
while not self.stop_event.is_set():
|
|
379
|
+
try:
|
|
380
|
+
response = self._fetch()
|
|
381
|
+
self.state.apply_response(response)
|
|
382
|
+
self._render(force=self.state.finished)
|
|
383
|
+
if self.state.finished:
|
|
384
|
+
return
|
|
385
|
+
except (HTTPError, URLError, OSError, ValueError, json.JSONDecodeError):
|
|
386
|
+
self.state.connection_status = "RECONNECTING"
|
|
387
|
+
self._render()
|
|
388
|
+
self.stop_event.wait(self.refresh_seconds)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def run_attached_top(
|
|
392
|
+
live_url: str,
|
|
393
|
+
*,
|
|
394
|
+
token: str,
|
|
395
|
+
command: list[str],
|
|
396
|
+
refresh_seconds: float = 0.50,
|
|
397
|
+
stream: TextIO | None = None,
|
|
398
|
+
) -> None:
|
|
399
|
+
"""Render an existing authenticated live session in the current terminal."""
|
|
400
|
+
stop_event = threading.Event()
|
|
401
|
+
client = TerminalTopClient(
|
|
402
|
+
live_url=live_url,
|
|
403
|
+
token=token,
|
|
404
|
+
command=command,
|
|
405
|
+
refresh_seconds=refresh_seconds,
|
|
406
|
+
stream=stream or sys.stdout,
|
|
407
|
+
stop_event=stop_event,
|
|
408
|
+
)
|
|
409
|
+
try:
|
|
410
|
+
client.run()
|
|
411
|
+
except KeyboardInterrupt:
|
|
412
|
+
stop_event.set()
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _dashboard_attach_argv(
|
|
416
|
+
live_url: str,
|
|
417
|
+
*,
|
|
418
|
+
token_file: Path,
|
|
419
|
+
command: list[str],
|
|
420
|
+
refresh_seconds: float,
|
|
421
|
+
) -> list[str]:
|
|
422
|
+
return [
|
|
423
|
+
sys.executable,
|
|
424
|
+
"-m",
|
|
425
|
+
"execweave",
|
|
426
|
+
"top",
|
|
427
|
+
"--attach",
|
|
428
|
+
live_url,
|
|
429
|
+
"--attach-token-file",
|
|
430
|
+
str(token_file),
|
|
431
|
+
"--attach-command-json",
|
|
432
|
+
json.dumps(command, ensure_ascii=False),
|
|
433
|
+
"--refresh",
|
|
434
|
+
str(refresh_seconds),
|
|
435
|
+
]
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _launch_macos_terminal(argv: list[str]) -> bool:
|
|
439
|
+
osascript = shutil.which("osascript")
|
|
440
|
+
if osascript is None:
|
|
441
|
+
return False
|
|
442
|
+
command = shlex.join(argv)
|
|
443
|
+
escaped = command.replace("\\", "\\\\").replace('"', '\\"')
|
|
444
|
+
script = (
|
|
445
|
+
'tell application "Terminal"\n'
|
|
446
|
+
"activate\n"
|
|
447
|
+
f'do script "{escaped}"\n'
|
|
448
|
+
"end tell"
|
|
449
|
+
)
|
|
450
|
+
subprocess.Popen(
|
|
451
|
+
[osascript, "-e", script],
|
|
452
|
+
stdout=subprocess.DEVNULL,
|
|
453
|
+
stderr=subprocess.DEVNULL,
|
|
454
|
+
)
|
|
455
|
+
return True
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _launch_linux_terminal(argv: list[str]) -> bool:
|
|
459
|
+
if not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
|
|
460
|
+
return False
|
|
461
|
+
candidates = (
|
|
462
|
+
("x-terminal-emulator", ["-e"]),
|
|
463
|
+
("gnome-terminal", ["--"]),
|
|
464
|
+
("konsole", ["-e"]),
|
|
465
|
+
("kitty", []),
|
|
466
|
+
("alacritty", ["-e"]),
|
|
467
|
+
)
|
|
468
|
+
for executable, prefix in candidates:
|
|
469
|
+
path = shutil.which(executable)
|
|
470
|
+
if path is None:
|
|
471
|
+
continue
|
|
472
|
+
subprocess.Popen(
|
|
473
|
+
[path, *prefix, *argv],
|
|
474
|
+
stdout=subprocess.DEVNULL,
|
|
475
|
+
stderr=subprocess.DEVNULL,
|
|
476
|
+
)
|
|
477
|
+
return True
|
|
478
|
+
return False
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def launch_dashboard_terminal(
|
|
482
|
+
live_url: str,
|
|
483
|
+
*,
|
|
484
|
+
token_file: Path,
|
|
485
|
+
command: list[str],
|
|
486
|
+
refresh_seconds: float,
|
|
487
|
+
) -> bool:
|
|
488
|
+
"""Launch the Top client in a separate terminal without touching Agent stdio."""
|
|
489
|
+
argv = _dashboard_attach_argv(
|
|
490
|
+
live_url,
|
|
491
|
+
token_file=token_file,
|
|
492
|
+
command=command,
|
|
493
|
+
refresh_seconds=refresh_seconds,
|
|
494
|
+
)
|
|
495
|
+
try:
|
|
496
|
+
if os.name == "nt":
|
|
497
|
+
creationflags = getattr(subprocess, "CREATE_NEW_CONSOLE", 0)
|
|
498
|
+
subprocess.Popen(argv, creationflags=creationflags)
|
|
499
|
+
return True
|
|
500
|
+
if sys.platform == "darwin":
|
|
501
|
+
return _launch_macos_terminal(argv)
|
|
502
|
+
return _launch_linux_terminal(argv)
|
|
503
|
+
except OSError:
|
|
504
|
+
return False
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def run_top(
|
|
508
|
+
command: list[str],
|
|
509
|
+
*,
|
|
510
|
+
watch_root: str | Path,
|
|
511
|
+
output_dir: str | Path | None = None,
|
|
512
|
+
poll_interval: float = 0.10,
|
|
513
|
+
refresh_seconds: float = 0.50,
|
|
514
|
+
collect_filesystem: bool = True,
|
|
515
|
+
collect_network: bool = True,
|
|
516
|
+
port: int = 0,
|
|
517
|
+
open_browser: bool = False,
|
|
518
|
+
linger_seconds: float = 2.0,
|
|
519
|
+
content_capture: str = "full",
|
|
520
|
+
stream: TextIO | None = None,
|
|
521
|
+
) -> LiveResult:
|
|
522
|
+
if not command:
|
|
523
|
+
raise ValueError("command must not be empty")
|
|
524
|
+
|
|
525
|
+
stop_event = threading.Event()
|
|
526
|
+
terminal_thread: threading.Thread | None = None
|
|
527
|
+
token_file: Path | None = None
|
|
528
|
+
access: dict[str, str | None] = {"url": None, "token": None}
|
|
529
|
+
dashboard_started = False
|
|
530
|
+
|
|
531
|
+
def maybe_start_dashboard() -> None:
|
|
532
|
+
nonlocal terminal_thread, token_file, dashboard_started
|
|
533
|
+
live_url, token = access["url"], access["token"]
|
|
534
|
+
if dashboard_started or live_url is None or token is None:
|
|
535
|
+
return
|
|
536
|
+
dashboard_started = True
|
|
537
|
+
if stream is not None:
|
|
538
|
+
client = TerminalTopClient(
|
|
539
|
+
live_url=live_url, token=token, command=command,
|
|
540
|
+
refresh_seconds=refresh_seconds, stream=stream, stop_event=stop_event,
|
|
541
|
+
)
|
|
542
|
+
terminal_thread = threading.Thread(
|
|
543
|
+
target=client.run, name="execweave-top-inline", daemon=True,
|
|
544
|
+
)
|
|
545
|
+
terminal_thread.start()
|
|
546
|
+
return
|
|
547
|
+
|
|
548
|
+
token_file = _create_attach_token_file(token)
|
|
549
|
+
launched = launch_dashboard_terminal(
|
|
550
|
+
live_url, token_file=token_file, command=command,
|
|
551
|
+
refresh_seconds=refresh_seconds,
|
|
552
|
+
)
|
|
553
|
+
if not launched:
|
|
554
|
+
attach = shlex.join(
|
|
555
|
+
_dashboard_attach_argv(
|
|
556
|
+
live_url, token_file=token_file, command=command,
|
|
557
|
+
refresh_seconds=refresh_seconds,
|
|
558
|
+
)
|
|
559
|
+
)
|
|
560
|
+
print(
|
|
561
|
+
"ExecWeave Top: no GUI terminal was detected. "
|
|
562
|
+
f"Open another terminal and run: {attach}",
|
|
563
|
+
file=sys.stderr, flush=True,
|
|
564
|
+
)
|
|
565
|
+
|
|
566
|
+
def announce(live_url: str) -> None:
|
|
567
|
+
access["url"] = live_url
|
|
568
|
+
maybe_start_dashboard()
|
|
569
|
+
|
|
570
|
+
def announce_api_token(token: str) -> None:
|
|
571
|
+
access["token"] = token
|
|
572
|
+
maybe_start_dashboard()
|
|
573
|
+
|
|
574
|
+
def announce_pairing_code(code: str) -> None:
|
|
575
|
+
if open_browser:
|
|
576
|
+
print(f"ExecWeave pairing code: {code}", file=sys.stderr, flush=True)
|
|
577
|
+
|
|
578
|
+
try:
|
|
579
|
+
return run_live(
|
|
580
|
+
command,
|
|
581
|
+
watch_root=watch_root,
|
|
582
|
+
output_dir=output_dir,
|
|
583
|
+
poll_interval=poll_interval,
|
|
584
|
+
collect_filesystem=collect_filesystem,
|
|
585
|
+
collect_network=collect_network,
|
|
586
|
+
port=port,
|
|
587
|
+
open_browser=open_browser,
|
|
588
|
+
linger_seconds=max(linger_seconds, refresh_seconds * 2),
|
|
589
|
+
content_capture=content_capture,
|
|
590
|
+
announce=announce,
|
|
591
|
+
announce_api_token=announce_api_token,
|
|
592
|
+
announce_pairing_code=announce_pairing_code,
|
|
593
|
+
)
|
|
594
|
+
finally:
|
|
595
|
+
stop_event.set()
|
|
596
|
+
if terminal_thread is not None:
|
|
597
|
+
terminal_thread.join(timeout=3)
|
|
598
|
+
if token_file is not None:
|
|
599
|
+
token_file.unlink(missing_ok=True)
|