activeagents-telemetry 0.3.2 → 0.4.0

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d5c22b8b7c041a5278a6c6c2f948a1820ea54a099d2f4bac96445099da53ae1e
4
- data.tar.gz: 9d1bd15b970d51f40a37a6f252f7254d9527ac6af075d07290dfcebc92d78a85
3
+ metadata.gz: b372988b96a6aaab46aa1084a9bedf7deff4b05fab4e329a84382250ece37bbf
4
+ data.tar.gz: 8536ef74f22ba83db6191b98aac392725f973c6875ab9cf7d5ca06e37e75353f
5
5
  SHA512:
6
- metadata.gz: add8d0851e06f9930eb6e10ea6e26e23bbb5f2fc1b90f76a185746b3c0a786868273249d33efd078ab756baf796b932bac797cec340f6ddbdb7adb7ef3d8fd07
7
- data.tar.gz: fb490fc4977187a2160851693b8a13fcf5e6330b601911cc96a9354f080f80ed84deaf5b0662558478ecf4335f2b36d603c27a4310d237880348e60ce4650f0d
6
+ metadata.gz: 9c4e88a3c7b3bf00785f208c4a5ef6a4f48e742e45ab61e92bfd8ddc8e3aeffbea79ced2a0da357d36b2fc4d44a3ae954fa2c03762aa318d27055630051a7759
7
+ data.tar.gz: 0d465f8bfc6a7205f382bf9797c25a5bca7cfd6f00ccd1be8fc27024ef1a23689728f02b708f82939a8fbfda2c69d4863ffaecef1c3e7aa2dd9b667062cf9fa5
data/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.0] - 2026-12-02
4
+
5
+ ### Added
6
+
7
+ - OpenTelemetry (OTLP) support in the core gem, in both directions.
8
+ - `ActiveAgents::Telemetry::OTLP.decode(body, content_type:, content_encoding:)`
9
+ reads an OTLP/HTTP trace export, protobuf or JSON, gzipped or not, and
10
+ returns traces in the native wire format. It is what lets a dashboard's
11
+ ingest endpoint accept traces from any OpenTelemetry SDK. Spans are read by
12
+ the OpenTelemetry GenAI semantic conventions (`gen_ai.*`); the attribute
13
+ names older instrumentations and OpenInference use are accepted too. Each
14
+ span keeps the attributes it arrived with and gains the ones the dashboard
15
+ reads (`llm.model`, `tool.name`, ...). Spans that are not GenAI spans are
16
+ dropped unless `gen_ai_only: false` is passed.
17
+ - `ActiveAgents::Telemetry::OTLP::Assembler.merge(trace, spans)` adds spans
18
+ that arrived in a later request to a stored trace. An OpenTelemetry
19
+ exporter sends spans as they end, so one trace arrives over several
20
+ requests, children first.
21
+ - `config.protocol = :otlp` delivers traces as OTLP/HTTP JSON instead of the
22
+ native envelope, so an app can report to any OpenTelemetry collector or
23
+ vendor. `config.headers` adds request headers for collectors that
24
+ authenticate with something other than a Bearer token. With this protocol
25
+ an `api_key` is only required for the hosted platform's endpoint.
26
+ - The protobuf reader is written in Ruby against the (stable) OTLP trace
27
+ proto, so the gem still has no dependencies. The decoder is tested against
28
+ request bodies captured from the OpenTelemetry Python SDK.
29
+
30
+ Not covered: OTLP over gRPC, and OTLP metrics and logs.
31
+
32
+ The RubyLLM adapter is republished at 0.4.0 with no changes, so the two gems
33
+ stay on one version.
34
+
3
35
  ## [0.3.2] - 2026-09-22
4
36
 
5
37
  ### Added
data/README.md CHANGED
@@ -54,6 +54,52 @@ Prompts, completions, and tool arguments/results are sent only when
54
54
  `capture_bodies` is enabled (off by default). Error messages are truncated and
55
55
  backtraces are never transmitted.
56
56
 
