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.
Files changed (104) hide show
  1. ether/__init__.py +32 -0
  2. ether/assets/wordlists/common_dirs.txt.gz +0 -0
  3. ether/assets/wordlists/common_params.txt.gz +0 -0
  4. ether/assets/wordlists/common_passwords.txt.gz +0 -0
  5. ether/assets/wordlists/common_usernames.txt.gz +0 -0
  6. ether/assets/wordlists/subdomains_500.txt.gz +0 -0
  7. ether/cli/__init__.py +5 -0
  8. ether/cli/__main__.py +8 -0
  9. ether/cli/commands/__init__.py +1 -0
  10. ether/cli/commands/doctor.py +21 -0
  11. ether/cli/commands/graph.py +311 -0
  12. ether/cli/commands/logs.py +45 -0
  13. ether/cli/commands/mcp.py +49 -0
  14. ether/cli/commands/run.py +146 -0
  15. ether/cli/commands/session.py +61 -0
  16. ether/cli/commands/telemetry.py +51 -0
  17. ether/cli/commands/tool.py +131 -0
  18. ether/cli/context.py +71 -0
  19. ether/cli/formatters.py +39 -0
  20. ether/cli/router.py +368 -0
  21. ether/common/__init__.py +201 -0
  22. ether/common/algorithms.py +407 -0
  23. ether/common/canonicalize.py +93 -0
  24. ether/common/context.py +25 -0
  25. ether/common/crypto.py +183 -0
  26. ether/common/embeddings.py +93 -0
  27. ether/common/exceptions.py +13 -0
  28. ether/common/logging.py +386 -0
  29. ether/common/secure_memory.py +159 -0
  30. ether/common/ssrf.py +93 -0
  31. ether/core/__init__.py +25 -0
  32. ether/core/diagnostics.py +368 -0
  33. ether/core/executor.py +296 -0
  34. ether/core/sandbox.py +118 -0
  35. ether/core/session.py +956 -0
  36. ether/gateway/__init__.py +21 -0
  37. ether/gateway/gate.py +392 -0
  38. ether/gateway/network.py +98 -0
  39. ether/gateway/preflight.py +802 -0
  40. ether/graph/__init__.py +13 -0
  41. ether/graph/analytics.py +334 -0
  42. ether/graph/store.py +1615 -0
  43. ether/graph/telemetry.py +334 -0
  44. ether/graph/timeline.py +185 -0
  45. ether/mcp/__init__.py +5 -0
  46. ether/mcp/server.py +382 -0
  47. ether/paths.py +176 -0
  48. ether/py.typed +0 -0
  49. ether/registry/__init__.py +7 -0
  50. ether/registry/adapter.py +194 -0
  51. ether/registry/manifest.py +53 -0
  52. ether/registry/registry.py +150 -0
  53. ether/registry/wordlists.py +156 -0
  54. ether/schemas/__init__.py +50 -0
  55. ether/schemas/base.py +122 -0
  56. ether/schemas/credential.py +50 -0
  57. ether/schemas/dns.py +116 -0
  58. ether/schemas/host_internal.py +58 -0
  59. ether/schemas/network.py +142 -0
  60. ether/schemas/power.py +68 -0
  61. ether/schemas/vulnerability.py +221 -0
  62. ether/schemas/web.py +172 -0
  63. ether_core-0.1.0.dist-info/METADATA +440 -0
  64. ether_core-0.1.0.dist-info/RECORD +104 -0
  65. ether_core-0.1.0.dist-info/WHEEL +4 -0
  66. ether_core-0.1.0.dist-info/entry_points.txt +2 -0
  67. ether_core-0.1.0.dist-info/licenses/LICENSE +21 -0
  68. tools/__init__.py +0 -0
  69. tools/dnspython/__init__.py +1 -0
  70. tools/dnspython/adapter.py +302 -0
  71. tools/dnspython/cli.py +202 -0
  72. tools/dnspython/manifest.toml +138 -0
  73. tools/ffuf/__init__.py +1 -0
  74. tools/ffuf/adapter.py +183 -0
  75. tools/ffuf/manifest.toml +121 -0
  76. tools/gobuster/__init__.py +0 -0
  77. tools/gobuster/adapter.py +90 -0
  78. tools/gobuster/manifest.toml +104 -0
  79. tools/http_probe/adapter.py +256 -0
  80. tools/http_probe/manifest.toml +40 -0
  81. tools/netexec/__init__.py +1 -0
  82. tools/netexec/adapter.py +163 -0
  83. tools/netexec/manifest.toml +83 -0
  84. tools/nikto/__init__.py +0 -0
  85. tools/nikto/adapter.py +145 -0
  86. tools/nikto/manifest.toml +108 -0
  87. tools/nmap/__init__.py +0 -0
  88. tools/nmap/adapter.py +97 -0
  89. tools/nmap/manifest.toml +159 -0
  90. tools/nuclei/__init__.py +1 -0
  91. tools/nuclei/adapter.py +171 -0
  92. tools/nuclei/manifest.toml +117 -0
  93. tools/searchsploit/__init__.py +1 -0
  94. tools/searchsploit/adapter.py +139 -0
  95. tools/searchsploit/manifest.toml +103 -0
  96. tools/sqlmap/__init__.py +1 -0
  97. tools/sqlmap/adapter.py +214 -0
  98. tools/sqlmap/manifest.toml +89 -0
  99. tools/subfinder/__init__.py +0 -0
  100. tools/subfinder/adapter.py +71 -0
  101. tools/subfinder/manifest.toml +104 -0
  102. tools/whois/__init__.py +0 -0
  103. tools/whois/adapter.py +80 -0
  104. tools/whois/manifest.toml +95 -0
