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,565 @@
1
+ from __future__ import annotations
2
+
3
+ import http.client
4
+ import ipaddress
5
+ import json
6
+ import sys
7
+ import threading
8
+ import uuid
9
+ from dataclasses import dataclass
10
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
+ from pathlib import Path
12
+ from typing import Any, Callable
13
+ from urllib.parse import SplitResult, urlsplit, urlunsplit
14
+
15
+ from .content_evidence import content_observation_event
16
+ from .content_store import FullFidelityContentStore
17
+ from .model_runtime_full_fidelity import runtime_exchange_to_content_events
18
+ from .openai_compatible import append_openai_compatible_records
19
+ from .openai_compatible_full_fidelity import exchange_to_content_events
20
+ from .privacy import full_content_capture_enabled
21
+ from .stream_assembly import (
22
+ OLLAMA_NDJSON,
23
+ OPENAI_CHAT_DELTA,
24
+ arguments_parse_cleanly,
25
+ assemble_stream,
26
+ assembled_tool_calls,
27
+ )
28
+
29
+ _HOP_BY_HOP = frozenset(
30
+ {
31
+ "connection",
32
+ "keep-alive",
33
+ "proxy-authenticate",
34
+ "proxy-authorization",
35
+ "te",
36
+ "trailer",
37
+ "transfer-encoding",
38
+ "upgrade",
39
+ }
40
+ )
41
+
42
+ _REQUEST_RELATIONS = frozenset(
43
+ {
44
+ "OBSERVED_INFERENCE_REQUEST",
45
+ "OBSERVED_INFERENCE_REQUEST_MESSAGES",
46
+ "OBSERVED_INFERENCE_REQUEST_PROMPT",
47
+ "OBSERVED_INFERENCE_REQUEST_INPUT",
48
+ "OBSERVED_INFERENCE_REQUEST_CONFIG",
49
+ "OBSERVED_TOOL_RESULT_MESSAGES",
50
+ "OBSERVED_SYSTEM_CONTEXT",
51
+ "OBSERVED_TOOL_DEFINITIONS",
52
+ }
53
+ )
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class ProxyConfig:
58
+ upstream: str
59
+ sidecar: Path
60
+ mode: str = "openai-compatible"
61
+ provider_name: str = "openai-compatible"
62
+ timeout_seconds: float = 120.0
63
+
64
+
65
+ def _parse_upstream(value: str) -> SplitResult:
66
+ split = urlsplit(value)
67
+ if split.scheme != "http" or not split.hostname:
68
+ raise ValueError("proxy upstream must be one explicit http:// URL")
69
+ if split.username is not None or split.password is not None:
70
+ raise ValueError("proxy upstream URL must not contain credentials")
71
+ if split.query or split.fragment:
72
+ raise ValueError("proxy upstream URL must not contain query or fragment components")
73
+ return split
74
+
75
+
76
+ def sanitize_upstream(value: str) -> str:
77
+ split = _parse_upstream(value)
78
+ host = split.hostname or ""
79
+ if ":" in host and not host.startswith("["):
80
+ host = f"[{host}]"
81
+ if split.port is not None:
82
+ host = f"{host}:{split.port}"
83
+ return urlunsplit(("http", host, split.path.rstrip("/"), "", ""))
84
+
85
+
86
+ def validate_listen_host(host: str) -> None:
87
+ if host == "localhost":
88
+ return
89
+ try:
90
+ address = ipaddress.ip_address(host)
91
+ except ValueError as exc:
92
+ raise ValueError("proxy listen host must be localhost or a loopback IP address") from exc
93
+ if not address.is_loopback:
94
+ raise ValueError("proxy listen host must be localhost or a loopback IP address")
95
+
96
+
97
+ def _target_path(upstream: SplitResult, incoming: str) -> str:
98
+ split = urlsplit(incoming)
99
+ if split.scheme or split.netloc or not split.path.startswith("/"):
100
+ raise ValueError("absolute-form proxy targets are not accepted")
101
+ base = upstream.path.rstrip("/")
102
+ path = f"{base}{split.path}" if base else split.path
103
+ return urlunsplit(("", "", path, split.query, ""))
104
+
105
+
106
+ def _json(payload: bytes) -> Any | None:
107
+ try:
108
+ return json.loads(payload.decode("utf-8")) if payload else None
109
+ except (UnicodeDecodeError, json.JSONDecodeError):
110
+ return None
111
+
112
+
113
+ def _stream_items(payload: bytes, content_type: str | None, request: Any) -> list[Any]:
114
+ media_type = (content_type or "").split(";", 1)[0].strip().lower()
115
+ if media_type == "text/event-stream":
116
+ values: list[Any] = []
117
+ for raw in payload.splitlines():
118
+ line = raw.decode("utf-8", errors="replace").strip()
119
+ if not line.startswith("data:"):
120
+ continue
121
+ data = line[5:].strip()
122
+ if not data or data == "[DONE]":
123
+ continue
124
+ try:
125
+ values.append(json.loads(data))
126
+ except json.JSONDecodeError:
127
+ values.append(data)
128
+ return values
129
+ streaming = isinstance(request, dict) and request.get("stream") is True
130
+ if not streaming and media_type not in {"application/x-ndjson", "application/ndjson"}:
131
+ return []
132
+ values = []
133
+ for raw in payload.splitlines():
134
+ if not raw.strip():
135
+ continue
136
+ try:
137
+ values.append(json.loads(raw.decode("utf-8")))
138
+ except (UnicodeDecodeError, json.JSONDecodeError):
139
+ values.append(raw.decode("utf-8", errors="replace"))
140
+ return values
141
+
142
+
143
+ def _tool_calls(value: Any) -> list[Any]:
144
+ calls: list[Any] = []
145
+
146
+ def walk(item: Any) -> None:
147
+ if isinstance(item, dict):
148
+ nested = item.get("tool_calls")
149
+ if isinstance(nested, list):
150
+ calls.extend(nested)
151
+ if item.get("type") in {"function_call", "tool_call", "tool_use"}:
152
+ calls.append(item)
153
+ for child in item.values():
154
+ walk(child)
155
+ elif isinstance(item, list):
156
+ for child in item:
157
+ walk(child)
158
+
159
+ walk(value)
160
+ return calls
161
+
162
+
163
+ def _has_relation(events: list[dict[str, Any]], relation: str) -> bool:
164
+ """Whether the full-fidelity emitter already published this relation."""
165
+ return any(event.get("relation") == relation for event in events)
166
+
167
+
168
+ def _raw_event(
169
+ store: FullFidelityContentStore,
170
+ source: dict[str, Any],
171
+ provider: str,
172
+ body: bytes,
173
+ *,
174
+ kind: str,
175
+ relation: str,
176
+ field: str,
177
+ media_type: str | None,
178
+ ) -> dict[str, Any]:
179
+ reference = store.put_bytes(
180
+ body,
181
+ content_kind=kind,
182
+ media_type=media_type or "application/octet-stream",
183
+ representation="raw_bytes",
184
+ )
185
+ return content_observation_event(
186
+ timestamp=source.get("attributes", {}).get("observed_at", ""),
187
+ provider=provider,
188
+ source=source,
189
+ reference=reference,
190
+ relation=relation,
191
+ observed_field=field,
192
+ evidence_source="localhost_http_proxy",
193
+ attribution="execweave_http_proxy",
194
+ event_type="http_proxy.content.observed",
195
+ attributes={"transport_relay_observed": True, "causal": False, "inferred": False},
196
+ )
197
+
198
+
199
+ def record_exchange_fail_open(
200
+ config: ProxyConfig,
201
+ *,
202
+ exchange_id: str,
203
+ request_body: bytes,
204
+ request_content_type: str | None,
205
+ response_body: bytes,
206
+ response_content_type: str | None,
207
+ method: str,
208
+ request_path: str,
209
+ status: int | None,
210
+ request_only: bool = False,
211
+ request_recorded: bool = False,
212
+ ) -> bool:
213
+ if not full_content_capture_enabled():
214
+ return False
215
+ try:
216
+ request = _json(request_body)
217
+ if not isinstance(request, dict):
218
+ request = {}
219
+ if request_only and not any(key in request for key in ("messages", "prompt", "input")):
220
+ return False
221
+ chunks = _stream_items(response_body, response_content_type, request)
222
+ # A streamed response must be reassembled. Taking one frame loses the body:
223
+ # the final frame of an OpenAI-style stream carries an empty delta, so the
224
+ # assistant text, the reasoning and every fragmented tool call would be
225
+ # dropped from the canonical record while surviving only as raw frames.
226
+ assembled = (
227
+ assemble_stream(
228
+ chunks,
229
+ wire_format=OLLAMA_NDJSON if config.mode == "ollama" else OPENAI_CHAT_DELTA,
230
+ )
231
+ if chunks
232
+ else None
233
+ )
234
+ response = assembled.response if assembled is not None else _json(response_body)
235
+ if not isinstance(response, dict):
236
+ response = {}
237
+ store = FullFidelityContentStore(config.sidecar.parent)
238
+ if config.mode == "ollama":
239
+ events = runtime_exchange_to_content_events(
240
+ {"request": request, "response": response},
241
+ store=store,
242
+ runtime="ollama",
243
+ endpoint=config.upstream,
244
+ request_id=exchange_id,
245
+ )
246
+ provider = "ollama"
247
+ else:
248
+ exchange = {"request": request, "response": response}
249
+ if chunks:
250
+ exchange["stream_chunks"] = chunks
251
+ events = exchange_to_content_events(
252
+ exchange,
253
+ store=store,
254
+ endpoint=config.upstream,
255
+ provider_name=config.provider_name,
256
+ request_id=exchange_id,
257
+ )
258
+ provider = config.provider_name
259
+ if request_only:
260
+ events = [event for event in events if event.get("relation") in _REQUEST_RELATIONS]
261
+ elif request_recorded:
262
+ events = [event for event in events if event.get("relation") not in _REQUEST_RELATIONS]
263
+ for event in events:
264
+ attrs = event.setdefault("attributes", {})
265
+ attrs.update(
266
+ {
267
+ "observation_scope": "localhost_http_proxy",
268
+ "caller_supplied_exchange": False,
269
+ "wire_interception_asserted": True,
270
+ "transport_relay_observed": True,
271
+ "evidence_source": "localhost_http_proxy",
272
+ "attribution": "execweave_http_proxy",
273
+ "proxy_method": method,
274
+ "proxy_request_path": request_path,
275
+ "proxy_status": status,
276
+ "proxy_upstream": sanitize_upstream(config.upstream),
277
+ "causal": False,
278
+ "inferred": False,
279
+ "capture_phase": "request" if request_only else "response",
280
+ "response_observed": not request_only,
281
+ }
282
+ )
283
+ if assembled is not None:
284
+ attrs.update(assembled.attributes())
285
+ attrs["stream_tool_arguments_parse_cleanly"] = arguments_parse_cleanly(response)
286
+ if assembled.notes:
287
+ attrs["stream_assembly_notes"] = assembled.notes
288
+ source = events[0]["source"]
289
+ source.setdefault("attributes", {})["observed_at"] = events[0]["timestamp"]
290
+ raw_events = [
291
+ _raw_event(
292
+ store,
293
+ source,
294
+ provider,
295
+ request_body,
296
+ kind="http_proxy.request_body_raw",
297
+ relation="OBSERVED_INFERENCE_REQUEST_RAW",
298
+ field="request.body.raw",
299
+ media_type=request_content_type,
300
+ ),
301
+ _raw_event(
302
+ store,
303
+ source,
304
+ provider,
305
+ response_body,
306
+ kind="http_proxy.response_body_raw",
307
+ relation="OBSERVED_INFERENCE_RESPONSE_RAW",
308
+ field="response.body.raw",
309
+ media_type=response_content_type,
310
+ ),
311
+ ]
312
+ events.extend(
313
+ raw_events[:1] if request_only else raw_events[1:] if request_recorded else raw_events
314
+ )
315
+ if request_only:
316
+ append_openai_compatible_records(config.sidecar, events)
317
+ return True
318
+ # Raw frames stay archived for both modes. The assembled response is the
319
+ # canonical record; these are the evidence it was rebuilt from. The
320
+ # OpenAI-compatible emitter already archives frames handed to it through
321
+ # ``stream_chunks``, so only supplement what it did not publish.
322
+ if chunks and not _has_relation(events, "OBSERVED_INFERENCE_STREAM_CHUNKS"):
323
+ kind = (
324
+ "http_proxy.ollama_stream_chunks"
325
+ if config.mode == "ollama"
326
+ else "http_proxy.stream_chunks"
327
+ )
328
+ reference = store.put_json(chunks, content_kind=kind)
329
+ events.append(
330
+ content_observation_event(
331
+ timestamp=events[0]["timestamp"],
332
+ provider=provider,
333
+ source=source,
334
+ reference=reference,
335
+ relation="OBSERVED_INFERENCE_STREAM_CHUNKS",
336
+ observed_field="response.stream_chunks",
337
+ evidence_source="localhost_http_proxy",
338
+ attribution="execweave_http_proxy",
339
+ event_type="http_proxy.content.observed",
340
+ attributes={"causal": False, "inferred": False},
341
+ )
342
+ )
343
+ # Tool calls come from the assembled response, never from raw frames: one
344
+ # call split across frames would otherwise be published as several partial
345
+ # calls, each carrying a slice of its JSON arguments. Once assembled they
346
+ # live in the response, so the full-fidelity emitter may already have
347
+ # published them; only supplement when it did not.
348
+ calls = (
349
+ []
350
+ if _has_relation(events, "OBSERVED_ASSISTANT_TOOL_CALLS")
351
+ else assembled_tool_calls(response)
352
+ if assembled is not None
353
+ else _tool_calls(response)
354
+ )
355
+ if calls:
356
+ reference = store.put_json(calls, content_kind="http_proxy.response_tool_calls")
357
+ events.append(
358
+ content_observation_event(
359
+ timestamp=events[0]["timestamp"],
360
+ provider=provider,
361
+ source=source,
362
+ reference=reference,
363
+ relation="OBSERVED_ASSISTANT_TOOL_CALLS",
364
+ observed_field="response.tool_calls",
365
+ evidence_source="localhost_http_proxy",
366
+ attribution="execweave_http_proxy",
367
+ event_type="http_proxy.content.observed",
368
+ attributes={"causal": False, "inferred": False},
369
+ )
370
+ )
371
+ append_openai_compatible_records(config.sidecar, events)
372
+ return True
373
+ except Exception as exc:
374
+ print(f"ExecWeave HTTP proxy capture warning: {exc}", file=sys.stderr)
375
+ return False
376
+
377
+
378
+ class ExecWeaveHTTPProxyServer(ThreadingHTTPServer):
379
+ daemon_threads = True
380
+
381
+ def __init__(
382
+ self,
383
+ address: tuple[str, int],
384
+ config: ProxyConfig,
385
+ recorder: Callable[..., None] = record_exchange_fail_open,
386
+ ) -> None:
387
+ validate_listen_host(address[0])
388
+ if config.mode not in {"ollama", "openai-compatible"}:
389
+ raise ValueError("proxy mode must be ollama or openai-compatible")
390
+ self.proxy_config = config
391
+ self.upstream = _parse_upstream(config.upstream)
392
+ self.recorder = recorder
393
+ # Handler threads are daemonic, so ThreadingMixIn.server_close() does not
394
+ # join them. A response can reach the client before its recording finishes,
395
+ # so closing the server waits for those recordings explicitly instead.
396
+ self._recordings = 0
397
+ self._recordings_done = threading.Condition()
398
+ super().__init__(address, ExecWeaveHTTPProxyHandler)
399
+
400
+ def begin_recording(self) -> None:
401
+ with self._recordings_done:
402
+ self._recordings += 1
403
+
404
+ def end_recording(self) -> None:
405
+ with self._recordings_done:
406
+ self._recordings -= 1
407
+ self._recordings_done.notify_all()
408
+
409
+ def wait_for_recordings(self, timeout: float | None = None) -> bool:
410
+ with self._recordings_done:
411
+ return self._recordings_done.wait_for(lambda: self._recordings == 0, timeout)
412
+
413
+ def server_close(self) -> None:
414
+ super().server_close()
415
+ self.wait_for_recordings()
416
+
417
+
418
+ class ExecWeaveHTTPProxyHandler(BaseHTTPRequestHandler):
419
+ server: ExecWeaveHTTPProxyServer
420
+ protocol_version = "HTTP/1.0"
421
+
422
+ def log_message(self, format: str, *args: object) -> None:
423
+ return
424
+
425
+ def do_CONNECT(self) -> None:
426
+ self.send_error(405, "CONNECT is disabled; ExecWeave does not perform TLS MITM")
427
+
428
+ def do_GET(self) -> None:
429
+ self._relay()
430
+
431
+ def do_HEAD(self) -> None:
432
+ self._relay()
433
+
434
+ def do_OPTIONS(self) -> None:
435
+ self._relay()
436
+
437
+ def do_POST(self) -> None:
438
+ self._relay()
439
+
440
+ def do_PUT(self) -> None:
441
+ self._relay()
442
+
443
+ def do_PATCH(self) -> None:
444
+ self._relay()
445
+
446
+ def do_DELETE(self) -> None:
447
+ self._relay()
448
+
449
+ def _read_body(self) -> bytes:
450
+ transfer = self.headers.get("Transfer-Encoding", "").lower()
451
+ if transfer:
452
+ if transfer != "chunked":
453
+ raise ValueError("unsupported request Transfer-Encoding")
454
+ chunks: list[bytes] = []
455
+ while True:
456
+ line = self.rfile.readline()
457
+ size = int(line.split(b";", 1)[0].strip(), 16)
458
+ if size == 0:
459
+ while self.rfile.readline() not in {b"\r\n", b"\n", b""}:
460
+ pass
461
+ return b"".join(chunks)
462
+ chunks.append(self.rfile.read(size))
463
+ if self.rfile.read(2) != b"\r\n":
464
+ raise ValueError("invalid chunk terminator")
465
+ length = int(self.headers.get("Content-Length", "0"))
466
+ return self.rfile.read(length)
467
+
468
+ def _headers(self, body: bytes) -> dict[str, str]:
469
+ result = {
470
+ key: value
471
+ for key, value in self.headers.items()
472
+ if key.lower() not in _HOP_BY_HOP | {"host", "content-length"}
473
+ }
474
+ if body:
475
+ result["Content-Length"] = str(len(body))
476
+ return result
477
+
478
+ def _relay(self) -> None:
479
+ try:
480
+ target = _target_path(self.server.upstream, self.path)
481
+ body = self._read_body()
482
+ except (TypeError, ValueError) as exc:
483
+ self.send_error(400, str(exc))
484
+ return
485
+ upstream = self.server.upstream
486
+ connection = http.client.HTTPConnection(
487
+ upstream.hostname,
488
+ upstream.port or 80,
489
+ timeout=self.server.proxy_config.timeout_seconds,
490
+ )
491
+ response_body = bytearray()
492
+ response_type: str | None = None
493
+ started = False
494
+ exchange_id = uuid.uuid4().hex
495
+ request_recorded = False
496
+ try:
497
+ connection.request(self.command, target, body=body or None, headers=self._headers(body))
498
+ # Publish only dispatched request evidence, before waiting for model
499
+ # headers/body. Custom recorder callbacks retain their one-call API.
500
+ if self.server.recorder is record_exchange_fail_open:
501
+ request_recorded = record_exchange_fail_open(
502
+ self.server.proxy_config,
503
+ exchange_id=exchange_id,
504
+ method=self.command,
505
+ request_path=target,
506
+ request_body=body,
507
+ request_content_type=self.headers.get("Content-Type"),
508
+ status=None,
509
+ response_body=b"",
510
+ response_content_type=None,
511
+ request_only=True,
512
+ )
513
+ response = connection.getresponse()
514
+ response_type = response.getheader("Content-Type")
515
+ self.send_response(response.status, response.reason)
516
+ started = True
517
+ for key, value in response.getheaders():
518
+ if key.lower() not in _HOP_BY_HOP | {"content-length", "connection"}:
519
+ self.send_header(key, value)
520
+ self.send_header("Connection", "close")
521
+ self.end_headers()
522
+ if self.command != "HEAD":
523
+ # read(n) can wait for n bytes or EOF, withholding flushed model
524
+ # output until completion. read1 forwards available stream data.
525
+ while chunk := response.read1(65536):
526
+ response_body.extend(chunk)
527
+ self.wfile.write(chunk)
528
+ self.wfile.flush()
529
+ except (OSError, http.client.HTTPException) as exc:
530
+ if not started:
531
+ self.send_error(502, f"upstream HTTP relay failed: {exc}")
532
+ return
533
+ finally:
534
+ connection.close()
535
+ try:
536
+ self.server.recorder(
537
+ self.server.proxy_config,
538
+ exchange_id=exchange_id,
539
+ method=self.command,
540
+ request_path=target,
541
+ request_body=body,
542
+ request_content_type=self.headers.get("Content-Type"),
543
+ status=response.status,
544
+ response_body=bytes(response_body),
545
+ response_content_type=response_type,
546
+ **(
547
+ {"request_recorded": request_recorded}
548
+ if self.server.recorder is record_exchange_fail_open
549
+ else {}
550
+ ),
551
+ )
552
+ except Exception as exc:
553
+ print(f"ExecWeave HTTP proxy recorder warning: {exc}", file=sys.stderr)
554
+
555
+
556
+ def create_proxy_server(
557
+ *,
558
+ listen_host: str,
559
+ listen_port: int,
560
+ config: ProxyConfig,
561
+ recorder: Callable[..., None] = record_exchange_fail_open,
562
+ ) -> ExecWeaveHTTPProxyServer:
563
+ if not 0 <= listen_port <= 65535:
564
+ raise ValueError("proxy listen port must be between 0 and 65535")
565
+ return ExecWeaveHTTPProxyServer((listen_host, listen_port), config, recorder)