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,560 @@
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 _entity(
19
+ entity_type: str,
20
+ entity_id: str,
21
+ *,
22
+ name: str | None = None,
23
+ attributes: dict[str, Any] | None = None,
24
+ ) -> dict[str, Any]:
25
+ return {"type": entity_type, "id": entity_id, "name": name, "attributes": attributes or {}}
26
+
27
+
28
+ def _event(
29
+ *,
30
+ timestamp: str,
31
+ event_type: str,
32
+ relation: str,
33
+ source: dict[str, Any],
34
+ target: dict[str, Any],
35
+ runtime: str,
36
+ attributes: dict[str, Any] | None = None,
37
+ ) -> dict[str, Any]:
38
+ merged = {
39
+ "backend": "model_runtime",
40
+ "attribution": "provider_api",
41
+ "evidence_source": "model_runtime_api",
42
+ "provider": runtime,
43
+ "causal": False,
44
+ }
45
+ if attributes:
46
+ merged.update(attributes)
47
+ return {
48
+ "timestamp": timestamp,
49
+ "event_type": event_type,
50
+ "relation": relation,
51
+ "source": source,
52
+ "target": target,
53
+ "attributes": merged,
54
+ }
55
+
56
+
57
+ def sanitize_endpoint(endpoint: str) -> str:
58
+ split = urlsplit(endpoint)
59
+ if split.scheme not in {"http", "https"} or not split.hostname:
60
+ raise ValueError("model runtime endpoint must be an http(s) URL")
61
+ host = split.hostname
62
+ if ":" in host and not host.startswith("["):
63
+ host = f"[{host}]"
64
+ if split.port is not None:
65
+ host = f"{host}:{split.port}"
66
+ path = split.path.rstrip("/")
67
+ return urlunsplit((split.scheme, host, path, "", ""))
68
+
69
+
70
+ def _endpoint_scope(endpoint: str) -> tuple[str, str]:
71
+ safe_endpoint = sanitize_endpoint(endpoint)
72
+ digest = hashlib.sha256(safe_endpoint.encode("utf-8")).hexdigest()[:24]
73
+ return safe_endpoint, digest
74
+
75
+
76
+ def _runtime_entity(runtime: str, endpoint: str) -> dict[str, Any]:
77
+ safe_endpoint, digest = _endpoint_scope(endpoint)
78
+ return _entity(
79
+ "model_runtime",
80
+ f"model-runtime:{runtime}:{digest}",
81
+ name=runtime,
82
+ attributes={"provider": runtime, "endpoint": safe_endpoint, "endpoint_scope": digest},
83
+ )
84
+
85
+
86
+ def _looks_like_local_model_path(model: str) -> bool:
87
+ normalized = model.replace("\\", "/")
88
+ if normalized.startswith(("/", "~/")):
89
+ return True
90
+ if len(model) >= 3 and model[1] == ":" and model[2] in {"/", "\\"}:
91
+ return True
92
+ return model.lower().endswith(".gguf") and ("/" in model or "\\" in model)
93
+
94
+
95
+ def _model_entity(runtime: str, model: str) -> dict[str, Any]:
96
+ redact = _looks_like_local_model_path(model)
97
+ if runtime == "llamacpp" and ("/" in model or "\\" in model or model.lower().endswith(".gguf")):
98
+ redact = True
99
+ if redact:
100
+ basename = model.replace("\\", "/").rsplit("/", 1)[-1] or "model"
101
+ digest = hashlib.sha256(model.encode("utf-8", errors="replace")).hexdigest()[:24]
102
+ return _entity(
103
+ "model",
104
+ f"model:{runtime}:redacted:{digest}",
105
+ name=basename,
106
+ attributes={"provider": runtime, "native_model_id_redacted": True},
107
+ )
108
+ return _entity(
109
+ "model",
110
+ f"model:{runtime}:{model}",
111
+ name=model,
112
+ attributes={"provider": runtime},
113
+ )
114
+
115
+
116
+ def _request_identity(
117
+ runtime: str,
118
+ payload: dict[str, Any],
119
+ explicit: str | None,
120
+ *,
121
+ endpoint_scope: str,
122
+ observed_at: str,
123
+ ) -> tuple[str, str]:
124
+ if explicit:
125
+ return explicit, "provided"
126
+ native = payload.get("id")
127
+ if isinstance(native, str) and native:
128
+ return native, "provider_native"
129
+ seed = {
130
+ "model": payload.get("model"),
131
+ "created_at": payload.get("created_at"),
132
+ "created": payload.get("created"),
133
+ "done_reason": payload.get("done_reason"),
134
+ "total_duration": payload.get("total_duration"),
135
+ "prompt_eval_count": payload.get("prompt_eval_count"),
136
+ "eval_count": payload.get("eval_count"),
137
+ }
138
+ raw = json.dumps(seed, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
139
+ occurrence = "\0".join((runtime, endpoint_scope, observed_at, raw))
140
+ digest = hashlib.sha256(occurrence.encode("utf-8", errors="replace")).hexdigest()[:32]
141
+ return digest, "execweave_observation"
142
+
143
+
144
+ def _inference_entities(
145
+ runtime: str,
146
+ payload: dict[str, Any],
147
+ *,
148
+ endpoint: str,
149
+ request_id: str | None,
150
+ timestamp: str,
151
+ attributes: dict[str, Any],
152
+ ) -> list[dict[str, Any]]:
153
+ runtime_entity = _runtime_entity(runtime, endpoint)
154
+ _, endpoint_scope = _endpoint_scope(endpoint)
155
+ request_native_id, request_id_source = _request_identity(
156
+ runtime,
157
+ payload,
158
+ request_id,
159
+ endpoint_scope=endpoint_scope,
160
+ observed_at=timestamp,
161
+ )
162
+ identity_attrs = {
163
+ **attributes,
164
+ "endpoint_scope": endpoint_scope,
165
+ "request_id_source": request_id_source,
166
+ }
167
+ request = _entity(
168
+ "inference_request",
169
+ f"inference-request:{runtime}:{endpoint_scope}:{request_native_id}",
170
+ name=request_native_id,
171
+ attributes={"provider": runtime, **identity_attrs},
172
+ )
173
+ events = [
174
+ _event(
175
+ timestamp=timestamp,
176
+ event_type=f"model_runtime.{runtime}.inference.observed",
177
+ relation="SERVED_INFERENCE",
178
+ source=runtime_entity,
179
+ target=request,
180
+ runtime=runtime,
181
+ attributes=identity_attrs,
182
+ )
183
+ ]
184
+ model = payload.get("model")
185
+ if isinstance(model, str) and model:
186
+ events.append(
187
+ _event(
188
+ timestamp=timestamp,
189
+ event_type=f"model_runtime.{runtime}.model.used",
190
+ relation="USED_MODEL",
191
+ source=request,
192
+ target=_model_entity(runtime, model),
193
+ runtime=runtime,
194
+ attributes=identity_attrs,
195
+ )
196
+ )
197
+ return events
198
+
199
+
200
+ def _copy_int(mapping: dict[str, Any], source: str, target: str, attrs: dict[str, Any]) -> None:
201
+ value = mapping.get(source)
202
+ if isinstance(value, int) and not isinstance(value, bool) and target not in attrs:
203
+ attrs[target] = value
204
+
205
+
206
+ def _openai_usage_attributes(payload: dict[str, Any]) -> dict[str, Any]:
207
+ attrs: dict[str, Any] = {"protocol": "openai_compatible"}
208
+ usage = payload.get("usage")
209
+ if not isinstance(usage, dict):
210
+ return attrs
211
+
212
+ for source, target in (
213
+ ("prompt_tokens", "prompt_tokens"),
214
+ ("input_tokens", "prompt_tokens"),
215
+ ("completion_tokens", "completion_tokens"),
216
+ ("output_tokens", "completion_tokens"),
217
+ ("total_tokens", "total_tokens"),
218
+ ):
219
+ _copy_int(usage, source, target, attrs)
220
+
221
+ for detail_key in ("prompt_tokens_details", "input_tokens_details"):
222
+ details = usage.get(detail_key)
223
+ if isinstance(details, dict):
224
+ _copy_int(details, "cached_tokens", "cached_prompt_tokens", attrs)
225
+ for detail_key in ("completion_tokens_details", "output_tokens_details"):
226
+ details = usage.get(detail_key)
227
+ if isinstance(details, dict):
228
+ _copy_int(details, "reasoning_tokens", "reasoning_tokens", attrs)
229
+ return attrs
230
+
231
+
232
+ def openai_compatible_response_to_events(
233
+ payload: dict[str, Any],
234
+ *,
235
+ runtime: str,
236
+ endpoint: str,
237
+ request_id: str | None = None,
238
+ timestamp: str | None = None,
239
+ extra_attributes: dict[str, Any] | None = None,
240
+ ) -> list[dict[str, Any]]:
241
+ attrs = _openai_usage_attributes(payload)
242
+ if extra_attributes:
243
+ attrs.update(extra_attributes)
244
+ return _inference_entities(
245
+ runtime,
246
+ payload,
247
+ endpoint=endpoint,
248
+ request_id=request_id,
249
+ timestamp=timestamp or _now(),
250
+ attributes=attrs,
251
+ )
252
+
253
+
254
+ def ollama_response_to_events(
255
+ payload: dict[str, Any],
256
+ *,
257
+ endpoint: str = "http://localhost:11434",
258
+ request_id: str | None = None,
259
+ timestamp: str | None = None,
260
+ ) -> list[dict[str, Any]]:
261
+ if not isinstance(payload.get("model"), str) or not payload.get("model"):
262
+ raise ValueError("Ollama response requires model")
263
+ attrs: dict[str, Any] = {"protocol": "ollama_native"}
264
+ mapping = {
265
+ "done_reason": "finish_reason",
266
+ "total_duration": "total_duration_ns",
267
+ "load_duration": "load_duration_ns",
268
+ "prompt_eval_count": "prompt_tokens",
269
+ "prompt_eval_duration": "prompt_eval_duration_ns",
270
+ "eval_count": "completion_tokens",
271
+ "eval_duration": "completion_duration_ns",
272
+ }
273
+ for source, target in mapping.items():
274
+ value = payload.get(source)
275
+ if isinstance(value, (str, int, float)) and not isinstance(value, bool):
276
+ attrs[target] = value
277
+ return _inference_entities(
278
+ "ollama",
279
+ payload,
280
+ endpoint=endpoint,
281
+ request_id=request_id,
282
+ timestamp=timestamp or _now(),
283
+ attributes=attrs,
284
+ )
285
+
286
+
287
+ def llamacpp_response_to_events(
288
+ payload: dict[str, Any],
289
+ *,
290
+ endpoint: str = "http://localhost:8080",
291
+ request_id: str | None = None,
292
+ timestamp: str | None = None,
293
+ ) -> list[dict[str, Any]]:
294
+ extra: dict[str, Any] = {}
295
+ timings = payload.get("timings")
296
+ if isinstance(timings, dict):
297
+ for key in (
298
+ "cache_n",
299
+ "prompt_n",
300
+ "prompt_ms",
301
+ "prompt_per_token_ms",
302
+ "prompt_per_second",
303
+ "predicted_n",
304
+ "predicted_ms",
305
+ "predicted_per_token_ms",
306
+ "predicted_per_second",
307
+ ):
308
+ value = timings.get(key)
309
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
310
+ extra[f"timing_{key}"] = value
311
+ return openai_compatible_response_to_events(
312
+ payload,
313
+ runtime="llamacpp",
314
+ endpoint=endpoint,
315
+ request_id=request_id,
316
+ timestamp=timestamp,
317
+ extra_attributes=extra,
318
+ )
319
+
320
+
321
+ def vllm_response_to_events(
322
+ payload: dict[str, Any],
323
+ *,
324
+ endpoint: str = "http://localhost:8000",
325
+ request_id: str | None = None,
326
+ timestamp: str | None = None,
327
+ ) -> list[dict[str, Any]]:
328
+ return openai_compatible_response_to_events(
329
+ payload,
330
+ runtime="vllm",
331
+ endpoint=endpoint,
332
+ request_id=request_id,
333
+ timestamp=timestamp,
334
+ )
335
+
336
+
337
+ def lmstudio_response_to_events(
338
+ payload: dict[str, Any],
339
+ *,
340
+ endpoint: str = "http://localhost:1234",
341
+ request_id: str | None = None,
342
+ timestamp: str | None = None,
343
+ ) -> list[dict[str, Any]]:
344
+ return openai_compatible_response_to_events(
345
+ payload,
346
+ runtime="lmstudio",
347
+ endpoint=endpoint,
348
+ request_id=request_id,
349
+ timestamp=timestamp,
350
+ )
351
+
352
+
353
+ def ollama_ps_to_events(
354
+ payload: dict[str, Any],
355
+ *,
356
+ endpoint: str = "http://localhost:11434",
357
+ timestamp: str | None = None,
358
+ ) -> list[dict[str, Any]]:
359
+ models = payload.get("models")
360
+ if not isinstance(models, list):
361
+ raise ValueError("Ollama /api/ps response requires models")
362
+ observed_at = timestamp or _now()
363
+ runtime = _runtime_entity("ollama", endpoint)
364
+ events: list[dict[str, Any]] = []
365
+ for item in models:
366
+ if not isinstance(item, dict):
367
+ continue
368
+ name = item.get("model") or item.get("name")
369
+ if not isinstance(name, str) or not name:
370
+ continue
371
+ attrs: dict[str, Any] = {}
372
+ for key in ("size", "size_vram", "context_length", "expires_at", "digest"):
373
+ value = item.get(key)
374
+ if isinstance(value, (str, int, float)) and not isinstance(value, bool):
375
+ attrs[key] = value
376
+ details = item.get("details")
377
+ if isinstance(details, dict):
378
+ for key in ("format", "family", "parameter_size", "quantization_level"):
379
+ value = details.get(key)
380
+ if isinstance(value, str) and value:
381
+ attrs[key] = value
382
+ events.append(
383
+ _event(
384
+ timestamp=observed_at,
385
+ event_type="model_runtime.ollama.model.loaded",
386
+ relation="LOADED_MODEL",
387
+ source=runtime,
388
+ target=_model_entity("ollama", name),
389
+ runtime="ollama",
390
+ attributes=attrs,
391
+ )
392
+ )
393
+ return events
394
+
395
+
396
+ def openai_compatible_models_to_events(
397
+ payload: dict[str, Any],
398
+ *,
399
+ runtime: str,
400
+ endpoint: str,
401
+ relation: str = "SERVES_MODEL",
402
+ event_suffix: str = "model.served",
403
+ timestamp: str | None = None,
404
+ meta_keys: tuple[str, ...] = (),
405
+ ) -> list[dict[str, Any]]:
406
+ data = payload.get("data")
407
+ if not isinstance(data, list):
408
+ raise ValueError("OpenAI-compatible /v1/models response requires data")
409
+ observed_at = timestamp or _now()
410
+ runtime_entity = _runtime_entity(runtime, endpoint)
411
+ events: list[dict[str, Any]] = []
412
+ for item in data:
413
+ if not isinstance(item, dict):
414
+ continue
415
+ model_id = item.get("id")
416
+ if not isinstance(model_id, str) or not model_id:
417
+ continue
418
+ attrs: dict[str, Any] = {"protocol": "openai_compatible"}
419
+ owned_by = item.get("owned_by")
420
+ if isinstance(owned_by, str) and owned_by:
421
+ attrs["owned_by"] = owned_by
422
+ created = item.get("created")
423
+ if isinstance(created, int) and not isinstance(created, bool):
424
+ attrs["created"] = created
425
+ meta = item.get("meta")
426
+ if isinstance(meta, dict):
427
+ for key in meta_keys:
428
+ value = meta.get(key)
429
+ if isinstance(value, (str, int, float)) and not isinstance(value, bool):
430
+ attrs[key] = value
431
+ events.append(
432
+ _event(
433
+ timestamp=observed_at,
434
+ event_type=f"model_runtime.{runtime}.{event_suffix}",
435
+ relation=relation,
436
+ source=runtime_entity,
437
+ target=_model_entity(runtime, model_id),
438
+ runtime=runtime,
439
+ attributes=attrs,
440
+ )
441
+ )
442
+ return events
443
+
444
+
445
+ def llamacpp_models_to_events(
446
+ payload: dict[str, Any],
447
+ *,
448
+ endpoint: str = "http://localhost:8080",
449
+ timestamp: str | None = None,
450
+ ) -> list[dict[str, Any]]:
451
+ return openai_compatible_models_to_events(
452
+ payload,
453
+ runtime="llamacpp",
454
+ endpoint=endpoint,
455
+ timestamp=timestamp,
456
+ meta_keys=("vocab_type", "n_vocab", "n_ctx_train", "n_embd", "n_params", "size"),
457
+ )
458
+
459
+
460
+ def vllm_models_to_events(
461
+ payload: dict[str, Any],
462
+ *,
463
+ endpoint: str = "http://localhost:8000",
464
+ timestamp: str | None = None,
465
+ ) -> list[dict[str, Any]]:
466
+ return openai_compatible_models_to_events(
467
+ payload,
468
+ runtime="vllm",
469
+ endpoint=endpoint,
470
+ timestamp=timestamp,
471
+ )
472
+
473
+
474
+ def lmstudio_models_to_events(
475
+ payload: dict[str, Any],
476
+ *,
477
+ endpoint: str = "http://localhost:1234",
478
+ timestamp: str | None = None,
479
+ ) -> list[dict[str, Any]]:
480
+ return openai_compatible_models_to_events(
481
+ payload,
482
+ runtime="lmstudio",
483
+ endpoint=endpoint,
484
+ relation="ADVERTISES_MODEL",
485
+ event_suffix="model.advertised",
486
+ timestamp=timestamp,
487
+ )
488
+
489
+
490
+ def llamacpp_metrics_to_events(
491
+ metrics_text: str,
492
+ *,
493
+ endpoint: str = "http://localhost:8080",
494
+ timestamp: str | None = None,
495
+ ) -> list[dict[str, Any]]:
496
+ values: dict[str, float] = {}
497
+ for raw_line in metrics_text.splitlines():
498
+ line = raw_line.strip()
499
+ if not line or line.startswith("#") or "{" in line:
500
+ continue
501
+ parts = line.split()
502
+ if len(parts) != 2 or not parts[0].startswith("llamacpp:"):
503
+ continue
504
+ try:
505
+ values[parts[0]] = float(parts[1])
506
+ except ValueError:
507
+ continue
508
+ if not values:
509
+ return []
510
+ observed_at = timestamp or _now()
511
+ runtime = _runtime_entity("llamacpp", endpoint)
512
+ raw = json.dumps(values, sort_keys=True, separators=(",", ":"))
513
+ digest = hashlib.sha256((observed_at + "\0" + raw).encode("utf-8")).hexdigest()[:24]
514
+ snapshot = _entity(
515
+ "model_runtime_snapshot",
516
+ f"model-runtime-snapshot:llamacpp:{digest}",
517
+ name="llama.cpp metrics",
518
+ attributes={"provider": "llamacpp", "metrics": values},
519
+ )
520
+ return [
521
+ _event(
522
+ timestamp=observed_at,
523
+ event_type="model_runtime.llamacpp.metrics.observed",
524
+ relation="REPORTED_METRICS",
525
+ source=runtime,
526
+ target=snapshot,
527
+ runtime="llamacpp",
528
+ attributes={"metric_count": len(values)},
529
+ )
530
+ ]
531
+
532
+
533
+ def append_model_runtime_records(path: str | Path, records: list[dict[str, Any]]) -> Path:
534
+ raw_output = Path(path).expanduser()
535
+ output = raw_output.parent.resolve() / raw_output.name
536
+ output.parent.mkdir(parents=True, exist_ok=True)
537
+ if not records:
538
+ return output
539
+ blob = "".join(
540
+ json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n"
541
+ for record in records
542
+ )
543
+ lock_dir = output.with_name(output.name + ".lock")
544
+ deadline = time.monotonic() + 5.0
545
+ while True:
546
+ try:
547
+ lock_dir.mkdir()
548
+ break
549
+ except FileExistsError:
550
+ if time.monotonic() >= deadline:
551
+ raise TimeoutError(f"timed out waiting for model runtime sidecar lock: {lock_dir}")
552
+ time.sleep(0.01)
553
+ try:
554
+ append_private_text(output, blob)
555
+ finally:
556
+ try:
557
+ lock_dir.rmdir()
558
+ except OSError:
559
+ pass
560
+ return output