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.
Files changed (234) hide show
  1. execweave/__init__.py +3 -0
  2. execweave/__main__.py +5 -0
  3. execweave/_conversation_records_core.py +902 -0
  4. execweave/_dashboard_shell_base.py +148 -0
  5. execweave/_http_proxy_base.py +565 -0
  6. execweave/_http_proxy_bounded.py +560 -0
  7. execweave/_http_proxy_stage.py +509 -0
  8. execweave/acceptance_output.py +19 -0
  9. execweave/agent_bootstrap.py +395 -0
  10. execweave/agent_topology.py +313 -0
  11. execweave/agent_trace.py +1162 -0
  12. execweave/agy_preview_sanitize.py +102 -0
  13. execweave/analysis.py +427 -0
  14. execweave/anthropic.py +228 -0
  15. execweave/anthropic_cli.py +171 -0
  16. execweave/anthropic_full_fidelity.py +385 -0
  17. execweave/antigravity_adapter.py +112 -0
  18. execweave/antigravity_adapter_base.py +479 -0
  19. execweave/antigravity_full_fidelity.py +656 -0
  20. execweave/antigravity_full_fidelity_base.py +172 -0
  21. execweave/antigravity_full_fidelity_collaboration_base.py +451 -0
  22. execweave/antigravity_hook_cli.py +209 -0
  23. execweave/antigravity_record.py +96 -0
  24. execweave/antigravity_subagent_linkage.py +449 -0
  25. execweave/antigravity_trace_capability.py +39 -0
  26. execweave/auto_specialized.py +547 -0
  27. execweave/backends.py +102 -0
  28. execweave/benchmark.py +80 -0
  29. execweave/claude_adapter.py +517 -0
  30. execweave/claude_child_transcript.py +314 -0
  31. execweave/claude_delegation.py +136 -0
  32. execweave/claude_full_fidelity.py +396 -0
  33. execweave/claude_hook_cli.py +209 -0
  34. execweave/claude_hook_contract.py +943 -0
  35. execweave/claude_model_observer.py +353 -0
  36. execweave/claude_record.py +106 -0
  37. execweave/cli.py +629 -0
  38. execweave/codex_adapter.py +455 -0
  39. execweave/codex_conversation.py +621 -0
  40. execweave/codex_full_fidelity.py +287 -0
  41. execweave/codex_hook_cli.py +301 -0
  42. execweave/codex_hook_entry.py +207 -0
  43. execweave/codex_hook_lifecycle.py +363 -0
  44. execweave/codex_message_diagnostics.py +322 -0
  45. execweave/codex_message_transport_diagnostics.py +399 -0
  46. execweave/codex_record.py +199 -0
  47. execweave/codex_rollout_structures.py +402 -0
  48. execweave/codex_rollout_trace.py +56 -0
  49. execweave/codex_rollout_trace_base.py +1509 -0
  50. execweave/collector.py +768 -0
  51. execweave/command.py +157 -0
  52. execweave/command_privacy.py +20 -0
  53. execweave/content_evidence.py +101 -0
  54. execweave/content_integrity.py +289 -0
  55. execweave/content_store.py +273 -0
  56. execweave/controlled_checks.py +561 -0
  57. execweave/conversation_archive.py +338 -0
  58. execweave/conversation_message_identity.py +264 -0
  59. execweave/conversation_preview.py +66 -0
  60. execweave/conversation_preview_antigravity.py +32 -0
  61. execweave/conversation_preview_claude.py +31 -0
  62. execweave/conversation_preview_codex.py +107 -0
  63. execweave/conversation_preview_common.py +180 -0
  64. execweave/conversation_preview_generic.py +188 -0
  65. execweave/conversation_preview_lines.py +133 -0
  66. execweave/conversation_preview_transcript.py +121 -0
  67. execweave/conversation_records.py +349 -0
  68. execweave/conversation_records_antigravity.py +370 -0
  69. execweave/conversation_records_codex.py +83 -0
  70. execweave/conversation_records_common.py +17 -0
  71. execweave/conversation_records_ollama.py +39 -0
  72. execweave/correlation.py +818 -0
  73. execweave/cursor_adapter.py +349 -0
  74. execweave/cursor_delegation.py +87 -0
  75. execweave/cursor_delegation_base.py +220 -0
  76. execweave/cursor_full_fidelity.py +489 -0
  77. execweave/cursor_hook_cli.py +195 -0
  78. execweave/cursor_hook_contract.py +439 -0
  79. execweave/cursor_lifecycle.py +159 -0
  80. execweave/cursor_record.py +96 -0
  81. execweave/dashboard_shell.py +283 -0
  82. execweave/delivery_status.py +94 -0
  83. execweave/entry.py +98 -0
  84. execweave/evidence_availability.py +113 -0
  85. execweave/evidence_grade.py +166 -0
  86. execweave/fidelity.py +304 -0
  87. execweave/filesystem.py +327 -0
  88. execweave/finalization.py +92 -0
  89. execweave/focus.py +118 -0
  90. execweave/framework_adapters/__init__.py +34 -0
  91. execweave/framework_adapters/autogen.py +398 -0
  92. execweave/framework_adapters/base.py +580 -0
  93. execweave/framework_adapters/camel.py +270 -0
  94. execweave/framework_adapters/camel_channel.py +71 -0
  95. execweave/framework_adapters/metagpt.py +315 -0
  96. execweave/framework_adapters/metagpt_ollama_compat.py +54 -0
  97. execweave/framework_adapters/metagpt_recording.py +342 -0
  98. execweave/framework_adapters/registry.py +90 -0
  99. execweave/graph.py +590 -0
  100. execweave/graph_ops.py +472 -0
  101. execweave/hook_command.py +32 -0
  102. execweave/hook_delivery.py +32 -0
  103. execweave/hook_input.py +16 -0
  104. execweave/http_proxy.py +187 -0
  105. execweave/http_proxy_cli.py +84 -0
  106. execweave/inference_gateway.py +476 -0
  107. execweave/inference_gateway_cli.py +211 -0
  108. execweave/inference_gateway_full_fidelity.py +613 -0
  109. execweave/inference_identity.py +76 -0
  110. execweave/inference_identity_cli.py +60 -0
  111. execweave/integrity.py +235 -0
  112. execweave/integrity_cli.py +55 -0
  113. execweave/investigation_index.py +445 -0
  114. execweave/litellm_callback.py +211 -0
  115. execweave/litellm_callback_cli.py +42 -0
  116. execweave/live.py +445 -0
  117. execweave/live_core.py +972 -0
  118. execweave/live_view.py +109 -0
  119. execweave/live_view_extra_style.py +11 -0
  120. execweave/live_view_markup.py +29 -0
  121. execweave/live_view_process_layout.py +650 -0
  122. execweave/live_view_readability.py +502 -0
  123. execweave/live_view_script_a.py +59 -0
  124. execweave/live_view_script_b.py +97 -0
  125. execweave/live_view_script_c.py +59 -0
  126. execweave/live_view_script_d.py +40 -0
  127. execweave/live_view_style.py +34 -0
  128. execweave/model_runtime.py +560 -0
  129. execweave/model_runtime_cli.py +265 -0
  130. execweave/model_runtime_full_fidelity.py +519 -0
  131. execweave/observation.py +53 -0
  132. execweave/observation_demo.py +69 -0
  133. execweave/openai_agents.py +267 -0
  134. execweave/openai_agents_sdk.py +453 -0
  135. execweave/openai_compatible.py +239 -0
  136. execweave/openai_compatible_cli.py +189 -0
  137. execweave/openai_compatible_full_fidelity.py +438 -0
  138. execweave/opencode_adapter.py +325 -0
  139. execweave/opencode_event_contract.py +734 -0
  140. execweave/opencode_full_fidelity.py +198 -0
  141. execweave/opencode_hook_cli.py +119 -0
  142. execweave/opencode_plugin_cli.py +150 -0
  143. execweave/opencode_record.py +96 -0
  144. execweave/opencode_task_linkage.py +225 -0
  145. execweave/overhead_benchmark.py +440 -0
  146. execweave/privacy.py +84 -0
  147. execweave/private_io.py +465 -0
  148. execweave/provider_capability.py +578 -0
  149. execweave/provider_lifecycle.py +282 -0
  150. execweave/provider_record.py +290 -0
  151. execweave/reader_identity.py +13 -0
  152. execweave/redacted_archive.py +906 -0
  153. execweave/risk.py +106 -0
  154. execweave/rule_pack.py +359 -0
  155. execweave/rule_pack_cli.py +57 -0
  156. execweave/run_assessment.py +200 -0
  157. execweave/runtime_endpoint_availability.py +44 -0
  158. execweave/scalability_benchmark.py +195 -0
  159. execweave/schema.py +62 -0
  160. execweave/scope.py +85 -0
  161. execweave/semantic.py +453 -0
  162. execweave/session_summary.py +159 -0
  163. execweave/sink.py +71 -0
  164. execweave/strace_backend.py +927 -0
  165. execweave/stream_assembly.py +363 -0
  166. execweave/task_artifacts.py +192 -0
  167. execweave/task_validation.py +317 -0
  168. execweave/theme.py +40 -0
  169. execweave/top.py +599 -0
  170. execweave/top_cli.py +150 -0
  171. execweave/validate.py +196 -0
  172. execweave/vendor/dagre.min.js +815 -0
  173. execweave/view_cli.py +49 -0
  174. execweave/viewer.py +474 -0
  175. execweave/viewer_agent_panel.py +630 -0
  176. execweave/viewer_agent_panel_antigravity.py +31 -0
  177. execweave/viewer_agent_panel_claude.py +9 -0
  178. execweave/viewer_agent_panel_codex.py +50 -0
  179. execweave/viewer_agent_panel_cursor.py +9 -0
  180. execweave/viewer_agent_panel_default.py +79 -0
  181. execweave/viewer_agent_panel_ollama.py +20 -0
  182. execweave/viewer_agent_panel_opencode.py +9 -0
  183. execweave/viewer_agent_panel_registry.py +20 -0
  184. execweave/viewer_archive_verifier.py +178 -0
  185. execweave/viewer_background_files.py +86 -0
  186. execweave/viewer_content_browser.py +307 -0
  187. execweave/viewer_content_health.py +208 -0
  188. execweave/viewer_content_inspector.py +309 -0
  189. execweave/viewer_controlled_checks.py +258 -0
  190. execweave/viewer_conversation_sync.py +115 -0
  191. execweave/viewer_dashboard_clean.py +405 -0
  192. execweave/viewer_dashboard_focus.py +127 -0
  193. execweave/viewer_dashboard_hardening.py +264 -0
  194. execweave/viewer_dashboard_hardening_v2.py +62 -0
  195. execweave/viewer_dashboard_projection.py +261 -0
  196. execweave/viewer_delivery_status.py +155 -0
  197. execweave/viewer_edge_decross.py +117 -0
  198. execweave/viewer_execution_flow.py +611 -0
  199. execweave/viewer_execution_flow_provider_normalization.py +107 -0
  200. execweave/viewer_execution_flow_safety.py +349 -0
  201. execweave/viewer_external_endpoints.py +307 -0
  202. execweave/viewer_flow_canvas.py +1140 -0
  203. execweave/viewer_flow_layout.py +922 -0
  204. execweave/viewer_fold_state.py +31 -0
  205. execweave/viewer_framework_flow.py +68 -0
  206. execweave/viewer_framework_model_output.py +133 -0
  207. execweave/viewer_gif.py +278 -0
  208. execweave/viewer_history_browser.py +225 -0
  209. execweave/viewer_investigation.py +268 -0
  210. execweave/viewer_layout_geometry.py +192 -0
  211. execweave/viewer_layout_v2.py +429 -0
  212. execweave/viewer_layout_v2_detached.py +25 -0
  213. execweave/viewer_limits.py +93 -0
  214. execweave/viewer_live_layout.py +61 -0
  215. execweave/viewer_message_handoffs.py +114 -0
  216. execweave/viewer_projection.py +488 -0
  217. execweave/viewer_projection_base.py +522 -0
  218. execweave/viewer_projection_bridges.py +214 -0
  219. execweave/viewer_recorded_sources.py +146 -0
  220. execweave/viewer_run_assessment.py +274 -0
  221. execweave/viewer_run_guide.py +175 -0
  222. execweave/viewer_runtime_evidence.py +258 -0
  223. execweave/viewer_semantic_projection.py +641 -0
  224. execweave/viewer_session_flow.py +491 -0
  225. execweave/viewer_structure_share.py +132 -0
  226. execweave/viewer_task_validation.py +241 -0
  227. execweave/viewer_tool_mirror_identity.py +75 -0
  228. execweave/viewer_workflow_mode.py +127 -0
  229. execweave/workflow.py +183 -0
  230. execweave-1.0.0.dist-info/METADATA +462 -0
  231. execweave-1.0.0.dist-info/RECORD +234 -0
  232. execweave-1.0.0.dist-info/WHEEL +4 -0
  233. execweave-1.0.0.dist-info/entry_points.txt +30 -0
  234. execweave-1.0.0.dist-info/licenses/LICENSE +16 -0