ether/core/session.py ADDED
@@ -0,0 +1,956 @@
1
+ """ExecutionSession: Deep module encapsulating action execution, output spooling, and stream multiplexing."""
2
+
3
+ import asyncio
4
+ import os
5
+ import shlex
6
+ import shutil
7
+ import subprocess
8
+ from contextlib import nullcontext
9
+ from dataclasses import dataclass, field
10
+ from datetime import UTC, datetime
11
+ from typing import (
12
+ Any,
13
+ AsyncIterator,
14
+ Callable,
15
+ ContextManager,
16
+ Dict,
17
+ List,
18
+ Optional,
19
+ Protocol,
20
+ runtime_checkable,
21
+ )
22
+ from uuid import UUID
23
+
24
+ from ether.common.context import ExecutionContext
25
+ from ether.core.executor import Executor, LogSpooler, sanitize_subprocess_env
26
+ from ether.graph.store import GraphStore
27
+ from ether.paths import get_action_log_path
28
+ from ether.registry.adapter import ToolAdapter
29
+ from ether.registry.registry import ToolRegistry
30
+ from ether.schemas.base import BaseFinding
31
+ from ether.schemas.power import ActionRequest, JobStatus, JobStatusEnum
32
+
33
+ # --- Protocols & Seams ---
34
+
35
+
36
+ @runtime_checkable
37
+ class ActionValidator(Protocol):
38
+ """Protocol for policy validation and entity variable resolution across execution boundaries."""
39
+
40
+ def resolve_entity_variables(self, pik: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
41
+ """Extract standard investigation variables ($TARGET, $PORT, $SERVICE, etc.)."""
42
+ ...
43
+
44
+ def interpolate_variables(self, text: str, variables: Dict[str, Any]) -> str:
45
+ """Replace $VAR placeholders in command text with resolved values."""
46
+ ...
47
+
48
+ async def validate_action(self, action: ActionRequest) -> bool:
49
+ """Validate an action request against registry, policy, and store state."""
50
+ ...
51
+
52
+
53
+ class PassthroughActionValidator:
54
+ """Default non-restricting action validator for standalone execution sessions."""
55
+
56
+ def resolve_entity_variables(self, pik: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
57
+ resolved: Dict[str, Any] = {}
58
+ if pik:
59
+ target = pik.get("ip") or pik.get("domain") or pik.get("host_ip")
60
+ if target:
61
+ resolved["TARGET"] = target
62
+ if "port" in pik:
63
+ resolved["PORT"] = pik["port"]
64
+ if "service" in pik:
65
+ resolved["SERVICE"] = pik["service"]
66
+ if "protocol" in pik:
67
+ resolved["PROTOCOL"] = pik["protocol"]
68
+ return resolved
69
+
70
+ def interpolate_variables(self, text: str, variables: Dict[str, Any]) -> str:
71
+ for var_name, val in variables.items():
72
+ placeholder = f"${var_name}"
73
+ if placeholder in text:
74
+ text = text.replace(placeholder, str(val))
75
+ return text
76
+
77
+ async def validate_action(self, action: ActionRequest) -> bool:
78
+ return True
79
+
80
+
81
+ @runtime_checkable
82
+ class TerminalSuspendContext(Protocol):
83
+ """Protocol for safely suspending a terminal UI during privileged operations."""
84
+
85
+ def suspend(self) -> ContextManager[None]:
86
+ """Context manager invoked before privileged execution to release terminal controls."""
87
+ ...
88
+
89
+
90
+ @runtime_checkable
91
+ class CommandRunner(Protocol):
92
+ """Protocol for executing tools or shell commands and streaming raw output."""
93
+
94
+ async def run(
95
+ self,
96
+ adapter: ToolAdapter,
97
+ target: BaseFinding,
98
+ params: Dict[str, Any],
99
+ task_id: str,
100
+ cwd: str,
101
+ env: Optional[Dict[str, str]] = None,
102
+ use_shell: bool = False,
103
+ shell_path: Optional[str] = None,
104
+ on_output: Optional[Callable[[str], Any]] = None,
105
+ on_error_output: Optional[Callable[[str], Any]] = None,
106
+ timeout_seconds: Optional[int] = None,
107
+ ) -> AsyncIterator[BaseFinding]: ...
108
+
109
+ async def stop(self, task_id: str) -> None: ...
110
+
111
+
112
+ class SubprocessCommandRunner:
113
+ """Production CommandRunner delegating to Executor subprocess management."""
114
+
115
+ def __init__(self, executor: Executor):
116
+ self.executor = executor
117
+
118
+ async def run(
119
+ self,
120
+ adapter: ToolAdapter,
121
+ target: BaseFinding,
122
+ params: Dict[str, Any],
123
+ task_id: str,
124
+ cwd: str,
125
+ env: Optional[Dict[str, str]] = None,
126
+ use_shell: bool = False,
127
+ shell_path: Optional[str] = None,
128
+ on_output: Optional[Callable[[str], Any]] = None,
129
+ on_error_output: Optional[Callable[[str], Any]] = None,
130
+ timeout_seconds: Optional[int] = None,
131
+ ) -> AsyncIterator[BaseFinding]:
132
+ async for finding in self.executor.run_tool(
133
+ adapter=adapter,
134
+ target=target,
135
+ params=params,
136
+ session_id=None,
137
+ task_id=task_id,
138
+ cwd=cwd,
139
+ env=env,
140
+ use_shell=use_shell,
141
+ shell_path=shell_path,
142
+ on_output=on_output,
143
+ on_error_output=on_error_output,
144
+ timeout_seconds=timeout_seconds,
145
+ ):
146
+ yield finding
147
+
148
+ async def stop(self, task_id: str) -> None:
149
+ await self.executor.stop_task(task_id)
150
+
151
+
152
+ # --- Typed Execution Events ---
153
+
154
+
155
+ @dataclass(frozen=True)
156
+ class ExecutionEvent:
157
+ """Base typed execution event emitted across the ExecutionSession stream."""
158
+
159
+ action_id: UUID
160
+ timestamp: datetime = field(default_factory=lambda: datetime.now(UTC))
161
+
162
+
163
+ @dataclass(frozen=True)
164
+ class ExecutionStarted(ExecutionEvent):
165
+ tool_name: str = ""
166
+ command_snippet: str = ""
167
+ log_file: str = ""
168
+
169
+
170
+ @dataclass(frozen=True)
171
+ class ExecutionChunk(ExecutionEvent):
172
+ text: str = ""
173
+ is_error: bool = False
174
+
175
+
176
+ @dataclass(frozen=True)
177
+ class ExecutionCompleted(ExecutionEvent):
178
+ status: JobStatusEnum = JobStatusEnum.DONE
179
+ findings_count: int = 0
180
+ duration_seconds: float = 0.0
181
+
182
+
183
+ @dataclass(frozen=True)
184
+ class ExecutionFailed(ExecutionEvent):
185
+ error: str = ""
186
+ duration_seconds: float = 0.0
187
+
188
+
189
+ # --- Internal Adapters ---
190
+
191
+
192
+ class InternalShellAdapter(ToolAdapter):
193
+ """Adapter for explicit shell commands (prefix '!')."""
194
+
195
+ def validate_install(self) -> bool:
196
+ return True
197
+
198
+ def build_command(self, target: BaseFinding, params: Dict[str, Any]) -> List[str]:
199
+ return shlex.split(params.get("raw_flags", ""))
200
+
201
+ async def parse_output(
202
+ self,
203
+ raw_stdout: str,
204
+ target: BaseFinding,
205
+ context: Optional[Dict[str, Any]] = None,
206
+ ) -> AsyncIterator[BaseFinding]:
207
+ if False:
208
+ yield target
209
+
210
+
211
+ # --- Deep ExecutionSession Module ---
212
+
213
+
214
+ class ExecutionSession:
215
+ """Encapsulates in-memory action execution lifecycles, streaming multiplexers,
216
+
217
+ disk log spooling, and interactive privileged command execution.
218
+ """
219
+
220
+ def __init__(
221
+ self,
222
+ store: GraphStore,
223
+ gateway: ActionValidator,
224
+ registry: ToolRegistry,
225
+ command_runner: CommandRunner,
226
+ user_env: Optional[Dict[str, str]] = None,
227
+ user_shell: Optional[str] = None,
228
+ ):
229
+ self.store = store
230
+ self.gateway = gateway
231
+ self.registry = registry
232
+ self.runner = command_runner
233
+ self.user_env = user_env or os.environ.copy()
234
+ self.user_shell = user_shell or "/bin/bash"
235
+
236
+ # Action tracking
237
+ self._active_jobs: Dict[UUID, JobStatus] = {}
238
+ self._job_actions: Dict[UUID, ActionRequest] = {}
239
+ self._job_buffers: Dict[UUID, List[str]] = {}
240
+ self._event_queues: Dict[UUID, List[asyncio.Queue[Optional[ExecutionEvent]]]] = {}
241
+ self._running_tasks: Dict[UUID, asyncio.Task] = {}
242
+ self._status_listeners: List[Callable[[JobStatus], Any]] = []
243
+ self._session_cwd: Dict[str, str] = {}
244
+ self.closed_job_ids: set[str] = set()
245
+ self._job_spoolers: Dict[UUID, LogSpooler] = {}
246
+
247
+ @classmethod
248
+ def create(
249
+ cls,
250
+ store: GraphStore,
251
+ gateway: Optional[ActionValidator] = None,
252
+ registry: Optional[ToolRegistry] = None,
253
+ command_runner: Optional[CommandRunner] = None,
254
+ user_env: Optional[Dict[str, str]] = None,
255
+ user_shell: Optional[str] = None,
256
+ ) -> "ExecutionSession":
257
+ """Create an ExecutionSession with standard defaults.
258
+
259
+ Automatically instantiates default ToolRegistry, Executor, and SubprocessCommandRunner
260
+ if not explicitly provided, eliminating caller assembly boilerplate.
261
+ """
262
+ reg = registry if registry is not None else ToolRegistry()
263
+ runner = (
264
+ command_runner if command_runner is not None else SubprocessCommandRunner(Executor())
265
+ )
266
+ gw = gateway if gateway is not None else PassthroughActionValidator()
267
+ return cls(
268
+ store=store,
269
+ gateway=gw,
270
+ registry=reg,
271
+ command_runner=runner,
272
+ user_env=user_env,
273
+ user_shell=user_shell,
274
+ )
275
+
276
+ def add_status_listener(self, listener: Callable[[JobStatus], Any]) -> None:
277
+ """Register a callback notified when any job changes status."""
278
+ self._status_listeners.append(listener)
279
+
280
+ def remove_status_listener(self, listener: Callable[[JobStatus], Any]) -> None:
281
+ if listener in self._status_listeners:
282
+ self._status_listeners.remove(listener)
283
+
284
+ def _notify_status(self, job: JobStatus) -> None:
285
+ for listener in list(self._status_listeners):
286
+ try:
287
+ listener(job)
288
+ except Exception:
289
+ pass
290
+
291
+ def get_job(self, action_id: UUID) -> Optional[JobStatus]:
292
+ return self._active_jobs.get(action_id)
293
+
294
+ def get_job_action(self, action_id: UUID) -> Optional[ActionRequest]:
295
+ """Get the original ActionRequest for a job."""
296
+ return self._job_actions.get(action_id)
297
+
298
+ def get_active_jobs(self) -> List[JobStatus]:
299
+ return list(self._active_jobs.values())
300
+
301
+ def get_running_task(self, action_id: UUID) -> Optional[asyncio.Task]:
302
+ return self._running_tasks.get(action_id)
303
+
304
+ def track_task(self, action_id: UUID, task: asyncio.Task) -> None:
305
+ """Register an asynchronous task under session lifecycle management."""
306
+ self._running_tasks[action_id] = task
307
+
308
+ def get_cwd(self, session_id: str) -> str:
309
+ return self._session_cwd.get(session_id, os.getcwd())
310
+
311
+ def set_cwd(self, session_id: str, new_path: str) -> None:
312
+ self._session_cwd[session_id] = new_path
313
+
314
+ def get_output_history(self, action_id: UUID) -> List[str]:
315
+ """Return buffered output chunks for replay when switching or restoring tabs."""
316
+ return list(self._job_buffers.get(action_id, []))
317
+
318
+ def get_active_jobs_count(self, session_id: Optional[str] = None) -> int:
319
+ """Get count of active (running/queued) jobs, optionally filtered by session_id."""
320
+ if session_id is None:
321
+ return sum(
322
+ 1
323
+ for j in self._active_jobs.values()
324
+ if j.status in (JobStatusEnum.RUNNING, JobStatusEnum.QUEUED)
325
+ )
326
+ return sum(
327
+ 1
328
+ for j in self._active_jobs.values()
329
+ if str(j.session_id) == str(session_id)
330
+ and j.status in (JobStatusEnum.RUNNING, JobStatusEnum.QUEUED)
331
+ )
332
+
333
+ def get_session_active_jobs(self, session_id: str) -> List[JobStatus]:
334
+ """Get all active/tracked jobs for a session."""
335
+ return [j for j in self._active_jobs.values() if str(j.session_id) == str(session_id)]
336
+
337
+ async def subscribe(self, action_id: UUID) -> AsyncIterator[ExecutionEvent]:
338
+ """Subscribe to live typed execution events for an action with backlog replay."""
339
+ q: asyncio.Queue[Optional[ExecutionEvent]] = asyncio.Queue()
340
+ if action_id not in self._event_queues:
341
+ self._event_queues[action_id] = []
342
+ self._event_queues[action_id].append(q)
343
+
344
+ # Replay backlog if already started
345
+ buffer_chunks = self.get_output_history(action_id)
346
+ for chunk in buffer_chunks:
347
+ await q.put(ExecutionChunk(action_id=action_id, text=chunk))
348
+
349
+ job = self.get_job(action_id)
350
+ if job and job.status != JobStatusEnum.RUNNING:
351
+ if job.status == JobStatusEnum.DONE:
352
+ await q.put(ExecutionCompleted(action_id=action_id, status=job.status))
353
+ else:
354
+ await q.put(
355
+ ExecutionFailed(action_id=action_id, error=job.error_snippet or "Failed")
356
+ )
357
+ await q.put(None)
358
+
359
+ try:
360
+ while True:
361
+ event = await q.get()
362
+ if event is None:
363
+ break
364
+ yield event
365
+ finally:
366
+ if action_id in self._event_queues and q in self._event_queues[action_id]:
367
+ self._event_queues[action_id].remove(q)
368
+ if not self._event_queues[action_id]:
369
+ self._event_queues.pop(action_id, None)
370
+
371
+ async def _emit_event(self, action_id: UUID, event: Optional[ExecutionEvent]) -> None:
372
+ queues = list(self._event_queues.get(action_id, []))
373
+ for q in queues:
374
+ try:
375
+ await q.put(event)
376
+ except Exception:
377
+ pass
378
+
379
+ async def dispatch(
380
+ self,
381
+ action: ActionRequest,
382
+ suspend_context: Optional[TerminalSuspendContext] = None,
383
+ on_chunk: Optional[Callable[[str], Any]] = None,
384
+ on_complete: Optional[Callable[[], Any]] = None,
385
+ ) -> UUID:
386
+ """Dispatch an action request through preflight validation, disk spooling, and execution."""
387
+ # 0. Session guard
388
+ session_info = await self.store.get_session(str(action.session_id))
389
+ if session_info and session_info.get("status") == "CLOSED":
390
+ raise PermissionError(
391
+ "Cannot execute actions in an archived session. Reopen the session first."
392
+ )
393
+
394
+ # 1. Variable substitution ($TARGET, $PORT, $LHOST, etc.) via ActionGateway
395
+ pik = None
396
+ if action.target_entity_id:
397
+ node_data = await self.store.get_node(str(action.session_id), action.target_entity_id)
398
+ if node_data:
399
+ import json
400
+
401
+ pik = json.loads(node_data.get("pik_json") or "{}")
402
+
403
+ resolved_vars = self.gateway.resolve_entity_variables(pik)
404
+ raw_flags = action.params.get("raw_flags", "") if action.params else ""
405
+ raw_flags = self.gateway.interpolate_variables(raw_flags, resolved_vars)
406
+ if action.params:
407
+ action.params["raw_flags"] = raw_flags
408
+
409
+ # 2. Builtin 'cd' handling
410
+ tool_data = self.registry.get_tool(action.tool_name)
411
+ if not tool_data and action.tool_name == "cd":
412
+ dest = raw_flags.strip()
413
+ current = self.get_cwd(str(action.session_id))
414
+ new_path = os.path.abspath(os.path.join(current, dest))
415
+ if os.path.isdir(new_path):
416
+ self.set_cwd(str(action.session_id), new_path)
417
+ msg = f"Changed directory to: {new_path}\n"
418
+ else:
419
+ msg = f"cd: no such directory: {dest}\n"
420
+ if on_chunk:
421
+ await on_chunk(msg)
422
+ return UUID(int=0)
423
+
424
+ # 3. Determine Adapter
425
+ if action.is_explicit_shell:
426
+ action.params["raw_flags"] = f"{action.tool_name} {raw_flags}".strip()
427
+ adapter = InternalShellAdapter()
428
+ elif tool_data:
429
+ action.params["raw_flags"] = raw_flags
430
+ adapter = tool_data["adapter"]
431
+ else:
432
+ raise ValueError(f"No tool or explicit shell prefix found for '{action.tool_name}'")
433
+
434
+ # 4. Preflight Validation
435
+ try:
436
+ await self.gateway.validate_action(action)
437
+ except Exception as e:
438
+ await self._emit_event(
439
+ action.action_id, ExecutionFailed(action_id=action.action_id, error=str(e))
440
+ )
441
+ await self._emit_event(action.action_id, None)
442
+ raise
443
+
444
+ # 5. Job status initialization
445
+ log_file_path = get_action_log_path(str(action.action_id))
446
+ cmd_raw = action.params.get("raw_flags", "") if action.params else ""
447
+ cmd_snippet = f"{action.tool_name} {cmd_raw}".strip() if cmd_raw else action.tool_name
448
+
449
+ job = JobStatus(
450
+ job_id=action.action_id,
451
+ session_id=action.session_id,
452
+ tool_name=action.tool_name,
453
+ status=JobStatusEnum.RUNNING,
454
+ log_file=log_file_path,
455
+ command_snippet=cmd_snippet,
456
+ )
457
+ self._active_jobs[job.job_id] = job
458
+ self._job_actions[job.job_id] = action
459
+ self._job_buffers[job.job_id] = []
460
+ self._notify_status(job)
461
+
462
+ # 6. Resolve target finding
463
+ if not action.is_explicit_shell and action.target_entity_id:
464
+ import json
465
+
466
+ node_data = await self.store.get_node(str(action.session_id), action.target_entity_id)
467
+ target = BaseFinding(
468
+ schema_type=node_data["schema_type"],
469
+ pik=json.loads(node_data["pik_json"]),
470
+ data=json.loads(node_data["data_json"]),
471
+ status=node_data.get("status", "confirmed"),
472
+ )
473
+ else:
474
+ target = BaseFinding(
475
+ schema_type="system.shell",
476
+ pik={"cmd": action.tool_name},
477
+ data={},
478
+ status="confirmed",
479
+ )
480
+
481
+ # 7. Privileged execution check (sudo)
482
+ is_sudo = action.tool_name == "sudo"
483
+ if is_sudo:
484
+ # Handle sudo interactively using suspend context
485
+ task = asyncio.create_task(
486
+ self._run_privileged_action(
487
+ action, cmd_raw, log_file_path, job, suspend_context, on_chunk, on_complete
488
+ )
489
+ )
490
+ else:
491
+ # Handle regular background action
492
+ task = asyncio.create_task(
493
+ self._run_background_action(
494
+ action, adapter, target, log_file_path, job, on_chunk, on_complete
495
+ )
496
+ )
497
+
498
+ self._running_tasks[action.action_id] = task
499
+ task.add_done_callback(lambda t: self._running_tasks.pop(action.action_id, None))
500
+ return job.job_id
501
+
502
+ async def _append_chunk(
503
+ self, action_id: UUID, text: str, log_file_path: str, is_error: bool = False
504
+ ) -> None:
505
+ buf = self._job_buffers.setdefault(action_id, [])
506
+ buf.append(text)
507
+ if len(buf) > 5000:
508
+ self._job_buffers[action_id] = buf[-2500:]
509
+
510
+ spooler = self._job_spoolers.get(action_id)
511
+ if spooler:
512
+ spooler.write(text)
513
+ elif log_file_path:
514
+ try:
515
+ with open(log_file_path, "a", encoding="utf-8", errors="replace") as f:
516
+ f.write(text)
517
+ except Exception:
518
+ pass
519
+
520
+ await self._emit_event(
521
+ action_id, ExecutionChunk(action_id=action_id, text=text, is_error=is_error)
522
+ )
523
+
524
+ async def _run_privileged_action(
525
+ self,
526
+ action: ActionRequest,
527
+ cmd_raw: str,
528
+ log_file_path: str,
529
+ job: JobStatus,
530
+ suspend_context: Optional[TerminalSuspendContext],
531
+ on_chunk: Optional[Callable[[str], Any]],
532
+ on_complete: Optional[Callable[[], Any]],
533
+ ) -> None:
534
+ start_time = asyncio.get_event_loop().time()
535
+ cwd = self.get_cwd(str(action.session_id))
536
+ clean_env = sanitize_subprocess_env(self.user_env)
537
+
538
+ # Initialize LogSpooler with 64KB buffering
539
+ spooler = LogSpooler(log_file_path)
540
+ self._job_spoolers[action.action_id] = spooler
541
+ spooler.write(
542
+ f"=== Privileged Execution Start: {datetime.now(UTC).isoformat()} ===\n"
543
+ f"Tool: sudo\n"
544
+ f"Session: {action.session_id}\n"
545
+ f"Action ID: {action.action_id}\n"
546
+ f"{'=' * 50}\n\n"
547
+ )
548
+
549
+ await self._emit_event(
550
+ action.action_id,
551
+ ExecutionStarted(
552
+ action_id=action.action_id,
553
+ tool_name="sudo",
554
+ command_snippet=job.command_snippet,
555
+ log_file=log_file_path,
556
+ ),
557
+ )
558
+
559
+ err_msg = None
560
+ target_args: List[str] = []
561
+ try:
562
+ tokens = shlex.split(cmd_raw) if cmd_raw else []
563
+ while tokens and tokens[0] == "sudo":
564
+ tokens = tokens[1:]
565
+ target_args = tokens
566
+
567
+ if not target_args:
568
+ cmd_args = ["sudo", "-h"]
569
+ else:
570
+ cmd_args = ["sudo"] + target_args
571
+
572
+ if not shutil.which("sudo"):
573
+ raise RuntimeError("'sudo' binary not found on system PATH")
574
+
575
+ # Check if sudo credentials are authenticated/cached or if passwordless sudo is configured.
576
+ # 'sudo -n true' exits 0 if cached or passwordless, and non-zero if a password prompt is required.
577
+ check_proc = subprocess.run(
578
+ ["sudo", "-n", "true"],
579
+ shell=False,
580
+ env=clean_env,
581
+ capture_output=True,
582
+ )
583
+ needs_auth = check_proc.returncode != 0
584
+
585
+ if needs_auth:
586
+ auth_notice = (
587
+ "❯ sudo: Authentication required. Suspending UI for password entry...\n"
588
+ )
589
+ await self._append_chunk(action.action_id, auth_notice, log_file_path)
590
+ if on_chunk:
591
+ try:
592
+ await on_chunk(auth_notice)
593
+ except Exception:
594
+ pass
595
+
596
+ suspend_cm = suspend_context.suspend() if suspend_context else nullcontext()
597
+ with suspend_cm:
598
+ auth_proc = subprocess.run(
599
+ ["sudo", "-v"],
600
+ shell=False,
601
+ env=clean_env,
602
+ cwd=cwd,
603
+ )
604
+ auth_code = auth_proc.returncode
605
+
606
+ if auth_code != 0:
607
+ raise PermissionError(
608
+ f"Sudo authentication failed or cancelled (code {auth_code})"
609
+ )
610
+
611
+ resumed_notice = "[Sudo credentials validated. Live output resumed below]\n"
612
+ await self._append_chunk(action.action_id, resumed_notice, log_file_path)
613
+ if on_chunk:
614
+ try:
615
+ await on_chunk(resumed_notice)
616
+ except Exception:
617
+ pass
618
+
619
+ # Stream the actual privileged command in the foreground/terminal tab
620
+ async def handle_stdout(text: str) -> None:
621
+ await self._append_chunk(action.action_id, text, log_file_path, is_error=False)
622
+ if on_chunk:
623
+ try:
624
+ await on_chunk(text)
625
+ except Exception:
626
+ pass
627
+
628
+ async def handle_stderr(text: str) -> None:
629
+ await self._append_chunk(action.action_id, text, log_file_path, is_error=True)
630
+ if on_chunk:
631
+ try:
632
+ await on_chunk(text)
633
+ except Exception:
634
+ pass
635
+
636
+ adapter = InternalShellAdapter()
637
+ target = BaseFinding(
638
+ schema_type="system.shell",
639
+ pik={"cmd": "sudo"},
640
+ data={},
641
+ status="confirmed",
642
+ )
643
+ params = {"raw_flags": shlex.join(cmd_args)}
644
+
645
+ async for _ in self.runner.run(
646
+ adapter=adapter,
647
+ target=target,
648
+ params=params,
649
+ task_id=str(action.action_id),
650
+ cwd=cwd,
651
+ env=clean_env,
652
+ use_shell=False,
653
+ on_output=handle_stdout,
654
+ on_error_output=handle_stderr,
655
+ timeout_seconds=getattr(action, "timeout_seconds", None),
656
+ ):
657
+ pass
658
+
659
+ if job.status == JobStatusEnum.RUNNING:
660
+ job.status = JobStatusEnum.DONE
661
+
662
+ except asyncio.CancelledError:
663
+ err_msg = "Job cancelled"
664
+ job.status = JobStatusEnum.FAILED
665
+ except Exception as e:
666
+ job.status = JobStatusEnum.FAILED
667
+ err_msg = str(e)
668
+ await self._append_chunk(
669
+ action.action_id,
670
+ f"[Privileged execution error: {e}]\n",
671
+ log_file_path,
672
+ is_error=True,
673
+ )
674
+ if on_chunk:
675
+ try:
676
+ await on_chunk(f"[Privileged execution error: {e}]\n")
677
+ except Exception:
678
+ pass
679
+ finally:
680
+ elapsed = asyncio.get_event_loop().time() - start_time
681
+ job.completed_at = datetime.now(UTC)
682
+ self._notify_status(job)
683
+
684
+ # Record final status in disk log and close spooler
685
+ status_str = "SUCCESS" if job.status == JobStatusEnum.DONE else f"FAILED ({err_msg})"
686
+ spooler.write(
687
+ f"\n\n=== Privileged Execution End: {datetime.now(UTC).isoformat()} [{status_str}] ===\n"
688
+ )
689
+ spooler.close()
690
+ self._job_spoolers.pop(action.action_id, None)
691
+
692
+ if job.status == JobStatusEnum.DONE:
693
+ await self._emit_event(
694
+ action.action_id,
695
+ ExecutionCompleted(
696
+ action_id=action.action_id,
697
+ status=JobStatusEnum.DONE,
698
+ duration_seconds=elapsed,
699
+ ),
700
+ )
701
+ else:
702
+ await self._emit_event(
703
+ action.action_id,
704
+ ExecutionFailed(
705
+ action_id=action.action_id,
706
+ error=err_msg or "Failed",
707
+ duration_seconds=elapsed,
708
+ ),
709
+ )
710
+ await self._emit_event(action.action_id, None)
711
+
712
+ # Persist to database event log
713
+ if not getattr(self.store, "_closed", False):
714
+ try:
715
+ buf_output = "".join(self.get_output_history(action.action_id))
716
+ if len(buf_output) > 200_000:
717
+ db_output = (
718
+ buf_output[:100_000]
719
+ + f"\n\n... [Log truncated for database storage. Full log at {log_file_path}] ...\n\n"
720
+ + buf_output[-100_000:]
721
+ )
722
+ else:
723
+ db_output = buf_output
724
+
725
+ command_summary = (
726
+ f"Ran sudo {shlex.join(target_args)}"
727
+ if target_args
728
+ else f"Ran sudo {cmd_raw}"
729
+ )
730
+ await self.store.append_event(
731
+ str(action.session_id),
732
+ action,
733
+ {"output": db_output, "log_file": log_file_path, "error": err_msg},
734
+ command_summary + (f" (failed: {err_msg})" if err_msg else ""),
735
+ )
736
+ if str(action.action_id) in self.closed_job_ids:
737
+ self.evict_job(action.action_id)
738
+ except Exception:
739
+ pass
740
+
741
+ if on_complete:
742
+ try:
743
+ await on_complete()
744
+ except Exception:
745
+ pass
746
+
747
+ async def _run_background_action(
748
+ self,
749
+ action: ActionRequest,
750
+ adapter: ToolAdapter,
751
+ target: BaseFinding,
752
+ log_file_path: str,
753
+ job: JobStatus,
754
+ on_chunk: Optional[Callable[[str], Any]],
755
+ on_complete: Optional[Callable[[], Any]],
756
+ ) -> None:
757
+ start_time = asyncio.get_event_loop().time()
758
+ cwd = self.get_cwd(str(action.session_id))
759
+ clean_env = sanitize_subprocess_env(self.user_env)
760
+
761
+ # Initialize LogSpooler with 64KB buffering
762
+ spooler = LogSpooler(log_file_path)
763
+ self._job_spoolers[action.action_id] = spooler
764
+ spooler.write(
765
+ f"=== Execution Start: {datetime.now(UTC).isoformat()} ===\n"
766
+ f"Tool: {action.tool_name}\n"
767
+ f"Session: {action.session_id}\n"
768
+ f"Action ID: {action.action_id}\n"
769
+ f"{'=' * 50}\n\n"
770
+ )
771
+
772
+ await self._emit_event(
773
+ action.action_id,
774
+ ExecutionStarted(
775
+ action_id=action.action_id,
776
+ tool_name=action.tool_name,
777
+ command_snippet=job.command_snippet,
778
+ log_file=log_file_path,
779
+ ),
780
+ )
781
+
782
+ async def handle_spool(text: str, is_error: bool = False) -> None:
783
+ await self._append_chunk(action.action_id, text, log_file_path, is_error=is_error)
784
+ if on_chunk:
785
+ try:
786
+ await on_chunk(text)
787
+ except Exception:
788
+ pass
789
+
790
+ exec_context = ExecutionContext(
791
+ action_id=str(action.action_id),
792
+ session_id=str(action.session_id),
793
+ policy=str(self.gateway.policy.value),
794
+ cwd=cwd,
795
+ env=clean_env,
796
+ use_shell=action.is_explicit_shell,
797
+ shell_path=self.user_shell,
798
+ timeout_seconds=getattr(action, "timeout_seconds", None),
799
+ runner=self.runner,
800
+ spool_fn=handle_spool,
801
+ )
802
+
803
+ err_msg = None
804
+ findings_count = 0
805
+ finding_buffer: List[BaseFinding] = []
806
+ last_flush = asyncio.get_event_loop().time()
807
+
808
+ async def flush_findings():
809
+ nonlocal last_flush
810
+ if not finding_buffer:
811
+ return
812
+ to_flush = list(finding_buffer)
813
+ finding_buffer.clear()
814
+ last_flush = asyncio.get_event_loop().time()
815
+ if not getattr(self.store, "_closed", False):
816
+ try:
817
+ await self.store.upsert_findings_batch(
818
+ str(action.session_id), to_flush, action_id=str(action.action_id)
819
+ )
820
+ except Exception:
821
+ pass
822
+
823
+ try:
824
+ async for finding in adapter.execute_action(
825
+ target=target,
826
+ params=action.params or {},
827
+ context=exec_context,
828
+ ):
829
+ findings_count += 1
830
+ finding_buffer.append(finding)
831
+ now = asyncio.get_event_loop().time()
832
+ if len(finding_buffer) >= 50 or (now - last_flush) >= 0.25:
833
+ await flush_findings()
834
+
835
+ await flush_findings()
836
+ if job.status == JobStatusEnum.RUNNING:
837
+ job.status = JobStatusEnum.DONE
838
+ except asyncio.CancelledError:
839
+ err_msg = "Job cancelled"
840
+ job.status = JobStatusEnum.FAILED
841
+ except Exception as e:
842
+ err_msg = str(e)
843
+ job.status = JobStatusEnum.FAILED
844
+ finally:
845
+ elapsed = asyncio.get_event_loop().time() - start_time
846
+ job.completed_at = datetime.now(UTC)
847
+
848
+ # Record final status in disk log and close spooler
849
+ status_str = "SUCCESS" if job.status == JobStatusEnum.DONE else f"FAILED ({err_msg})"
850
+ spooler.write(
851
+ f"\n\n=== Execution End: {datetime.now(UTC).isoformat()} [{status_str}] ===\n"
852
+ )
853
+ spooler.close()
854
+ self._job_spoolers.pop(action.action_id, None)
855
+
856
+ # Persist to database event log
857
+ if not getattr(self.store, "_closed", False):
858
+ try:
859
+ buf_output = "".join(self.get_output_history(action.action_id))
860
+ if len(buf_output) > 200_000:
861
+ db_output = (
862
+ buf_output[:100_000]
863
+ + f"\n\n... [Log truncated for database storage. Full log at {log_file_path}] ...\n\n"
864
+ + buf_output[-100_000:]
865
+ )
866
+ else:
867
+ db_output = buf_output
868
+
869
+ await self.store.append_event(
870
+ str(action.session_id),
871
+ action,
872
+ {"output": db_output, "log_file": log_file_path, "error": err_msg},
873
+ f"Ran {action.tool_name}" + (f" (failed: {err_msg})" if err_msg else ""),
874
+ )
875
+ if str(action.action_id) in self.closed_job_ids:
876
+ await self.store.mark_event_closed(
877
+ str(action.action_id), session_id=str(action.session_id)
878
+ )
879
+ except Exception:
880
+ pass
881
+
882
+ self._notify_status(job)
883
+
884
+ if job.status == JobStatusEnum.DONE:
885
+ await self._emit_event(
886
+ action.action_id,
887
+ ExecutionCompleted(
888
+ action_id=action.action_id,
889
+ status=JobStatusEnum.DONE,
890
+ findings_count=findings_count,
891
+ duration_seconds=elapsed,
892
+ ),
893
+ )
894
+ else:
895
+ await self._emit_event(
896
+ action.action_id,
897
+ ExecutionFailed(
898
+ action_id=action.action_id,
899
+ error=err_msg or "Failed",
900
+ duration_seconds=elapsed,
901
+ ),
902
+ )
903
+ await self._emit_event(action.action_id, None)
904
+
905
+ if on_complete:
906
+ try:
907
+ await on_complete()
908
+ except Exception:
909
+ pass
910
+
911
+ async def kill_job(self, action_id: UUID) -> bool:
912
+ """Cancel and terminate an active execution."""
913
+ job = self.get_job(action_id)
914
+ if not job or job.status != JobStatusEnum.RUNNING:
915
+ return False
916
+
917
+ try:
918
+ await self.runner.stop(str(action_id))
919
+ except Exception:
920
+ pass
921
+ task = self.get_running_task(action_id)
922
+ if task and not task.done():
923
+ task.cancel()
924
+
925
+ job.status = JobStatusEnum.FAILED
926
+ self._notify_status(job)
927
+ return True
928
+
929
+ abort_action = kill_job
930
+
931
+ async def evict_session(self, session_id: str) -> None:
932
+ """Clean up and purge all tracked execution jobs, buffers, and state for a session."""
933
+ target_jobs = [j for j in self.get_active_jobs() if str(j.session_id) == str(session_id)]
934
+ for job in target_jobs:
935
+ try:
936
+ await self.kill_job(job.job_id)
937
+ except Exception:
938
+ pass
939
+ self._active_jobs.pop(job.job_id, None)
940
+ self._job_actions.pop(job.job_id, None)
941
+ self._job_buffers.pop(job.job_id, None)
942
+ self._running_tasks.pop(job.job_id, None)
943
+ self.closed_job_ids.discard(str(job.job_id))
944
+
945
+ async def evict_sessions(self, session_ids: set[str] | List[str]) -> None:
946
+ """Clean up and purge all tracked execution jobs for multiple sessions."""
947
+ for sid in session_ids:
948
+ await self.evict_session(sid)
949
+
950
+ async def shutdown(self) -> None:
951
+ """Gracefully stop all running executions."""
952
+ tasks = list(self._running_tasks.values())
953
+ if tasks:
954
+ for t in tasks:
955
+ t.cancel()
956
+ await asyncio.gather(*tasks, return_exceptions=True)