57
+ ## OpenTelemetry
58
+
59
+ The core gem speaks OTLP, OpenTelemetry's wire protocol, over HTTP.
60
+
61
+ **Sending to a collector.** To report to an OpenTelemetry collector or a
62
+ vendor that takes OTLP, instead of an ActiveAgent dashboard:
63
+
64
+ ```ruby
65
+ ActiveAgents::Telemetry.configure do |config|
66
+ config.protocol = :otlp
67
+ config.endpoint = "http://localhost:4318/v1/traces"
68
+ config.headers = { "x-honeycomb-team" => ENV["HONEYCOMB_API_KEY"] } # if the collector needs one
69
+ end
70
+ ```
71
+
72
+ Spans are named and attributed by the
73
+ [GenAI semantic conventions](https://github.com/open-telemetry/semantic-conventions-genai)
74
+ (`chat gpt-4o`, `gen_ai.usage.input_tokens`, ...), with the native attributes
75
+ kept beside them. The body is OTLP/JSON.
76
+
77
+ **Receiving from any OpenTelemetry SDK.** An ActiveAgent dashboard
78
+ (actionagent 1.10 or later, and the hosted platform) accepts OTLP at its
79
+ trace endpoint, so an app in any language reports to it with its usual
80
+ OpenTelemetry exporter and no ActiveAgents gem:
81
+
82
+ ```bash
83
+ OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.activeagents.ai/v1/traces
84
+ OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer $ACTIVEAGENTS_API_KEY"
85
+ ```
86
+
87
+ The decoding behind that endpoint is `ActiveAgents::Telemetry::OTLP.decode`,
88
+ which any Rack app can call:
89
+
90
+ ```ruby
91
+ result = ActiveAgents::Telemetry::OTLP.decode(
92
+ request.body.read,
93
+ content_type: request.content_type, # application/x-protobuf or application/json
94
+ content_encoding: request.get_header("HTTP_CONTENT_ENCODING")
95
+ )
96
+ result.traces # => traces in the native wire format
97
+ ```
98
+
99
+ Only GenAI spans are kept by default: an app usually exports every span it
100
+ records, and a trace with no model call in it is dropped. OTLP over gRPC is
101
+ not supported; use the exporter's `http/protobuf` or `http/json` protocol.
102
+
57
103
  ## Self-hosting
58
104
 
59
105
  Point the endpoint at your mounted dashboard — same gems, same wire format.
@@ -34,7 +34,8 @@ module ActiveAgents
34
34
  :resource_attributes, :logger, :timeout, :open_timeout,
35
35
  :async, :sample_rate, :error_message_limit,
36
36
  :enabled, :batch_size, :flush_interval,
37
- :capture_bodies, :redact_attributes, :local_store
37
+ :capture_bodies, :redact_attributes, :local_store,
38
+ :protocol, :headers
38
39
 
39
40
  def initialize
40
41
  @enabled = true
@@ -54,13 +55,32 @@ module ActiveAgents
54
55
  @capture_bodies = false
55
56
  @redact_attributes = DEFAULT_REDACT_ATTRIBUTES.dup
56
57
  @local_store = nil
58
+ @protocol = :native
59
+ @headers = {}
60
+ end
61
+
62
+ # Whether traces are delivered as OTLP/HTTP JSON (`protocol = :otlp`)
63
+ # instead of the native envelope. Point `endpoint` at the collector's
64
+ # traces URL (for a local collector, "http://localhost:4318/v1/traces")
65
+ # and put whatever the collector authenticates with in `headers`; an
66
+ # `api_key`, when set, is still sent as a Bearer token.
67
+ def otlp?
68
+ protocol.to_s == "otlp"
57
69
  end
58
70
 
59
71
  # Traces are only sent when there is somewhere to send them: an endpoint
60
72
  # plus something to authenticate with, or a local store that bypasses
61
73
  # HTTP entirely.
62
74
  def configured?
63
- local_store? || (!endpoint.to_s.empty? && !api_key.to_s.empty?)
75
+ return true if local_store?
76
+ return false if endpoint.to_s.empty?
77
+
78
+ # A collector is often unauthenticated (a sidecar) or authenticated
79
+ # by a vendor header, so OTLP delivery to one does not require an
80
+ # api_key. The hosted platform always does.
81
+ return true if otlp? && endpoint != DEFAULT_ENDPOINT
82
+
83
+ !api_key.to_s.empty?
64
84
  end
65
85
 
66
86
  # An explicit kill-switch over and above configured?. Defaults to true —
@@ -130,6 +150,8 @@ module ActiveAgents
130
150
  {
131
151
  enabled: enabled,
132
152
  endpoint: endpoint,
153
+ protocol: protocol.to_s,
154
+ headers: (headers || {}).transform_values { "[REDACTED]" },
133
155
  api_key: api_key ? "[REDACTED]" : nil,
134
156
  service_name: resolved_service_name,
135
157
  environment: resolved_environment,
@@ -0,0 +1,145 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module ActiveAgents
6
+ module Telemetry
7
+ module OTLP
8
+ # Shapes the spans of one OTLP trace into what the dashboard expects of
9
+ # a trace: exactly one root, every other span reachable from it, and
10
+ # each token counted once.
11
+ #
12
+ # OpenTelemetry exports spans as they end, in batches, so one trace
13
+ # arrives over several requests and a parent usually arrives after its
14
+ # children. And because non-GenAI spans are filtered out, a kept span's
15
+ # parent may never arrive at all. So assembly is repeatable: store the
16
+ # result, and when more spans of the trace arrive call .merge with what
17
+ # is stored and what arrived.
18
+ module Assembler
19
+ SYNTHETIC = "otel.synthetic_root"
20
+
21
+ module_function
22
+
23
+ # @param trace [Hash] a native trace whose spans carry
24
+ # source_parent_span_id (the parent as the exporter reported it)
25
+ # @return [Hash] the trace with spans re-rooted and a timestamp
26
+ def assemble(trace)
27
+ spans = normalize(trace["spans"])
28
+ ids = spans.to_h { |span| [ span["span_id"], true ] }
29
+
30
+ spans.each do |span|
31
+ parent = span.key?("source_parent_span_id") ? span["source_parent_span_id"] : span["parent_span_id"]
32
+ span["parent_span_id"] = ids[parent] ? parent : nil
33
+ end
34
+
35
+ roll_up_tokens(spans)
36
+ tops = spans.select { |span| span["parent_span_id"].nil? }
37
+ if tops.size > 1
38
+ root = synthetic_root(trace, spans, tops)
39
+ tops.each { |span| span["parent_span_id"] = root["span_id"] }
40
+ spans.unshift(root)
41
+ end
42
+
43
+ trace.merge(
44
+ "spans" => spans,
45
+ "timestamp" => spans.filter_map { |span| span["end_time"] || span["start_time"] }.max || now
46
+ )
47
+ end
48
+
49
+ # The trace with +incoming+ spans added to it. A span that arrives
50
+ # twice (an exporter retrying a batch) replaces its earlier copy.
51
+ #
52
+ # @param trace [Hash] a trace as .assemble returned it
53
+ # @param incoming [Array<Hash>] spans of the same trace
54
+ def merge(trace, incoming)
55
+ assemble(trace.merge("spans" => Array(trace["spans"]) + Array(incoming)))
56
+ end
57
+
58
+ # Spans as string-keyed hashes, without an earlier synthetic root,
59
+ # one per span id, oldest first.
60
+ def normalize(spans)
61
+ Array(spans)
62
+ .select { |span| span.is_a?(Hash) }
63
+ .map { |span| span.transform_keys(&:to_s) }
64
+ .reject { |span| span.dig("attributes", SYNTHETIC) }
65
+ .each_with_object({}) { |span, by_id| by_id[span["span_id"]] = span }
66
+ .values
67
+ .sort_by { |span| span["start_time"].to_s }
68
+ end
69
+
70
+ # Two instrumentations often cover one model call (a framework's span
71
+ # around the provider SDK's), and each reports the usage. Count the
72
+ # innermost: a model span with a model span beneath it gives up its
73
+ # tokens.
74
+ def roll_up_tokens(spans)
75
+ by_id = spans.to_h { |span| [ span["span_id"], span ] }
76
+
77
+ spans.each do |span|
78
+ next unless span["type"] == "llm" && token_sum(span).positive?
79
+
80
+ ancestor = by_id[span["parent_span_id"]]
81
+ hops = 0
82
+ while ancestor && hops < 64
83
+ if ancestor["type"] == "llm" && token_sum(ancestor).positive?
84
+ ancestor["attributes"] = (ancestor["attributes"] || {}).merge("otel.usage.counted_on_child" => true)
85
+ ancestor["tokens"] = Span::ZERO_TOKENS.dup
86
+ end
87
+ ancestor = by_id[ancestor["parent_span_id"]]
88
+ hops += 1
89
+ end
90
+ end
91
+ end
92
+
93
+ def token_sum(span)
94
+ tokens = span["tokens"] || {}
95
+ tokens["input"].to_i + tokens["output"].to_i + tokens["thinking"].to_i
96
+ end
97
+
98
+ # Stands in for the application span the kept spans hung from. Its id
99
+ # is derived from the trace id, so reassembling yields the same span.
100
+ def synthetic_root(trace, spans, tops)
101
+ started = spans.filter_map { |span| span["start_time"] }.min
102
+ ended = spans.filter_map { |span| span["end_time"] }.max
103
+ failed = tops.find { |span| span["status"] == Span::ERROR }
104
+ agent = (tops + spans).filter_map { |span| span.dig("attributes", "agent.class") }.first
105
+
106
+ attributes = { SYNTHETIC => true }
107
+ attributes["agent.class"] = agent if agent
108
+ if failed
109
+ attributes["error.message"] = failed.dig("attributes", "error.message")
110
+ attributes["error.type"] = failed.dig("attributes", "error.type")
111
+ end
112
+
113
+ {
114
+ "span_id" => trace["trace_id"].to_s[0, 16],
115
+ "trace_id" => trace["trace_id"],
116
+ "parent_span_id" => nil,
117
+ "source_parent_span_id" => nil,
118
+ "name" => agent || trace["service_name"] || "trace",
119
+ "type" => "root",
120
+ "start_time" => started,
121
+ "end_time" => ended,
122
+ "duration_ms" => duration_ms(started, ended),
123
+ "status" => failed ? Span::ERROR : Span::OK,
124
+ "status_message" => failed && failed["status_message"],
125
+ "attributes" => attributes.compact,
126
+ "tokens" => Span::ZERO_TOKENS.dup,
127
+ "events" => []
128
+ }
129
+ end
130
+
131
+ def duration_ms(started, ended)
132
+ return nil unless started && ended
133
+
134
+ ((Time.iso8601(ended) - Time.iso8601(started)) * 1000).round(2)
135
+ rescue ArgumentError
136
+ nil
137
+ end
138
+
139
+ def now
140
+ Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%6N%:z")
141
+ end
142
+ end
143
+ end
144
+ end
145
+ end
@@ -0,0 +1,362 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+
6
+ module ActiveAgents
7
+ module Telemetry
8
+ module OTLP
9
+ # Turns an OTLP trace export (as the Hash OTLP/JSON describes) into
10
+ # traces in this gem's wire format, so anything that speaks OpenTelemetry
11
+ # can report to an ActiveAgent dashboard.
12
+ #
13
+ # Spans are read by the OpenTelemetry GenAI semantic conventions
14
+ # (gen_ai.* attributes), with the names older instrumentations and
15
+ # OpenInference use accepted as fallbacks. Each span keeps every
16
+ # attribute it arrived with; the keys the dashboard reads (llm.model,
17
+ # tool.name, ...) are added beside them.
18
+ #
19
+ # An application usually exports all of its spans, not only the model
20
+ # calls. By default only GenAI spans are kept, and a trace holding none
21
+ # is dropped; pass gen_ai_only: false to keep everything.
22
+ class Decoder
23
+ INFERENCE_OPERATIONS = %w[chat generate_content text_completion realtime_inference fetch_response].freeze
24
+ AGENT_OPERATIONS = %w[invoke_agent create_agent invoke_workflow plan].freeze
25
+
26
+ # OpenInference's openinference.span.kind values.
27
+ OPENINFERENCE_KINDS = {
28
+ "LLM" => "llm", "EMBEDDING" => "embedding", "TOOL" => "tool",
29
+ "AGENT" => "root", "CHAIN" => "root", "RETRIEVER" => "tool"
30
+ }.freeze
31
+
32
+ STATUS_CODES = {
33
+ 0 => Span::UNSET, 1 => Span::OK, 2 => Span::ERROR,
34
+ "STATUS_CODE_UNSET" => Span::UNSET, "STATUS_CODE_OK" => Span::OK, "STATUS_CODE_ERROR" => Span::ERROR
35
+ }.freeze
36
+
37
+ ERROR_MESSAGE_LIMIT = 500
38
+
39
+ Result = Struct.new(:traces, :sdk, :span_count, :dropped_span_count, keyword_init: true)
40
+
41
+ def initialize(gen_ai_only: true)
42
+ @gen_ai_only = gen_ai_only
43
+ end
44
+
45
+ # @param request [Hash] an ExportTraceServiceRequest
46
+ # @return [Result] traces in the native wire format, each already
47
+ # assembled (see Assembler), plus the SDK that produced them
48
+ def call(request)
49
+ raise DecodeError, "expected an object with resourceSpans" unless request.is_a?(Hash)
50
+
51
+ grouped = {}
52
+ sdk = nil
53
+ seen = 0
54
+ kept = 0
55
+
56
+ list(fetch(request, "resourceSpans")).each do |resource_spans|
57
+ next unless resource_spans.is_a?(Hash)
58
+
59
+ resource = attributes(fetch(resource_spans, "resource").then { |r| r.is_a?(Hash) ? fetch(r, "attributes") : nil })
60
+ sdk ||= sdk_info(resource)
61
+
62
+ list(fetch(resource_spans, "scopeSpans")).each do |scope_spans|
63
+ next unless scope_spans.is_a?(Hash)
64
+
65
+ scope = fetch(scope_spans, "scope")
66
+ scope_name = scope.is_a?(Hash) ? scope["name"].to_s : ""
67
+
68
+ list(fetch(scope_spans, "spans")).each do |raw|
69
+ next unless raw.is_a?(Hash)
70
+
71
+ seen += 1
72
+ span = translate(raw, scope_name)
73
+ next if span.nil?
74
+
75
+ kept += 1
76
+ trace = (grouped[span["trace_id"]] ||= new_trace(span["trace_id"], resource))
77
+ trace["spans"] << span
78
+ end
79
+ end
80
+ end
81
+
82
+ traces = grouped.values.map { |trace| Assembler.assemble(trace) }
83
+ Result.new(traces: traces, sdk: sdk || default_sdk, span_count: seen, dropped_span_count: seen - kept)
84
+ end
85
+
86
+ private
87
+
88
+ def new_trace(trace_id, resource)
89
+ {
90
+ "trace_id" => trace_id,
91
+ "service_name" => resource["service.name"]&.to_s,
92
+ "environment" => (resource["deployment.environment.name"] || resource["deployment.environment"])&.to_s,
93
+ "resource_attributes" => resource,
94
+ "format" => FORMAT,
95
+ "spans" => []
96
+ }
97
+ end
98
+
99
+ def sdk_info(resource)
100
+ return nil if resource["telemetry.sdk.name"].nil? && resource["telemetry.sdk.language"].nil?
101
+
102
+ {
103
+ "name" => (resource["telemetry.sdk.name"] || "opentelemetry").to_s,
104
+ "version" => resource["telemetry.sdk.version"]&.to_s,
105
+ "language" => resource["telemetry.sdk.language"]&.to_s,
106
+ "protocol" => FORMAT
107
+ }.compact
108
+ end
109
+
110
+ def default_sdk
111
+ { "name" => "opentelemetry", "protocol" => FORMAT }
112
+ end
113
+
114
+ # @return [Hash, nil] the span in the native wire format, or nil when
115
+ # it is malformed or filtered out
116
+ def translate(raw, scope_name)
117
+ trace_id = id(fetch(raw, "traceId"), 32)
118
+ span_id = id(fetch(raw, "spanId"), 16)
119
+ return nil if trace_id.nil? || span_id.nil?
120
+
121
+ attrs = attributes(fetch(raw, "attributes"))
122
+ type = attrs["activeagents.span.type"]&.to_s || type_of(attrs)
123
+ return nil if type.nil? && @gen_ai_only
124
+
125
+ started = time(fetch(raw, "startTimeUnixNano"))
126
+ ended = time(fetch(raw, "endTimeUnixNano"))
127
+ events = list(fetch(raw, "events")).grep(Hash).map { |event| translate_event(event) }
128
+ status, message = status_of(fetch(raw, "status"))
129
+ parent = id(fetch(raw, "parentSpanId"), 16)
130
+
131
+ name = (attrs.delete("activeagents.span.name") || raw["name"]).to_s
132
+ attrs.delete("activeagents.span.type")
133
+ attrs["otel.scope.name"] = scope_name unless scope_name.empty?
134
+ apply_aliases(type, attrs, raw["name"].to_s)
135
+ apply_error(attrs, message, events) if status == Span::ERROR
136
+
137
+ {
138
+ "span_id" => span_id,
139
+ "trace_id" => trace_id,
140
+ "parent_span_id" => parent,
141
+ "source_parent_span_id" => parent,
142
+ "name" => name,
143
+ "type" => type || "span",
144
+ "start_time" => started && iso8601(started),
145
+ "end_time" => ended && iso8601(ended),
146
+ "duration_ms" => started && ended ? ((ended - started) * 1000).round(2) : nil,
147
+ "status" => status,
148
+ "status_message" => message,
149
+ "attributes" => attrs,
150
+ "tokens" => %w[llm embedding].include?(type) ? tokens(attrs) : Span::ZERO_TOKENS.dup,
151
+ "events" => events
152
+ }
153
+ end
154
+
155
+ def translate_event(event)
156
+ at = time(fetch(event, "timeUnixNano"))
157
+ { "name" => event["name"].to_s, "timestamp" => at && iso8601(at), "attributes" => attributes(fetch(event, "attributes")) }
158
+ end
159
+
160
+ # Which native span type an OTel span is, or nil when it is not a
161
+ # GenAI span at all.
162
+ def type_of(attrs)
163
+ operation = attrs["gen_ai.operation.name"].to_s
164
+ return "llm" if INFERENCE_OPERATIONS.include?(operation)
165
+ return "embedding" if operation == "embeddings"
166
+ return "tool" if operation == "execute_tool"
167
+ return "root" if AGENT_OPERATIONS.include?(operation)
168
+
169
+ if (kind = OPENINFERENCE_KINDS[attrs["openinference.span.kind"].to_s.upcase])
170
+ return kind
171
+ end
172
+
173
+ return "tool" if attrs.key?("gen_ai.tool.name")
174
+ return "root" if attrs.key?("gen_ai.agent.name") || attrs.key?("gen_ai.agent.id")
175
+ # An unrecognised operation, or an instrumentation older than
176
+ # gen_ai.operation.name: a model was named, so it is a model call.
177
+ return "llm" if attrs.key?("gen_ai.request.model") || attrs.key?("gen_ai.response.model")
178
+ return "root" unless operation.empty?
179
+
180
+ nil
181
+ end
182
+
183
+ # Adds the attribute names the dashboard reads beside the OTel ones.
184
+ # Never overwrites a key the span already carried.
185
+ def apply_aliases(type, attrs, span_name)
186
+ case type
187
+ when "llm", "embedding"
188
+ put(attrs, "llm.provider", attrs["gen_ai.provider.name"] || attrs["gen_ai.system"])
189
+ put(attrs, "llm.model", attrs["gen_ai.response.model"] || attrs["gen_ai.request.model"] || attrs["llm.model_name"])
190
+ put(attrs, "llm.finish_reason", list(attrs["gen_ai.response.finish_reasons"]).first)
191
+ put(attrs, "llm.instructions", text_of(attrs["gen_ai.system_instructions"]))
192
+ put(attrs, "prompt.input.messages", input_messages(attrs["gen_ai.input.messages"]))
193
+ put(attrs, "llm.prompt", string(attrs["gen_ai.prompt"] || attrs["input.value"])) unless attrs.key?("prompt.input.messages")
194
+ put(attrs, "llm.output.message", output_text(attrs["gen_ai.output.messages"]) || string(attrs["gen_ai.completion"] || attrs["output.value"]))
195
+ when "tool"
196
+ put(attrs, "tool.name", attrs["gen_ai.tool.name"] || span_name.delete_prefix("execute_tool ").then { |n| n.empty? ? nil : n })
197
+ put(attrs, "tool.id", attrs["gen_ai.tool.call.id"])
198
+ put(attrs, "tool.call_id", attrs["gen_ai.tool.call.id"])
199
+ put(attrs, "tool.arguments", string(attrs["gen_ai.tool.call.arguments"] || attrs["input.value"]))
200
+ put(attrs, "tool.result", string(attrs["gen_ai.tool.call.result"] || attrs["output.value"]))
201
+ end
202
+
203
+ put(attrs, "agent.class", attrs["gen_ai.agent.name"])
204
+ end
205
+
206
+ def apply_error(attrs, message, events)
207
+ exception = events.find { |event| event["name"] == "exception" }&.fetch("attributes", nil) || {}
208
+ put(attrs, "error.type", exception["exception.type"])
209
+ text = message.to_s.empty? ? exception["exception.message"].to_s : message.to_s
210
+ text = attrs["error.type"].to_s if text.empty?
211
+ put(attrs, "error.message", truncate(text)) unless text.empty?
212
+ end
213
+
214
+ # gen_ai.usage.output_tokens includes reasoning tokens; the native
215
+ # format counts thinking separately, so it is taken back out.
216
+ def tokens(attrs)
217
+ input = integer(attrs["gen_ai.usage.input_tokens"] || attrs["gen_ai.usage.prompt_tokens"] || attrs["llm.token_count.prompt"])
218
+ output = integer(attrs["gen_ai.usage.output_tokens"] || attrs["gen_ai.usage.completion_tokens"] || attrs["llm.token_count.completion"])
219
+ thinking = [ integer(attrs["gen_ai.usage.reasoning.output_tokens"]), output ].min
220
+ output -= thinking
221
+ { "input" => input, "output" => output, "thinking" => thinking, "total" => input + output + thinking }
222
+ end
223
+
224
+ # gen_ai.input.messages as the JSON array of {role, content} the
225
+ # dashboard's conversation view reads.
226
+ def input_messages(value)
227
+ messages = list(structured(value)).grep(Hash).filter_map do |message|
228
+ content = text_of(message["parts"] || message["content"])
229
+ { "role" => (message["role"] || "user").to_s, "content" => content } if content
230
+ end
231
+ messages.empty? ? nil : JSON.generate(messages)
232
+ end
233
+
234
+ def output_text(value)
235
+ texts = list(structured(value)).grep(Hash).filter_map { |message| text_of(message["parts"] || message["content"]) }
236
+ texts.empty? ? nil : texts.join("\n")
237
+ end
238
+
239
+ # The text of a message's parts ([{type: "text", content: "..."}]),
240
+ # or of a plain string.
241
+ def text_of(value)
242
+ value = structured(value)
243
+ return (value.empty? ? nil : value) if value.is_a?(String)
244
+
245
+ texts = list(value).filter_map do |part|
246
+ next part if part.is_a?(String)
247
+ next unless part.is_a?(Hash) && part.fetch("type", "text").to_s == "text"
248
+
249
+ (part["content"] || part["text"])&.to_s
250
+ end
251
+ texts.reject(&:empty?).then { |found| found.empty? ? nil : found.join("\n") }
252
+ end
253
+
254
+ # Content attributes arrive either structured or as a JSON string,
255
+ # depending on the instrumentation.
256
+ def structured(value)
257
+ return value unless value.is_a?(String)
258
+
259
+ stripped = value.lstrip
260
+ return value unless stripped.start_with?("[", "{")
261
+
262
+ JSON.parse(value)
263
+ rescue JSON::ParserError
264
+ value
265
+ end
266
+
267
+ def string(value)
268
+ case value
269
+ when nil then nil
270
+ when String then value
271
+ else JSON.generate(value)
272
+ end
273
+ end
274
+
275
+ def put(attrs, key, value)
276
+ attrs[key] = value unless value.nil? || attrs.key?(key)
277
+ end
278
+
279
+ # A list of OTLP KeyValue ([{key, value: {stringValue: ...}}]) as a
280
+ # plain Hash.
281
+ def attributes(pairs)
282
+ list(pairs).each_with_object({}) do |pair, out|
283
+ next unless pair.is_a?(Hash) && pair["key"].is_a?(String)
284
+
285
+ out[pair["key"]] = any_value(pair["value"], 0)
286
+ end
287
+ end
288
+
289
+ def any_value(value, depth)
290
+ return nil unless value.is_a?(Hash)
291
+ raise DecodeError, "attribute value nested too deeply" if depth > Protobuf::MAX_VALUE_DEPTH
292
+
293
+ if value.key?("stringValue") then value["stringValue"].to_s
294
+ elsif value.key?("boolValue") then value["boolValue"] == true
295
+ elsif value.key?("intValue") then integer(value["intValue"])
296
+ elsif value.key?("doubleValue") then value["doubleValue"].to_f
297
+ elsif (array = fetch(value, "arrayValue"))
298
+ list(array.is_a?(Hash) ? array["values"] : nil).map { |item| any_value(item, depth + 1) }
299
+ elsif (map = fetch(value, "kvlistValue"))
300
+ list(map.is_a?(Hash) ? map["values"] : nil).each_with_object({}) do |pair, out|
301
+ out[pair["key"].to_s] = any_value(pair["value"], depth + 1) if pair.is_a?(Hash)
302
+ end
303
+ elsif value.key?("bytesValue") then value["bytesValue"].to_s
304
+ end
305
+ end
306
+
307
+ def status_of(status)
308
+ return [ Span::OK, nil ] unless status.is_a?(Hash)
309
+
310
+ code = STATUS_CODES.fetch(status["code"], Span::UNSET)
311
+ # OpenTelemetry leaves a successful span's status unset; natively
312
+ # a finished span is OK.
313
+ code = Span::OK if code == Span::UNSET
314
+ [ code, status["message"].to_s.empty? ? nil : truncate(status["message"].to_s) ]
315
+ end
316
+
317
+ # Ids are hex in OTLP/JSON. An all-zero or missing parent means none.
318
+ def id(value, length)
319
+ value = value.to_s.downcase
320
+ return nil unless value.match?(/\A\h{#{length}}\z/)
321
+ return nil if value.delete("0").empty?
322
+
323
+ value
324
+ end
325
+
326
+ def time(nanos)
327
+ nanos = integer(nanos)
328
+ nanos.positive? ? Time.at(nanos / 1_000_000_000, nanos % 1_000_000_000, :nsec).utc : nil
329
+ end
330
+
331
+ def iso8601(time)
332
+ time.strftime("%Y-%m-%dT%H:%M:%S.%6N%:z")
333
+ end
334
+
335
+ def integer(value)
336
+ case value
337
+ when Integer then value
338
+ when Float then value.finite? ? value.to_i : 0
339
+ when String then value.match?(/\A-?\d+\z/) ? value.to_i : 0
340
+ else 0
341
+ end
342
+ end
343
+
344
+ def truncate(string)
345
+ string.length > ERROR_MESSAGE_LIMIT ? "#{string[0, ERROR_MESSAGE_LIMIT - 1]}…" : string
346
+ end
347
+
348
+ def list(value)
349
+ value.is_a?(Array) ? value : []
350
+ end
351
+
352
+ # OTLP/JSON names fields in lowerCamelCase; receivers may also take
353
+ # the proto's snake_case names.
354
+ def fetch(hash, key)
355
+ return hash[key] if hash.key?(key)
356
+
357
+ hash[key.gsub(/[A-Z]/) { |letter| "_#{letter.downcase}" }]
358
+ end
359
+ end
360
+ end
361
+ end
362
+ end
@@ -0,0 +1,158 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+
6
+ module ActiveAgents
7
+ module Telemetry
8
+ module OTLP
9
+ # Writes traces in this gem's wire format as an OTLP/JSON
10
+ # ExportTraceServiceRequest, so they can be sent to any OpenTelemetry
11
+ # collector or vendor (see Configuration#protocol).
12
+ #
13
+ # Spans are named and attributed by the OpenTelemetry GenAI semantic
14
+ # conventions. The native attributes are kept beside the gen_ai.* ones,
15
+ # and the native span name and type travel as activeagents.span.*, so
16
+ # a dashboard that receives the export reads it back unchanged.
17
+ class Encoder
18
+ KIND_INTERNAL = 1
19
+ KIND_CLIENT = 3
20
+
21
+ STATUS_CODES = { Span::UNSET => 0, Span::OK => 1, Span::ERROR => 2 }.freeze
22
+ OPERATIONS = { "llm" => "chat", "embedding" => "embeddings", "tool" => "execute_tool" }.freeze
23
+ SCOPE = "activeagents-telemetry"
24
+
25
+ # @param traces [Array<Hash>] serialized traces (Trace#to_h)
26
+ # @param sdk [Hash] the reporter's sdk block ("name", "version")
27
+ # @return [Hash] { "resourceSpans" => [...] }
28
+ def call(traces, sdk: {})
29
+ {
30
+ "resourceSpans" => traces.map do |trace|
31
+ {
32
+ "resource" => { "attributes" => key_values(resource(trace, sdk)) },
33
+ "scopeSpans" => [ {
34
+ "scope" => { "name" => (sdk["name"] || SCOPE).to_s, "version" => sdk["version"].to_s },
35
+ "spans" => Array(trace["spans"]).map { |span| encode_span(span, trace) }
36
+ } ]
37
+ }
38
+ end
39
+ }
40
+ end
41
+
42
+ private
43
+
44
+ def resource(trace, sdk)
45
+ (trace["resource_attributes"] || {}).merge(
46
+ "service.name" => trace["service_name"],
47
+ "deployment.environment.name" => trace["environment"],
48
+ "telemetry.sdk.name" => (sdk["name"] || SCOPE).to_s,
49
+ "telemetry.sdk.version" => sdk["version"],
50
+ "telemetry.sdk.language" => "ruby"
51
+ ).compact
52
+ end
53
+
54
+ def encode_span(span, trace)
55
+ type = span["type"].to_s
56
+ attributes = gen_ai_attributes(type, span).merge(span["attributes"] || {})
57
+ attributes["activeagents.span.name"] = span["name"]
58
+ attributes["activeagents.span.type"] = type
59
+
60
+ {
61
+ "traceId" => span["trace_id"] || trace["trace_id"],
62
+ "spanId" => span["span_id"],
63
+ "parentSpanId" => span["parent_span_id"],
64
+ "name" => span_name(type, span, attributes),
65
+ "kind" => %w[llm embedding].include?(type) ? KIND_CLIENT : KIND_INTERNAL,
66
+ "startTimeUnixNano" => nanos(span["start_time"]),
67
+ "endTimeUnixNano" => nanos(span["end_time"] || span["start_time"]),
68
+ "attributes" => key_values(attributes),
69
+ "events" => Array(span["events"]).map { |event| encode_event(event) },
70
+ "status" => { "code" => STATUS_CODES.fetch(span["status"], 0), "message" => span["status_message"] }.compact
71
+ }.compact
72
+ end
73
+
74
+ def encode_event(event)
75
+ { "name" => event["name"].to_s, "timeUnixNano" => nanos(event["timestamp"]), "attributes" => key_values(event["attributes"] || {}) }
76
+ end
77
+
78
+ # The convention's attributes for a native span. Values the span
79
+ # already carries under a gen_ai.* key win in #encode_span.
80
+ def gen_ai_attributes(type, span)
81
+ native = span["attributes"] || {}
82
+ tokens = span["tokens"] || {}
83
+ out = {}
84
+
85
+ case type
86
+ when "llm", "embedding"
87
+ out["gen_ai.operation.name"] = OPERATIONS[type]
88
+ out["gen_ai.provider.name"] = native["llm.provider"] || native["agent.provider"]
89
+ out["gen_ai.request.model"] = native["llm.model"] || native["agent.model"]
90
+ out["gen_ai.response.finish_reasons"] = [ native["llm.finish_reason"] ] if native["llm.finish_reason"]
91
+ if tokens.values_at("input", "output", "thinking").any? { |count| count.to_i.positive? }
92
+ out["gen_ai.usage.input_tokens"] = tokens["input"].to_i
93
+ # The convention's output count includes reasoning tokens.
94
+ out["gen_ai.usage.output_tokens"] = tokens["output"].to_i + tokens["thinking"].to_i
95
+ out["gen_ai.usage.reasoning.output_tokens"] = tokens["thinking"].to_i if tokens["thinking"].to_i.positive?
96
+ end
97
+ when "tool"
98
+ out["gen_ai.operation.name"] = OPERATIONS[type]
99
+ out["gen_ai.tool.name"] = native["tool.name"] || span["name"].to_s.delete_prefix("tool.")
100
+ out["gen_ai.tool.call.id"] = native["tool.id"] || native["tool.call_id"]
101
+ out["gen_ai.tool.call.arguments"] = native["tool.input.args"] || native["tool.arguments"]
102
+ out["gen_ai.tool.call.result"] = native["tool.output.result"] || native["tool.result"]
103
+ when "root"
104
+ if native["agent.class"]
105
+ out["gen_ai.operation.name"] = "invoke_agent"
106
+ out["gen_ai.agent.name"] = native["agent.class"]
107
+ out["gen_ai.provider.name"] = native["agent.provider"]
108
+ out["gen_ai.request.model"] = native["agent.model"]
109
+ end
110
+ end
111
+
112
+ out["error.type"] = native["error.type"] || "_OTHER" if span["status"] == Span::ERROR
113
+ out.compact
114
+ end
115
+
116
+ # "{operation} {target}", as the conventions name GenAI spans.
117
+ def span_name(type, span, attributes)
118
+ operation = attributes["gen_ai.operation.name"]
119
+ target = case type
120
+ when "llm", "embedding" then attributes["gen_ai.request.model"]
121
+ when "tool" then attributes["gen_ai.tool.name"]
122
+ when "root" then attributes["gen_ai.agent.name"]
123
+ end
124
+ operation && target ? "#{operation} #{target}" : span["name"].to_s
125
+ end
126
+
127
+ def key_values(hash)
128
+ hash.filter_map do |key, value|
129
+ { "key" => key.to_s, "value" => any_value(value) } unless value.nil?
130
+ end
131
+ end
132
+
133
+ def any_value(value)
134
+ case value
135
+ when String then { "stringValue" => value }
136
+ when Symbol then { "stringValue" => value.to_s }
137
+ when true, false then { "boolValue" => value }
138
+ # int64 travels as a string in OTLP/JSON.
139
+ when Integer then { "intValue" => value.to_s }
140
+ when Float then { "doubleValue" => value }
141
+ when Array then { "arrayValue" => { "values" => value.map { |item| any_value(item) } } }
142
+ when Hash then { "kvlistValue" => { "values" => key_values(value) } }
143
+ else { "stringValue" => value.to_s }
144
+ end
145
+ end
146
+
147
+ def nanos(timestamp)
148
+ return nil if timestamp.nil?
149
+
150
+ time = timestamp.is_a?(Time) ? timestamp : Time.iso8601(timestamp.to_s)
151
+ (time.to_i * 1_000_000_000 + time.nsec).to_s
152
+ rescue ArgumentError
153
+ nil
154
+ end
155
+ end
156
+ end
157
+ end
158
+ end
@@ -0,0 +1,236 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveAgents
4
+ module Telemetry
5
+ module OTLP
6
+ # Reads an OTLP ExportTraceServiceRequest from its protobuf encoding into
7
+ # the same Hash shape OTLP/JSON uses (lowerCamelCase keys, hex ids), so
8
+ # one translator serves both encodings.
9
+ #
10
+ # Written by hand against opentelemetry/proto/trace/v1/trace.proto rather
11
+ # than generated: the trace messages are small and frozen (the proto is
12
+ # stable), and this keeps google-protobuf, a native extension, out of
13
+ # every app that only wants to send or receive traces. Unknown fields
14
+ # are skipped, as protobuf requires.
15
+ module Protobuf
16
+ VARINT = 0
17
+ FIXED64 = 1
18
+ BYTES = 2
19
+ FIXED32 = 5
20
+
21
+ # Nesting allowed inside one attribute value (arrays of maps of ...).
22
+ MAX_VALUE_DEPTH = 32
23
+
24
+ module_function
25
+
26
+ # @param bytes [String] the request body
27
+ # @return [Hash] { "resourceSpans" => [...] }
28
+ def decode_request(bytes)
29
+ resource_spans = []
30
+ each_field(bytes.b) do |number, type, value|
31
+ resource_spans << resource_spans(value) if number == 1 && type == BYTES
32
+ end
33
+ { "resourceSpans" => resource_spans }
34
+ end
35
+
36
+ def resource_spans(bytes)
37
+ out = { "scopeSpans" => [] }
38
+ each_field(bytes) do |number, type, value|
39
+ next unless type == BYTES
40
+
41
+ case number
42
+ when 1 then out["resource"] = resource(value)
43
+ when 2 then out["scopeSpans"] << scope_spans(value)
44
+ end
45
+ end
46
+ out
47
+ end
48
+
49
+ def resource(bytes)
50
+ attributes = []
51
+ each_field(bytes) do |number, type, value|
52
+ attributes << key_value(value, 0) if number == 1 && type == BYTES
53
+ end
54
+ { "attributes" => attributes }
55
+ end
56
+
57
+ def scope_spans(bytes)
58
+ out = { "spans" => [] }
59
+ each_field(bytes) do |number, type, value|
60
+ next unless type == BYTES
61
+
62
+ case number
63
+ when 1 then out["scope"] = scope(value)
64
+ when 2 then out["spans"] << span(value)
65
+ end
66
+ end
67
+ out
68
+ end
69
+
70
+ def scope(bytes)
71
+ out = {}
72
+ each_field(bytes) do |number, type, value|
73
+ next unless type == BYTES
74
+
75
+ case number
76
+ when 1 then out["name"] = text(value)
77
+ when 2 then out["version"] = text(value)
78
+ end
79
+ end
80
+ out
81
+ end
82
+
83
+ def span(bytes)
84
+ out = { "attributes" => [], "events" => [] }
85
+ each_field(bytes) do |number, type, value|
86
+ case [ number, type ]
87
+ when [ 1, BYTES ] then out["traceId"] = hex(value)
88
+ when [ 2, BYTES ] then out["spanId"] = hex(value)
89
+ when [ 4, BYTES ] then out["parentSpanId"] = hex(value)
90
+ when [ 5, BYTES ] then out["name"] = text(value)
91
+ when [ 6, VARINT ] then out["kind"] = value
92
+ when [ 7, FIXED64 ] then out["startTimeUnixNano"] = value
93
+ when [ 8, FIXED64 ] then out["endTimeUnixNano"] = value
94
+ when [ 9, BYTES ] then out["attributes"] << key_value(value, 0)
95
+ when [ 11, BYTES ] then out["events"] << event(value)
96
+ when [ 15, BYTES ] then out["status"] = status(value)
97
+ end
98
+ end
99
+ out
100
+ end
101
+
102
+ def event(bytes)
103
+ out = { "attributes" => [] }
104
+ each_field(bytes) do |number, type, value|
105
+ case [ number, type ]
106
+ when [ 1, FIXED64 ] then out["timeUnixNano"] = value
107
+ when [ 2, BYTES ] then out["name"] = text(value)
108
+ when [ 3, BYTES ] then out["attributes"] << key_value(value, 0)
109
+ end
110
+ end
111
+ out
112
+ end
113
+
114
+ def status(bytes)
115
+ out = {}
116
+ each_field(bytes) do |number, type, value|
117
+ case [ number, type ]
118
+ when [ 2, BYTES ] then out["message"] = text(value)
119
+ when [ 3, VARINT ] then out["code"] = value
120
+ end
121
+ end
122
+ out
123
+ end
124
+
125
+ def key_value(bytes, depth)
126
+ out = {}
127
+ each_field(bytes) do |number, type, value|
128
+ next unless type == BYTES
129
+
130
+ case number
131
+ when 1 then out["key"] = text(value)
132
+ when 2 then out["value"] = any_value(value, depth)
133
+ end
134
+ end
135
+ out
136
+ end
137
+
138
+ def any_value(bytes, depth)
139
+ raise DecodeError, "attribute value nested too deeply" if depth > MAX_VALUE_DEPTH
140
+
141
+ out = {}
142
+ each_field(bytes) do |number, type, value|
143
+ case [ number, type ]
144
+ when [ 1, BYTES ] then out = { "stringValue" => text(value) }
145
+ when [ 2, VARINT ] then out = { "boolValue" => value != 0 }
146
+ when [ 3, VARINT ] then out = { "intValue" => signed64(value) }
147
+ when [ 4, FIXED64 ] then out = { "doubleValue" => [ value ].pack("Q<").unpack1("E") }
148
+ when [ 5, BYTES ] then out = { "arrayValue" => { "values" => repeated(value) { |item| any_value(item, depth + 1) } } }
149
+ when [ 6, BYTES ] then out = { "kvlistValue" => { "values" => repeated(value) { |item| key_value(item, depth + 1) } } }
150
+ when [ 7, BYTES ] then out = { "bytesValue" => [ value ].pack("m0") }
151
+ end
152
+ end
153
+ out
154
+ end
155
+
156
+ # The elements of a message whose only field is `repeated X = 1`
157
+ # (ArrayValue, KeyValueList).
158
+ def repeated(bytes)
159
+ items = []
160
+ each_field(bytes) do |number, type, value|
161
+ items << yield(value) if number == 1 && type == BYTES
162
+ end
163
+ items
164
+ end
165
+
166
+ # Yields (field number, wire type, value) for each field in a message.
167
+ # A length-delimited value is yielded as its raw bytes.
168
+ def each_field(bytes)
169
+ position = 0
170
+ size = bytes.bytesize
171
+ while position < size
172
+ tag, position = varint(bytes, position)
173
+ number = tag >> 3
174
+ type = tag & 0x7
175
+ raise DecodeError, "invalid field number 0" if number.zero?
176
+
177
+ case type
178
+ when VARINT
179
+ value, position = varint(bytes, position)
180
+ when FIXED64
181
+ value = slice(bytes, position, 8).unpack1("Q<")
182
+ position += 8
183
+ when BYTES
184
+ length, position = varint(bytes, position)
185
+ value = slice(bytes, position, length)
186
+ position += length
187
+ when FIXED32
188
+ value = slice(bytes, position, 4).unpack1("L<")
189
+ position += 4
190
+ else
191
+ raise DecodeError, "unsupported wire type #{type}"
192
+ end
193
+ yield number, type, value
194
+ end
195
+ end
196
+
197
+ def varint(bytes, position)
198
+ result = 0
199
+ shift = 0
200
+ loop do
201
+ byte = bytes.getbyte(position)
202
+ raise DecodeError, "truncated varint" if byte.nil?
203
+ raise DecodeError, "varint too long" if shift > 63
204
+
205
+ position += 1
206
+ result |= (byte & 0x7f) << shift
207
+ return [ result & 0xffff_ffff_ffff_ffff, position ] if byte < 0x80
208
+
209
+ shift += 7
210
+ end
211
+ end
212
+
213
+ def slice(bytes, position, length)
214
+ raise DecodeError, "truncated field" if position + length > bytes.bytesize
215
+
216
+ bytes.byteslice(position, length)
217
+ end
218
+
219
+ def signed64(value)
220
+ value >= 0x8000_0000_0000_0000 ? value - 0x1_0000_0000_0000_0000 : value
221
+ end
222
+
223
+ def hex(bytes)
224
+ bytes.unpack1("H*")
225
+ end
226
+
227
+ # Strings on the wire are UTF-8; a reporter that sent something else
228
+ # gets it scrubbed rather than the whole request refused.
229
+ def text(bytes)
230
+ string = bytes.dup.force_encoding(Encoding::UTF_8)
231
+ string.valid_encoding? ? string : string.scrub("�")
232
+ end
233
+ end
234
+ end
235
+ end
236
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "stringio"
5
+ require "zlib"
6
+
7
+ module ActiveAgents
8
+ module Telemetry
9
+ # OpenTelemetry's wire protocol (OTLP) for traces, in both directions:
10
+ #
11
+ # OTLP.decode(body, content_type: "application/x-protobuf")
12
+ # # => traces in the native wire format, for an ingest endpoint
13
+ #
14
+ # OTLP.encode(traces)
15
+ # # => an OTLP/JSON request body, for any OpenTelemetry collector
16
+ #
17
+ # Only OTLP over HTTP is covered (protobuf and JSON bodies, optionally
18
+ # gzipped); OTLP over gRPC is not.
19
+ module OTLP
20
+ # Raised when a request body is not a readable OTLP trace export.
21
+ class DecodeError < StandardError; end
22
+
23
+ # Marks a trace or SDK block that came through OTLP.
24
+ FORMAT = "otlp"
25
+
26
+ PROTOBUF = "application/x-protobuf"
27
+ JSON_TYPE = "application/json"
28
+
29
+ # Largest body accepted after decompression.
30
+ MAX_BYTES = 32 * 1024 * 1024
31
+
32
+ class << self
33
+ # @param body [String] the request body
34
+ # @param content_type [String] application/x-protobuf or
35
+ # application/json (parameters such as charset are ignored)
36
+ # @param content_encoding [String, nil] "gzip" when the body is
37
+ # compressed
38
+ # @param gen_ai_only [Boolean] keep only GenAI spans (see Decoder)
39
+ # @return [Decoder::Result]
40
+ # @raise [DecodeError]
41
+ def decode(body, content_type: PROTOBUF, content_encoding: nil, gen_ai_only: true, max_bytes: MAX_BYTES)
42
+ body = inflate(body.to_s, content_encoding, max_bytes)
43
+ raise DecodeError, "body larger than #{max_bytes} bytes" if body.bytesize > max_bytes
44
+
45
+ decode_request(parse(body, content_type), gen_ai_only: gen_ai_only)
46
+ end
47
+
48
+ # @param request [Hash] an already-parsed OTLP/JSON request
49
+ # @return [Decoder::Result]
50
+ def decode_request(request, gen_ai_only: true)
51
+ Decoder.new(gen_ai_only: gen_ai_only).call(request)
52
+ rescue DecodeError
53
+ raise
54
+ rescue StandardError => e
55
+ raise DecodeError, "unreadable OTLP request: #{e.class}: #{e.message}"
56
+ end
57
+
58
+ # @param traces [Array<Hash, Trace>]
59
+ # @return [Hash] an OTLP/JSON ExportTraceServiceRequest
60
+ def encode(traces, sdk: {})
61
+ traces = [ traces ] unless traces.is_a?(Array)
62
+ Encoder.new.call(traces.map { |trace| trace.is_a?(Trace) ? trace.to_h : trace }, sdk: sdk)
63
+ end
64
+
65
+ # Whether a request is an OTLP trace export rather than the native
66
+ # {"traces": [...]} envelope.
67
+ def request?(content_type:, body: nil)
68
+ return true if media_type(content_type) == PROTOBUF
69
+
70
+ body.is_a?(Hash) && (body.key?("resourceSpans") || body.key?("resource_spans"))
71
+ end
72
+
73
+ def media_type(content_type)
74
+ content_type.to_s.split(";").first.to_s.strip.downcase
75
+ end
76
+
77
+ private
78
+
79
+ def parse(body, content_type)
80
+ case media_type(content_type)
81
+ when PROTOBUF
82
+ Protobuf.decode_request(body)
83
+ when JSON_TYPE, ""
84
+ JSON.parse(body)
85
+ else
86
+ raise DecodeError, "unsupported content type #{media_type(content_type).inspect}"
87
+ end
88
+ rescue JSON::ParserError => e
89
+ raise DecodeError, "invalid JSON: #{e.message}"
90
+ end
91
+
92
+ # Reads at most max_bytes + 1 of the decompressed body, so a small
93
+ # request cannot expand without bound.
94
+ def inflate(body, content_encoding, max_bytes)
95
+ case content_encoding.to_s.strip.downcase
96
+ when "", "identity"
97
+ body
98
+ when "gzip"
99
+ Zlib::GzipReader.new(StringIO.new(body)).read(max_bytes + 1).to_s
100
+ else
101
+ raise DecodeError, "unsupported content encoding #{content_encoding.inspect}"
102
+ end
103
+ rescue Zlib::Error => e
104
+ raise DecodeError, "invalid gzip body: #{e.message}"
105
+ end
106
+ end
107
+ end
108
+ end
109
+ end
110
+
111
+ require_relative "otlp/protobuf"
112
+ require_relative "otlp/assembler"
113
+ require_relative "otlp/decoder"
114
+ require_relative "otlp/encoder"
@@ -140,11 +140,12 @@ module ActiveAgents
140
140
 
141
141
  request = Net::HTTP::Post.new(uri.request_uri)
142
142
  request["Content-Type"] = "application/json"
143
- request["Authorization"] = "Bearer #{configuration.api_key}"
143
+ request["Authorization"] = "Bearer #{configuration.api_key}" unless configuration.api_key.to_s.empty?
144
144
  request["User-Agent"] = "#{@sdk_name}/#{@sdk_version} Ruby/#{RUBY_VERSION}"
145
145
  request["X-Service-Name"] = configuration.resolved_service_name.to_s
146
146
  request["X-Environment"] = configuration.resolved_environment.to_s
147
- request.body = JSON.generate(body)
147
+ (configuration.headers || {}).each { |name, value| request[name.to_s] = value.to_s }
148
+ request.body = JSON.generate(configuration.otlp? ? OTLP.encode(body["traces"], sdk: body["sdk"]) : body)
148
149
 
149
150
  response = http.request(request)
150
151
  log("ingest rejected traces: #{response.code} #{response.message}") unless response.is_a?(Net::HTTPSuccess)
@@ -2,6 +2,6 @@
2
2
 
3
3
  module ActiveAgents
4
4
  module Telemetry
5
- VERSION = "0.3.2"
5
+ VERSION = "0.4.0"
6
6
  end
7
7
  end
@@ -6,6 +6,7 @@ require_relative "telemetry/version"
6
6
  require_relative "telemetry/configuration"
7
7
  require_relative "telemetry/span"
8
8
  require_relative "telemetry/trace"
9
+ require_relative "telemetry/otlp"
9
10
  require_relative "telemetry/reporter"
10
11
  require_relative "telemetry/batching_reporter"
11
12
 
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: activeagents-telemetry
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.2
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - ActiveAgents
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-07 00:00:00.000000000 Z
11
+ date: 2026-12-02 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: |
14
14
  The wire format, configuration, and delivery layer behind ActiveAgents
@@ -28,6 +28,11 @@ files:
28
28
  - lib/activeagents/telemetry.rb
29
29
  - lib/activeagents/telemetry/batching_reporter.rb
30
30
  - lib/activeagents/telemetry/configuration.rb
31
+ - lib/activeagents/telemetry/otlp.rb
32
+ - lib/activeagents/telemetry/otlp/assembler.rb
33
+ - lib/activeagents/telemetry/otlp/decoder.rb
34
+ - lib/activeagents/telemetry/otlp/encoder.rb
35
+ - lib/activeagents/telemetry/otlp/protobuf.rb
31
36
  - lib/activeagents/telemetry/reporter.rb
32
37
  - lib/activeagents/telemetry/span.rb
33
38
  - lib/activeagents/telemetry/trace.rb