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,453 @@
1
+ """Opt-in native OpenAI Agents SDK trace bridge.
2
+
3
+ Consumes SDK tracing callbacks, not HTTP traffic or inferred OS effects.
4
+ The module remains importable without the optional openai-agents package.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import os
10
+ import threading
11
+ from collections import Counter
12
+ from typing import Any
13
+
14
+ from .framework_adapters.base import (
15
+ AdapterContext, AgentRecord, ContentCapturePolicy, MessageRecord,
16
+ TaskRecord,
17
+ ModelCallRecord, ToolCallRecord,
18
+ )
19
+
20
+ try:
21
+ from agents.tracing import TracingProcessor
22
+ except ImportError: # Optional dependency: pip install execweave[agents]
23
+ TracingProcessor = object
24
+
25
+ _BLOCKED = frozenset({
26
+ "authorization", "api_key", "apikey", "password", "token",
27
+ "access_token", "refresh_token", "client_secret", "cookie",
28
+ "reasoning", "chain_of_thought", "hidden_reasoning", "private_reasoning",
29
+ })
30
+
31
+
32
+ def _safe(value: Any, depth: int = 0) -> Any:
33
+ """Serialize explicitly exposed content with bounded depth/size.
34
+
35
+ Keys suggesting credentials or hidden reasoning are never retained.
36
+ Arbitrary object repr() and exception messages are never stored.
37
+ """
38
+ if depth > 6:
39
+ return "[depth limit]"
40
+ if value is None or type(value) in (bool, int, float):
41
+ return value
42
+ if isinstance(value, str):
43
+ return value[:32768]
44
+ if isinstance(value, (tuple, list)):
45
+ return [_safe(item, depth + 1) for item in value[:100]]
46
+ if isinstance(value, dict):
47
+ if value.get("type") in {"reasoning", "chain_of_thought", "hidden_reasoning"}:
48
+ return "[reasoning omitted]"
49
+ return {
50
+ str(k)[:128]: _safe(v, depth + 1)
51
+ for k, v in list(value.items())[:100]
52
+ if str(k).lower().replace("-", "_") not in _BLOCKED
53
+ }
54
+ if hasattr(value, "model_dump"):
55
+ try:
56
+ return _safe(value.model_dump(mode="json"), depth + 1)
57
+ except (AttributeError, TypeError, ValueError):
58
+ return "[unserializable SDK value]"
59
+ return "[unsupported content type]"
60
+
61
+
62
+ def _name(value: Any, default: str) -> str:
63
+ return value[:160] if isinstance(value, str) and value.strip() else default
64
+
65
+
66
+ class AgentsSDKTraceProcessor(TracingProcessor):
67
+ """Synchronous SDK processor producing run-bound canonical evidence.
68
+
69
+ No recorder is enabled unless ExecWeave supplied both session and sidecar.
70
+ A function-tool result is framework-reported and *not* proof of an OS effect.
71
+ """
72
+
73
+ def __init__(self, *, capture_mode: str = "prompt_and_response") -> None:
74
+ import os
75
+
76
+ ContentCapturePolicy(capture_mode)
77
+ self.enabled = bool(
78
+ os.environ.get("EXECWEAVE_SESSION_ID")
79
+ and os.environ.get("EXECWEAVE_SEMANTIC_SIDECAR")
80
+ )
81
+ self.context = (
82
+ AdapterContext.from_environment("openai-agents-sdk", capture_mode=capture_mode)
83
+ if self.enabled else None
84
+ )
85
+ self.capture_mode = capture_mode
86
+ self.callback_errors = 0
87
+ self._lock = threading.RLock()
88
+ self._runs: dict[str, dict[str, Any]] = {}
89
+
90
+ def _state(self, trace_id: str) -> dict[str, Any]:
91
+ return self._runs.setdefault(trace_id, {
92
+ "owners": {}, "parents": {}, "models": {}, "model_input_at_start": {},
93
+ "tasks": {}, "seen": set(),
94
+ "started": set(), "ended": set(), "counts": Counter(),
95
+ "unattributed": 0,
96
+ })
97
+
98
+ @staticmethod
99
+ def _owner_from_ancestors(state: dict[str, Any], parent_id: str | None):
100
+ """Find the nearest SDK-observed agent through intermediate task/turn spans.
101
+
102
+ An unobserved parent stays unattributed; names in turn metadata are not
103
+ silently promoted into authoritative agent identities.
104
+ """
105
+ cursor = parent_id
106
+ seen: set[str] = set()
107
+ while cursor is not None and cursor not in seen:
108
+ seen.add(cursor)
109
+ owner = state["owners"].get(cursor)
110
+ if owner is not None:
111
+ return owner
112
+ cursor = state["parents"].get(cursor)
113
+ return None
114
+
115
+ def _agent(self, trace_id: str, agent_name: str):
116
+ assert self.context is not None
117
+ return self.context.entity(
118
+ "agent", f"{trace_id}:{agent_name}", name=agent_name,
119
+ attributes={
120
+ "conversation_scope": "framework_agent",
121
+ "conversation_agent_path": f"/openai-agents-sdk/{agent_name}",
122
+ "provider": "openai-agents-sdk",
123
+ },
124
+ )
125
+
126
+ def _identity(self, span: Any) -> dict[str, Any]:
127
+ """Stable evidence pointer, without user-controlled payloads."""
128
+ return {
129
+ "sdk_trace_id": str(span.trace_id),
130
+ "sdk_span_id": str(span.span_id),
131
+ "sdk_parent_span_id": str(span.parent_id) if span.parent_id else None,
132
+ "evidence_source": "agents_sdk_tracing_callback",
133
+ "process_effect_verified": False,
134
+ }
135
+
136
+ def on_trace_start(self, trace: Any) -> None:
137
+ self._guard(self._trace_start, trace)
138
+
139
+ def _trace_start(self, trace: Any) -> None:
140
+ if not self.enabled:
141
+ return
142
+ assert self.context is not None
143
+ with self._lock:
144
+ trace_id = str(trace.trace_id)
145
+ self._state(trace_id)
146
+ task = self.context.entity("task", f"trace:{trace_id}", name="SDK trace")
147
+ group_id = getattr(trace, "group_id", None)
148
+ attrs = {
149
+ "sdk_trace_id": trace_id,
150
+ "evidence_source": "agents_sdk_tracing_callback",
151
+ "task_category": "sdk_trace",
152
+ "span_completion_is_not_task_success": True,
153
+ }
154
+ if isinstance(group_id, str) and group_id:
155
+ attrs["sdk_group_sha256"] = hashlib.sha256(
156
+ group_id.encode("utf-8")
157
+ ).hexdigest()
158
+ self.context.record_task(TaskRecord(task, attributes=attrs))
159
+
160
+ def on_trace_end(self, trace: Any) -> None:
161
+ self._guard(self._trace_end, trace)
162
+
163
+ def _trace_end(self, trace: Any) -> None:
164
+ if not self.enabled:
165
+ return
166
+ assert self.context is not None
167
+ with self._lock:
168
+ trace_id = str(trace.trace_id)
169
+ state = self._runs.pop(trace_id, None)
170
+ if state is None:
171
+ return
172
+ task = self.context.entity("task", f"trace:{trace_id}", name="SDK trace")
173
+ self.context.emit(
174
+ "TASK_UPDATED", "OBSERVATION_COVERAGE", source=task,
175
+ attributes={
176
+ "sdk_trace_id": trace_id,
177
+ "span_counts": dict(state["counts"]),
178
+ "unattributed_spans": state["unattributed"],
179
+ "unclosed_spans": len(state["started"] - state["ended"]),
180
+ "callback_errors": self.callback_errors,
181
+ "coverage_scope": "sdk_callbacks_only",
182
+ "runtime_effects_verified": False,
183
+ },
184
+ )
185
+
186
+ def on_span_start(self, span: Any) -> None:
187
+ self._guard(self._span_start, span)
188
+
189
+ def _span_start(self, span: Any) -> None:
190
+ if not self.enabled:
191
+ return
192
+ assert self.context is not None
193
+ with self._lock:
194
+ trace_id = str(span.trace_id)
195
+ span_id = str(span.span_id)
196
+ state = self._state(trace_id)
197
+ if span_id in state["started"]:
198
+ return
199
+ state["started"].add(span_id)
200
+ parent_id = str(span.parent_id) if span.parent_id else None
201
+ state["parents"][span_id] = parent_id
202
+ data = span.span_data
203
+ kind = getattr(data, "type", "unknown")
204
+ state["counts"][str(kind)] += 1
205
+ owner = self._owner_from_ancestors(state, parent_id)
206
+ if kind == "agent":
207
+ name = _name(getattr(data, "name", None), "unnamed-agent")
208
+ owner = self._agent(trace_id, name)
209
+ if owner.id not in state["seen"]:
210
+ self.context.record_agent(AgentRecord(
211
+ owner, role=name,
212
+ attributes={"sdk_trace_id": trace_id, "source": "sdk_agent_span"},
213
+ ))
214
+ state["seen"].add(owner.id)
215
+ self.context.emit(
216
+ "AGENT_STARTED", "AGENT_STARTED", source=owner,
217
+ attributes=self._identity(span),
218
+ )
219
+ # Tools listed on an AgentSpan are *available*, not executed.
220
+ available = getattr(data, "tools", None)
221
+ if isinstance(available, list):
222
+ self.context.emit(
223
+ "TASK_UPDATED", "AVAILABLE_TOOLS", source=owner,
224
+ attributes={
225
+ **self._identity(span),
226
+ "tool_names": [_name(x, "unknown") for x in available[:100]],
227
+ "tool_list_truncated": len(available) > 100,
228
+ "selection_not_inferred": True,
229
+ },
230
+ )
231
+ state["owners"][span_id] = owner
232
+ if kind == "task":
233
+ task = self.context.entity("task", f"{trace_id}:{span_id}", name="SDK Runner task")
234
+ parent_task = self.context.entity(
235
+ "task", f"trace:{trace_id}", name="SDK trace"
236
+ )
237
+ self.context.record_task(TaskRecord(
238
+ task, owner=owner, parent_task=parent_task,
239
+ attributes={
240
+ **self._identity(span),
241
+ "task_category": "sdk_runner_invocation",
242
+ "span_completion_is_not_task_success": True,
243
+ },
244
+ ))
245
+ self.context.emit("TASK_STARTED", "SDK_TASK_STARTED",
246
+ source=owner or task, target=task,
247
+ attributes=self._identity(span))
248
+ state["tasks"][span_id] = task
249
+ elif kind == "turn":
250
+ self.context.emit(
251
+ "TASK_UPDATED", "SDK_TURN_STARTED", source=owner,
252
+ attributes={
253
+ **self._identity(span),
254
+ "sdk_turn_number": getattr(data, "turn", None),
255
+ "sdk_turn_agent_name": _name(
256
+ getattr(data, "agent_name", None), "unknown"
257
+ ),
258
+ "turn_completion_is_not_task_success": True,
259
+ },
260
+ )
261
+ if kind not in ("agent",) and owner is None:
262
+ state["unattributed"] += 1
263
+ if kind in ("generation", "response"):
264
+ response_object = getattr(data, "response", None)
265
+ model_name = _name(
266
+ getattr(data, "model", None)
267
+ or getattr(response_object, "model", None),
268
+ "unknown",
269
+ )
270
+ state["models"][span_id] = model_name
271
+ observed_input = getattr(data, "input", None)
272
+ state["model_input_at_start"][span_id] = observed_input is not None
273
+ model = self.context.entity("model", model_name, name=model_name)
274
+ call = self.context.entity("model_call", f"{trace_id}:{span_id}")
275
+ self.context.record_model_call(ModelCallRecord(
276
+ call, owner, model,
277
+ request=_safe(observed_input)
278
+ if self.capture_mode != "metadata_only" else None,
279
+ attributes={
280
+ **self._identity(span),
281
+ "input_observed_at_start": observed_input is not None,
282
+ },
283
+ ))
284
+ elif kind == "function":
285
+ name = _name(getattr(data, "name", None), "unknown-tool")
286
+ tool = self.context.entity("tool", name, name=name)
287
+ call = self.context.entity("tool_call", f"{trace_id}:{span_id}")
288
+ self.context.record_tool_call(ToolCallRecord(
289
+ call, owner, tool,
290
+ arguments=_safe(getattr(data, "input", None))
291
+ if self.capture_mode != "metadata_only" else None,
292
+ attributes={**self._identity(span),
293
+ "effect_attestation": "not_provided",
294
+ "sdk_host_pid": os.getpid(),
295
+ "sdk_callback_tid": threading.get_native_id(),
296
+ "sdk_host_pid_source": "sdk_callback_self_report"},
297
+ ))
298
+
299
+ def on_span_end(self, span: Any) -> None:
300
+ self._guard(self._span_end, span)
301
+
302
+ def _span_end(self, span: Any) -> None:
303
+ if not self.enabled:
304
+ return
305
+ assert self.context is not None
306
+ with self._lock:
307
+ trace_id = str(span.trace_id)
308
+ span_id = str(span.span_id)
309
+ state = self._state(trace_id)
310
+ if span_id in state["ended"]:
311
+ return
312
+ if span_id not in state["started"]:
313
+ # No invented start event when a callback was missed.
314
+ state["counts"]["end_without_start"] += 1
315
+ return
316
+ state["ended"].add(span_id)
317
+ data = span.span_data
318
+ kind = getattr(data, "type", "unknown")
319
+ owner = state["owners"].get(span_id)
320
+ failed = getattr(span, "error", None) is not None
321
+ evidence = {**self._identity(span), "sdk_span_error": failed}
322
+ if kind == "agent":
323
+ self.context.emit(
324
+ "AGENT_STOPPED", "AGENT_STOPPED", source=owner,
325
+ attributes=evidence,
326
+ )
327
+ elif kind == "task":
328
+ task = state["tasks"].get(span_id)
329
+ if task is not None:
330
+ self.context.emit(
331
+ "TASK_UPDATED", "SDK_TASK_SPAN_ENDED",
332
+ source=owner or task, target=task,
333
+ attributes={**evidence, "task_success_verified": False},
334
+ )
335
+ elif kind == "turn":
336
+ self.context.emit(
337
+ "TASK_UPDATED", "SDK_TURN_ENDED", source=owner,
338
+ attributes={**evidence, "turn_success_verified": False},
339
+ )
340
+ elif kind in ("generation", "response"):
341
+ initial_model = state["models"].get(span_id, "unknown")
342
+ call = self.context.entity("model_call", f"{trace_id}:{span_id}")
343
+ observed_response = (
344
+ getattr(data, "response", None) if kind == "response"
345
+ else getattr(data, "output", None)
346
+ )
347
+ # The SDK can fill in the final model identity only when the
348
+ # span ends. Preserve the initial unknown instead of claiming
349
+ # that the model was known at request time.
350
+ resolved_model = _name(
351
+ getattr(data, "model", None)
352
+ or getattr(observed_response, "model", None),
353
+ initial_model,
354
+ )
355
+ model = self.context.entity("model", resolved_model, name=resolved_model)
356
+ # The official Responses SDK populates span_data.input
357
+ # *after* the model call. Keep the original request boundary
358
+ # intact and append content with its true observation stage.
359
+ late_input = getattr(data, "input", None)
360
+ if (
361
+ self.capture_mode != "metadata_only"
362
+ and late_input is not None
363
+ and not state["model_input_at_start"].get(span_id, False)
364
+ ):
365
+ self.context.record_model_call(ModelCallRecord(
366
+ call, owner, model, request=_safe(late_input),
367
+ attributes={
368
+ **evidence,
369
+ "content_observed_at": "sdk_span_end",
370
+ "late_request_content": True,
371
+ "request_timestamp_not_inferred": True,
372
+ },
373
+ ))
374
+ response = (
375
+ _safe(observed_response)
376
+ if self.capture_mode == "prompt_and_response" else None
377
+ )
378
+ self.context.record_model_call(ModelCallRecord(
379
+ call, owner, model, response=response,
380
+ status="failure" if failed else "response",
381
+ attributes={
382
+ **evidence,
383
+ "sdk_reported_model": resolved_model,
384
+ "sdk_initial_model": initial_model,
385
+ "model_identity_resolved_at_end": resolved_model != initial_model,
386
+ },
387
+ ))
388
+ elif kind == "function":
389
+ name = _name(getattr(data, "name", None), "unknown-tool")
390
+ tool = self.context.entity("tool", name, name=name)
391
+ call = self.context.entity("tool_call", f"{trace_id}:{span_id}")
392
+ response = (
393
+ _safe(getattr(data, "output", None))
394
+ if self.capture_mode == "prompt_and_response" else None
395
+ )
396
+ self.context.record_tool_call(ToolCallRecord(
397
+ call, owner, tool, result=response,
398
+ status="failure" if failed else "result",
399
+ attributes={**evidence, "effect_attestation": "not_provided",
400
+ "sdk_host_pid": os.getpid(),
401
+ "sdk_callback_tid": threading.get_native_id(),
402
+ "sdk_host_pid_source": "sdk_callback_self_report"},
403
+ ))
404
+ elif kind == "handoff" and not failed:
405
+ sender_name = getattr(data, "from_agent", None)
406
+ recipient_name = getattr(data, "to_agent", None)
407
+ if sender_name and recipient_name:
408
+ sender = self._agent(trace_id, sender_name)
409
+ recipient = self._agent(trace_id, recipient_name)
410
+ for agent in (sender, recipient):
411
+ if agent.id not in state["seen"]:
412
+ self.context.record_agent(AgentRecord(agent, role=agent.name))
413
+ state["seen"].add(agent.id)
414
+ message = self.context.entity("message", f"{trace_id}:{span_id}")
415
+ self.context.record_message(MessageRecord(
416
+ message, sender, recipient, direction="sent",
417
+ attributes={**evidence, "receive_observed": False,
418
+ "handoff_proof": "sdk_handoff_span_only"},
419
+ ))
420
+ else:
421
+ self.context.emit(
422
+ "MESSAGE_UNROUTED", "HANDOFF_UNROUTED",
423
+ attributes={**evidence, "reason": "missing_agent_identity"},
424
+ )
425
+
426
+ def _guard(self, handler: Any, value: Any) -> None:
427
+ try:
428
+ handler(value)
429
+ except Exception:
430
+ # Never surface SDK payloads, exception messages or tracebacks.
431
+ with self._lock:
432
+ self.callback_errors += 1
433
+
434
+ def force_flush(self) -> None:
435
+ """Events are synchronously written to the run-bound sidecar."""
436
+
437
+ def shutdown(self) -> None:
438
+ """No external resources or background worker to close."""
439
+
440
+
441
+ def install_agents_sdk_tracing(*, capture_mode: str = "prompt_and_response") -> AgentsSDKTraceProcessor:
442
+ """Register an additive processor before Runner.run.
443
+
444
+ Does not disable the SDK's own tracing exporter or change its privacy policy.
445
+ """
446
+ try:
447
+ from agents.tracing import add_trace_processor
448
+ except ImportError as exc:
449
+ raise ImportError("Install the optional 'openai-agents' package") from exc
450
+ processor = AgentsSDKTraceProcessor(capture_mode=capture_mode)
451
+ if processor.enabled:
452
+ add_trace_processor(processor)
453
+ return processor
@@ -0,0 +1,239 @@
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_openai_compatible_endpoint(endpoint: str) -> str:
19
+ split = urlsplit(endpoint)
20
+ if split.scheme not in {"http", "https"} or not split.hostname:
21
+ raise ValueError("OpenAI-compatible 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 _entity(
32
+ entity_type: str,
33
+ entity_id: str,
34
+ *,
35
+ name: str | None = None,
36
+ attributes: dict[str, Any] | None = None,
37
+ ) -> dict[str, Any]:
38
+ return {"type": entity_type, "id": entity_id, "name": name, "attributes": attributes or {}}
39
+
40
+
41
+ def _endpoint_digest(endpoint: str) -> str:
42
+ safe_endpoint = sanitize_openai_compatible_endpoint(endpoint)
43
+ return hashlib.sha256(safe_endpoint.encode("utf-8")).hexdigest()[:24]
44
+
45
+
46
+ def _api_entity(provider_name: str, endpoint: str) -> dict[str, Any]:
47
+ safe_endpoint = sanitize_openai_compatible_endpoint(endpoint)
48
+ digest = _endpoint_digest(safe_endpoint)
49
+ return _entity(
50
+ "inference_api",
51
+ f"inference-api:openai-compatible:{digest}",
52
+ name=provider_name,
53
+ attributes={
54
+ "protocol": "openai_compatible",
55
+ "provider_name": provider_name,
56
+ "endpoint": safe_endpoint,
57
+ },
58
+ )
59
+
60
+
61
+ def _model_entity(provider_name: str, endpoint: str, model: str) -> dict[str, Any]:
62
+ endpoint_scope = _endpoint_digest(endpoint)
63
+ return _entity(
64
+ "model",
65
+ f"model:openai-compatible:{endpoint_scope}:{model}",
66
+ name=model,
67
+ attributes={
68
+ "catalog_id": model,
69
+ "provider_name": provider_name,
70
+ "endpoint_scope": endpoint_scope,
71
+ "identity_scope": "openai_compatible_endpoint",
72
+ },
73
+ )
74
+
75
+
76
+ def _request_identity(
77
+ payload: dict[str, Any],
78
+ explicit: str | None,
79
+ *,
80
+ endpoint_scope: str,
81
+ observed_at: str,
82
+ ) -> tuple[str, str]:
83
+ if isinstance(explicit, str) and explicit:
84
+ return explicit, "provided"
85
+ native = payload.get("id")
86
+ if isinstance(native, str) and native:
87
+ return native, "provider_native"
88
+ seed = {
89
+ "model": payload.get("model"),
90
+ "created": payload.get("created"),
91
+ "usage": payload.get("usage"),
92
+ }
93
+ raw = json.dumps(seed, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
94
+ occurrence = "\0".join(("openai-compatible", endpoint_scope, observed_at, raw))
95
+ digest = hashlib.sha256(occurrence.encode("utf-8", errors="replace")).hexdigest()[:32]
96
+ return digest, "execweave_observation"
97
+
98
+
99
+ def _copy_int(mapping: dict[str, Any], source: str, target: str, attrs: dict[str, Any]) -> None:
100
+ value = mapping.get(source)
101
+ if isinstance(value, int) and not isinstance(value, bool) and target not in attrs:
102
+ attrs[target] = value
103
+
104
+
105
+ def _usage_attributes(payload: dict[str, Any]) -> dict[str, Any]:
106
+ attrs: dict[str, Any] = {"protocol": "openai_compatible"}
107
+ usage = payload.get("usage")
108
+ if not isinstance(usage, dict):
109
+ return attrs
110
+ for source, target in (
111
+ ("prompt_tokens", "prompt_tokens"),
112
+ ("input_tokens", "prompt_tokens"),
113
+ ("completion_tokens", "completion_tokens"),
114
+ ("output_tokens", "completion_tokens"),
115
+ ("total_tokens", "total_tokens"),
116
+ ):
117
+ _copy_int(usage, source, target, attrs)
118
+ for detail_key in ("prompt_tokens_details", "input_tokens_details"):
119
+ details = usage.get(detail_key)
120
+ if isinstance(details, dict):
121
+ _copy_int(details, "cached_tokens", "cached_prompt_tokens", attrs)
122
+ for detail_key in ("completion_tokens_details", "output_tokens_details"):
123
+ details = usage.get(detail_key)
124
+ if isinstance(details, dict):
125
+ _copy_int(details, "reasoning_tokens", "reasoning_tokens", attrs)
126
+ return attrs
127
+
128
+
129
+ def response_to_events(
130
+ payload: dict[str, Any],
131
+ *,
132
+ endpoint: str,
133
+ provider_name: str = "openai-compatible",
134
+ requested_model: str | None = None,
135
+ request_id: str | None = None,
136
+ timestamp: str | None = None,
137
+ ) -> list[dict[str, Any]]:
138
+ observed_at = timestamp or _now()
139
+ safe_endpoint = sanitize_openai_compatible_endpoint(endpoint)
140
+ endpoint_scope = _endpoint_digest(safe_endpoint)
141
+ api = _api_entity(provider_name, safe_endpoint)
142
+ native_id, request_id_source = _request_identity(
143
+ payload,
144
+ request_id,
145
+ endpoint_scope=endpoint_scope,
146
+ observed_at=observed_at,
147
+ )
148
+ attrs = _usage_attributes(payload)
149
+ attrs.update(
150
+ {
151
+ "backend": "openai_compatible_api",
152
+ "attribution": "direct_api_response",
153
+ "evidence_source": "openai_compatible_response",
154
+ "provider_name": provider_name,
155
+ "endpoint_scope": endpoint_scope,
156
+ "request_id_source": request_id_source,
157
+ "causal": False,
158
+ "inferred": False,
159
+ }
160
+ )
161
+ request = _entity(
162
+ "inference_request",
163
+ f"inference-request:openai-compatible:{endpoint_scope}:{native_id}",
164
+ name=native_id,
165
+ attributes={
166
+ "provider_name": provider_name,
167
+ "endpoint_scope": endpoint_scope,
168
+ "request_id_source": request_id_source,
169
+ **_usage_attributes(payload),
170
+ },
171
+ )
172
+ events = [
173
+ {
174
+ "timestamp": observed_at,
175
+ "event_type": "openai_compatible.response.observed",
176
+ "relation": "SERVED_INFERENCE",
177
+ "source": api,
178
+ "target": request,
179
+ "attributes": attrs,
180
+ }
181
+ ]
182
+ if isinstance(requested_model, str) and requested_model:
183
+ events.append(
184
+ {
185
+ "timestamp": observed_at,
186
+ "event_type": "openai_compatible.model.requested",
187
+ "relation": "REQUESTED_MODEL",
188
+ "source": request,
189
+ "target": _model_entity(provider_name, safe_endpoint, requested_model),
190
+ "attributes": attrs,
191
+ }
192
+ )
193
+ resolved_model = payload.get("model")
194
+ if isinstance(resolved_model, str) and resolved_model:
195
+ events.append(
196
+ {
197
+ "timestamp": observed_at,
198
+ "event_type": "openai_compatible.model.used",
199
+ "relation": "USED_MODEL",
200
+ "source": request,
201
+ "target": _model_entity(provider_name, safe_endpoint, resolved_model),
202
+ "attributes": attrs,
203
+ }
204
+ )
205
+ return events
206
+
207
+
208
+ def append_openai_compatible_records(
209
+ path: str | Path, records: list[dict[str, Any]]
210
+ ) -> Path:
211
+ raw_output = Path(path).expanduser()
212
+ output = raw_output.parent.resolve() / raw_output.name
213
+ output.parent.mkdir(parents=True, exist_ok=True)
214
+ if not records:
215
+ return output
216
+ blob = "".join(
217
+ json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n"
218
+ for record in records
219
+ )
220
+ lock_dir = output.with_name(output.name + ".lock")
221
+ deadline = time.monotonic() + 5.0
222
+ while True:
223
+ try:
224
+ lock_dir.mkdir()
225
+ break
226
+ except FileExistsError:
227
+ if time.monotonic() >= deadline:
228
+ raise TimeoutError(
229
+ f"timed out waiting for OpenAI-compatible sidecar lock: {lock_dir}"
230
+ )
231
+ time.sleep(0.01)
232
+ try:
233
+ append_private_text(output, blob)
234
+ finally:
235
+ try:
236
+ lock_dir.rmdir()
237
+ except OSError:
238
+ pass
239
+ return output