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,476 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import time
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from .private_io import append_private_text
11
+ from urllib.parse import urlsplit, urlunsplit
12
+
13
+
14
+ def _now() -> str:
15
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
16
+
17
+
18
+ def sanitize_gateway_endpoint(endpoint: str) -> str:
19
+ split = urlsplit(endpoint)
20
+ if split.scheme not in {"http", "https"} or not split.hostname:
21
+ raise ValueError("inference gateway endpoint must be an http(s) URL")
22
+ host = split.hostname
23
+ if ":" in host and not host.startswith("["):
24
+ host = f"[{host}]"
25
+ if split.port is not None:
26
+ host = f"{host}:{split.port}"
27
+ path = split.path.rstrip("/")
28
+ return urlunsplit((split.scheme, host, path, "", ""))
29
+
30
+
31
+ def _gateway_endpoint_scope(endpoint: str) -> tuple[str, str]:
32
+ safe_endpoint = sanitize_gateway_endpoint(endpoint)
33
+ digest = hashlib.sha256(safe_endpoint.encode("utf-8")).hexdigest()[:24]
34
+ return safe_endpoint, digest
35
+
36
+
37
+ def _entity(
38
+ entity_type: str,
39
+ entity_id: str,
40
+ *,
41
+ name: str | None = None,
42
+ attributes: dict[str, Any] | None = None,
43
+ ) -> dict[str, Any]:
44
+ return {"type": entity_type, "id": entity_id, "name": name, "attributes": attributes or {}}
45
+
46
+
47
+ def _gateway_entity(gateway: str, endpoint: str) -> dict[str, Any]:
48
+ safe_endpoint, digest = _gateway_endpoint_scope(endpoint)
49
+ return _entity(
50
+ "inference_gateway",
51
+ f"inference-gateway:{gateway}:{digest}",
52
+ name=gateway,
53
+ attributes={"gateway": gateway, "endpoint": safe_endpoint, "endpoint_scope": digest},
54
+ )
55
+
56
+
57
+ def _model_entity(gateway: str, endpoint: str, model: str) -> dict[str, Any]:
58
+ _, endpoint_scope = _gateway_endpoint_scope(endpoint)
59
+ return _entity(
60
+ "model",
61
+ f"model:gateway:{gateway}:{endpoint_scope}:{model}",
62
+ name=model,
63
+ attributes={
64
+ "catalog_id": model,
65
+ "gateway": gateway,
66
+ "endpoint_scope": endpoint_scope,
67
+ "identity_scope": "gateway_endpoint",
68
+ },
69
+ )
70
+
71
+
72
+ def _provider_entity(provider: str) -> dict[str, Any]:
73
+ slug = hashlib.sha256(provider.encode("utf-8", errors="replace")).hexdigest()[:24]
74
+ return _entity(
75
+ "inference_provider",
76
+ f"inference-provider:{slug}",
77
+ name=provider,
78
+ attributes={"provider_name": provider},
79
+ )
80
+
81
+
82
+ def _deployment_entity(gateway: str, endpoint: str, deployment: str) -> dict[str, Any]:
83
+ _, endpoint_scope = _gateway_endpoint_scope(endpoint)
84
+ slug = hashlib.sha256(deployment.encode("utf-8", errors="replace")).hexdigest()[:24]
85
+ return _entity(
86
+ "inference_deployment",
87
+ f"inference-deployment:{gateway}:{endpoint_scope}:{slug}",
88
+ name=deployment,
89
+ attributes={
90
+ "gateway": gateway,
91
+ "endpoint_scope": endpoint_scope,
92
+ "deployment_id": deployment,
93
+ },
94
+ )
95
+
96
+
97
+ def _event(
98
+ *,
99
+ timestamp: str,
100
+ event_type: str,
101
+ relation: str,
102
+ source: dict[str, Any],
103
+ target: dict[str, Any],
104
+ gateway: str,
105
+ attributes: dict[str, Any] | None = None,
106
+ ) -> dict[str, Any]:
107
+ merged = {
108
+ "backend": "inference_gateway",
109
+ "attribution": "gateway_api",
110
+ "evidence_source": "gateway_response",
111
+ "gateway": gateway,
112
+ "causal": False,
113
+ }
114
+ if attributes:
115
+ merged.update(attributes)
116
+ return {
117
+ "timestamp": timestamp,
118
+ "event_type": event_type,
119
+ "relation": relation,
120
+ "source": source,
121
+ "target": target,
122
+ "attributes": merged,
123
+ }
124
+
125
+
126
+ def _request_identity(
127
+ payload: dict[str, Any],
128
+ explicit: str | None,
129
+ *,
130
+ gateway: str,
131
+ endpoint_scope: str,
132
+ observed_at: str,
133
+ ) -> tuple[str, str]:
134
+ if explicit:
135
+ return explicit, "provided"
136
+ native = payload.get("id")
137
+ if isinstance(native, str) and native:
138
+ return native, "provider_native"
139
+ seed = {
140
+ "model": payload.get("model"),
141
+ "created": payload.get("created"),
142
+ "usage": payload.get("usage"),
143
+ }
144
+ raw = json.dumps(seed, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
145
+ occurrence = "\0".join((gateway, endpoint_scope, observed_at, raw))
146
+ digest = hashlib.sha256(occurrence.encode("utf-8", errors="replace")).hexdigest()[:32]
147
+ return digest, "execweave_observation"
148
+
149
+
150
+ def _request_entity(
151
+ gateway: str,
152
+ endpoint: str,
153
+ request_native_id: str,
154
+ *,
155
+ attributes: dict[str, Any],
156
+ ) -> dict[str, Any]:
157
+ _, endpoint_scope = _gateway_endpoint_scope(endpoint)
158
+ return _entity(
159
+ "inference_request",
160
+ f"inference-request:{gateway}:{endpoint_scope}:{request_native_id}",
161
+ name=request_native_id,
162
+ attributes={"gateway": gateway, "endpoint_scope": endpoint_scope, **attributes},
163
+ )
164
+
165
+
166
+ def _copy_int(mapping: dict[str, Any], source: str, target: str, attrs: dict[str, Any]) -> None:
167
+ value = mapping.get(source)
168
+ if isinstance(value, int) and not isinstance(value, bool) and target not in attrs:
169
+ attrs[target] = value
170
+
171
+
172
+ def _usage_attributes(payload: dict[str, Any]) -> dict[str, Any]:
173
+ attrs: dict[str, Any] = {"protocol": "openai_compatible"}
174
+ usage = payload.get("usage")
175
+ if not isinstance(usage, dict):
176
+ return attrs
177
+ for source, target in (
178
+ ("prompt_tokens", "prompt_tokens"),
179
+ ("input_tokens", "prompt_tokens"),
180
+ ("completion_tokens", "completion_tokens"),
181
+ ("output_tokens", "completion_tokens"),
182
+ ("total_tokens", "total_tokens"),
183
+ ):
184
+ _copy_int(usage, source, target, attrs)
185
+ cost = usage.get("cost")
186
+ if isinstance(cost, (int, float)) and not isinstance(cost, bool):
187
+ attrs["cost_usd"] = float(cost)
188
+ for detail_key in ("prompt_tokens_details", "input_tokens_details"):
189
+ details = usage.get(detail_key)
190
+ if not isinstance(details, dict):
191
+ continue
192
+ for source, target in (
193
+ ("cached_tokens", "cached_prompt_tokens"),
194
+ ("cache_write_tokens", "cache_write_tokens"),
195
+ ):
196
+ _copy_int(details, source, target, attrs)
197
+ for detail_key in ("completion_tokens_details", "output_tokens_details"):
198
+ details = usage.get(detail_key)
199
+ if isinstance(details, dict):
200
+ _copy_int(details, "reasoning_tokens", "reasoning_tokens", attrs)
201
+ for source, target in (
202
+ ("cache_creation_input_tokens", "cache_write_tokens"),
203
+ ("cache_read_input_tokens", "cached_prompt_tokens"),
204
+ ):
205
+ _copy_int(usage, source, target, attrs)
206
+ return attrs
207
+
208
+
209
+ def gateway_response_to_events(
210
+ payload: dict[str, Any],
211
+ *,
212
+ gateway_name: str,
213
+ endpoint: str,
214
+ requested_model: str | None = None,
215
+ resolved_model: str | None = None,
216
+ provider_name: str | None = None,
217
+ deployment_id: str | None = None,
218
+ request_id: str | None = None,
219
+ timestamp: str | None = None,
220
+ ) -> list[dict[str, Any]]:
221
+ observed_at = timestamp or _now()
222
+ gateway = _gateway_entity(gateway_name, endpoint)
223
+ _, endpoint_scope = _gateway_endpoint_scope(endpoint)
224
+ native_id, request_id_source = _request_identity(
225
+ payload,
226
+ request_id,
227
+ gateway=gateway_name,
228
+ endpoint_scope=endpoint_scope,
229
+ observed_at=observed_at,
230
+ )
231
+ response_model = payload.get("model")
232
+ resolved = resolved_model
233
+ if not isinstance(resolved, str) or not resolved:
234
+ resolved = response_model if isinstance(response_model, str) and response_model else None
235
+
236
+ attrs = _usage_attributes(payload)
237
+ attrs["endpoint_scope"] = endpoint_scope
238
+ attrs["request_id_source"] = request_id_source
239
+ if isinstance(requested_model, str) and requested_model:
240
+ attrs["requested_model"] = requested_model
241
+ if isinstance(resolved, str) and resolved:
242
+ attrs["resolved_model"] = resolved
243
+ if isinstance(provider_name, str) and provider_name:
244
+ attrs["provider_name"] = provider_name
245
+ if isinstance(deployment_id, str) and deployment_id:
246
+ attrs["deployment_id"] = deployment_id
247
+
248
+ request = _request_entity(
249
+ gateway_name,
250
+ endpoint,
251
+ native_id,
252
+ attributes=attrs,
253
+ )
254
+ events = [
255
+ _event(
256
+ timestamp=observed_at,
257
+ event_type=f"inference_gateway.{gateway_name}.response.observed",
258
+ relation="SERVED_INFERENCE",
259
+ source=gateway,
260
+ target=request,
261
+ gateway=gateway_name,
262
+ attributes=attrs,
263
+ )
264
+ ]
265
+ if isinstance(requested_model, str) and requested_model:
266
+ events.append(
267
+ _event(
268
+ timestamp=observed_at,
269
+ event_type=f"inference_gateway.{gateway_name}.model.requested",
270
+ relation="REQUESTED_MODEL",
271
+ source=request,
272
+ target=_model_entity(gateway_name, endpoint, requested_model),
273
+ gateway=gateway_name,
274
+ attributes=attrs,
275
+ )
276
+ )
277
+ if isinstance(resolved, str) and resolved:
278
+ events.append(
279
+ _event(
280
+ timestamp=observed_at,
281
+ event_type=f"inference_gateway.{gateway_name}.model.resolved",
282
+ relation="ROUTED_TO_MODEL",
283
+ source=request,
284
+ target=_model_entity(gateway_name, endpoint, resolved),
285
+ gateway=gateway_name,
286
+ attributes=attrs,
287
+ )
288
+ )
289
+ if isinstance(provider_name, str) and provider_name:
290
+ events.append(
291
+ _event(
292
+ timestamp=observed_at,
293
+ event_type=f"inference_gateway.{gateway_name}.provider.resolved",
294
+ relation="ROUTED_TO_PROVIDER",
295
+ source=request,
296
+ target=_provider_entity(provider_name),
297
+ gateway=gateway_name,
298
+ attributes=attrs,
299
+ )
300
+ )
301
+ if isinstance(deployment_id, str) and deployment_id:
302
+ events.append(
303
+ _event(
304
+ timestamp=observed_at,
305
+ event_type=f"inference_gateway.{gateway_name}.deployment.resolved",
306
+ relation="ROUTED_TO_DEPLOYMENT",
307
+ source=request,
308
+ target=_deployment_entity(gateway_name, endpoint, deployment_id),
309
+ gateway=gateway_name,
310
+ attributes=attrs,
311
+ )
312
+ )
313
+ return events
314
+
315
+
316
+ def openrouter_response_to_events(
317
+ payload: dict[str, Any],
318
+ *,
319
+ requested_model: str | None = None,
320
+ resolved_model: str | None = None,
321
+ provider_name: str | None = None,
322
+ deployment_id: str | None = None,
323
+ endpoint: str = "https://openrouter.ai/api/v1",
324
+ request_id: str | None = None,
325
+ timestamp: str | None = None,
326
+ ) -> list[dict[str, Any]]:
327
+ return gateway_response_to_events(
328
+ payload,
329
+ gateway_name="openrouter",
330
+ endpoint=endpoint,
331
+ requested_model=requested_model,
332
+ resolved_model=resolved_model,
333
+ provider_name=provider_name,
334
+ deployment_id=deployment_id,
335
+ request_id=request_id,
336
+ timestamp=timestamp,
337
+ )
338
+
339
+
340
+ def litellm_response_to_events(
341
+ payload: dict[str, Any],
342
+ *,
343
+ requested_model: str | None = None,
344
+ resolved_model: str | None = None,
345
+ provider_name: str | None = None,
346
+ deployment_id: str | None = None,
347
+ endpoint: str = "http://localhost:4000",
348
+ request_id: str | None = None,
349
+ timestamp: str | None = None,
350
+ ) -> list[dict[str, Any]]:
351
+ return gateway_response_to_events(
352
+ payload,
353
+ gateway_name="litellm",
354
+ endpoint=endpoint,
355
+ requested_model=requested_model,
356
+ resolved_model=resolved_model,
357
+ provider_name=provider_name,
358
+ deployment_id=deployment_id,
359
+ request_id=request_id,
360
+ timestamp=timestamp,
361
+ )
362
+
363
+
364
+ def openrouter_generation_to_events(
365
+ payload: dict[str, Any],
366
+ *,
367
+ endpoint: str = "https://openrouter.ai/api/v1",
368
+ timestamp: str | None = None,
369
+ ) -> list[dict[str, Any]]:
370
+ data = payload.get("data") if isinstance(payload.get("data"), dict) else payload
371
+ if not isinstance(data, dict):
372
+ raise ValueError("OpenRouter generation payload must be a JSON object")
373
+ generation_id = data.get("id")
374
+ if not isinstance(generation_id, str) or not generation_id:
375
+ raise ValueError("OpenRouter generation metadata requires id")
376
+ observed_at = timestamp or _now()
377
+ gateway = _gateway_entity("openrouter", endpoint)
378
+ _, endpoint_scope = _gateway_endpoint_scope(endpoint)
379
+
380
+ attrs: dict[str, Any] = {
381
+ "protocol": "openrouter_generation",
382
+ "endpoint_scope": endpoint_scope,
383
+ "request_id_source": "provider_native",
384
+ }
385
+ for key in (
386
+ "latency",
387
+ "generation_time",
388
+ "total_cost",
389
+ "tokens_prompt",
390
+ "tokens_completion",
391
+ "native_tokens_prompt",
392
+ "native_tokens_completion",
393
+ ):
394
+ value = data.get(key)
395
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
396
+ attrs[key] = value
397
+ for key in ("streamed", "cancelled"):
398
+ value = data.get(key)
399
+ if isinstance(value, bool):
400
+ attrs[key] = value
401
+
402
+ request = _request_entity(
403
+ "openrouter",
404
+ endpoint,
405
+ generation_id,
406
+ attributes=attrs,
407
+ )
408
+ events = [
409
+ _event(
410
+ timestamp=observed_at,
411
+ event_type="inference_gateway.openrouter.generation.observed",
412
+ relation="REPORTED_GENERATION_METADATA",
413
+ source=gateway,
414
+ target=request,
415
+ gateway="openrouter",
416
+ attributes=attrs,
417
+ )
418
+ ]
419
+
420
+ model = data.get("model") or data.get("model_name")
421
+ if isinstance(model, str) and model:
422
+ events.append(
423
+ _event(
424
+ timestamp=observed_at,
425
+ event_type="inference_gateway.openrouter.model.resolved",
426
+ relation="ROUTED_TO_MODEL",
427
+ source=request,
428
+ target=_model_entity("openrouter", endpoint, model),
429
+ gateway="openrouter",
430
+ attributes=attrs,
431
+ )
432
+ )
433
+ provider = data.get("provider_name") or data.get("provider")
434
+ if isinstance(provider, str) and provider:
435
+ events.append(
436
+ _event(
437
+ timestamp=observed_at,
438
+ event_type="inference_gateway.openrouter.provider.resolved",
439
+ relation="ROUTED_TO_PROVIDER",
440
+ source=request,
441
+ target=_provider_entity(provider),
442
+ gateway="openrouter",
443
+ attributes=attrs,
444
+ )
445
+ )
446
+ return events
447
+
448
+
449
+ def append_gateway_records(path: str | Path, records: list[dict[str, Any]]) -> Path:
450
+ raw_output = Path(path).expanduser()
451
+ output = raw_output.parent.resolve() / raw_output.name
452
+ output.parent.mkdir(parents=True, exist_ok=True)
453
+ if not records:
454
+ return output
455
+ blob = "".join(
456
+ json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n"
457
+ for record in records
458
+ )
459
+ lock_dir = output.with_name(output.name + ".lock")
460
+ deadline = time.monotonic() + 5.0
461
+ while True:
462
+ try:
463
+ lock_dir.mkdir()
464
+ break
465
+ except FileExistsError:
466
+ if time.monotonic() >= deadline:
467
+ raise TimeoutError(f"timed out waiting for inference gateway sidecar lock: {lock_dir}")
468
+ time.sleep(0.01)
469
+ try:
470
+ append_private_text(output, blob)
471
+ finally:
472
+ try:
473
+ lock_dir.rmdir()
474
+ except OSError:
475
+ pass
476
+ return output
@@ -0,0 +1,211 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import sys
7
+ from datetime import datetime, timezone
8
+ from pathlib import Path
9
+
10
+ from .content_store import FullFidelityContentStore
11
+ from .privacy import full_content_capture_enabled
12
+ from .inference_gateway import (
13
+ append_gateway_records,
14
+ litellm_response_to_events,
15
+ openrouter_generation_to_events,
16
+ openrouter_response_to_events,
17
+ sanitize_gateway_endpoint,
18
+ )
19
+ from .inference_gateway_full_fidelity import (
20
+ openrouter_exchange_to_content_events,
21
+ openrouter_response_to_content_events,
22
+ )
23
+
24
+ _GATEWAYS = ("openrouter", "litellm")
25
+
26
+
27
+ def _now() -> str:
28
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
29
+
30
+
31
+ def _sidecar(value: Path | None) -> Path:
32
+ if value is not None:
33
+ return value
34
+ configured = os.environ.get("EXECWEAVE_SEMANTIC_SIDECAR")
35
+ if configured:
36
+ return Path(configured)
37
+ raise ValueError("--sidecar or EXECWEAVE_SEMANTIC_SIDECAR is required")
38
+
39
+
40
+ def _read_json_stdin() -> dict:
41
+ raw = sys.stdin.read()
42
+ if not raw.strip():
43
+ raise ValueError("stdin is empty")
44
+ try:
45
+ payload = json.loads(raw)
46
+ except json.JSONDecodeError as exc:
47
+ raise ValueError(f"stdin is invalid JSON: {exc.msg}") from exc
48
+ if not isinstance(payload, dict):
49
+ raise ValueError("stdin must contain one JSON object")
50
+ return payload
51
+
52
+
53
+ def _default_endpoint(gateway: str) -> str:
54
+ return {
55
+ "openrouter": "https://openrouter.ai/api/v1",
56
+ "litellm": "http://localhost:4000",
57
+ }[gateway]
58
+
59
+
60
+ def build_parser() -> argparse.ArgumentParser:
61
+ parser = argparse.ArgumentParser(
62
+ prog="execweave-inference-gateway",
63
+ description=(
64
+ "Capture inference gateway semantic metadata plus complete content exposed by the "
65
+ "selected integration point."
66
+ ),
67
+ )
68
+ sub = parser.add_subparsers(dest="command", required=True)
69
+
70
+ event = sub.add_parser(
71
+ "event",
72
+ help="Capture one final gateway response; this is response-only evidence.",
73
+ )
74
+ event.add_argument("--gateway", choices=_GATEWAYS, required=True)
75
+ event.add_argument("--endpoint", default=None)
76
+ event.add_argument("--requested-model", default=None)
77
+ event.add_argument("--resolved-model", default=None)
78
+ event.add_argument("--provider-name", default=None)
79
+ event.add_argument("--deployment-id", default=None)
80
+ event.add_argument("--request-id", default=None)
81
+ event.add_argument("--sidecar", type=Path, default=None)
82
+
83
+ exchange = sub.add_parser(
84
+ "exchange",
85
+ help=(
86
+ "Capture caller-supplied OpenRouter request+response JSON; this is not wire "
87
+ "interception."
88
+ ),
89
+ )
90
+ exchange.add_argument("--gateway", choices=["openrouter"], required=True)
91
+ exchange.add_argument("--endpoint", default=None)
92
+ exchange.add_argument("--provider-name", default=None)
93
+ exchange.add_argument("--deployment-id", default=None)
94
+ exchange.add_argument("--request-id", default=None)
95
+ exchange.add_argument("--sidecar", type=Path, default=None)
96
+
97
+ generation = sub.add_parser(
98
+ "generation",
99
+ help="Convert OpenRouter generation metadata into routing/performance events.",
100
+ )
101
+ generation.add_argument("--gateway", choices=["openrouter"], required=True)
102
+ generation.add_argument("--endpoint", default=None)
103
+ generation.add_argument("--sidecar", type=Path, default=None)
104
+ return parser
105
+
106
+
107
+ def _append_full_fidelity_fail_open(sidecar: Path, records_factory) -> int:
108
+ if not full_content_capture_enabled():
109
+ return 0
110
+ try:
111
+ records = records_factory(FullFidelityContentStore(sidecar.parent))
112
+ append_gateway_records(sidecar, records)
113
+ return len(records)
114
+ except (OSError, RuntimeError, TimeoutError, TypeError, ValueError) as exc:
115
+ print(f"ExecWeave inference gateway full-fidelity warning: {exc}", file=sys.stderr)
116
+ return 0
117
+
118
+
119
+ def main(argv: list[str] | None = None) -> int:
120
+ parser = build_parser()
121
+ args = parser.parse_args(argv)
122
+ try:
123
+ payload = _read_json_stdin()
124
+ endpoint = sanitize_gateway_endpoint(args.endpoint or _default_endpoint(args.gateway))
125
+ sidecar = _sidecar(args.sidecar).expanduser().resolve()
126
+ observed_at = _now()
127
+ if args.command == "event":
128
+ converters = {
129
+ "openrouter": openrouter_response_to_events,
130
+ "litellm": litellm_response_to_events,
131
+ }
132
+ records = converters[args.gateway](
133
+ payload,
134
+ requested_model=args.requested_model,
135
+ resolved_model=args.resolved_model,
136
+ provider_name=args.provider_name,
137
+ deployment_id=args.deployment_id,
138
+ endpoint=endpoint,
139
+ request_id=args.request_id,
140
+ timestamp=observed_at,
141
+ )
142
+ output = append_gateway_records(sidecar, records)
143
+ full_records = 0
144
+ if args.gateway == "openrouter":
145
+ full_records = _append_full_fidelity_fail_open(
146
+ sidecar,
147
+ lambda store: openrouter_response_to_content_events(
148
+ payload,
149
+ store=store,
150
+ endpoint=endpoint,
151
+ request_id=args.request_id,
152
+ timestamp=observed_at,
153
+ provider_name=args.provider_name,
154
+ deployment_id=args.deployment_id,
155
+ ),
156
+ )
157
+ elif args.command == "exchange":
158
+ request_payload = payload.get("request")
159
+ response_payload = payload.get("response")
160
+ if not isinstance(request_payload, dict) or not isinstance(response_payload, dict):
161
+ raise ValueError("exchange stdin requires JSON-object request and response fields")
162
+ requested_model = request_payload.get("model")
163
+ if not isinstance(requested_model, str) or not requested_model:
164
+ requested_model = None
165
+ records = openrouter_response_to_events(
166
+ response_payload,
167
+ requested_model=requested_model,
168
+ provider_name=args.provider_name,
169
+ deployment_id=args.deployment_id,
170
+ endpoint=endpoint,
171
+ request_id=args.request_id,
172
+ timestamp=observed_at,
173
+ )
174
+ output = append_gateway_records(sidecar, records)
175
+ full_records = _append_full_fidelity_fail_open(
176
+ sidecar,
177
+ lambda store: openrouter_exchange_to_content_events(
178
+ payload,
179
+ store=store,
180
+ endpoint=endpoint,
181
+ request_id=args.request_id,
182
+ timestamp=observed_at,
183
+ provider_name=args.provider_name,
184
+ deployment_id=args.deployment_id,
185
+ ),
186
+ )
187
+ else:
188
+ records = openrouter_generation_to_events(
189
+ payload,
190
+ endpoint=endpoint,
191
+ timestamp=observed_at,
192
+ )
193
+ output = append_gateway_records(sidecar, records)
194
+ full_records = 0
195
+ except (OSError, TimeoutError, ValueError) as exc:
196
+ parser.error(str(exc))
197
+ print(
198
+ json.dumps(
199
+ {
200
+ "full_fidelity_records": full_records,
201
+ "records": len(records),
202
+ "sidecar": str(output),
203
+ },
204
+ sort_keys=True,
205
+ )
206
+ )
207
+ return 0
208
+
209
+
210
+ if __name__ == "__main__":
211
+ raise SystemExit(main())