glowtrace 0.3.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.

Potentially problematic release.


This version of glowtrace might be problematic. Click here for more details.

glowtrace/otel.py ADDED
@@ -0,0 +1,542 @@
1
+ """OTLP traces → glowtrace graph events.
2
+
3
+ Understands the three span conventions agent frameworks actually emit:
4
+
5
+ * OpenTelemetry GenAI semantic conventions (gen_ai.*) — OpenLIT, OpenAI Agents SDK
6
+ exporters, Google ADK, Semantic Kernel, Pydantic AI / Logfire, Strands, …
7
+ * OpenInference (openinference.span.kind, llm.*, input.value) — Arize Phoenix
8
+ instrumentors for LangChain/LangGraph, LlamaIndex, CrewAI, DSPy, smolagents, …
9
+ * OpenLLMetry (traceloop.*, gen_ai.prompt.N.*) — Traceloop instrumentors.
10
+
11
+ Spans are usually exported when they *end*, so children arrive before their
12
+ parents. Unknown parents get a placeholder node (shown as running) that is
13
+ filled in when the real span arrives.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from dataclasses import dataclass, field
19
+ from typing import Any
20
+
21
+ MAX_TEXT = 20_000
22
+ ERROR = 2
23
+
24
+
25
+ @dataclass
26
+ class Span:
27
+ trace_id: str
28
+ span_id: str
29
+ parent_id: str
30
+ name: str
31
+ start: float
32
+ end: float | None
33
+ status: int = 0
34
+ status_msg: str = ""
35
+ attrs: dict = field(default_factory=dict)
36
+ resource: dict = field(default_factory=dict)
37
+ events: list = field(default_factory=list)
38
+
39
+
40
+ # ----------------------------------------------------------------- parsing
41
+ def _pb_value(v):
42
+ kind = v.WhichOneof("value")
43
+ if kind is None:
44
+ return None
45
+ if kind == "array_value":
46
+ return [_pb_value(x) for x in v.array_value.values]
47
+ if kind == "kvlist_value":
48
+ return {kv.key: _pb_value(kv.value) for kv in v.kvlist_value.values}
49
+ if kind == "bytes_value":
50
+ return v.bytes_value.hex()
51
+ return getattr(v, kind)
52
+
53
+
54
+ def parse_protobuf(body: bytes) -> list[Span]:
55
+ from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
56
+
57
+ req = ExportTraceServiceRequest()
58
+ req.ParseFromString(body)
59
+ out = []
60
+ for rs in req.resource_spans:
61
+ res = {kv.key: _pb_value(kv.value) for kv in rs.resource.attributes}
62
+ for ss in rs.scope_spans:
63
+ for s in ss.spans:
64
+ out.append(Span(
65
+ s.trace_id.hex(), s.span_id.hex(), s.parent_span_id.hex(), s.name,
66
+ s.start_time_unix_nano / 1e9, (s.end_time_unix_nano / 1e9) or None,
67
+ s.status.code, s.status.message,
68
+ {kv.key: _pb_value(kv.value) for kv in s.attributes}, res,
69
+ [{"name": e.name, **{kv.key: _pb_value(kv.value) for kv in e.attributes}} for e in s.events]))
70
+ return out
71
+
72
+
73
+ def _json_value(v: dict):
74
+ if not isinstance(v, dict):
75
+ return v
76
+ for k, x in v.items():
77
+ if k == "stringValue":
78
+ return x
79
+ if k == "intValue":
80
+ return int(x)
81
+ if k == "doubleValue":
82
+ return float(x)
83
+ if k == "boolValue":
84
+ return bool(x)
85
+ if k == "arrayValue":
86
+ return [_json_value(i) for i in x.get("values", [])]
87
+ if k == "kvlistValue":
88
+ return {kv["key"]: _json_value(kv.get("value", {})) for kv in x.get("values", [])}
89
+ if k == "bytesValue":
90
+ return x
91
+ return None
92
+
93
+
94
+ def _json_attrs(items) -> dict:
95
+ return {kv["key"]: _json_value(kv.get("value", {})) for kv in items or []}
96
+
97
+
98
+ def parse_json(doc: dict) -> list[Span]:
99
+ out = []
100
+ for rs in doc.get("resourceSpans", []):
101
+ res = _json_attrs(rs.get("resource", {}).get("attributes"))
102
+ for ss in rs.get("scopeSpans", rs.get("instrumentationLibrarySpans", [])):
103
+ for s in ss.get("spans", []):
104
+ code = s.get("status", {}).get("code", 0)
105
+ code = ERROR if code in (2, "STATUS_CODE_ERROR") else 0
106
+ end = int(s.get("endTimeUnixNano") or 0) / 1e9
107
+ out.append(Span(
108
+ s.get("traceId", ""), s.get("spanId", ""), s.get("parentSpanId", "") or "", s.get("name", ""),
109
+ int(s.get("startTimeUnixNano") or 0) / 1e9, end or None,
110
+ code, s.get("status", {}).get("message", ""),
111
+ _json_attrs(s.get("attributes")), res,
112
+ [{"name": e.get("name", ""), **_json_attrs(e.get("attributes"))} for e in s.get("events", [])]))
113
+ return out
114
+
115
+
116
+ # ----------------------------------------------------------------- helpers
117
+ def _first(a: dict, *keys):
118
+ for k in keys:
119
+ v = a.get(k)
120
+ if v not in (None, "", [], {}):
121
+ return v
122
+ return None
123
+
124
+
125
+ def _num(v) -> int:
126
+ try:
127
+ return int(float(v))
128
+ except (TypeError, ValueError):
129
+ return 0
130
+
131
+
132
+ def _text(v) -> str | None:
133
+ if v is None:
134
+ return None
135
+ if not isinstance(v, str):
136
+ v = json.dumps(v, indent=2, default=str, ensure_ascii=False)
137
+ else:
138
+ s = v.strip()
139
+ if s[:1] in "[{":
140
+ try:
141
+ v = json.dumps(json.loads(s), indent=2, ensure_ascii=False)
142
+ except ValueError:
143
+ pass
144
+ return v if len(v) <= MAX_TEXT else v[:MAX_TEXT] + "\n… (truncated)"
145
+
146
+
147
+ def _part_text(p) -> str:
148
+ if isinstance(p, str):
149
+ return p
150
+ if not isinstance(p, dict):
151
+ return str(p)
152
+ t = p.get("type")
153
+ if t == "tool_call":
154
+ return f"→ tool_call {p.get('name')}({json.dumps(p.get('arguments'), ensure_ascii=False, default=str)})"
155
+ if t == "tool_call_response":
156
+ return f"← tool result: {_part_text(p.get('response') or p.get('result') or '')}"
157
+ return str(p.get("content") or p.get("text") or json.dumps(p, ensure_ascii=False, default=str))
158
+
159
+
160
+ def _semconv_messages(raw) -> list[tuple[str, str]]:
161
+ """gen_ai.input.messages / gen_ai.output.messages (JSON string or list)."""
162
+ if isinstance(raw, str):
163
+ try:
164
+ raw = json.loads(raw)
165
+ except ValueError:
166
+ return [("message", raw)]
167
+ if isinstance(raw, dict):
168
+ raw = [raw]
169
+ out = []
170
+ for m in raw or []:
171
+ if not isinstance(m, dict):
172
+ out.append(("message", str(m)))
173
+ continue
174
+ parts = m.get("parts")
175
+ if parts is not None:
176
+ txt = "\n".join(_part_text(p) for p in parts)
177
+ else:
178
+ c = m.get("content")
179
+ txt = "\n".join(_part_text(p) for p in c) if isinstance(c, list) else str(c or "")
180
+ for tc in m.get("tool_calls") or []:
181
+ fn = tc.get("function", tc)
182
+ txt += f"\n→ tool_call {fn.get('name')}({fn.get('arguments')})"
183
+ out.append((m.get("role", "message"), txt.strip()))
184
+ return out
185
+
186
+
187
+ def _indexed(a: dict, prefix: str, role_key: str, content_key: str) -> list[tuple[str, str]]:
188
+ """Flattened lists: gen_ai.prompt.0.content, llm.input_messages.0.message.content, …"""
189
+ rows: dict[int, dict] = {}
190
+ for k, v in a.items():
191
+ if k.startswith(prefix):
192
+ idx, _, rest = k[len(prefix):].partition(".")
193
+ if idx.isdigit():
194
+ rows.setdefault(int(idx), {})[rest] = v
195
+ out = []
196
+ for _, d in sorted(rows.items()):
197
+ txt = str(d.get(content_key) or "")
198
+ names = sorted(k for k in d if k.endswith("function.name") or k.endswith("tool_call.name"))
199
+ for nk in names:
200
+ ak = nk.rsplit(".", 1)[0] + ".arguments"
201
+ txt += f"\n→ tool_call {d[nk]}({d.get(ak, '')})"
202
+ if txt.strip():
203
+ out.append((str(d.get(role_key) or "message"), txt.strip()))
204
+ return out
205
+
206
+
207
+ def _messages(a: dict, events: list, which: str) -> list[tuple[str, str]]:
208
+ if which == "input":
209
+ m = _first(a, "gen_ai.input.messages")
210
+ if m is not None:
211
+ return _semconv_messages(m)
212
+ return (_indexed(a, "gen_ai.prompt.", "role", "content")
213
+ or _indexed(a, "llm.input_messages.", "message.role", "message.content")
214
+ or [(e["name"].split(".")[1], str(e.get("content") or e.get("gen_ai.event.content") or ""))
215
+ for e in events if e.get("name", "").startswith("gen_ai.") and e["name"].endswith(".message")])
216
+ m = _first(a, "gen_ai.output.messages")
217
+ if m is not None:
218
+ return _semconv_messages(m)
219
+ return (_indexed(a, "gen_ai.completion.", "role", "content")
220
+ or _indexed(a, "llm.output_messages.", "message.role", "message.content")
221
+ or [("assistant", str(e.get("message") or e.get("content") or ""))
222
+ for e in events if e.get("name") == "gen_ai.choice"])
223
+
224
+
225
+ def _langchain_messages(v) -> str | None:
226
+ """LangChain/LangGraph state dumps ({"messages": [...]}) → readable "[human] …" text."""
227
+ if isinstance(v, str):
228
+ if '"messages"' not in v[:200] and '"data"' not in v[:200]:
229
+ return None
230
+ try:
231
+ v = json.loads(v)
232
+ except ValueError:
233
+ return None
234
+ if isinstance(v, dict) and isinstance(v.get("data"), dict) and "content" in v["data"]:
235
+ content = v["data"]["content"] # a single serialized message (e.g. a ToolMessage result)
236
+ return _text(content if isinstance(content, str) else json.dumps(content, ensure_ascii=False, default=str))
237
+ if not isinstance(v, dict) or not isinstance(v.get("messages"), list):
238
+ return None
239
+ rows = []
240
+ for m in v["messages"]:
241
+ if not isinstance(m, dict):
242
+ continue
243
+ data = m.get("data") if isinstance(m.get("data"), dict) else m
244
+ role = data.get("type") or m.get("type") or data.get("role") or "message"
245
+ content = data.get("content")
246
+ if isinstance(content, list):
247
+ content = "\n".join(_part_text(p) for p in content)
248
+ txt = str(content or "").strip()
249
+ for tc in data.get("tool_calls") or []:
250
+ txt += f"\n→ tool_call {tc.get('name')}({json.dumps(tc.get('args'), ensure_ascii=False, default=str)})"
251
+ if data.get("name") and role in ("ai", "tool"):
252
+ role = f"{role} · {data['name']}"
253
+ if txt.strip():
254
+ rows.append((str(role), txt.strip()))
255
+ return _fmt(rows) if rows else None
256
+
257
+
258
+ def _readable(v):
259
+ return _langchain_messages(v) or _text(v)
260
+
261
+
262
+ def _fmt(msgs: list[tuple[str, str]]) -> str | None:
263
+ if not msgs:
264
+ return None
265
+ if len(msgs) == 1 and msgs[0][0] in ("message", "assistant", "user"):
266
+ return _text(msgs[0][1])
267
+ return _text("\n\n".join(f"[{r}]\n{t}" for r, t in msgs))
268
+
269
+
270
+ # ----------------------------------------------------------------- mapping
271
+ GENAI_PREFIXES = ("gen_ai.", "llm.", "traceloop.", "openinference.", "glowtrace.", "embedding.", "retrieval.")
272
+
273
+
274
+ def classify(s: Span, all_spans: bool = False) -> str | None:
275
+ a = s.attrs
276
+ forced = str(a.get("glowtrace.kind", "")).lower()
277
+ if forced:
278
+ return forced
279
+ op = str(a.get("gen_ai.operation.name", "")).lower()
280
+ oi = str(a.get("openinference.span.kind", "")).upper()
281
+ tl = str(a.get("traceloop.span.kind", "")).lower()
282
+ if op in ("invoke_agent", "create_agent") or oi == "AGENT" or tl == "agent":
283
+ return "agent"
284
+ if op == "execute_tool" or oi == "TOOL" or tl == "tool":
285
+ return "tool"
286
+ if (op in ("chat", "text_completion", "generate_content", "embeddings", "completion")
287
+ or oi in ("LLM", "EMBEDDING") or "gen_ai.request.model" in a or "llm.model_name" in a):
288
+ return "llm"
289
+ if "gen_ai.tool.name" in a:
290
+ return "tool"
291
+ if "gen_ai.agent.name" in a:
292
+ return "agent"
293
+ if oi or tl or any(k.startswith(GENAI_PREFIXES) for k in a):
294
+ return "step"
295
+ return "step" if all_spans else None
296
+
297
+
298
+ def details(s: Span, kind: str) -> dict[str, Any]:
299
+ a = s.attrs
300
+ d: dict[str, Any] = {}
301
+ model = _first(a, "gen_ai.response.model", "gen_ai.request.model", "llm.model_name")
302
+ if model:
303
+ d["model"] = str(model)
304
+ tokens = (_num(_first(a, "gen_ai.usage.input_tokens", "gen_ai.usage.prompt_tokens", "llm.token_count.prompt"))
305
+ + _num(_first(a, "gen_ai.usage.output_tokens", "gen_ai.usage.completion_tokens", "llm.token_count.completion")))
306
+ tokens = tokens or _num(_first(a, "llm.token_count.total", "llm.usage.total_tokens"))
307
+ if tokens:
308
+ d["tokens"] = tokens
309
+
310
+ ins = _messages(a, s.events, "input")
311
+ system = _first(a, "gen_ai.system_instructions")
312
+ sys_msgs = [t for r, t in ins if r == "system"]
313
+ d["system"] = _text(system if system is not None else ("\n\n".join(sys_msgs) if sys_msgs else None))
314
+ d["input"] = _fmt([(r, t) for r, t in ins if r != "system"]) or _readable(
315
+ _first(a, "input.value", "traceloop.entity.input", "gen_ai.prompt"))
316
+ d["output"] = _fmt(_messages(a, s.events, "output")) or _readable(
317
+ _first(a, "output.value", "traceloop.entity.output", "gen_ai.completion"))
318
+
319
+ if kind == "tool":
320
+ d["args"] = _text(_first(a, "gen_ai.tool.call.arguments", "tool.parameters", "input.value", "traceloop.entity.input"))
321
+ d["result"] = _readable(_first(a, "gen_ai.tool.call.result", "output.value", "traceloop.entity.output"))
322
+ d.pop("input", None)
323
+ d.pop("output", None)
324
+ if kind == "agent":
325
+ role = _first(a, "gen_ai.agent.description")
326
+ if role:
327
+ d["role"] = str(role)[:120]
328
+
329
+ if s.status == ERROR:
330
+ exc = next((e for e in s.events if e.get("name") == "exception"), {})
331
+ d["note"] = str(exc.get("exception.type") or s.status_msg or "error")[:60]
332
+ msg = exc.get("exception.message") or s.status_msg
333
+ if msg:
334
+ d["result" if kind == "tool" else "output"] = _text(f"ERROR: {msg}")
335
+ d["attrs"] = {k: (v if len(str(v)) < 400 else str(v)[:400] + "…") for k, v in sorted(a.items())}
336
+ return {k: v for k, v in d.items() if v not in (None, "", {})}
337
+
338
+
339
+ def title_of(s: Span, kind: str) -> str:
340
+ a = s.attrs
341
+ if kind == "agent":
342
+ return str(_first(a, "gen_ai.agent.name", "agent.name", "traceloop.entity.name") or s.name)
343
+ if kind == "tool":
344
+ return str(_first(a, "gen_ai.tool.name", "tool.name", "traceloop.entity.name") or s.name)
345
+ if kind == "llm":
346
+ op = _first(a, "gen_ai.operation.name") or "llm"
347
+ model = _first(a, "gen_ai.response.model", "gen_ai.request.model", "llm.model_name")
348
+ return f"{op} · {model}" if model else s.name
349
+ return str(_first(a, "traceloop.entity.name", "graph.node.id", "langgraph.node") or s.name)
350
+
351
+
352
+ GENERIC_AGENT = {"agent", "agents", "agentexecutor", "agent executor"}
353
+ # framework wrappers that just call one sub-agent (langgraph-supervisor's call_agent, …)
354
+ WRAPPERS = {"call_agent", "acall_agent", "invoke_agent"}
355
+
356
+
357
+ def _explicit(s: Span) -> bool:
358
+ """Spans the user explicitly marked as a workflow stage — never collapse those."""
359
+ a = s.attrs
360
+ return bool(a.get("glowtrace.kind")) or str(a.get("traceloop.span.kind", "")).lower() in ("workflow", "task")
361
+
362
+
363
+ class Mapper:
364
+ """Stateful: turns a stream of spans (in any order, starts and/or ends) into graph events.
365
+
366
+ Compact mode (default) keeps what a human cares about — agents, LLM calls, tool
367
+ calls and the top-level stages of a workflow — and folds framework plumbing
368
+ (RunnableSequence, prompt templates, routers, HTTP calls …) into its parent.
369
+ """
370
+
371
+ def __init__(self, all_spans: bool = False, max_traces: int = 200):
372
+ self.all_spans = all_spans
373
+ self.max_traces = max_traces
374
+ self.traces: dict[str, dict] = {}
375
+
376
+ def ingest(self, spans: list[Span]) -> list[dict]:
377
+ events: list[dict] = []
378
+ for s in sorted(spans, key=lambda x: x.end or x.start): # chronological: starts and ends as they happened
379
+ events += self._one(s)
380
+ return [{k: v for k, v in e.items() if v is not None} for e in events]
381
+
382
+ # ---------------------------------------------------------------- state
383
+ def _state(self, s: Span, ev: list) -> dict:
384
+ st = self.traces.get(s.trace_id)
385
+ if st is None:
386
+ if len(self.traces) >= self.max_traces:
387
+ self.traces.pop(next(iter(self.traces)))
388
+ title = str(s.resource.get("service.name") or "")
389
+ st = self.traces[s.trace_id] = {
390
+ "sid": "trace-" + s.trace_id, "nodes": {}, "skip": {}, "root": None, "raw": {}, "names": {},
391
+ "promote": set(), "generic": {}, "ended": set(), "generic_title": not title or title.startswith("unknown_service")}
392
+ ev.append({"type": "node", "id": st["sid"], "kind": "session", "title": title if not st["generic_title"] else "trace",
393
+ "status": "running", "ts": s.start, "start_ts": s.start})
394
+ return st
395
+
396
+ def _resolve(self, st: dict, p: str, s: Span, ev: list) -> str:
397
+ """Display parent for raw parent id p (walks through folded spans, creates placeholders)."""
398
+ hops = 0
399
+ while p and hops < 64:
400
+ if p == st["root"]:
401
+ return st["sid"]
402
+ if p in st["nodes"]:
403
+ return p
404
+ if p in st["skip"]:
405
+ p, hops = st["skip"][p], hops + 1
406
+ continue
407
+ st["nodes"][p] = {"parent": st["sid"], "kind": "step", "chain": True}
408
+ ev.append({"type": "node", "id": p, "kind": "step", "title": "…", "parent": st["sid"],
409
+ "status": "running", "ts": s.start, "start_ts": s.start})
410
+ return p
411
+ return st["sid"]
412
+
413
+ def _fold(self, st: dict, nid: str, s: Span | None, ev: list):
414
+ """Remove a displayed node; its children move up to its (real) parent."""
415
+ raw_parent = st["raw"].get(nid, "")
416
+ if s is not None:
417
+ p = self._resolve(st, raw_parent, s, ev)
418
+ if st["nodes"][nid]["parent"] != p:
419
+ st["nodes"][nid]["parent"] = p
420
+ ev.append({"type": "node", "id": nid, "parent": p})
421
+ node = st["nodes"].pop(nid)
422
+ for c in st["nodes"].values():
423
+ if c["parent"] == nid:
424
+ c["parent"] = node["parent"]
425
+ st["skip"][nid] = raw_parent
426
+ ev.append({"type": "remove", "id": nid})
427
+
428
+ # ---------------------------------------------------------------- spans
429
+ def _one(self, s: Span) -> list[dict]:
430
+ ev: list[dict] = []
431
+ st = self._state(s, ev)
432
+ if s.end is not None:
433
+ # the same finished span can arrive twice (glowtrace.instrument + a normal exporter)
434
+ if s.span_id in st["ended"]:
435
+ return ev
436
+ st["ended"].add(s.span_id)
437
+ elif s.span_id in st["ended"]:
438
+ return ev # a late "start" for a span we already closed
439
+ st["names"][s.span_id] = s.name
440
+ st["raw"][s.span_id] = s.parent_id
441
+ running = s.end is None
442
+ compact = not self.all_spans
443
+
444
+ if not s.parent_id: # the trace root becomes the session itself
445
+ if st["root"] is None:
446
+ st["root"] = s.span_id
447
+ if s.span_id in st["nodes"]:
448
+ self._fold(st, s.span_id, None, ev)
449
+ if not running:
450
+ d = details(s, classify(s) or "step")
451
+ close = {"type": "update", "id": st["sid"], "status": "error" if s.status == ERROR else "done",
452
+ "ts": s.end, "end_ts": s.end, "output": d.get("output"), "input": d.get("input")}
453
+ if st["generic_title"]:
454
+ close["title"] = s.name
455
+ ev.append(close)
456
+ if compact:
457
+ self._compact(st, s, ev)
458
+ return ev
459
+
460
+ kind = classify(s, self.all_spans)
461
+
462
+ if running: # span start (from glowtrace.instrument): show it now, decide what it is later
463
+ if s.span_id in st["nodes"]:
464
+ return ev
465
+ parent = self._resolve(st, s.parent_id, s, ev)
466
+ k = kind or "step"
467
+ st["nodes"][s.span_id] = {"parent": parent, "kind": k, "chain": k == "step", "open": True, "title": title_of(s, k)}
468
+ ev.append({"type": "node", "id": s.span_id, "kind": k, "parent": parent, "title": title_of(s, k),
469
+ "status": "running", "ts": s.start, "start_ts": s.start})
470
+ if kind in ("agent", "llm", "tool"):
471
+ d = details(s, kind)
472
+ ev.append({"type": "message", "from": parent, "to": s.span_id, "ts": s.start,
473
+ "content": d.get("input") or d.get("args") or s.name})
474
+ return ev
475
+
476
+ # ---- span end
477
+ if kind is None: # plumbing: HTTP call, DB query … fold it away
478
+ if s.span_id in st["nodes"]:
479
+ self._fold(st, s.span_id, s, ev)
480
+ else:
481
+ st["skip"][s.span_id] = s.parent_id
482
+ return ev
483
+
484
+ title = title_of(s, kind)
485
+ # LangGraph-style prebuilt agents: a generic "agent" node inside a named sub-graph
486
+ # → the sub-graph *is* the agent; fold the generic node into it.
487
+ parent_name = st["names"].get(s.parent_id, "")
488
+ is_generic = compact and kind == "agent" and title.strip().lower() in GENERIC_AGENT and s.parent_id != st["root"]
489
+ if is_generic and not parent_name: # parent not seen yet: remember, decide when it ends
490
+ st["generic"].setdefault(s.parent_id, []).append(s.span_id)
491
+ if is_generic and parent_name and parent_name.lower() not in GENERIC_AGENT:
492
+ st["promote"].add(s.parent_id)
493
+ p = self._resolve(st, s.parent_id, s, ev)
494
+ if p == s.parent_id:
495
+ st["nodes"][p].update(kind="agent", chain=False, title=parent_name)
496
+ ev.append({"type": "node", "id": p, "kind": "agent", "title": parent_name})
497
+ if s.span_id in st["nodes"]:
498
+ self._fold(st, s.span_id, s, ev)
499
+ else:
500
+ st["skip"][s.span_id] = s.parent_id
501
+ return ev
502
+
503
+ late = st["generic"].pop(s.span_id, []) if s.name.lower() not in GENERIC_AGENT else []
504
+ if late:
505
+ st["promote"].add(s.span_id)
506
+ if s.span_id in st["promote"]:
507
+ kind, title = "agent", s.name
508
+ # a wrapper whose only child is the same thing one level down
509
+ # (step "researcher" → agent "researcher", or call_agent → agent): show the child only
510
+ if compact and kind in ("agent", "step") and s.span_id not in st["promote"] and not _explicit(s):
511
+ kids = [c for c, v in st["nodes"].items() if v["parent"] == s.span_id]
512
+ if len(kids) == 1 and st["nodes"][kids[0]]["kind"] in ("agent", "step"):
513
+ kid_title = st["nodes"][kids[0]].get("title", "")
514
+ if kid_title == title or title.lower() in WRAPPERS:
515
+ if s.span_id in st["nodes"]:
516
+ self._fold(st, s.span_id, s, ev)
517
+ else:
518
+ st["skip"][s.span_id] = s.parent_id
519
+ return ev
520
+ parent = self._resolve(st, s.parent_id, s, ev)
521
+ d = details(s, kind)
522
+ chain = kind == "step" and s.span_id not in st["promote"] and not _explicit(s)
523
+ st["nodes"][s.span_id] = {"parent": parent, "kind": kind, "chain": chain, "title": title}
524
+ ev.append({"type": "node", "id": s.span_id, "kind": kind, "parent": parent, "title": title,
525
+ "status": "error" if s.status == ERROR else "done",
526
+ "ts": s.end, "start_ts": s.start, "end_ts": s.end, **d})
527
+ for gid in late: # fold the generic "agent" nodes we kept earlier
528
+ if gid in st["nodes"]:
529
+ self._fold(st, gid, s, ev)
530
+ if compact and chain and st["root"] and s.parent_id != st["root"]:
531
+ self._fold(st, s.span_id, s, ev) # nested framework plumbing
532
+ return ev
533
+ content = d.get("output") or d.get("result") or f"{title} finished"
534
+ ev.append({"type": "message", "from": s.span_id, "to": parent, "ts": s.end, "content": content,
535
+ "label": "error" if s.status == ERROR else None, "tokens": d.get("tokens")})
536
+ return ev
537
+
538
+ def _compact(self, st: dict, root: Span, ev: list):
539
+ """Root just finished: fold every nested plumbing step we kept while the root was unknown."""
540
+ for nid in [n for n, v in st["nodes"].items() if v["chain"] and not v.get("open") and n not in st["promote"]]:
541
+ if nid in st["nodes"] and st["raw"].get(nid) not in (st["root"], None):
542
+ self._fold(st, nid, root, ev)
glowtrace/server.py ADDED
@@ -0,0 +1,133 @@
1
+ """One process, one port (4318 = the standard OTLP/HTTP port).
2
+
3
+ GET / the live UI
4
+ GET /ws event stream for browsers (and glowtrace.Tracer producers)
5
+ POST /v1/traces OTLP/HTTP traces, protobuf or JSON, optionally gzipped
6
+
7
+ Because 4318 is OpenTelemetry's default, anything already instrumented with
8
+ OTel shows up without changing a line of code.
9
+
10
+ With --token, only requests carrying it (?token=… or `Authorization: Bearer …`)
11
+ may send data; everyone else is a read-only viewer.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import gzip
17
+ import hmac
18
+ import json
19
+ from importlib import resources
20
+
21
+ from aiohttp import WSMsgType, web
22
+
23
+ from .otel import Mapper, parse_json, parse_protobuf
24
+
25
+ MAX_HISTORY = 20_000
26
+
27
+
28
+ class Hub:
29
+ def __init__(self, token: str | None = None, all_spans: bool = False):
30
+ self.token = token
31
+ self.clients: set[web.WebSocketResponse] = set()
32
+ self.history: list[str] = []
33
+ self.mapper = Mapper(all_spans=all_spans)
34
+ html = resources.files("glowtrace").joinpath("static/index.html").read_text("utf-8")
35
+ self.page = html.replace("<!--GLOWTRACE_CONFIG-->", '<script>window.GLOWTRACE_WS="/ws";</script>')
36
+
37
+ # ------------------------------------------------------------ auth
38
+ def authorized(self, req: web.Request) -> bool:
39
+ if not self.token:
40
+ return True
41
+ given = req.query.get("token") or req.headers.get("Authorization", "").removeprefix("Bearer ").strip()
42
+ return hmac.compare_digest(given, self.token)
43
+
44
+ # ------------------------------------------------------------ routes
45
+ async def index(self, _req):
46
+ return web.Response(text=self.page, content_type="text/html", headers={"Cache-Control": "no-cache"})
47
+
48
+ async def health(self, _req):
49
+ return web.json_response({"ok": True, "viewers": len(self.clients), "events": len(self.history)})
50
+
51
+ async def ws(self, req: web.Request):
52
+ ws = web.WebSocketResponse(heartbeat=25, max_msg_size=8 * 2**20)
53
+ await ws.prepare(req)
54
+ writer = self.authorized(req)
55
+ self.clients.add(ws)
56
+ try:
57
+ if self.history:
58
+ await ws.send_str("[" + ",".join(self.history) + "]")
59
+ async for m in ws:
60
+ if m.type != WSMsgType.TEXT or not writer:
61
+ continue
62
+ try:
63
+ data = json.loads(m.data)
64
+ except ValueError:
65
+ continue
66
+ events = data if isinstance(data, list) else [data]
67
+ self.publish([e for e in events if isinstance(e, dict)], exclude=ws)
68
+ finally:
69
+ self.clients.discard(ws)
70
+ return ws
71
+
72
+ async def otlp(self, req: web.Request):
73
+ if not self.authorized(req):
74
+ return web.Response(status=401, text="missing or wrong token")
75
+ body = await req.read()
76
+ if req.headers.get("Content-Encoding", "").lower() == "gzip":
77
+ body = gzip.decompress(body)
78
+ is_json = "json" in req.content_type
79
+ try:
80
+ spans = parse_json(json.loads(body)) if is_json else parse_protobuf(body)
81
+ except Exception as e: # malformed payload
82
+ return web.Response(status=400, text=f"could not parse OTLP payload: {e}")
83
+ self.publish(self.mapper.ingest(spans))
84
+ if is_json:
85
+ return web.json_response({})
86
+ return web.Response(body=b"", content_type="application/x-protobuf") # empty ExportTraceServiceResponse
87
+
88
+ # ------------------------------------------------------------ fan-out
89
+ def publish(self, events: list[dict], exclude=None):
90
+ if not events:
91
+ return
92
+ for e in events:
93
+ if e.get("type") == "reset":
94
+ self.history.clear()
95
+ self.history.append(json.dumps(e, default=str))
96
+ del self.history[:-MAX_HISTORY]
97
+ raw = json.dumps(events, default=str)
98
+ for c in list(self.clients):
99
+ if c is not exclude and not c.closed:
100
+ asyncio.ensure_future(c.send_str(raw))
101
+
102
+
103
+ @web.middleware
104
+ async def cors(request, handler):
105
+ if request.method == "OPTIONS":
106
+ resp = web.Response()
107
+ else:
108
+ resp = await handler(request)
109
+ resp.headers.update({"Access-Control-Allow-Origin": "*",
110
+ "Access-Control-Allow-Headers": "Content-Type, Content-Encoding, Authorization",
111
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS"})
112
+ return resp
113
+
114
+
115
+ def make_app(token: str | None = None, all_spans: bool = False) -> web.Application:
116
+ hub = Hub(token, all_spans)
117
+ app = web.Application(middlewares=[cors], client_max_size=32 * 2**20)
118
+ app["hub"] = hub
119
+ app.router.add_get("/", hub.index)
120
+ app.router.add_get("/index.html", hub.index)
121
+ app.router.add_get("/healthz", hub.health)
122
+ app.router.add_get("/ws", hub.ws)
123
+ app.router.add_post("/v1/traces", hub.otlp)
124
+ app.router.add_route("OPTIONS", "/v1/traces", hub.otlp)
125
+ return app
126
+
127
+
128
+ def run(host: str = "localhost", port: int = 4318, token: str | None = None, all_spans: bool = False):
129
+ shown = "localhost" if host in ("0.0.0.0", "") else host
130
+ print(f"\n glowtrace → http://{shown}:{port}\n"
131
+ f" OTLP in → http://{shown}:{port}/v1/traces"
132
+ f"{' (token required to send)' if token else ''}\n")
133
+ web.run_app(make_app(token, all_spans), host=host, port=port, print=None)