ioc-scope-api 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 (106) hide show
  1. ioc_scope_api-1.0.0.dist-info/METADATA +306 -0
  2. ioc_scope_api-1.0.0.dist-info/RECORD +106 -0
  3. ioc_scope_api-1.0.0.dist-info/WHEEL +4 -0
  4. ioc_scope_api-1.0.0.dist-info/entry_points.txt +2 -0
  5. scope/__init__.py +27 -0
  6. scope/api/__init__.py +119 -0
  7. scope/api/api_v1/__init__.py +2 -0
  8. scope/api/api_v1/api.py +71 -0
  9. scope/api/api_v1/endpoints/__init__.py +2 -0
  10. scope/api/api_v1/endpoints/agentic_protocols_metrics.py +39 -0
  11. scope/api/api_v1/endpoints/applications.py +440 -0
  12. scope/api/api_v1/endpoints/cache.py +50 -0
  13. scope/api/api_v1/endpoints/concepts.py +123 -0
  14. scope/api/api_v1/endpoints/features.py +19 -0
  15. scope/api/api_v1/endpoints/helpers.py +65 -0
  16. scope/api/api_v1/endpoints/kg.py +195 -0
  17. scope/api/api_v1/endpoints/labels.py +71 -0
  18. scope/api/api_v1/endpoints/live_topology.py +89 -0
  19. scope/api/api_v1/endpoints/metrics.py +1014 -0
  20. scope/api/api_v1/endpoints/reasoning.py +62 -0
  21. scope/api/api_v1/endpoints/semanticgroups.py +144 -0
  22. scope/api/api_v1/endpoints/sessions.py +339 -0
  23. scope/api/api_v1/endpoints/spans.py +41 -0
  24. scope/api/api_v1/endpoints/symbolic.py +186 -0
  25. scope/api/api_v1/endpoints/ui.py +145 -0
  26. scope/api/api_v1/endpoints/waste_estimation.py +182 -0
  27. scope/api/api_v2/__init__.py +3 -0
  28. scope/api/api_v2/api.py +23 -0
  29. scope/api/api_v2/endpoints/__init__.py +3 -0
  30. scope/api/api_v2/endpoints/metrics.py +193 -0
  31. scope/app.py +30 -0
  32. scope/cache.py +64 -0
  33. scope/client/__init__.py +27 -0
  34. scope/client/_concepts.py +137 -0
  35. scope/client/_kg.py +64 -0
  36. scope/client/_labels.py +86 -0
  37. scope/client/_live_topology.py +912 -0
  38. scope/client/_metrics.py +561 -0
  39. scope/client/_semanticgroups.py +166 -0
  40. scope/client/_sessions.py +168 -0
  41. scope/client/_symbolic.py +1354 -0
  42. scope/client/_ui.py +599 -0
  43. scope/client/agentic_protocols.py +289 -0
  44. scope/client/application_charts.py +1786 -0
  45. scope/client/applications.py +2246 -0
  46. scope/client/base.py +49 -0
  47. scope/client/cognition_protocols.py +302 -0
  48. scope/client/constants.py +81 -0
  49. scope/client/dal.py +2382 -0
  50. scope/client/failures.py +70 -0
  51. scope/client/local.py +161 -0
  52. scope/client/mock/__init__.py +7 -0
  53. scope/client/mock/client.py +1034 -0
  54. scope/client/sessions.py +1688 -0
  55. scope/client/spans.py +95 -0
  56. scope/client/utils.py +392 -0
  57. scope/connectors/__init__.py +13 -0
  58. scope/connectors/base.py +52 -0
  59. scope/connectors/clickhouse.py +105 -0
  60. scope/connectors/neo4j.py +220 -0
  61. scope/connectors/sqlalchemy.py +131 -0
  62. scope/core/config.py +530 -0
  63. scope/core/exceptions.py +64 -0
  64. scope/dependencies.py +164 -0
  65. scope/health.py +10 -0
  66. scope/interfaces/__init__.py +33 -0
  67. scope/interfaces/data_provider.py +61 -0
  68. scope/interfaces/integration_example.py +310 -0
  69. scope/interfaces/kg_provider.py +91 -0
  70. scope/interfaces/metrics_provider.py +92 -0
  71. scope/interfaces/models.py +185 -0
  72. scope/models/kg.py +48 -0
  73. scope/models/live_topology.py +78 -0
  74. scope/models/otel_traces.py +1595 -0
  75. scope/providers/__init__.py +277 -0
  76. scope/providers/_graph.py +59 -0
  77. scope/providers/cognition_protocols.py +178 -0
  78. scope/providers/kg.py +702 -0
  79. scope/providers/kg_query_runner.py +109 -0
  80. scope/providers/neo4j_mce.py +18 -0
  81. scope/providers/scope_metrics.py +7 -0
  82. scope/query_builders/__init__.py +14 -0
  83. scope/query_builders/cognition_protocol_graph.py +191 -0
  84. scope/query_builders/concepts.py +112 -0
  85. scope/query_builders/dal.py +931 -0
  86. scope/query_builders/failure_graph.py +102 -0
  87. scope/query_builders/features.py +5 -0
  88. scope/query_builders/kg.py +416 -0
  89. scope/query_builders/labels.py +53 -0
  90. scope/query_builders/live_topology.py +503 -0
  91. scope/query_builders/metric_graph.py +196 -0
  92. scope/query_builders/metrics.py +354 -0
  93. scope/query_builders/semanticgroups.py +46 -0
  94. scope/query_builders/sessions.py +208 -0
  95. scope/query_builders/symbolic.py +615 -0
  96. scope/query_builders/trajectory.py +76 -0
  97. scope/query_builders/types.py +20 -0
  98. scope/query_builders/ui.py +3278 -0
  99. scope/query_builders/waste_estimation.py +221 -0
  100. scope/repositories/__init__.py +28 -0
  101. scope/repositories/clickhouse_otel_repository.py +135 -0
  102. scope/repositories/otel_repository.py +97 -0
  103. scope/repositories/sqlite_repository.py +215 -0
  104. scope/scripts/__init__.py +2 -0
  105. scope/scripts/seed.py +35 -0
  106. scope/workarounds.py +38 -0
