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,580 @@
1
+ """Public framework adapter SDK.
2
+
3
+ Framework integrations translate authoritative callbacks/events into canonical
4
+ records here. The core collector never guesses logical agents from process
5
+ names or network traffic.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import re
14
+ import sys
15
+ import threading
16
+ import time
17
+ from dataclasses import asdict, dataclass, field
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+ from typing import Any, Literal, Mapping
21
+ from uuid import uuid4
22
+
23
+ import psutil
24
+
25
+ from ..content_store import ContentReference, FullFidelityContentStore
26
+ from ..private_io import append_private_text
27
+ from ..schema import SCHEMA_VERSION
28
+
29
+ CaptureMode = Literal[
30
+ "metadata_only",
31
+ "content_ref_only",
32
+ "prompt_only",
33
+ "prompt_and_response",
34
+ ]
35
+
36
+ CANONICAL_EVENT_TYPES = frozenset(
37
+ {
38
+ "AGENT_CREATED", "AGENT_STARTED", "AGENT_STOPPED",
39
+ "TASK_CREATED", "TASK_ASSIGNED", "TASK_STARTED", "TASK_UPDATED",
40
+ "TASK_CONTENT_RECORDED",
41
+ "TASK_COMPLETED", "TASK_FAILED",
42
+ "MESSAGE_SENT", "MESSAGE_RECEIVED", "MESSAGE_UNROUTED",
43
+ "MODEL_REQUEST", "MODEL_RESPONSE", "MODEL_FAILURE",
44
+ "TOOL_CALL", "TOOL_RESULT", "TOOL_FAILURE",
45
+ "MESSAGE_CONTENT_RECORDED", "MODEL_CONTENT_RECORDED", "TOOL_CONTENT_RECORDED",
46
+ }
47
+ )
48
+ _CAPTURE_MODES = frozenset({"metadata_only", "content_ref_only", "prompt_only", "prompt_and_response"})
49
+ _HIDDEN_CONTENT_MARKERS = frozenset({
50
+ "chain_of_thought", "chain-of-thought", "internal_reasoning",
51
+ "hidden_reasoning", "thinking_tokens", "private_reasoning",
52
+ })
53
+ _ID_SAFE = re.compile(r"[^A-Za-z0-9_.:-]+")
54
+ _CREDENTIAL_KEYS = frozenset({
55
+ "authorization", "proxy-authorization", "cookie", "set-cookie",
56
+ "x-api-key", "api-key", "api_key", "apikey", "access_token",
57
+ "refresh_token", "client_secret", "password", "token",
58
+ })
59
+
60
+
61
+ def utc_now() -> str:
62
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
63
+
64
+
65
+ def stable_id(entity_type: str, native_id: str | int | None, *, framework: str, run_id: str) -> str:
66
+ """Create a deterministic run-scoped ID without timestamps or content."""
67
+ if not entity_type or not framework or not run_id:
68
+ raise ValueError("entity_type, framework, and run_id are required")
69
+ native = str(native_id).strip() if native_id is not None else "anonymous"
70
+ native = native or "anonymous"
71
+ def clean(value):
72
+ return _ID_SAFE.sub("_", str(value).strip())
73
+ if native_id is not None:
74
+ return f"{clean(entity_type).lower()}:{clean(framework).lower()}:{clean(run_id)}:{clean(native)}"
75
+ digest = hashlib.sha256(f"{entity_type}\0{framework}\0{run_id}".encode()).hexdigest()[:20]
76
+ return f"{clean(entity_type).lower()}:{clean(framework).lower()}:{clean(run_id)}:{digest}"
77
+
78
+
79
+ def _clean_metadata(value: Any) -> Any:
80
+ if isinstance(value, Mapping):
81
+ return {
82
+ str(key): _clean_metadata(child)
83
+ for key, child in value.items()
84
+ if str(key).lower() not in _CREDENTIAL_KEYS
85
+ }
86
+ if isinstance(value, list):
87
+ return [_clean_metadata(child) for child in value]
88
+ if isinstance(value, tuple):
89
+ return [_clean_metadata(child) for child in value]
90
+ return value
91
+
92
+
93
+ def _string(value: Any) -> str | None:
94
+ if value is None:
95
+ return None
96
+ text = str(value).strip()
97
+ return text or None
98
+
99
+
100
+ def _entity_label(entity: EntityRef | None) -> str | None:
101
+ if entity is None:
102
+ return None
103
+ return entity.name or entity.id
104
+
105
+
106
+ @dataclass(frozen=True)
107
+ class EntityRef:
108
+ type: str
109
+ id: str
110
+ name: str | None = None
111
+ attributes: Mapping[str, Any] = field(default_factory=dict)
112
+
113
+ def __post_init__(self) -> None:
114
+ if not self.type or not self.id:
115
+ raise ValueError("entity type and id must be non-empty")
116
+
117
+ def to_dict(self) -> dict[str, Any]:
118
+ return {
119
+ "type": self.type,
120
+ "id": self.id,
121
+ "name": self.name,
122
+ "attributes": _clean_metadata(dict(self.attributes)),
123
+ }
124
+
125
+
126
+ @dataclass(frozen=True)
127
+ class ProcessRef:
128
+ pid: int
129
+ create_time: float | None = None
130
+ executable: str | None = None
131
+
132
+ def to_entity(self) -> EntityRef:
133
+ if self.pid <= 0:
134
+ raise ValueError("process pid must be positive")
135
+ attributes: dict[str, Any] = {"pid": self.pid}
136
+ if self.create_time is not None:
137
+ attributes["create_time"] = float(self.create_time)
138
+ if self.executable:
139
+ attributes["executable"] = self.executable
140
+ identity = f"{self.pid}:{self.create_time}" if self.create_time is not None else str(self.pid)
141
+ return EntityRef("process_reference", f"process-reference:{identity}", self.executable or f"pid {self.pid}", attributes)
142
+
143
+
144
+ def _current_process_ref() -> ProcessRef:
145
+ """Return the authoritative identity of the adapter's current process."""
146
+ process = psutil.Process(os.getpid())
147
+ try:
148
+ create_time = process.create_time()
149
+ except (psutil.AccessDenied, psutil.NoSuchProcess, psutil.ZombieProcess):
150
+ create_time = None
151
+ try:
152
+ executable = process.exe()
153
+ except (psutil.AccessDenied, psutil.NoSuchProcess, psutil.ZombieProcess):
154
+ executable = sys.executable
155
+ return ProcessRef(os.getpid(), create_time, executable or sys.executable)
156
+
157
+
158
+ @dataclass(frozen=True)
159
+ class AdapterCapabilities:
160
+ events: tuple[str, ...] = ()
161
+ entities: tuple[str, ...] = ("agent", "task", "message", "model", "tool", "process")
162
+ content_modes: tuple[str, ...] = ("metadata_only",)
163
+ authoritative_surfaces: tuple[str, ...] = ()
164
+ known_limitations: tuple[str, ...] = ()
165
+
166
+ def __post_init__(self) -> None:
167
+ unknown = set(self.events) - CANONICAL_EVENT_TYPES
168
+ if unknown:
169
+ raise ValueError(f"unknown canonical event types: {sorted(unknown)}")
170
+ unknown_modes = set(self.content_modes) - _CAPTURE_MODES
171
+ if unknown_modes:
172
+ raise ValueError(f"unknown capture modes: {sorted(unknown_modes)}")
173
+
174
+ def to_dict(self) -> dict[str, Any]:
175
+ return asdict(self)
176
+
177
+
178
+ @dataclass(frozen=True)
179
+ class FrameworkCompatibility:
180
+ framework: str
181
+ detected_version: str | None
182
+ tested_versions: tuple[str, ...] = ()
183
+ compatibility_status: Literal["verified", "warn", "unsupported", "unknown"] = "unknown"
184
+ capabilities: AdapterCapabilities = field(default_factory=AdapterCapabilities)
185
+ known_limitations: tuple[str, ...] = ()
186
+
187
+ def to_dict(self) -> dict[str, Any]:
188
+ result = asdict(self)
189
+ result["capabilities"] = self.capabilities.to_dict()
190
+ return result
191
+
192
+
193
+ @dataclass(frozen=True)
194
+ class ContentCapturePolicy:
195
+ mode: CaptureMode = "metadata_only"
196
+ redact_metadata: bool = True
197
+
198
+ def __post_init__(self) -> None:
199
+ if self.mode not in _CAPTURE_MODES:
200
+ raise ValueError(f"unsupported capture mode: {self.mode}")
201
+
202
+ def allows(self, content_kind: str) -> bool:
203
+ normalized = content_kind.strip().lower()
204
+ if any(marker in normalized for marker in _HIDDEN_CONTENT_MARKERS):
205
+ return False
206
+ if self.mode == "metadata_only":
207
+ return False
208
+ if self.mode == "prompt_only":
209
+ return any(token in normalized for token in ("prompt", "request", "message", "task"))
210
+ return True
211
+
212
+
213
+ class ContentWriter:
214
+ """Policy-aware facade over the run-local content-addressed store."""
215
+
216
+ def __init__(self, run_root: str | Path, *, policy: ContentCapturePolicy = ContentCapturePolicy()) -> None:
217
+ self.policy = policy
218
+ self.store = FullFidelityContentStore(run_root)
219
+
220
+ def put_text(self, value: str, *, content_kind: str, media_type: str = "text/plain; charset=utf-8") -> ContentReference | None:
221
+ if not isinstance(value, str):
222
+ raise TypeError("content value must be text")
223
+ if not self.policy.allows(content_kind):
224
+ return None
225
+ return self.store.put_text(value, content_kind=content_kind, media_type=media_type)
226
+
227
+ def put_json(self, value: Any, *, content_kind: str) -> ContentReference | None:
228
+ if not self.policy.allows(content_kind):
229
+ return None
230
+ return self.store.put_json(value, content_kind=content_kind)
231
+
232
+ def reference_attributes(self, reference: ContentReference | None) -> dict[str, Any]:
233
+ if reference is None:
234
+ return {"capture_mode": "metadata_only", "content_available": False}
235
+ return {
236
+ "capture_mode": "content_ref_only",
237
+ "content_available": True,
238
+ "content_ref": reference.path,
239
+ "content_sha256": reference.sha256,
240
+ "content_kind": reference.content_kind,
241
+ "content_media_type": reference.media_type,
242
+ "content_size_bytes": reference.size_bytes,
243
+ "content_complete_from_source": reference.complete_from_source,
244
+ }
245
+
246
+
247
+ class SemanticWriter:
248
+ """Append canonical semantic records to the active ExecWeave sidecar."""
249
+
250
+ _process_locks: dict[str, threading.Lock] = {}
251
+
252
+ def __init__(self, path: str | Path | None = None) -> None:
253
+ configured = path or os.environ.get("EXECWEAVE_SEMANTIC_SIDECAR")
254
+ if configured:
255
+ raw_path = Path(configured).expanduser()
256
+ self.path = raw_path.parent.resolve() / raw_path.name
257
+ else:
258
+ self.path = None
259
+
260
+ @property
261
+ def enabled(self) -> bool:
262
+ return self.path is not None
263
+
264
+ def emit(self, *, event_type: str, relation: str, source: EntityRef | None = None, target: EntityRef | None = None, attributes: Mapping[str, Any] | None = None, timestamp: str | None = None, event_id: str | None = None) -> dict[str, Any]:
265
+ if event_type not in CANONICAL_EVENT_TYPES:
266
+ raise ValueError(f"unsupported canonical event type: {event_type}")
267
+ if not relation:
268
+ raise ValueError("relation must not be empty")
269
+ if self.path is None:
270
+ raise RuntimeError("semantic output is disabled; set EXECWEAVE_SEMANTIC_SIDECAR or pass a path")
271
+ record = {
272
+ "schema_version": SCHEMA_VERSION,
273
+ "event_id": event_id or f"semantic:{uuid4()}",
274
+ "timestamp": timestamp or utc_now(),
275
+ "event_type": event_type,
276
+ "relation": relation,
277
+ "source": source.to_dict() if source is not None else None,
278
+ "target": target.to_dict() if target is not None else None,
279
+ "attributes": _clean_metadata(dict(attributes or {})),
280
+ }
281
+ self.append(record)
282
+ return record
283
+
284
+ def append(self, record: Mapping[str, Any]) -> None:
285
+ if self.path is None:
286
+ raise RuntimeError("semantic output is disabled")
287
+ self.path.parent.mkdir(parents=True, exist_ok=True)
288
+ payload = json.dumps(dict(record), ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n"
289
+ lock = self._process_locks.setdefault(str(self.path), threading.Lock())
290
+ with lock:
291
+ lock_dir = self.path.with_name(self.path.name + ".lock")
292
+ deadline = time.monotonic() + 5.0
293
+ while True:
294
+ try:
295
+ lock_dir.mkdir()
296
+ break
297
+ except FileExistsError:
298
+ if time.monotonic() >= deadline:
299
+ raise TimeoutError(f"timed out waiting for semantic sidecar lock: {lock_dir}")
300
+ time.sleep(0.01)
301
+ try:
302
+ append_private_text(self.path, payload)
303
+ finally:
304
+ lock_dir.rmdir()
305
+
306
+
307
+ @dataclass(frozen=True)
308
+ class AgentRecord:
309
+ agent: EntityRef
310
+ role: str | None = None
311
+ process: ProcessRef | None = None
312
+ parent_agent: EntityRef | None = None
313
+ attributes: Mapping[str, Any] = field(default_factory=dict)
314
+
315
+
316
+ @dataclass(frozen=True)
317
+ class TaskRecord:
318
+ task: EntityRef
319
+ owner: EntityRef | None = None
320
+ parent_task: EntityRef | None = None
321
+ content: str | None = None
322
+ content_kind: str = "task_prompt"
323
+ attributes: Mapping[str, Any] = field(default_factory=dict)
324
+
325
+
326
+ @dataclass(frozen=True)
327
+ class MessageRecord:
328
+ message: EntityRef
329
+ source: EntityRef | None
330
+ target: EntityRef | None
331
+ role: str | None = None
332
+ task: EntityRef | None = None
333
+ parent_message: EntityRef | None = None
334
+ content: str | None = None
335
+ content_kind: str = "message"
336
+ direction: Literal["sent", "received"] = "sent"
337
+ attributes: Mapping[str, Any] = field(default_factory=dict)
338
+ content_payload: Any | None = None
339
+
340
+
341
+ @dataclass(frozen=True)
342
+ class ModelCallRecord:
343
+ model_call: EntityRef
344
+ requesting_agent: EntityRef | None
345
+ model: EntityRef
346
+ request: Any | None = None
347
+ response: Any | None = None
348
+ content_kind: str = "model_request"
349
+ status: Literal["request", "response", "failure"] = "request"
350
+ task: EntityRef | None = None
351
+ attributes: Mapping[str, Any] = field(default_factory=dict)
352
+
353
+
354
+ @dataclass(frozen=True)
355
+ class ToolCallRecord:
356
+ tool_call: EntityRef
357
+ requesting_agent: EntityRef | None
358
+ tool: EntityRef
359
+ arguments: Any | None = None
360
+ result: Any | None = None
361
+ status: Literal["call", "result", "failure"] = "call"
362
+ task: EntityRef | None = None
363
+ attributes: Mapping[str, Any] = field(default_factory=dict)
364
+
365
+
366
+ class AdapterContext:
367
+ """Run-scoped state shared by a framework adapter."""
368
+
369
+ def __init__(self, *, framework: str, run_id: str | None = None, session_id: str | None = None, conversation_id: str | None = None, sidecar: str | Path | None = None, content_root: str | Path | None = None, capture_policy: ContentCapturePolicy = ContentCapturePolicy(), process: ProcessRef | None = None) -> None:
370
+ if not framework.strip():
371
+ raise ValueError("framework must not be empty")
372
+ self.framework = framework.strip().lower()
373
+ self.run_id = run_id or os.environ.get("EXECWEAVE_RUN_ID") or uuid4().hex
374
+ self.session_id = session_id or os.environ.get("EXECWEAVE_SESSION_ID") or self.run_id
375
+ self.conversation_id = conversation_id or os.environ.get("EXECWEAVE_CONVERSATION_ID")
376
+ self.writer = SemanticWriter(sidecar)
377
+ root = Path(content_root or (self.writer.path.parent if self.writer.path else Path.cwd()))
378
+ self.content = ContentWriter(root, policy=capture_policy)
379
+ self.capture_policy = capture_policy
380
+ self.process = process
381
+
382
+ @classmethod
383
+ def from_environment(cls, framework: str, *, capture_mode: CaptureMode = "metadata_only", content_root: str | Path | None = None, run_id: str | None = None, session_id: str | None = None, conversation_id: str | None = None, process: ProcessRef | None = None) -> "AdapterContext":
384
+ if (
385
+ process is None
386
+ and os.environ.get("EXECWEAVE_SEMANTIC_SIDECAR")
387
+ and os.environ.get("EXECWEAVE_SESSION_ID")
388
+ ):
389
+ process = _current_process_ref()
390
+ return cls(framework=framework, run_id=run_id, session_id=session_id, conversation_id=conversation_id, content_root=content_root, capture_policy=ContentCapturePolicy(capture_mode), process=process)
391
+
392
+ def entity(self, entity_type: str, native_id: str | int | None, *, name: str | None = None, attributes: Mapping[str, Any] | None = None) -> EntityRef:
393
+ values = dict(attributes or {})
394
+ values.setdefault("framework", self.framework)
395
+ values.setdefault("run_id", self.run_id)
396
+ values.setdefault("session_id", self.session_id)
397
+ if self.conversation_id:
398
+ values.setdefault("conversation_id", self.conversation_id)
399
+ return EntityRef(entity_type, stable_id(entity_type, native_id, framework=self.framework, run_id=self.run_id), name or _string(native_id), values)
400
+
401
+ def emit(self, event_type: str, relation: str, *, source: EntityRef | None = None, target: EntityRef | None = None, attributes: Mapping[str, Any] | None = None, timestamp: str | None = None) -> dict[str, Any]:
402
+ values = {"framework": self.framework, "run_id": self.run_id, "session_id": self.session_id, "capture_mode": self.capture_policy.mode, **dict(attributes or {})}
403
+ if self.conversation_id:
404
+ values.setdefault("conversation_id", self.conversation_id)
405
+ return self.writer.emit(event_type=event_type, relation=relation, source=source, target=target, attributes=values, timestamp=timestamp)
406
+
407
+ def correlate_process(self, entity: EntityRef, process: ProcessRef | None = None) -> dict[str, Any] | None:
408
+ reference = process or self.process
409
+ if reference is None:
410
+ return None
411
+ return self.emit("AGENT_STARTED", "CORRELATED_WITH_PROCESS", source=entity, target=reference.to_entity(), attributes={"correlation_kind": "logical_agent_to_process"})
412
+
413
+ def record_agent(self, record: AgentRecord, *, event_type: str = "AGENT_CREATED") -> EntityRef:
414
+ self.emit(event_type, event_type, source=record.agent, attributes={"role": record.role, **dict(record.attributes)})
415
+ if record.process is not None or self.process is not None:
416
+ self.correlate_process(record.agent, record.process)
417
+ if record.parent_agent is not None:
418
+ self.emit("AGENT_CREATED", "PARENT_AGENT", source=record.parent_agent, target=record.agent, attributes={"relationship": "child_agent", **dict(record.attributes)})
419
+ return record.agent
420
+
421
+ def record_task(self, record: TaskRecord, *, event_type: str = "TASK_CREATED") -> EntityRef:
422
+ content_reference = None
423
+ if record.content is not None:
424
+ content_kind = record.content_kind
425
+ if "." not in content_kind:
426
+ content_kind = f"{self.framework}.{content_kind}"
427
+ content_reference = self.content.put_text(record.content, content_kind=content_kind)
428
+ task_attributes = {
429
+ "parent_task_id": record.parent_task.id if record.parent_task else None,
430
+ **self.content.reference_attributes(content_reference),
431
+ **dict(record.attributes),
432
+ }
433
+ self.emit(event_type, event_type, source=record.owner, target=record.task, attributes=task_attributes)
434
+ if record.parent_task is not None:
435
+ self.emit("TASK_CREATED", "PARENT_TASK", source=record.parent_task, target=record.task, attributes={"parent_task_id": record.parent_task.id})
436
+ if content_reference is not None:
437
+ content = EntityRef(
438
+ "observed_content",
439
+ f"observed-content:task:sha256:{content_reference.sha256}",
440
+ content_reference.content_kind,
441
+ content_reference.to_dict(),
442
+ )
443
+ self.emit(
444
+ "TASK_CONTENT_RECORDED",
445
+ "HAS_TASK_CONTENT",
446
+ source=record.task,
447
+ target=content,
448
+ attributes={
449
+ "task_id": record.task.id,
450
+ "conversation_scope": "task",
451
+ **self.content.reference_attributes(content_reference),
452
+ },
453
+ )
454
+ return record.task
455
+
456
+ def record_message(self, record: MessageRecord) -> EntityRef:
457
+ content_kind = f"{self.framework}.agent_message"
458
+ message_payload = record.content_payload if record.content_payload is not None else {
459
+ "message_id": record.message.id,
460
+ "text": record.content,
461
+ "sender": _entity_label(record.source),
462
+ "recipient": _entity_label(record.target),
463
+ "role": record.role,
464
+ "kind": "agent_message",
465
+ "phase": "received" if record.direction == "received" else "sent",
466
+ "content_state": "plaintext",
467
+ }
468
+ reference = self.content.put_json(message_payload, content_kind=content_kind) if record.content is not None else None
469
+ attrs = {"message_id": record.message.id, "role": record.role, "task_id": record.task.id if record.task else None, "parent_message_id": record.parent_message.id if record.parent_message else None, "sender_agent_id": record.source.id if record.source and record.source.type == "agent" else None, "recipient_agent_id": record.target.id if record.target and record.target.type == "agent" else None, **self.content.reference_attributes(reference), **dict(record.attributes)}
470
+ event_type = "MESSAGE_SENT" if record.direction == "sent" else "MESSAGE_RECEIVED"
471
+ self.emit(event_type, event_type, source=record.source, target=record.target or record.message, attributes=attrs)
472
+ if reference is not None:
473
+ content = EntityRef("observed_content", f"observed-content:message:sha256:{reference.sha256}", reference.content_kind, reference.to_dict())
474
+ participants: list[tuple[EntityRef, str]] = []
475
+ for side, participant in (("sender", record.source), ("recipient", record.target)):
476
+ if participant is None or participant.type != "agent":
477
+ continue
478
+ if any(existing.id == participant.id for existing, _ in participants):
479
+ participants = [(existing, "sender_and_recipient" if existing.id == participant.id else existing_side) for existing, existing_side in participants]
480
+ continue
481
+ participants.append((participant, side))
482
+ if not participants:
483
+ participants = [(record.message, "message")]
484
+ for participant, side in participants:
485
+ self.emit(
486
+ "MESSAGE_CONTENT_RECORDED",
487
+ "HAS_MESSAGE_CONTENT",
488
+ source=participant,
489
+ target=content,
490
+ attributes={
491
+ "message_id": record.message.id,
492
+ "conversation_scope": "agent" if participant.type == "agent" else "message",
493
+ "conversation_side": side,
494
+ "conversation_agent_id": participant.id if participant.type == "agent" else None,
495
+ **self.content.reference_attributes(reference),
496
+ },
497
+ )
498
+ return record.message
499
+
500
+ def record_model_call(self, record: ModelCallRecord) -> EntityRef:
501
+ if record.status == "request":
502
+ event_type, relation, value, kind = "MODEL_REQUEST", "REQUESTS_MODEL_CALL", record.request, f"{self.framework}.model_request"
503
+ elif record.status == "response":
504
+ event_type, relation, value, kind = "MODEL_RESPONSE", "MODEL_CALL_RESPONDS", record.response, f"{self.framework}.model_response"
505
+ else:
506
+ event_type, relation, value, kind = "MODEL_FAILURE", "MODEL_CALL_FAILED", record.response or record.request, f"{self.framework}.model_failure"
507
+ reference = self.content.put_text(value, content_kind=kind) if isinstance(value, str) else self.content.put_json(value, content_kind=kind) if value is not None else None
508
+ attrs = {"model_call_id": record.model_call.id, "task_id": record.task.id if record.task else None, "requesting_agent_id": record.requesting_agent.id if record.requesting_agent else None, **self.content.reference_attributes(reference), **dict(record.attributes)}
509
+ self.emit(event_type, relation, source=record.requesting_agent, target=record.model, attributes=attrs)
510
+ if reference is not None:
511
+ content = EntityRef("observed_content", f"observed-content:model:sha256:{reference.sha256}", reference.content_kind, reference.to_dict())
512
+ self.emit(
513
+ "MODEL_CONTENT_RECORDED",
514
+ "HAS_MODEL_CONTENT",
515
+ source=record.requesting_agent or record.model_call,
516
+ target=content,
517
+ attributes={
518
+ "model_call_id": record.model_call.id,
519
+ "conversation_scope": "agent" if record.requesting_agent is not None else "model_call",
520
+ "conversation_agent_id": record.requesting_agent.id if record.requesting_agent else None,
521
+ **self.content.reference_attributes(reference),
522
+ },
523
+ )
524
+ return record.model_call
525
+
526
+ def record_tool_call(self, record: ToolCallRecord) -> EntityRef:
527
+ if record.status == "call":
528
+ event_type, relation, value, kind = "TOOL_CALL", "REQUESTS_TOOL_CALL", record.arguments, "tool_arguments"
529
+ elif record.status == "result":
530
+ event_type, relation, value, kind = "TOOL_RESULT", "TOOL_CALL_RETURNS", record.result, "tool_result"
531
+ else:
532
+ event_type, relation, value, kind = "TOOL_FAILURE", "TOOL_CALL_FAILED", record.result or record.arguments, "tool_failure"
533
+ reference = self.content.put_text(value, content_kind=kind) if isinstance(value, str) else self.content.put_json(value, content_kind=kind) if value is not None else None
534
+ attrs = {"tool_call_id": record.tool_call.id, "task_id": record.task.id if record.task else None, "requesting_agent_id": record.requesting_agent.id if record.requesting_agent else None, **self.content.reference_attributes(reference), **dict(record.attributes)}
535
+ self.emit(event_type, relation, source=record.requesting_agent, target=record.tool, attributes=attrs)
536
+ if reference is not None:
537
+ content = EntityRef("observed_content", f"observed-content:tool:sha256:{reference.sha256}", reference.content_kind, reference.to_dict())
538
+ self.emit("TOOL_CONTENT_RECORDED", "HAS_TOOL_CONTENT", source=record.tool_call, target=content, attributes={"tool_call_id": record.tool_call.id, **self.content.reference_attributes(reference)})
539
+ return record.tool_call
540
+
541
+
542
+ class FrameworkAdapter:
543
+ """Base class for framework-specific authoritative event adapters."""
544
+
545
+ framework_name = "generic"
546
+ capabilities = AdapterCapabilities()
547
+
548
+ def __init__(self, context: AdapterContext) -> None:
549
+ if context.framework != self.framework_name:
550
+ raise ValueError(f"context framework {context.framework!r} does not match {self.framework_name!r}")
551
+ self.context = context
552
+
553
+ @classmethod
554
+ def compatibility(cls) -> FrameworkCompatibility:
555
+ return FrameworkCompatibility(framework=cls.framework_name, detected_version=None, capabilities=cls.capabilities, known_limitations=cls.capabilities.known_limitations)
556
+
557
+ def entity(self, entity_type: str, native_id: str | int | None, **kwargs: Any) -> EntityRef:
558
+ return self.context.entity(entity_type, native_id, **kwargs)
559
+
560
+ def emit(self, event_type: str, relation: str, **kwargs: Any) -> dict[str, Any]:
561
+ return self.context.emit(event_type, relation, **kwargs)
562
+
563
+ def agent(self, native_id: str | int, *, name: str | None = None, **attributes: Any) -> EntityRef:
564
+ native = _ID_SAFE.sub("_", str(native_id).strip()) or "agent"
565
+ values = {
566
+ "conversation_scope": "framework_agent",
567
+ "conversation_agent_id": str(native_id),
568
+ "conversation_agent_path": f"/{self.framework_name}/{native}",
569
+ **attributes,
570
+ }
571
+ return self.entity("agent", native_id, name=name, attributes=values)
572
+
573
+ def task(self, native_id: str | int, *, name: str | None = None, **attributes: Any) -> EntityRef:
574
+ return self.entity("task", native_id, name=name, attributes=attributes)
575
+
576
+ def model(self, native_id: str | int, *, name: str | None = None, **attributes: Any) -> EntityRef:
577
+ return self.entity("model", native_id, name=name, attributes=attributes)
578
+
579
+ def tool(self, native_id: str | int, *, name: str | None = None, **attributes: Any) -> EntityRef:
580
+ return self.entity("tool", native_id, name=name, attributes=attributes)