@@ -0,0 +1,547 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import socket
6
+ import sys
7
+ import threading
8
+ import time
9
+ from contextlib import contextmanager
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any, Iterator
13
+ from urllib.error import HTTPError, URLError
14
+ from urllib.parse import urlsplit, urlunsplit
15
+ from urllib.request import Request, urlopen
16
+
17
+ from .runtime_endpoint_availability import windows_exclusive_endpoint_available
18
+
19
+ from .model_runtime import (
20
+ append_model_runtime_records,
21
+ llamacpp_models_to_events,
22
+ lmstudio_models_to_events,
23
+ ollama_ps_to_events,
24
+ vllm_models_to_events,
25
+ )
26
+
27
+ _SEMANTIC_ENV = "EXECWEAVE_SEMANTIC_SIDECAR"
28
+ _OLLAMA_DEFAULT_ENDPOINT = "http://127.0.0.1:11434"
29
+ _OLLAMA_INFERENCE_PATHS = frozenset(
30
+ {
31
+ "/api/chat",
32
+ "/api/generate",
33
+ "/api/embed",
34
+ "/api/embeddings",
35
+ "/v1/chat/completions",
36
+ "/v1/completions",
37
+ "/v1/embeddings",
38
+ "/v1/responses",
39
+ }
40
+ )
41
+ _PROBE_INTERVAL_SECONDS = 0.50
42
+ _PROBE_TIMEOUT_SECONDS = 0.35
43
+ _PROBE_STARTUP_GRACE_SECONDS = 0.10
44
+ _POST_PROBE_ATTEMPTS = 6
45
+ _POST_PROBE_RETRY_SECONDS = 0.10
46
+ _LOCAL_HOSTS = {"127.0.0.1", "localhost", "::1", "0.0.0.0", "::"}
47
+ _PROBE_ERRORS = (HTTPError, URLError, OSError, TimeoutError, ValueError, json.JSONDecodeError)
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class _ProbeSpec:
52
+ runtime: str
53
+ endpoint: str
54
+ path: str
55
+
56
+
57
+ def _command_name(value: str) -> str:
58
+ name = value.replace("\\", "/").rsplit("/", 1)[-1].lower()
59
+ for suffix in (".exe", ".cmd", ".bat", ".ps1"):
60
+ if name.endswith(suffix):
61
+ return name[: -len(suffix)]
62
+ return name
63
+
64
+
65
+ def _is_ollama_serve(command: list[str]) -> bool:
66
+ return (
67
+ len(command) >= 2
68
+ and _command_name(command[0]) == "ollama"
69
+ and command[1].lower() == "serve"
70
+ )
71
+
72
+
73
+ def _is_ollama_run(command: list[str]) -> bool:
74
+ return (
75
+ len(command) >= 2
76
+ and _command_name(command[0]) == "ollama"
77
+ and command[1].lower() == "run"
78
+ )
79
+
80
+
81
+ def _is_llamacpp_server(command: list[str]) -> bool:
82
+ return bool(command) and _command_name(command[0]) == "llama-server"
83
+
84
+
85
+ def _is_vllm_server(command: list[str]) -> bool:
86
+ if len(command) >= 2 and _command_name(command[0]) == "vllm":
87
+ return command[1].lower() == "serve"
88
+ for index, value in enumerate(command[:-1]):
89
+ if value == "-m" and command[index + 1] == "vllm.entrypoints.openai.api_server":
90
+ return True
91
+ return False
92
+
93
+
94
+ def _is_lmstudio_server_start(command: list[str]) -> bool:
95
+ return (
96
+ len(command) >= 3
97
+ and _command_name(command[0]) == "lms"
98
+ and command[1].lower() == "server"
99
+ and command[2].lower() == "start"
100
+ )
101
+
102
+
103
+ def _flag_value(command: list[str], flag: str) -> str | None:
104
+ prefix = f"{flag}="
105
+ for index, value in enumerate(command):
106
+ if value.startswith(prefix):
107
+ return value[len(prefix) :]
108
+ if value == flag and index + 1 < len(command):
109
+ return command[index + 1]
110
+ return None
111
+
112
+
113
+ def _local_endpoint(host: str, port: int) -> str | None:
114
+ if host not in _LOCAL_HOSTS or not (1 <= port <= 65535):
115
+ return None
116
+ probe_host = "127.0.0.1" if host in {"0.0.0.0", "::"} else host
117
+ rendered_host = "[::1]" if probe_host == "::1" else probe_host
118
+ return urlunsplit(("http", f"{rendered_host}:{port}", "", "", ""))
119
+
120
+
121
+ def _server_endpoint(command: list[str], *, default_port: int) -> str | None:
122
+ host = _flag_value(command, "--host") or "127.0.0.1"
123
+ raw_port = _flag_value(command, "--port")
124
+ try:
125
+ port = int(raw_port) if raw_port is not None else default_port
126
+ except ValueError:
127
+ return None
128
+ return _local_endpoint(host, port)
129
+
130
+
131
+ def _ollama_endpoint_from_environment() -> str | None:
132
+ raw = os.environ.get("OLLAMA_HOST", "").strip()
133
+ if not raw:
134
+ return _OLLAMA_DEFAULT_ENDPOINT
135
+ candidate = raw if "://" in raw else f"http://{raw}"
136
+ try:
137
+ parsed = urlsplit(candidate)
138
+ port = parsed.port or 11434
139
+ except ValueError:
140
+ return None
141
+ if parsed.scheme != "http" or parsed.username is not None or parsed.password is not None:
142
+ return None
143
+ hostname = parsed.hostname
144
+ if hostname is None or hostname not in _LOCAL_HOSTS:
145
+ return None
146
+ if parsed.path not in {"", "/"} or parsed.query or parsed.fragment:
147
+ return None
148
+ return _local_endpoint(hostname, port)
149
+
150
+
151
+ def _ollama_serve_relay_address() -> tuple[str, int] | None:
152
+ """Return a loopback endpoint ExecWeave can safely own for ``ollama serve``."""
153
+ raw = os.environ.get("OLLAMA_HOST", "").strip()
154
+ if not raw:
155
+ return ("127.0.0.1", 11434)
156
+ candidate = raw if "://" in raw else f"http://{raw}"
157
+ try:
158
+ parsed = urlsplit(candidate)
159
+ port = parsed.port or 11434
160
+ except ValueError:
161
+ return None
162
+ if parsed.scheme != "http" or parsed.username is not None or parsed.password is not None:
163
+ return None
164
+ if parsed.path not in {"", "/"} or parsed.query or parsed.fragment:
165
+ return None
166
+ hostname = parsed.hostname
167
+ # Do not silently narrow wildcard/external/IPv6 exposure to IPv4 loopback.
168
+ if hostname not in {"127.0.0.1", "localhost"} or not (1 <= port <= 65535):
169
+ return None
170
+ return ("127.0.0.1", port)
171
+
172
+
173
+ def _allocate_loopback_port() -> int:
174
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
175
+ sock.bind(("127.0.0.1", 0))
176
+ return int(sock.getsockname()[1])
177
+
178
+
179
+ def _record_ollama_inference_exchange(config: Any, **kwargs: Any) -> None:
180
+ """Record inference exchanges while still relaying every Ollama API route."""
181
+ method = str(kwargs.get("method", "")).upper()
182
+ request_path = str(kwargs.get("request_path", ""))
183
+ if method != "POST" or urlsplit(request_path).path not in _OLLAMA_INFERENCE_PATHS:
184
+ return
185
+ from .http_proxy import record_exchange_fail_open
186
+
187
+ record_exchange_fail_open(config, **kwargs)
188
+
189
+
190
+ def _lmstudio_post_probe_spec(command: list[str]) -> _ProbeSpec | None:
191
+ if not _is_lmstudio_server_start(command):
192
+ return None
193
+ raw_port = _flag_value(command, "--port")
194
+ if raw_port is None:
195
+ return None
196
+ host = _flag_value(command, "--bind") or os.environ.get("LMS_SERVER_HOST", "").strip()
197
+ host = host or "127.0.0.1"
198
+ try:
199
+ port = int(raw_port)
200
+ except ValueError:
201
+ return None
202
+ endpoint = _local_endpoint(host, port)
203
+ return _ProbeSpec("lmstudio", endpoint, "/v1/models") if endpoint else None
204
+
205
+
206
+ def _probe_spec(command: list[str]) -> _ProbeSpec | None:
207
+ if _is_ollama_serve(command):
208
+ endpoint = _ollama_endpoint_from_environment()
209
+ return _ProbeSpec("ollama", endpoint, "/api/ps") if endpoint else None
210
+ if _is_llamacpp_server(command):
211
+ endpoint = _server_endpoint(command, default_port=8080)
212
+ return _ProbeSpec("llamacpp", endpoint, "/v1/models") if endpoint else None
213
+ if _is_vllm_server(command):
214
+ endpoint = _server_endpoint(command, default_port=8000)
215
+ return _ProbeSpec("vllm", endpoint, "/v1/models") if endpoint else None
216
+ return None
217
+
218
+
219
+ @dataclass(frozen=True)
220
+ class _LiveProbeAdmission:
221
+ # Prepared before the child (and any managed relay) is launched. A grace
222
+ # period is a scheduling aid, never evidence of endpoint ownership.
223
+ spec: _ProbeSpec | None
224
+
225
+
226
+ def prepare_live_specialized_probe(command: list[str]) -> _LiveProbeAdmission:
227
+ """Do not attach an already listening or uncertain endpoint to a new run.
228
+
229
+ A refused connection establishes absence at this pre-launch boundary. A
230
+ Windows connect timeout requires independent exclusive-bind proof for every
231
+ resolved loopback address; a timeout alone never authorizes a probe. Other
232
+ unknown/denied states abstain. This affects automatic catalog polling only,
233
+ not command execution or explicit request/response capture.
234
+ """
235
+ if not os.environ.get(_SEMANTIC_ENV):
236
+ return _LiveProbeAdmission(None)
237
+ spec = _probe_spec(command)
238
+ if spec is None:
239
+ return _LiveProbeAdmission(None)
240
+ address = urlsplit(spec.endpoint)
241
+ try:
242
+ with socket.create_connection(
243
+ (str(address.hostname), int(address.port or 80)),
244
+ timeout=_PROBE_TIMEOUT_SECONDS,
245
+ ):
246
+ pass
247
+ except ConnectionRefusedError:
248
+ return _LiveProbeAdmission(spec)
249
+ except TimeoutError:
250
+ if windows_exclusive_endpoint_available(str(address.hostname), int(address.port or 80)):
251
+ return _LiveProbeAdmission(spec)
252
+ except OSError:
253
+ pass
254
+ print(
255
+ f"ExecWeave {spec.runtime} probe: endpoint {spec.endpoint} was not "
256
+ "proven unused before launch; automatic catalog evidence is disabled.",
257
+ file=sys.stderr,
258
+ )
259
+ return _LiveProbeAdmission(None)
260
+
261
+
262
+ def _get_json(url: str, *, timeout: float) -> dict[str, object]:
263
+ request = Request(url, headers={"Accept": "application/json"})
264
+ with urlopen(request, timeout=timeout) as response:
265
+ payload = json.loads(response.read().decode("utf-8"))
266
+ if not isinstance(payload, dict):
267
+ raise ValueError("model runtime probe did not return a JSON object")
268
+ return payload
269
+
270
+
271
+ def _probe_records(spec: _ProbeSpec, payload: dict[str, object]) -> list[dict[str, object]]:
272
+ if spec.runtime == "ollama":
273
+ return ollama_ps_to_events(payload, endpoint=spec.endpoint)
274
+ if spec.runtime == "llamacpp":
275
+ return llamacpp_models_to_events(payload, endpoint=spec.endpoint)
276
+ if spec.runtime == "vllm":
277
+ return vllm_models_to_events(payload, endpoint=spec.endpoint)
278
+ if spec.runtime == "lmstudio":
279
+ return lmstudio_models_to_events(payload, endpoint=spec.endpoint)
280
+ return []
281
+
282
+
283
+ def _record_identity(record: dict[str, object]) -> str:
284
+ target = record.get("target")
285
+ if isinstance(target, dict):
286
+ target_id = target.get("id")
287
+ if isinstance(target_id, str) and target_id:
288
+ return f"{record.get('relation')}:{target_id}"
289
+ return json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
290
+
291
+
292
+ def _record_fingerprint(record: dict[str, object]) -> str:
293
+ stable = {
294
+ "event_type": record.get("event_type"),
295
+ "relation": record.get("relation"),
296
+ "source": record.get("source"),
297
+ "target": record.get("target"),
298
+ "attributes": record.get("attributes"),
299
+ }
300
+ return json.dumps(stable, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
301
+
302
+
303
+ def _run_model_probe(
304
+ *,
305
+ spec: _ProbeSpec,
306
+ sidecar: Path,
307
+ stop_event: threading.Event,
308
+ ) -> None:
309
+ if stop_event.wait(_PROBE_STARTUP_GRACE_SECONDS):
310
+ return
311
+ previous: dict[str, str] = {}
312
+ url = f"{spec.endpoint.rstrip('/')}{spec.path}"
313
+ while not stop_event.is_set():
314
+ try:
315
+ payload = _get_json(url, timeout=_PROBE_TIMEOUT_SECONDS)
316
+ records = _probe_records(spec, payload)
317
+ current = {
318
+ _record_identity(record): _record_fingerprint(record)
319
+ for record in records
320
+ }
321
+ changed = [
322
+ record
323
+ for record in records
324
+ if current[_record_identity(record)]
325
+ != previous.get(_record_identity(record))
326
+ ]
327
+ if changed:
328
+ append_model_runtime_records(sidecar, changed)
329
+ previous = current
330
+ except _PROBE_ERRORS:
331
+ pass
332
+ stop_event.wait(_PROBE_INTERVAL_SECONDS)
333
+
334
+
335
+ def _run_ollama_probe(
336
+ *,
337
+ endpoint: str,
338
+ sidecar: Path,
339
+ stop_event: threading.Event,
340
+ ) -> None:
341
+ _run_model_probe(
342
+ spec=_ProbeSpec("ollama", endpoint, "/api/ps"),
343
+ sidecar=sidecar,
344
+ stop_event=stop_event,
345
+ )
346
+
347
+
348
+ def prepare_post_command_specialized_probe(command: list[str]) -> _ProbeSpec | None:
349
+ """Prepare an attribution-safe post-command probe for short-lived launch CLIs."""
350
+ spec = _lmstudio_post_probe_spec(command)
351
+ if spec is None:
352
+ return None
353
+ try:
354
+ _get_json(
355
+ f"{spec.endpoint.rstrip('/')}{spec.path}",
356
+ timeout=_PROBE_TIMEOUT_SECONDS,
357
+ )
358
+ except _PROBE_ERRORS:
359
+ return spec
360
+ return None
361
+
362
+
363
+ def run_post_command_specialized_probe(
364
+ spec: _ProbeSpec | None,
365
+ *,
366
+ return_code: int,
367
+ ) -> None:
368
+ """Materialize a prepared short-lived launcher probe after successful exit."""
369
+ configured_sidecar = os.environ.get(_SEMANTIC_ENV)
370
+ if spec is None or return_code != 0 or not configured_sidecar:
371
+ return
372
+ url = f"{spec.endpoint.rstrip('/')}{spec.path}"
373
+ for attempt in range(_POST_PROBE_ATTEMPTS):
374
+ try:
375
+ payload = _get_json(url, timeout=_PROBE_TIMEOUT_SECONDS)
376
+ records = _probe_records(spec, payload)
377
+ if records:
378
+ append_model_runtime_records(
379
+ Path(configured_sidecar).expanduser().resolve(),
380
+ records,
381
+ )
382
+ return
383
+ except _PROBE_ERRORS:
384
+ if attempt + 1 < _POST_PROBE_ATTEMPTS:
385
+ time.sleep(_POST_PROBE_RETRY_SECONDS)
386
+
387
+
388
+ @contextmanager
389
+ def auto_specialized_launch(
390
+ command: list[str],
391
+ *,
392
+ server_relay: bool = False,
393
+ ) -> Iterator[dict[str, str]]:
394
+ """Prepare child launch wiring for supported transparent local integrations.
395
+
396
+ ``server_relay`` is deliberately opt-in so direct library callers preserve the
397
+ existing contract. RuntimeCollector enables it for a real managed server run.
398
+ """
399
+ environment = dict(os.environ)
400
+ configured_sidecar = os.environ.get(_SEMANTIC_ENV)
401
+ wants_run_relay = _is_ollama_run(command)
402
+ wants_serve_relay = server_relay and _is_ollama_serve(command)
403
+ if not configured_sidecar or not (wants_run_relay or wants_serve_relay):
404
+ yield environment
405
+ return
406
+
407
+ from .http_proxy import ExecWeaveHTTPProxyServer, ProxyConfig
408
+
409
+ sidecar = Path(configured_sidecar).expanduser().resolve()
410
+
411
+ if wants_run_relay:
412
+ upstream = _ollama_endpoint_from_environment()
413
+ if upstream is None:
414
+ yield environment
415
+ return
416
+ try:
417
+ server = ExecWeaveHTTPProxyServer(
418
+ ("127.0.0.1", 0),
419
+ ProxyConfig(upstream=upstream, sidecar=sidecar, mode="ollama"),
420
+ recorder=_record_ollama_inference_exchange,
421
+ )
422
+ except OSError:
423
+ yield environment
424
+ return
425
+ thread = threading.Thread(
426
+ target=server.serve_forever,
427
+ kwargs={"poll_interval": 0.05},
428
+ name="execweave-ollama-run-relay",
429
+ daemon=True,
430
+ )
431
+ thread.start()
432
+ host, port = server.server_address[:2]
433
+ environment["OLLAMA_HOST"] = f"http://{host}:{port}"
434
+ try:
435
+ yield environment
436
+ finally:
437
+ server.shutdown()
438
+ server.server_close()
439
+ thread.join(timeout=2.0)
440
+ return
441
+
442
+ listen_address = _ollama_serve_relay_address()
443
+ if listen_address is None:
444
+ yield environment
445
+ return
446
+ listen_host, listen_port = listen_address
447
+ public_endpoint = f"http://{listen_host}:{listen_port}"
448
+ try:
449
+ existing = _get_json(
450
+ f"{public_endpoint}/api/ps",
451
+ timeout=_PROBE_TIMEOUT_SECONDS,
452
+ )
453
+ except _PROBE_ERRORS:
454
+ existing = None
455
+ if isinstance(existing, dict) and isinstance(existing.get("models"), list):
456
+ print(
457
+ "ExecWeave Ollama relay: existing Ollama server detected at "
458
+ f"{public_endpoint}; leaving that server unclaimed.",
459
+ file=sys.stderr,
460
+ )
461
+ yield environment
462
+ return
463
+
464
+ internal_port = _allocate_loopback_port()
465
+ upstream = f"http://127.0.0.1:{internal_port}"
466
+ server: ExecWeaveHTTPProxyServer | None = None
467
+ last_bind_error: OSError | None = None
468
+ for attempt in range(5):
469
+ try:
470
+ server = ExecWeaveHTTPProxyServer(
471
+ (listen_host, listen_port),
472
+ ProxyConfig(upstream=upstream, sidecar=sidecar, mode="ollama"),
473
+ recorder=_record_ollama_inference_exchange,
474
+ )
475
+ break
476
+ except OSError as exc:
477
+ last_bind_error = exc
478
+ if attempt < 4:
479
+ time.sleep(0.05)
480
+ if server is None:
481
+ raise RuntimeError(
482
+ "ExecWeave could not reserve the Ollama endpoint "
483
+ f"{public_endpoint} for transparent conversation capture. "
484
+ "Stop any existing Ollama server using that endpoint or set "
485
+ "OLLAMA_HOST to a free loopback port before starting "
486
+ "`execweave live -- ollama serve`."
487
+ ) from last_bind_error
488
+ thread = threading.Thread(
489
+ target=server.serve_forever,
490
+ kwargs={"poll_interval": 0.05},
491
+ name="execweave-ollama-serve-relay",
492
+ daemon=True,
493
+ )
494
+ thread.start()
495
+ environment["OLLAMA_HOST"] = upstream
496
+ print(
497
+ "ExecWeave Ollama relay: "
498
+ f"http://{listen_host}:{listen_port} -> {upstream}",
499
+ file=sys.stderr,
500
+ )
501
+ try:
502
+ yield environment
503
+ finally:
504
+ server.shutdown()
505
+ server.server_close()
506
+ thread.join(timeout=2.0)
507
+
508
+
509
+ @contextmanager
510
+ def auto_specialized_probe(
511
+ command: list[str],
512
+ *,
513
+ admission: _LiveProbeAdmission | None = None,
514
+ ) -> Iterator[None]:
515
+ """Poll a prepared launch, or an explicitly requested library observation.
516
+
517
+ RuntimeCollector always supplies pre-launch admission. A direct library
518
+ caller without admission retains the explicit endpoint-observation API.
519
+ """
520
+ configured_sidecar = os.environ.get(_SEMANTIC_ENV)
521
+ spec = admission.spec if admission is not None else _probe_spec(command)
522
+ if not configured_sidecar or spec is None:
523
+ yield
524
+ return
525
+
526
+ sidecar = Path(configured_sidecar).expanduser().resolve()
527
+ stop_event = threading.Event()
528
+ thread = threading.Thread(
529
+ target=_run_model_probe,
530
+ kwargs={"spec": spec, "sidecar": sidecar, "stop_event": stop_event},
531
+ name=f"execweave-{spec.runtime}-live-probe",
532
+ daemon=True,
533
+ )
534
+ thread.start()
535
+ try:
536
+ yield
537
+ finally:
538
+ stop_event.set()
539
+ thread.join(
540
+ timeout=max(
541
+ 1.0,
542
+ _PROBE_STARTUP_GRACE_SECONDS
543
+ + _PROBE_TIMEOUT_SECONDS
544
+ + _PROBE_INTERVAL_SECONDS
545
+ + 0.2,
546
+ )
547
+ )
execweave/backends.py ADDED
@@ -0,0 +1,102 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from dataclasses import replace
5
+ from pathlib import Path
6
+ from typing import Literal
7
+
8
+ from .collector import RuntimeCollector
9
+ from .schema import RuntimeEvent
10
+ from .scope import protect_filesystem_scope
11
+ from .sink import JsonlSink
12
+ from .strace_backend import StraceRuntimeCollector, strace_available
13
+
14
+ BackendName = Literal["auto", "portable", "strace"]
15
+
16
+
17
+ class _FidelityContextSink:
18
+ """Decorate the canonical session start with facts known at collector creation.
19
+
20
+ The context is injected before the existing JsonlSink assigns a sequence number,
21
+ so it remains part of the canonical event stream instead of living only in a
22
+ derived report. The wrapper never suppresses or rewrites non-session events.
23
+ """
24
+
25
+ def __init__(self, sink: JsonlSink, context: dict[str, object]) -> None:
26
+ self._sink = sink
27
+ self._context = context
28
+ self.path = sink.path
29
+
30
+ def emit(self, event: RuntimeEvent) -> None:
31
+ if event.event_type == "session.started":
32
+ event = replace(event, attributes={**event.attributes, **self._context})
33
+ self._sink.emit(event)
34
+
35
+
36
+ def resolve_backend(requested: BackendName) -> str:
37
+ if requested == "portable":
38
+ return "portable"
39
+ if requested == "strace":
40
+ if not strace_available():
41
+ raise RuntimeError("strace backend requested, but Linux strace is not available")
42
+ return "strace"
43
+ if requested != "auto":
44
+ raise ValueError(f"unknown backend: {requested}")
45
+ return "strace" if strace_available() else "portable"
46
+
47
+
48
+ def create_collector(
49
+ *,
50
+ backend: BackendName,
51
+ session_id: str,
52
+ sink: JsonlSink,
53
+ watch_root: Path,
54
+ poll_interval: float,
55
+ collect_filesystem: bool,
56
+ collect_network: bool,
57
+ keep_raw_trace: bool = False,
58
+ allow_broad_filesystem_scope: bool = False,
59
+ ):
60
+ scope = protect_filesystem_scope(
61
+ watch_root,
62
+ collect_filesystem=collect_filesystem,
63
+ allow_broad_scope=allow_broad_filesystem_scope,
64
+ )
65
+ resolved = resolve_backend(backend)
66
+ context: dict[str, object] = {
67
+ "platform": sys.platform,
68
+ "filesystem_requested": collect_filesystem,
69
+ "filesystem_collected": scope.collect_filesystem,
70
+ "filesystem_scope_downgraded": collect_filesystem and not scope.collect_filesystem,
71
+ "network_requested": collect_network,
72
+ "network_collected": collect_network,
73
+ }
74
+ contextual_sink = _FidelityContextSink(sink, context)
75
+ if resolved == "strace":
76
+ return StraceRuntimeCollector(
77
+ session_id=session_id,
78
+ sink=contextual_sink,
79
+ watch_root=scope.watch_root,
80
+ collect_filesystem=scope.collect_filesystem,
81
+ collect_network=collect_network,
82
+ keep_raw_trace=keep_raw_trace,
83
+ )
84
+ collector = RuntimeCollector(
85
+ session_id=session_id,
86
+ sink=contextual_sink,
87
+ watch_root=scope.watch_root,
88
+ poll_interval=poll_interval,
89
+ collect_filesystem=scope.collect_filesystem,
90
+ collect_network=collect_network,
91
+ )
92
+ context["configured_process_poll_interval_ms"] = round(collector.poll_interval * 1000, 3)
93
+ return collector
94
+
95
+
96
+ def backend_diagnostics() -> dict[str, object]:
97
+ return {
98
+ "platform": sys.platform,
99
+ "portable": True,
100
+ "strace": strace_available(),
101
+ "auto_selected": resolve_backend("auto"),
102
+ }