@@ -0,0 +1,912 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Live topology methods for :class:`LocalClient`."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import logging
9
+ from datetime import datetime, timedelta, timezone
10
+ from uuid import uuid4
11
+
12
+ from scope.connectors.base import Connector
13
+ from scope.core.exceptions import DatabaseError
14
+ from scope.models.live_topology import (
15
+ LiveAgents,
16
+ LiveTopologySessions,
17
+ LiveTools,
18
+ RealtimeTopologyEdge,
19
+ RealtimeTopologyNode,
20
+ RealtimeTopologyResponse,
21
+ )
22
+ from scope.query_builders import live_topology as live_topology_queries
23
+ from scope.query_builders.types import Dialect
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ class LiveTopologyClient:
29
+ db: Connector
30
+ _dialect: Dialect
31
+
32
+ _ORPHAN_SESSION_IDLE_MINUTES = 5
33
+ # Skip re-emitting for the same session within this window even if the
34
+ # newly-written completion event isn't visible in the aggregate query yet.
35
+ _ORPHAN_EMISSION_DEDUPE_SECONDS = 300
36
+ # Bound the amount of write work triggered by a single /sessions request.
37
+ _MAX_ORPHAN_EMISSIONS_PER_CALL = 25
38
+
39
+ def _get_orphan_emission_cache(self) -> dict[str, datetime]:
40
+ """Lazily-initialised per-instance dedupe cache: session_id -> emit ts."""
41
+ cache = getattr(self, "_orphan_emission_cache", None)
42
+ if cache is None:
43
+ cache = {}
44
+ self._orphan_emission_cache = cache
45
+ return cache
46
+
47
+ @staticmethod
48
+ def _as_utc_datetime(value: object) -> datetime | None:
49
+ if value is None:
50
+ return None
51
+ if isinstance(value, datetime):
52
+ if value.tzinfo is None:
53
+ return value.replace(tzinfo=timezone.utc)
54
+ return value.astimezone(timezone.utc)
55
+
56
+ text = str(value).strip()
57
+ if not text:
58
+ return None
59
+ if text.endswith("Z"):
60
+ text = f"{text[:-1]}+00:00"
61
+
62
+ try:
63
+ parsed = datetime.fromisoformat(text)
64
+ if parsed.tzinfo is None:
65
+ return parsed.replace(tzinfo=timezone.utc)
66
+ return parsed.astimezone(timezone.utc)
67
+ except ValueError:
68
+ pass
69
+
70
+ for fmt in ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S"):
71
+ try:
72
+ return datetime.strptime(text, fmt).replace(tzinfo=timezone.utc)
73
+ except ValueError:
74
+ continue
75
+ return None
76
+
77
+ def _emit_synthetic_session_completed_event(
78
+ self, *, session_id: str
79
+ ) -> datetime | None:
80
+ """Insert a synthetic completion event; return its timestamp on success."""
81
+ now = datetime.now(tz=timezone.utc)
82
+
83
+ if self._dialect is Dialect.SQLITE:
84
+ payload = {
85
+ "session.id": session_id,
86
+ "synthetic": True,
87
+ "synthetic.reason": "orphan_session_no_recent_activity",
88
+ "synthetic.emitted_at": now.isoformat(),
89
+ }
90
+ command = """
91
+ INSERT INTO otel_logs (
92
+ timestamp,
93
+ span_id,
94
+ body,
95
+ log_attributes,
96
+ service_name,
97
+ duration,
98
+ resource_attributes,
99
+ scope_name,
100
+ event_name,
101
+ application_id,
102
+ agent_id
103
+ ) VALUES (
104
+ :timestamp,
105
+ :span_id,
106
+ :body,
107
+ :log_attributes,
108
+ :service_name,
109
+ :duration,
110
+ :resource_attributes,
111
+ :scope_name,
112
+ :event_name,
113
+ :application_id,
114
+ :agent_id
115
+ )
116
+ """
117
+ params = {
118
+ "timestamp": now.isoformat(),
119
+ "span_id": f"synthetic-{uuid4().hex}",
120
+ "body": "Synthetic topology.session.completed for orphan session",
121
+ "log_attributes": json.dumps(payload),
122
+ "service_name": "scope.live_topology",
123
+ "duration": 0,
124
+ "resource_attributes": "{}",
125
+ "scope_name": "scope.live_topology",
126
+ "event_name": "topology.session.completed",
127
+ "application_id": "",
128
+ "agent_id": "",
129
+ }
130
+ else:
131
+ command = """
132
+ INSERT INTO otel_logs (
133
+ Timestamp,
134
+ SpanId,
135
+ Body,
136
+ LogAttributes,
137
+ ServiceName,
138
+ ResourceAttributes,
139
+ ScopeName,
140
+ EventName
141
+ ) VALUES (
142
+ %(timestamp)s,
143
+ %(span_id)s,
144
+ %(body)s,
145
+ map(
146
+ 'session.id', %(session_id)s,
147
+ 'synthetic', 'true',
148
+ 'synthetic.reason', %(synthetic_reason)s,
149
+ 'synthetic.emitted_at', %(synthetic_emitted_at)s
150
+ ),
151
+ %(service_name)s,
152
+ map('service.name', %(service_name)s),
153
+ %(scope_name)s,
154
+ %(event_name)s
155
+ )
156
+ """
157
+ params = {
158
+ "timestamp": now,
159
+ "span_id": f"synthetic-{uuid4().hex}",
160
+ "body": "Synthetic topology.session.completed for orphan session",
161
+ "session_id": session_id,
162
+ "synthetic_reason": "orphan_session_no_recent_activity",
163
+ "synthetic_emitted_at": now.isoformat(),
164
+ "service_name": "scope.live_topology",
165
+ "scope_name": "scope.live_topology",
166
+ "event_name": "topology.session.completed",
167
+ }
168
+
169
+ try:
170
+ self.db.execute_command(command, params)
171
+ logger.info(
172
+ "Emitted synthetic topology.session.completed for orphan session '%s'",
173
+ session_id,
174
+ )
175
+ return now
176
+ except Exception as exc:
177
+ logger.warning(
178
+ "Failed to emit synthetic session completion for '%s': %s",
179
+ session_id,
180
+ exc,
181
+ )
182
+ return None
183
+
184
+ def _reconcile_orphan_sessions(self) -> dict[str, datetime]:
185
+ """Emit synthetic completions for stale orphan sessions.
186
+
187
+ Returns a mapping ``session_id -> completion_time`` for sessions
188
+ reconciled during this call. The caller uses this to patch the
189
+ in-memory sessions listing without an extra query round-trip.
190
+ """
191
+ stmt = live_topology_queries.get_orphan_live_topology_sessions(self._dialect)
192
+ try:
193
+ rows = self.db.execute(stmt)
194
+ except Exception as exc:
195
+ logger.warning("Failed orphan-session reconciliation lookup: %s", exc)
196
+ return {}
197
+
198
+ now = datetime.now(tz=timezone.utc)
199
+ idle_cutoff = now - timedelta(minutes=self._ORPHAN_SESSION_IDLE_MINUTES)
200
+ dedupe_cutoff = now - timedelta(seconds=self._ORPHAN_EMISSION_DEDUPE_SECONDS)
201
+ cache = self._get_orphan_emission_cache()
202
+ # Purge stale dedupe entries so the cache doesn't grow unbounded.
203
+ for stale_id in [sid for sid, ts in cache.items() if ts < dedupe_cutoff]:
204
+ cache.pop(stale_id, None)
205
+
206
+ reconciled: dict[str, datetime] = {}
207
+
208
+ for row in rows:
209
+ if len(reconciled) >= self._MAX_ORPHAN_EMISSIONS_PER_CALL:
210
+ logger.info(
211
+ "Orphan reconciliation cap (%d) reached; deferring remaining"
212
+ " orphans to the next call",
213
+ self._MAX_ORPHAN_EMISSIONS_PER_CALL,
214
+ )
215
+ break
216
+
217
+ session_id = str(row[0]) if row and row[0] else ""
218
+ if not session_id:
219
+ continue
220
+ if session_id in cache:
221
+ # Already emitted recently; skip until dedupe window elapses.
222
+ continue
223
+
224
+ last_activity = self._as_utc_datetime(row[1] if len(row) > 1 else None)
225
+ if last_activity is None:
226
+ continue
227
+ if last_activity > idle_cutoff:
228
+ continue
229
+
230
+ emitted_at = self._emit_synthetic_session_completed_event(
231
+ session_id=session_id
232
+ )
233
+ if emitted_at is not None:
234
+ reconciled[session_id] = emitted_at
235
+ cache[session_id] = emitted_at
236
+
237
+ return reconciled
238
+
239
+ # ── GET /sessions ─────────────────────────────────────────────────────
240
+
241
+ def get_live_topology_sessions(
242
+ self, *, application_name: str | None = None
243
+ ) -> LiveTopologySessions:
244
+ """Return live topology sessions."""
245
+ reconciled = self._reconcile_orphan_sessions()
246
+ stmt = live_topology_queries.get_live_topology_sessions(
247
+ self._dialect, application_name=application_name
248
+ )
249
+ try:
250
+ rows = self.db.execute(stmt)
251
+ except Exception as exc:
252
+ raise DatabaseError(f"Failed to get live topology sessions: {exc}") from exc
253
+
254
+ sessions: list[dict[str, object]] = []
255
+ for row in rows:
256
+ session_id = str(row[0]) if row[0] is not None else ""
257
+ has_completed = bool(row[2])
258
+ end_time_val = row[3]
259
+
260
+ if not has_completed and session_id in reconciled:
261
+ has_completed = True
262
+ if not end_time_val:
263
+ end_time_val = reconciled[session_id].isoformat()
264
+
265
+ sessions.append(
266
+ {
267
+ "session_id": row[0],
268
+ "start_time": str(row[1]),
269
+ "status": "completed" if has_completed else "active",
270
+ "end_time": str(end_time_val) if end_time_val else None,
271
+ }
272
+ )
273
+
274
+ return LiveTopologySessions(sessions=sessions)
275
+
276
+ # ── GET /agents ───────────────────────────────────────────────────────
277
+
278
+ def get_live_agents(self) -> LiveAgents:
279
+ """Return live topology agents."""
280
+ stmt = live_topology_queries.get_live_topology_agents(self._dialect)
281
+ try:
282
+ rows = self.db.execute(stmt)
283
+ except Exception as exc:
284
+ raise DatabaseError(f"Failed to get live topology agents: {exc}") from exc
285
+
286
+ def _to_int(value: object) -> int:
287
+ try:
288
+ return int(value) if value is not None else 0
289
+ except (TypeError, ValueError):
290
+ return 0
291
+
292
+ return LiveAgents(
293
+ agents=[
294
+ {
295
+ "agent_name": row[0],
296
+ "start_time": str(row[1]),
297
+ "status": (
298
+ "active" if _to_int(row[2]) > _to_int(row[3]) else "completed"
299
+ ),
300
+ "end_time": (
301
+ str(row[4])
302
+ if row[4] and _to_int(row[2]) <= _to_int(row[3])
303
+ else None
304
+ ),
305
+ }
306
+ for row in rows
307
+ ]
308
+ )
309
+
310
+ # ── GET /tools ────────────────────────────────────────────────────────
311
+
312
+ def get_live_tools(self) -> LiveTools:
313
+ """Return live topology tools."""
314
+ stmt = live_topology_queries.get_live_topology_tools(self._dialect)
315
+ try:
316
+ rows = self.db.execute(stmt)
317
+ except Exception as exc:
318
+ raise DatabaseError(f"Failed to get live topology tools: {exc}") from exc
319
+
320
+ def _to_int(value: object) -> int:
321
+ try:
322
+ return int(value) if value is not None else 0
323
+ except (TypeError, ValueError):
324
+ return 0
325
+
326
+ def _infer_tools_from_agent_input(
327
+ *, current_agent: str, payload: object
328
+ ) -> dict[str, dict[str, object]]:
329
+ """Infer tool details from an agent input payload."""
330
+ if not isinstance(payload, dict):
331
+ return {}
332
+
333
+ args = payload.get("args")
334
+ if not isinstance(args, list) or not args:
335
+ return {}
336
+
337
+ first_arg = args[0]
338
+ if not isinstance(first_arg, dict):
339
+ return {}
340
+
341
+ messages = first_arg.get("messages")
342
+ if not isinstance(messages, list) or not messages:
343
+ return {}
344
+
345
+ decision_index: int | None = None
346
+ for idx, msg in enumerate(messages):
347
+ if not isinstance(msg, dict):
348
+ continue
349
+ if str(msg.get("type") or "") != "AIMessage":
350
+ continue
351
+ content = msg.get("content")
352
+ if not isinstance(content, str):
353
+ continue
354
+ first_line = content.splitlines()[0].strip() if content else ""
355
+ if not first_line.startswith("DECISION:"):
356
+ continue
357
+ decided_agent = first_line.split("DECISION:", 1)[1].strip()
358
+ if decided_agent == current_agent:
359
+ decision_index = idx
360
+
361
+ if decision_index is None:
362
+ return {}
363
+
364
+ inferred: dict[str, dict[str, object]] = {}
365
+ for msg in messages[decision_index + 1 :]:
366
+ if not isinstance(msg, dict):
367
+ continue
368
+
369
+ msg_type = str(msg.get("type") or "")
370
+ if msg_type == "AIMessage":
371
+ content = msg.get("content")
372
+ if isinstance(content, str):
373
+ first_line = content.splitlines()[0].strip() if content else ""
374
+ if first_line.startswith("DECISION:"):
375
+ break
376
+
377
+ tool_calls = msg.get("tool_calls")
378
+ if isinstance(tool_calls, list):
379
+ for call in tool_calls:
380
+ if not isinstance(call, dict):
381
+ continue
382
+ name = str(call.get("name") or "")
383
+ if not name:
384
+ continue
385
+ inferred.setdefault(
386
+ name,
387
+ {
388
+ "status": "active",
389
+ },
390
+ )
391
+ elif msg_type == "ToolMessage":
392
+ name = str(msg.get("name") or "")
393
+ if name:
394
+ inferred.setdefault(name, {"status": "active"})
395
+ inferred[name]["status"] = "completed"
396
+
397
+ return inferred
398
+
399
+ if not rows:
400
+ fallback_stmt = (
401
+ live_topology_queries.get_live_topology_tool_inference_events(
402
+ self._dialect,
403
+ )
404
+ )
405
+ try:
406
+ fallback_rows = self.db.execute(fallback_stmt)
407
+ except Exception:
408
+ fallback_rows = []
409
+
410
+ inferred_by_tool: dict[str, dict] = {}
411
+ for row in fallback_rows:
412
+ agent_name = str(row[0]) if row[0] else ""
413
+ ts = str(row[1]) if row[1] else ""
414
+ raw_agent_input = row[2]
415
+
416
+ agent_input: object = None
417
+ if raw_agent_input:
418
+ try:
419
+ agent_input = json.loads(str(raw_agent_input))
420
+ except (json.JSONDecodeError, TypeError):
421
+ agent_input = str(raw_agent_input)
422
+
423
+ inferred_tools = _infer_tools_from_agent_input(
424
+ current_agent=agent_name,
425
+ payload=agent_input,
426
+ )
427
+
428
+ for tool_name, data in inferred_tools.items():
429
+ if not tool_name:
430
+ continue
431
+ if tool_name not in inferred_by_tool:
432
+ inferred_by_tool[tool_name] = {
433
+ "started_count": 0,
434
+ "completed_count": 0,
435
+ "start_time": ts,
436
+ "end_time": None,
437
+ }
438
+
439
+ inferred_by_tool[tool_name]["started_count"] += 1
440
+ if str(data.get("status") or "") == "completed":
441
+ inferred_by_tool[tool_name]["completed_count"] += 1
442
+ inferred_by_tool[tool_name]["end_time"] = ts
443
+
444
+ if ts and (
445
+ not inferred_by_tool[tool_name]["start_time"]
446
+ or ts > inferred_by_tool[tool_name]["start_time"]
447
+ ):
448
+ inferred_by_tool[tool_name]["start_time"] = ts
449
+
450
+ return LiveTools(
451
+ tools=[
452
+ {
453
+ "tool_name": tool_name,
454
+ "start_time": str(values["start_time"]),
455
+ "status": (
456
+ "active"
457
+ if _to_int(values["started_count"])
458
+ > _to_int(values["completed_count"])
459
+ else "completed"
460
+ ),
461
+ "end_time": (
462
+ str(values["end_time"])
463
+ if values["end_time"]
464
+ and _to_int(values["started_count"])
465
+ <= _to_int(values["completed_count"])
466
+ else None
467
+ ),
468
+ }
469
+ for tool_name, values in inferred_by_tool.items()
470
+ ]
471
+ )
472
+
473
+ return LiveTools(
474
+ tools=[
475
+ {
476
+ "tool_name": row[0],
477
+ "start_time": str(row[1]),
478
+ "status": (
479
+ "active" if _to_int(row[2]) > _to_int(row[3]) else "completed"
480
+ ),
481
+ "end_time": (
482
+ str(row[4])
483
+ if row[4] and _to_int(row[2]) <= _to_int(row[3])
484
+ else None
485
+ ),
486
+ }
487
+ for row in rows
488
+ ]
489
+ )
490
+
491
+ # ── GET /sessions/{session_id}/topology ─────────────────────────────
492
+
493
+ def get_realtime_topology(self, *, session_id: str) -> RealtimeTopologyResponse:
494
+ """Return a real-time topology graph built from ``otel_logs`` events.
495
+
496
+ Processes all topology events for the session in chronological order
497
+ to reconstruct agents (nodes), agent handoffs (edges), and tool
498
+ invocations, along with the live status of each.
499
+ """
500
+ stmt = live_topology_queries.get_topology_events_by_session(
501
+ self._dialect, session_id=session_id
502
+ )
503
+ try:
504
+ rows = self.db.execute(stmt)
505
+ except Exception as exc:
506
+ raise DatabaseError(
507
+ f"Failed to get topology events for session '{session_id}': {exc}"
508
+ ) from exc
509
+
510
+ if not rows:
511
+ return RealtimeTopologyResponse(session_id=session_id)
512
+
513
+ # ── Parse events chronologically ─────────────────────────────────
514
+ session_status: str = "unknown"
515
+
516
+ # agent_name -> tracking dict
517
+ agent_map: dict[str, dict] = {}
518
+ # tool_name -> tracking dict
519
+ tool_map: dict[str, dict] = {}
520
+ # edge_id -> edge dict (dedup by edge_id)
521
+ edge_map: dict[str, dict] = {}
522
+
523
+ # Stack of currently executing agents (for tool -> agent association)
524
+ active_agent_stack: list[str] = []
525
+
526
+ def _infer_tools_from_agent_input(
527
+ *, current_agent: str, payload: object
528
+ ) -> dict[str, dict[str, object]]:
529
+ """Infer tool details from agent input message history.
530
+
531
+ Returns a mapping of ``tool_name -> {status, input, output}``.
532
+ """
533
+ if not isinstance(payload, dict):
534
+ return {}
535
+
536
+ args = payload.get("args")
537
+ if not isinstance(args, list) or not args:
538
+ return {}
539
+
540
+ first_arg = args[0]
541
+ if not isinstance(first_arg, dict):
542
+ return {}
543
+
544
+ messages = first_arg.get("messages")
545
+ if not isinstance(messages, list) or not messages:
546
+ return {}
547
+
548
+ decision_index: int | None = None
549
+ for idx, msg in enumerate(messages):
550
+ if not isinstance(msg, dict):
551
+ continue
552
+ if str(msg.get("type") or "") != "AIMessage":
553
+ continue
554
+ content = msg.get("content")
555
+ if not isinstance(content, str):
556
+ continue
557
+ first_line = content.splitlines()[0].strip() if content else ""
558
+ if not first_line.startswith("DECISION:"):
559
+ continue
560
+ decided_agent = first_line.split("DECISION:", 1)[1].strip()
561
+ if decided_agent == current_agent:
562
+ decision_index = idx
563
+
564
+ if decision_index is None:
565
+ return {}
566
+
567
+ inferred: dict[str, dict[str, object]] = {}
568
+ pending_by_id: dict[str, dict[str, object]] = {}
569
+
570
+ def _normalize_input(raw: object) -> object:
571
+ if isinstance(raw, str):
572
+ try:
573
+ return json.loads(raw)
574
+ except (json.JSONDecodeError, TypeError):
575
+ return raw
576
+ return raw
577
+
578
+ def _extract_tool_calls(msg: dict) -> list[dict]:
579
+ tool_calls = msg.get("tool_calls")
580
+ if isinstance(tool_calls, list):
581
+ return [c for c in tool_calls if isinstance(c, dict)]
582
+
583
+ additional_kwargs = msg.get("additional_kwargs")
584
+ if isinstance(additional_kwargs, dict):
585
+ alt_calls = additional_kwargs.get("tool_calls")
586
+ if isinstance(alt_calls, list):
587
+ return [c for c in alt_calls if isinstance(c, dict)]
588
+
589
+ return []
590
+
591
+ def _extract_call_fields(call: dict) -> tuple[str, str, object]:
592
+ function_obj = call.get("function")
593
+ function_dict = function_obj if isinstance(function_obj, dict) else {}
594
+
595
+ name = str(call.get("name") or function_dict.get("name") or "")
596
+ call_id = str(call.get("id") or "")
597
+
598
+ raw_input = None
599
+ for key in (
600
+ "args",
601
+ "arguments",
602
+ "input",
603
+ "toolArguments",
604
+ "inputParams",
605
+ ):
606
+ if call.get(key) is not None:
607
+ raw_input = call.get(key)
608
+ break
609
+
610
+ if raw_input is None and function_dict.get("arguments") is not None:
611
+ raw_input = function_dict.get("arguments")
612
+
613
+ return name, call_id, _normalize_input(raw_input)
614
+
615
+ for msg in messages[decision_index + 1 :]:
616
+ if not isinstance(msg, dict):
617
+ continue
618
+
619
+ msg_type = str(msg.get("type") or "")
620
+ if msg_type == "AIMessage":
621
+ content = msg.get("content")
622
+ if isinstance(content, str):
623
+ first_line = content.splitlines()[0].strip() if content else ""
624
+ if first_line.startswith("DECISION:"):
625
+ break
626
+
627
+ for call in _extract_tool_calls(msg):
628
+ name, call_id, inferred_input = _extract_call_fields(call)
629
+ if not name:
630
+ continue
631
+
632
+ effective_input = inferred_input
633
+ if effective_input is None and call_id:
634
+ effective_input = {"tool_call_id": call_id}
635
+
636
+ inferred.setdefault(
637
+ name,
638
+ {
639
+ "status": "active",
640
+ "input": None,
641
+ "output": None,
642
+ },
643
+ )
644
+
645
+ if inferred[name].get("input") is None:
646
+ inferred[name]["input"] = effective_input
647
+
648
+ if call_id:
649
+ pending_by_id[call_id] = {
650
+ "name": name,
651
+ "input": inferred[name].get("input"),
652
+ }
653
+
654
+ elif msg_type == "ToolMessage":
655
+ name = str(msg.get("name") or "")
656
+ tool_call_id = str(msg.get("tool_call_id") or "")
657
+
658
+ if not name and tool_call_id:
659
+ pending = pending_by_id.get(tool_call_id)
660
+ if isinstance(pending, dict):
661
+ name = str(pending.get("name") or "")
662
+
663
+ if name:
664
+ inferred.setdefault(
665
+ name,
666
+ {
667
+ "status": "active",
668
+ "input": None,
669
+ "output": None,
670
+ },
671
+ )
672
+ if inferred[name].get("input") is None and tool_call_id:
673
+ pending = pending_by_id.get(tool_call_id)
674
+ if isinstance(pending, dict):
675
+ inferred[name]["input"] = pending.get("input")
676
+ else:
677
+ inferred[name]["input"] = {"tool_call_id": tool_call_id}
678
+ inferred[name]["status"] = "completed"
679
+ inferred[name]["output"] = msg.get("content")
680
+
681
+ return inferred
682
+
683
+ for row in rows:
684
+ event_name = str(row[0]) if row[0] else ""
685
+ agent_name = str(row[1]) if row[1] else ""
686
+ tool_name = str(row[2]) if row[2] else ""
687
+ source_agent = str(row[3]) if row[3] else ""
688
+ target_agent = str(row[4]) if row[4] else ""
689
+ ev_edge_id = str(row[5]) if row[5] else ""
690
+ ev_edge_kind = str(row[6]) if row[6] else ""
691
+ ts = str(row[8]) if row[8] else ""
692
+ raw_agent_input = row[9]
693
+ raw_tool_input = row[10]
694
+ raw_tool_output = row[11]
695
+
696
+ # Parse JSON input fields — they are stored as JSON strings
697
+ agent_input: object = None
698
+ if raw_agent_input:
699
+ try:
700
+ agent_input = json.loads(str(raw_agent_input))
701
+ except (json.JSONDecodeError, TypeError):
702
+ agent_input = str(raw_agent_input)
703
+
704
+ tool_input: object = None
705
+ if raw_tool_input:
706
+ try:
707
+ tool_input = json.loads(str(raw_tool_input))
708
+ except (json.JSONDecodeError, TypeError):
709
+ tool_input = str(raw_tool_input)
710
+
711
+ tool_output: object = None
712
+ if raw_tool_output:
713
+ try:
714
+ tool_output = json.loads(str(raw_tool_output))
715
+ except (json.JSONDecodeError, TypeError):
716
+ tool_output = str(raw_tool_output)
717
+
718
+ if event_name == "topology.session.started":
719
+ session_status = "active"
720
+
721
+ elif event_name == "topology.session.completed":
722
+ session_status = "completed"
723
+
724
+ elif event_name == "topology.node.started" and agent_name:
725
+ if agent_name not in agent_map:
726
+ agent_map[agent_name] = {
727
+ "status": "active",
728
+ "start_time": ts,
729
+ "end_time": None,
730
+ "tools": [],
731
+ "input": agent_input,
732
+ }
733
+ else:
734
+ # Agent re-entered (multiple invocations in session)
735
+ agent_map[agent_name]["status"] = "active"
736
+ agent_map[agent_name]["start_time"] = ts
737
+ agent_map[agent_name]["end_time"] = None
738
+ agent_map[agent_name]["input"] = agent_input
739
+ active_agent_stack.append(agent_name)
740
+
741
+ elif event_name == "topology.node.completed" and agent_name:
742
+ if agent_name not in agent_map:
743
+ agent_map[agent_name] = {
744
+ "status": "completed",
745
+ "start_time": None,
746
+ "end_time": ts,
747
+ "tools": [],
748
+ "input": None,
749
+ }
750
+ else:
751
+ agent_map[agent_name]["status"] = "completed"
752
+ agent_map[agent_name]["end_time"] = ts
753
+
754
+ # Pop last occurrence from active stack
755
+ for i in range(len(active_agent_stack) - 1, -1, -1):
756
+ if active_agent_stack[i] == agent_name:
757
+ active_agent_stack.pop(i)
758
+ break
759
+
760
+ elif (
761
+ event_name == "topology.edge.updated"
762
+ and ev_edge_id
763
+ and source_agent
764
+ and target_agent
765
+ ):
766
+ # Deduplicate by edge_id — keep first observed occurrence
767
+ if ev_edge_id not in edge_map:
768
+ edge_map[ev_edge_id] = {
769
+ "source": source_agent,
770
+ "target": target_agent,
771
+ "label": ev_edge_kind or "agent_handoff",
772
+ }
773
+
774
+ elif event_name == "tool.started" and tool_name:
775
+ cur_agent = active_agent_stack[-1] if active_agent_stack else None
776
+ if tool_name not in tool_map:
777
+ tool_map[tool_name] = {
778
+ "status": "active",
779
+ "start_time": ts,
780
+ "end_time": None,
781
+ "input": tool_input,
782
+ "output": None,
783
+ }
784
+ else:
785
+ tool_map[tool_name]["status"] = "active"
786
+ tool_map[tool_name]["start_time"] = ts
787
+ tool_map[tool_name]["end_time"] = None
788
+ if tool_input is not None:
789
+ tool_map[tool_name]["input"] = tool_input
790
+ # Associate tool with active agent and add a directed edge
791
+ if cur_agent and cur_agent in agent_map:
792
+ if tool_name not in agent_map[cur_agent]["tools"]:
793
+ agent_map[cur_agent]["tools"].append(tool_name)
794
+ # Add agent -> tool edge (dedup by composite key)
795
+ tool_edge_id = f"tool_invocation:{cur_agent}->{tool_name}"
796
+ if tool_edge_id not in edge_map:
797
+ edge_map[tool_edge_id] = {
798
+ "source": cur_agent,
799
+ "target": tool_name,
800
+ "label": "tool_invocation",
801
+ }
802
+
803
+ elif event_name == "tool.completed" and tool_name:
804
+ if tool_name not in tool_map:
805
+ tool_map[tool_name] = {
806
+ "status": "completed",
807
+ "start_time": None,
808
+ "end_time": ts,
809
+ "input": tool_input,
810
+ "output": tool_output,
811
+ }
812
+ else:
813
+ tool_map[tool_name]["status"] = "completed"
814
+ tool_map[tool_name]["end_time"] = ts
815
+ if (
816
+ tool_input is not None
817
+ and tool_map[tool_name].get("input") is None
818
+ ):
819
+ tool_map[tool_name]["input"] = tool_input
820
+ if tool_output is not None:
821
+ tool_map[tool_name]["output"] = tool_output
822
+
823
+ # Fallback: infer tool invocations from agent input payloads for traces
824
+ # where explicit tool.started/tool.completed events are not emitted.
825
+ for agent_name, data in agent_map.items():
826
+ inferred_tools = _infer_tools_from_agent_input(
827
+ current_agent=agent_name,
828
+ payload=data.get("input"),
829
+ )
830
+ for inferred_tool, inferred_data in inferred_tools.items():
831
+ if inferred_tool not in data["tools"]:
832
+ data["tools"].append(inferred_tool)
833
+
834
+ if inferred_tool not in tool_map:
835
+ tool_map[inferred_tool] = {
836
+ "status": str(inferred_data.get("status") or "active"),
837
+ "start_time": None,
838
+ "end_time": None,
839
+ "input": inferred_data.get("input"),
840
+ "output": inferred_data.get("output"),
841
+ }
842
+ elif (
843
+ str(inferred_data.get("status") or "") == "completed"
844
+ and tool_map[inferred_tool]["status"] != "completed"
845
+ ):
846
+ tool_map[inferred_tool]["status"] = "completed"
847
+ if (
848
+ inferred_data.get("input") is not None
849
+ and tool_map[inferred_tool].get("input") is None
850
+ ):
851
+ tool_map[inferred_tool]["input"] = inferred_data.get("input")
852
+ if inferred_data.get("output") is not None:
853
+ tool_map[inferred_tool]["output"] = inferred_data.get("output")
854
+
855
+ tool_edge_id = f"tool_invocation:{agent_name}->{inferred_tool}"
856
+ if tool_edge_id not in edge_map:
857
+ edge_map[tool_edge_id] = {
858
+ "source": agent_name,
859
+ "target": inferred_tool,
860
+ "label": "tool_invocation",
861
+ }
862
+
863
+ # ── Build response ────────────────────────────────────────────────
864
+ nodes: list[RealtimeTopologyNode] = []
865
+
866
+ for name, data in agent_map.items():
867
+ node_data: object = {
868
+ "input": data["input"],
869
+ "tools": data["tools"] or [],
870
+ }
871
+ nodes.append(
872
+ RealtimeTopologyNode(
873
+ id=name,
874
+ name=name,
875
+ type="agent",
876
+ status=data["status"],
877
+ start_time=data["start_time"],
878
+ end_time=data["end_time"],
879
+ data=node_data,
880
+ )
881
+ )
882
+
883
+ for name, data in tool_map.items():
884
+ node_data = {"input": data.get("input"), "output": data.get("output")}
885
+ nodes.append(
886
+ RealtimeTopologyNode(
887
+ id=name,
888
+ name=name,
889
+ type="tool",
890
+ status=data["status"],
891
+ start_time=data["start_time"],
892
+ end_time=data["end_time"],
893
+ data=node_data,
894
+ )
895
+ )
896
+
897
+ edges: list[RealtimeTopologyEdge] = [
898
+ RealtimeTopologyEdge(
899
+ source=e["source"],
900
+ target=e["target"],
901
+ label=e["label"],
902
+ )
903
+ for e in edge_map.values()
904
+ ]
905
+
906
+ return RealtimeTopologyResponse(
907
+ session_id=session_id,
908
+ session_status=session_status, # type: ignore[arg-type]
909
+ nodes=nodes,
910
+ edges=edges,
911
+ last_updated=datetime.now(tz=timezone.utc).isoformat(),
912
+ )