agentcat 0.0.1 → 1.1.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.
Files changed (51) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +2 -11
  3. data/README.md +265 -20
  4. data/lib/agentcat/adapters/base.rb +98 -0
  5. data/lib/agentcat/adapters/official.rb +277 -0
  6. data/lib/agentcat/client.rb +189 -0
  7. data/lib/agentcat/clock.rb +16 -0
  8. data/lib/agentcat/custom_event.rb +215 -0
  9. data/lib/agentcat/delivery.rb +58 -0
  10. data/lib/agentcat/diagnostics.rb +434 -0
  11. data/lib/agentcat/error_capture.rb +117 -0
  12. data/lib/agentcat/event_id.rb +19 -0
  13. data/lib/agentcat/event_pipeline.rb +82 -0
  14. data/lib/agentcat/event_queue.rb +151 -0
  15. data/lib/agentcat/exporters/base.rb +135 -0
  16. data/lib/agentcat/exporters/datadog.rb +137 -0
  17. data/lib/agentcat/exporters/otlp.rb +157 -0
  18. data/lib/agentcat/exporters/posthog.rb +185 -0
  19. data/lib/agentcat/exporters/sentry.rb +242 -0
  20. data/lib/agentcat/exporters/trace_context.rb +79 -0
  21. data/lib/agentcat/exporters.rb +108 -0
  22. data/lib/agentcat/fork_safety.rb +30 -0
  23. data/lib/agentcat/hooks.rb +190 -0
  24. data/lib/agentcat/http_post.rb +61 -0
  25. data/lib/agentcat/interceptor.rb +728 -0
  26. data/lib/agentcat/log.rb +80 -0
  27. data/lib/agentcat/options.rb +313 -0
  28. data/lib/agentcat/payload_limits.rb +71 -0
  29. data/lib/agentcat/private_members.rb +286 -0
  30. data/lib/agentcat/redaction.rb +176 -0
  31. data/lib/agentcat/rejected_calls.rb +147 -0
  32. data/lib/agentcat/request_context.rb +266 -0
  33. data/lib/agentcat/sanitization.rb +191 -0
  34. data/lib/agentcat/schema/prompts.rb +44 -0
  35. data/lib/agentcat/server_info.rb +280 -0
  36. data/lib/agentcat/session_manager.rb +83 -0
  37. data/lib/agentcat/tags.rb +61 -0
  38. data/lib/agentcat/test_mode.rb +86 -0
  39. data/lib/agentcat/testing.rb +153 -0
  40. data/lib/agentcat/text.rb +68 -0
  41. data/lib/agentcat/token_estimate.rb +98 -0
  42. data/lib/agentcat/tool_call.rb +129 -0
  43. data/lib/agentcat/tool_handle.rb +289 -0
  44. data/lib/agentcat/tracker.rb +204 -0
  45. data/lib/agentcat/truncation.rb +265 -0
  46. data/lib/agentcat/unredacted_event.rb +155 -0
  47. data/lib/agentcat/user_identity.rb +11 -0
  48. data/lib/agentcat/version.rb +2 -2
  49. data/lib/agentcat.rb +393 -21
  50. metadata +194 -16
  51. data/agentcat.gemspec +0 -30
@@ -0,0 +1,277 @@
1
+ # typed: true
2
+
3
+ require "json"
4
+ require_relative "base"
5
+ require_relative "../tool_handle"
6
+ require_relative "../rejected_calls"
7
+
8
+ module AgentCat
9
+ module Adapters
10
+ # Adapter for the official `mcp` gem (`MCP::Server`).
11
+ class Official < Base
12
+ extend T::Sig
13
+
14
+ sig { params(server: T.untyped).returns(T::Boolean) }
15
+ def self.supports?(server)
16
+ !!(defined?(::MCP::Server) && server.is_a?(::MCP::Server))
17
+ end
18
+
19
+ sig { returns(T::Hash[Symbol, T.untyped]) }
20
+ def server_info
21
+ {name: @server.name, version: @server.version}
22
+ end
23
+
24
+ sig { returns(T::Array[AgentCat::ToolHandle]) }
25
+ def tool_handles
26
+ tools = tools_hash
27
+ return [] if tools.nil?
28
+
29
+ tools.keys.filter_map { |name| wrap(name) }
30
+ end
31
+
32
+ sig do
33
+ params(
34
+ name: String,
35
+ call_fn: T.untyped,
36
+ description: T.nilable(String),
37
+ input_schema: T.untyped,
38
+ output_schema: T.untyped,
39
+ annotations: T.untyped
40
+ ).returns(T.nilable(AgentCat::ToolHandle))
41
+ end
42
+ def register_tool(name:, call_fn:, description: nil, input_schema: nil, output_schema: nil, annotations: nil)
43
+ tools = tools_hash
44
+ return nil if tools.nil?
45
+ return wrap(name) if tools.key?(name)
46
+
47
+ @server.define_tool(name: name, description: description, input_schema: input_schema, output_schema: output_schema, annotations: annotations) do |server_context: nil, **arguments|
48
+ call_fn.call(arguments.transform_keys(&:to_s), server_context)
49
+ end
50
+ wrap(name)
51
+ end
52
+
53
+ # MCP::Server has no public "before dispatch" hook, so this wraps handle (most
54
+ # transports) and handle_json (streamable HTTP's legacy path) to run sync first —
55
+ # only when needs_sync? says it's actually needed, so the common case (a tool
56
+ # we've already wrapped) skips the extra work. Safe to call once: track() already
57
+ # guards against tracking the same server twice.
58
+ sig { params(sync: T.proc.void).void }
59
+ def before_dispatch(&sync)
60
+ wrap_dispatch_method(AgentCat::PrivateMembers::SERVER_HANDLE, &sync)
61
+ wrap_dispatch_method(AgentCat::PrivateMembers::SERVER_HANDLE_JSON, &sync)
62
+ end
63
+
64
+ sig { void }
65
+ def watch_rejected_calls
66
+ AgentCat::RejectedCalls.install(@server)
67
+ end
68
+
69
+ sig { params(name: T.untyped).returns(T.untyped) }
70
+ def tool_named(name)
71
+ tools_hash&.[](name)
72
+ end
73
+
74
+ sig { params(block: T.proc.void).void }
75
+ def on_tools_list(&block)
76
+ @on_tools_list = T.let(block, T.nilable(T.proc.void))
77
+ end
78
+
79
+ # The gem's own handler from `@handlers`, called the way its dispatch calls it: with
80
+ # `server_context:` only when the handler declares that keyword. nil when the
81
+ # server's capabilities turn the request away, as the gem does over the wire.
82
+ sig { params(method: String).returns(T.untyped) }
83
+ def list_handler(method)
84
+ member = AgentCat::PrivateMembers::SERVER_HANDLERS
85
+ return nil unless AgentCat::PrivateMembers.enabled?(member.feature)
86
+ return nil unless answers?(method)
87
+
88
+ handlers = @server.instance_variable_get(member.name.to_sym)
89
+ handler = handlers.is_a?(Hash) ? handlers[method] : nil
90
+ return nil unless handler.respond_to?(:call)
91
+
92
+ if declares_server_context?(handler)
93
+ ->(params, server_context) { handler.call(params, server_context: server_context) }
94
+ else
95
+ ->(params, _server_context) { handler.call(params) }
96
+ end
97
+ end
98
+
99
+ sig { returns(String) }
100
+ def server_title
101
+ @server.title.to_s
102
+ end
103
+
104
+ sig { returns(String) }
105
+ def instructions
106
+ @server.instructions.to_s
107
+ end
108
+
109
+ # A `tools/list` always needs a fresh sync, so a tool registered since the last one is
110
+ # listed with AgentCat's parameters. A `tools/call` only needs one when it names a tool
111
+ # this adapter hasn't wrapped yet — the case a server's `install!` ran on but that
112
+ # received no `tools/list` before its first real call: built fresh per request, or a
113
+ # client that already knew the tool's name from an earlier instance's listing.
114
+ #
115
+ # `handle` receives an already-parsed request Hash; `handle_json` a raw JSON string. A
116
+ # request this can't make sense of (malformed JSON, an unexpected shape) just skips the
117
+ # sync — the original method's own error handling still sees it unchanged.
118
+ sig { params(request: T.untyped).returns(T::Boolean) }
119
+ def needs_sync?(request)
120
+ parsed = request.is_a?(String) ? JSON.parse(request) : request
121
+ return false unless parsed.is_a?(Hash)
122
+
123
+ method = parsed[:method] || parsed["method"]
124
+ case method
125
+ when "tools/list"
126
+ true
127
+ when "tools/call"
128
+ params = parsed[:params] || parsed["params"]
129
+ name = params.is_a?(Hash) ? (params[:name] || params["name"]) : nil
130
+ tools = tools_hash
131
+ !name.nil? && !tools.nil? && !tools[name].is_a?(AgentCat::ToolHandle)
132
+ else
133
+ false
134
+ end
135
+ rescue JSON::ParserError, TypeError
136
+ false
137
+ end
138
+
139
+ private
140
+
141
+ # The server's own tools Hash, which AgentCat writes `ToolHandle`s into
142
+ # (`PrivateMembers::SERVER_TOOLS`), or nil when that feature is off.
143
+ sig { returns(T.nilable(T::Hash[T.untyped, T.untyped])) }
144
+ def tools_hash
145
+ member = AgentCat::PrivateMembers::SERVER_TOOLS
146
+ return nil unless AgentCat::PrivateMembers.enabled?(member.feature)
147
+
148
+ tools = @server.tools
149
+ return tools if tools.is_a?(Hash)
150
+
151
+ AgentCat::PrivateMembers.missing!(member)
152
+ nil
153
+ rescue NoMethodError
154
+ AgentCat::PrivateMembers.missing!(AgentCat::PrivateMembers::SERVER_TOOLS)
155
+ nil
156
+ end
157
+
158
+ sig { params(member: AgentCat::PrivateMembers::Member, sync: T.proc.void).void }
159
+ def wrap_dispatch_method(member, &sync)
160
+ method_name = member.name.to_sym
161
+ return unless AgentCat::PrivateMembers.enabled?(member.feature) && @server.respond_to?(method_name)
162
+
163
+ original = @server.method(method_name)
164
+ adapter = self
165
+ @server.define_singleton_method(method_name) do |request, **kwargs|
166
+ listing = adapter.before_request(request, sync)
167
+ begin
168
+ original.call(request, **kwargs)
169
+ ensure
170
+ adapter.after_request(listing)
171
+ end
172
+ end
173
+ end
174
+
175
+ public
176
+
177
+ # Runs ahead of every request the wrapped `handle`/`handle_json` gets. Never raises:
178
+ # the request always reaches the gem. Returns whether the request is a `tools/list`.
179
+ sig { params(request: T.untyped, sync: T.proc.void).returns(T::Boolean) }
180
+ def before_request(request, sync)
181
+ # Cheap retry (a boolean after the first success): if the HTTP transport wasn't
182
+ # loaded when `track` ran, this installs the request-header hook the first time a
183
+ # request reaches the server, so a later `require` doesn't silently cost headers.
184
+ AgentCat::RequestContext.install!
185
+ parsed = parse_request(request)
186
+ sync.call if needs_sync?(parsed)
187
+ request_method(parsed) == "tools/list"
188
+ rescue => e
189
+ AgentCat::Log.warn("AgentCat could not instrument new tools before a request: #{e.class}")
190
+ AgentCat.logger.debug { "before_request failed: #{e.class}: #{e.message}" }
191
+ false
192
+ end
193
+
194
+ # Runs once the gem has answered the request, so the `on_tools_list` work never runs
195
+ # beside it. Never raises.
196
+ sig { params(listing: T::Boolean).void }
197
+ def after_request(listing)
198
+ @on_tools_list&.call if listing
199
+ rescue
200
+ nil
201
+ end
202
+
203
+ private
204
+
205
+ # The request as a Hash: `handle` gets one, `handle_json` a JSON string. nil when it
206
+ # is neither.
207
+ sig { params(request: T.untyped).returns(T.untyped) }
208
+ def parse_request(request)
209
+ parsed = request.is_a?(String) ? JSON.parse(request) : request
210
+ parsed.is_a?(Hash) ? parsed : nil
211
+ rescue JSON::ParserError, TypeError
212
+ nil
213
+ end
214
+
215
+ sig { params(parsed: T.untyped).returns(T.untyped) }
216
+ def request_method(parsed)
217
+ parsed.is_a?(Hash) ? (parsed[:method] || parsed["method"]) : nil
218
+ end
219
+
220
+ sig { params(method: String).returns(T::Boolean) }
221
+ def answers?(method)
222
+ ::MCP::Methods.ensure_capability!(method, @server.capabilities)
223
+ true
224
+ # MissingRequiredCapabilityError, or capabilities the gem itself cannot read.
225
+ rescue
226
+ false
227
+ end
228
+
229
+ # Same rule as the gem's `handler_declares_server_context?`.
230
+ sig { params(handler: T.untyped).returns(T::Boolean) }
231
+ def declares_server_context?(handler)
232
+ return false unless handler.respond_to?(:parameters)
233
+
234
+ handler.parameters.any? { |type, name| name == :server_context && (type == :key || type == :keyreq) }
235
+ end
236
+
237
+ sig { params(name: String).returns(T.nilable(AgentCat::ToolHandle)) }
238
+ def wrap(name)
239
+ tools = tools_hash
240
+ return nil if tools.nil?
241
+
242
+ tool = tools[name]
243
+ return tool if tool.is_a?(AgentCat::ToolHandle)
244
+
245
+ handle = AgentCat::ToolHandle.new(
246
+ name: tool.name_value,
247
+ title: tool.title_value,
248
+ description: tool.description_value,
249
+ icons: tool.icons_value,
250
+ annotations: tool.annotations_value,
251
+ meta: tool.meta_value,
252
+ input_schema: tool.input_schema_value,
253
+ output_schema: tool.output_schema_value,
254
+ call_fn: call_fn_for(tool)
255
+ )
256
+ tools[name] = handle
257
+ handle
258
+ end
259
+
260
+ # Mirrors `MCP::Server#accepts_server_context?`: a tool receives `server_context:` when its
261
+ # `call` declares that keyword or accepts arbitrary keywords.
262
+ sig { params(tool: T.untyped).returns(T.untyped) }
263
+ def call_fn_for(tool)
264
+ parameters = tool.method(:call).parameters
265
+ accepts_context = parameters.any? do |type, param_name|
266
+ type == :keyrest || (param_name == :server_context && (type == :key || type == :keyreq))
267
+ end
268
+
269
+ if accepts_context
270
+ ->(arguments, server_context) { tool.call(**arguments.transform_keys(&:to_sym), server_context: server_context) }
271
+ else
272
+ ->(arguments, _server_context) { tool.call(**arguments.transform_keys(&:to_sym)) }
273
+ end
274
+ end
275
+ end
276
+ end
277
+ end
@@ -0,0 +1,189 @@
1
+ # typed: strict
2
+
3
+ require "uri"
4
+ require "agentcat-api"
5
+ require_relative "diagnostics"
6
+
7
+ module AgentCatApi
8
+ # `PublishEventRequest#event_type=` validates against the OpenAPI spec's enum, which
9
+ # predates `agentcat:custom` (see `AgentCat::Client::CUSTOM_EVENT_TYPE`) — the backend
10
+ # has accepted that value since the TypeScript SDK's 2.0 release, but every generated
11
+ # client (Ruby, Python, TS's own type alias) still ships the stale list, because
12
+ # they're all generated from the same spec snapshot. Left alone, every custom event
13
+ # would fail construction right here and vanish into `Client#post_event`'s rescue.
14
+ #
15
+ # Same fix the Python SDK ships (`agentcat/types.py`'s `Event#event_type_validate_enum`
16
+ # override) — don't remove this expecting a future `agentcat-api` bump to carry it;
17
+ # regenerating from the same stale spec would silently reintroduce the rejection.
18
+ # `test/test_client.rb`'s custom-event-type test is the tripwire.
19
+ class PublishEventRequest
20
+ extend T::Sig
21
+
22
+ alias_method :_generated_event_type=, :event_type=
23
+
24
+ sig { params(event_type: T.untyped).void }
25
+ def event_type=(event_type)
26
+ if event_type == AgentCat::Client::CUSTOM_EVENT_TYPE
27
+ @event_type = T.let(event_type, T.nilable(String))
28
+ else
29
+ self._generated_event_type = event_type
30
+ end
31
+ end
32
+ end
33
+
34
+ # Every generated model's `_to_hash` calls `value.compact` on arrays before it maps
35
+ # them, so a payload array `[1, nil, 2]` would go out as `[1, 2]`, and the event would not
36
+ # say what the tool got or returned. Same reasoning as the `event_type=` reopening
37
+ # above - a regenerated `agentcat-api` would bring the `compact` back, so the fix
38
+ # lives here. `test/test_client.rb`'s nil-element tests are the tripwire.
39
+ module KeepNilArrayElements
40
+ extend T::Sig
41
+
42
+ sig { params(value: T.untyped).returns(T.untyped) }
43
+ def _to_hash(value)
44
+ return value.map { |element| _to_hash(element) } if value.is_a?(Array)
45
+
46
+ super
47
+ end
48
+ end
49
+
50
+ constants.each do |name|
51
+ klass = const_get(name)
52
+ next unless klass.is_a?(Class) && klass.method_defined?(:_to_hash)
53
+
54
+ klass.prepend(KeepNilArrayElements) unless klass.ancestors.include?(KeepNilArrayElements)
55
+ end
56
+ end
57
+
58
+ module AgentCat
59
+ # Thin wrapper around the generated agentcat-api client. Runs on the event queue's
60
+ # worker thread, never the caller's (see EventQueue, Delivery).
61
+ #
62
+ # AGENTCAT_API_URL is just the base (scheme, host, optional port/path prefix) — the
63
+ # generated client appends the events path itself.
64
+ class Client
65
+ DEFAULT_API_URL = "https://api.agentcat.com"
66
+ ENV_API_URL = "AGENTCAT_API_URL"
67
+ ENV_API_KEY = "AGENTCAT_API_KEY"
68
+ # See the `AgentCatApi::PublishEventRequest` reopening above this class.
69
+ CUSTOM_EVENT_TYPE = "agentcat:custom"
70
+ # Without these a hung connection stalls the worker thread forever and the queue
71
+ # just stops draining. 10s read / 1s open, matching the reference SDKs;
72
+ # Options#request_timeout overrides the read side.
73
+ OPEN_TIMEOUT_SECONDS = 1
74
+ DEFAULT_READ_TIMEOUT_SECONDS = 10
75
+ EVENT_FIELDS = T.let(AgentCatApi::PublishEventRequest.attribute_map.keys.freeze, T::Array[Symbol])
76
+
77
+ # First `track` call wins — this is process-wide, same as the queue and exporters.
78
+ @configured_read_timeout = T.let(nil, T.nilable(Float))
79
+ @configured_api_url = T.let(nil, T.nilable(String))
80
+
81
+ class << self
82
+ extend T::Sig
83
+
84
+ # `Options#api_base_url` takes precedence over AGENTCAT_API_URL; first `track`
85
+ # call wins, same as the read timeout.
86
+ sig { params(url: String).void }
87
+ def configure_base_url(url)
88
+ @configured_api_url ||= url
89
+ end
90
+
91
+ sig { returns(String) }
92
+ def api_url
93
+ @configured_api_url || env_api_url
94
+ end
95
+
96
+ sig { returns(T.nilable(String)) }
97
+ def api_key
98
+ value = ENV[ENV_API_KEY]
99
+ (value.nil? || value.empty?) ? nil : value
100
+ end
101
+
102
+ sig { params(seconds: Numeric).void }
103
+ def configure_timeout(seconds)
104
+ @configured_read_timeout ||= seconds.to_f
105
+ end
106
+
107
+ sig { returns(Float) }
108
+ def read_timeout_seconds
109
+ @configured_read_timeout || DEFAULT_READ_TIMEOUT_SECONDS.to_f
110
+ end
111
+
112
+ sig { void }
113
+ def reset_timeout!
114
+ @configured_read_timeout = nil
115
+ end
116
+
117
+ sig { void }
118
+ def reset_base_url!
119
+ @configured_api_url = nil
120
+ end
121
+
122
+ # Publishes one event. Never raises; returns the API response or nil on failure.
123
+ sig { params(event: T::Hash[Symbol, T.untyped]).returns(T.nilable(AgentCatApi::EventAcceptedResponse)).checked(:tests) }
124
+ def post_event(event)
125
+ attributes = EVENT_FIELDS.each_with_object({}) { |field, acc| acc[field] = event[field] if event.key?(field) }
126
+ request = AgentCatApi::PublishEventRequest.new(attributes)
127
+ headers = {}
128
+ headers["Authorization"] = "Bearer #{api_key}" if api_key
129
+
130
+ # Authorization is set explicitly above; disabling the generated auth scheme avoids a nil header when no key is configured.
131
+ events_api.publish_event(publish_event_request: request, header_params: headers, debug_auth_names: [])
132
+ rescue => e
133
+ # The API error's message carries the response body: debug only.
134
+ code = e.is_a?(AgentCatApi::ApiError) ? e.code : nil
135
+ status = code ? " (HTTP #{code})" : ""
136
+ AgentCat::Log.error("failed to publish event to AgentCat: #{e.class}#{status}")
137
+ AgentCat.logger.debug { "failed to publish event: #{e.class}: #{e.message}" }
138
+ nil
139
+ end
140
+
141
+ # Publishes the server info heartbeat to the base URL of the events, with no
142
+ # `Authorization` header and a fixed 10 s read timeout. Never raises and logs at
143
+ # debug only; returns the HTTP status of the answer, or nil when no answer came.
144
+ sig { params(body: T::Hash[Symbol, T.untyped]).returns(T.nilable(Integer)) }
145
+ def post_server_info(body)
146
+ request = AgentCatApi::PublishServerInfoRequest.new(body)
147
+ api = AgentCatApi::ServerInfoApi.new(AgentCatApi::ApiClient.new(configuration(read_timeout: DEFAULT_READ_TIMEOUT_SECONDS.to_f)))
148
+ _data, status, _headers = api.publish_server_info_with_http_info(publish_server_info_request: request, debug_auth_names: [])
149
+ status
150
+ rescue AgentCatApi::ApiError => e
151
+ AgentCat.logger.debug { "failed to publish server info: #{e.class} (HTTP #{e.code.inspect})" }
152
+ code = e.code
153
+ (code.is_a?(Integer) && code.positive?) ? code : nil
154
+ rescue => e
155
+ AgentCat.logger.debug { "failed to publish server info: #{e.class}" }
156
+ nil
157
+ end
158
+
159
+ sig { params(read_timeout: Float).returns(AgentCatApi::Configuration) }
160
+ def configuration(read_timeout: read_timeout_seconds)
161
+ uri = URI.parse(api_url)
162
+ AgentCatApi::Configuration.new.tap do |config|
163
+ config.scheme = uri.scheme
164
+ config.host = (uri.port == uri.default_port) ? uri.host : "#{uri.host}:#{uri.port}"
165
+ config.base_path = uri.path.to_s.sub(%r{/+\z}, "")
166
+ config.ignore_operation_servers = true
167
+ config.timeout = read_timeout
168
+ config.configure_faraday_connection do |conn|
169
+ conn.options.open_timeout = OPEN_TIMEOUT_SECONDS
170
+ conn.options.timeout = read_timeout
171
+ end
172
+ end
173
+ end
174
+
175
+ private
176
+
177
+ sig { returns(String) }
178
+ def env_api_url
179
+ value = ENV[ENV_API_URL]
180
+ (value.nil? || value.empty?) ? DEFAULT_API_URL : value
181
+ end
182
+
183
+ sig { returns(AgentCatApi::EventsApi) }
184
+ def events_api
185
+ AgentCatApi::EventsApi.new(AgentCatApi::ApiClient.new(configuration))
186
+ end
187
+ end
188
+ end
189
+ end
@@ -0,0 +1,16 @@
1
+ # typed: true
2
+
3
+ module AgentCat
4
+ # Monotonic clock for measuring elapsed time. Don't use Time.now for this; NTP can
5
+ # step it backwards mid-call. Interceptor and EventQueue both depend on it.
6
+ module Clock
7
+ class << self
8
+ extend T::Sig
9
+
10
+ sig { returns(Float) }
11
+ def monotonic_now
12
+ Process.clock_gettime(Process::CLOCK_MONOTONIC).to_f
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,215 @@
1
+ # typed: true
2
+
3
+ require_relative "client"
4
+ require_relative "event_id"
5
+ require_relative "unredacted_event"
6
+ require_relative "tags"
7
+ require_relative "delivery"
8
+ require_relative "event_pipeline"
9
+
10
+ module AgentCat
11
+ # `AgentCat.publish_custom_event`'s body - one `agentcat:custom` event for work
12
+ # that is not a tool call: a background job, a webhook, a checkout step, anything
13
+ # the customer wants on the same timeline as the tool calls AgentCat captures
14
+ # automatically.
15
+ #
16
+ # Parity with the canonical SDKs' `publishCustomEvent`/`publish_custom_event`
17
+ # (TS/Python) - Python's is the more defensive of the two, and is what this
18
+ # follows field-for-field: fire-and-forget (never raises), and a single
19
+ # unusable field costs only that field, never the whole event.
20
+ module CustomEvent
21
+ extend T::Sig
22
+
23
+ sig do
24
+ params(
25
+ server_or_session_id: T.untyped,
26
+ project_id: T.untyped,
27
+ session_id: T.untyped,
28
+ resource_name: T.untyped,
29
+ parameters: T.untyped,
30
+ response: T.untyped,
31
+ message: T.untyped,
32
+ duration: T.untyped,
33
+ is_error: T.untyped,
34
+ error: T.untyped,
35
+ tags: T.untyped,
36
+ properties: T.untyped
37
+ ).void
38
+ end
39
+ def self.publish(
40
+ server_or_session_id,
41
+ project_id,
42
+ session_id: nil,
43
+ resource_name: nil,
44
+ parameters: nil,
45
+ response: nil,
46
+ message: nil,
47
+ duration: nil,
48
+ is_error: nil,
49
+ error: nil,
50
+ tags: nil,
51
+ properties: nil
52
+ )
53
+ session_id = wire_string("session_id", session_id)
54
+ session_id = nil if session_id && session_id.empty?
55
+
56
+ event = build_event(
57
+ resource_name: resource_name, parameters: parameters, response: response,
58
+ message: message, duration: duration, is_error: is_error, error: error,
59
+ tags: tags, properties: properties
60
+ )
61
+
62
+ if server_or_session_id.is_a?(String)
63
+ # TS: `eventData.sessionId || serverOrSessionId`, and "" goes out as null.
64
+ publish_untracked(event, session_id || (server_or_session_id.empty? ? nil : server_or_session_id), project_id)
65
+ else
66
+ publish_tracked(event, server_or_session_id, session_id)
67
+ end
68
+ rescue => e
69
+ Log.error("failed to publish custom event: #{e.class}; the event is lost")
70
+ AgentCat.logger.debug { "failed to publish custom event: #{e.class}: #{e.message}" }
71
+ end
72
+
73
+ sig { params(event: UnredactedEvent, session_id: T.nilable(String), project_id: T.untyped).void }
74
+ def self.publish_untracked(event, session_id, project_id)
75
+ project = wire_string("project_id", project_id)
76
+ if project.nil? || project.empty?
77
+ Log.warn("publish_custom_event: project_id is required when the first argument is a session ID string; event dropped")
78
+ return
79
+ end
80
+
81
+ event.session_id = session_id
82
+ event.project_id = project
83
+ epoch = AgentCat.event_epoch
84
+ # No tracker, so no hooks and no per-server exporters: like TS's queue, the event
85
+ # goes to the process-wide exporters (the first `track` that had any).
86
+ exporters = AgentCat.process_exporters
87
+ AgentCat.event_queue.enqueue do
88
+ EventPipeline.normalize(event, label: "a custom event")
89
+ next if EventPipeline.record_in_fake(event, epoch)
90
+
91
+ Delivery.publish(AgentCat::Client, event.to_wire_hash, epoch: epoch)
92
+ Exporters.dispatch(exporters, event)
93
+ end
94
+ end
95
+ private_class_method :publish_untracked
96
+
97
+ sig { params(event: UnredactedEvent, server: T.untyped, session_id: T.nilable(String)).void }
98
+ def self.publish_tracked(event, server, session_id)
99
+ tracker = AgentCat.tracker_for(server)
100
+ unless tracker
101
+ Log.warn(
102
+ "publish_custom_event: first argument is neither a tracked server nor a session ID string " \
103
+ "(got #{server.class}); event dropped. Call AgentCat.track() first, or pass a session ID."
104
+ )
105
+ return
106
+ end
107
+
108
+ options = tracker.options
109
+ # Tracing off means nothing gets published for this server, custom events included.
110
+ # Accepted and dropped quietly, same as the Go SDK.
111
+ return unless options.enable_tracing
112
+
113
+ event.session_id = session_id
114
+ event.project_id = tracker.project_id
115
+ epoch = AgentCat.event_epoch
116
+ AgentCat.event_queue(queue_size: options.queue_size).enqueue do
117
+ EventPipeline.run(event, tracker, epoch: epoch, label: "a custom event", redact_strings: false)
118
+ end
119
+ end
120
+ private_class_method :publish_tracked
121
+
122
+ sig do
123
+ params(
124
+ resource_name: T.untyped,
125
+ parameters: T.untyped,
126
+ response: T.untyped,
127
+ message: T.untyped,
128
+ duration: T.untyped,
129
+ is_error: T.untyped,
130
+ error: T.untyped,
131
+ tags: T.untyped,
132
+ properties: T.untyped
133
+ ).returns(UnredactedEvent)
134
+ end
135
+ def self.build_event(resource_name:, parameters:, response:, message:, duration:, is_error:, error:, tags:, properties:)
136
+ UnredactedEvent.new(
137
+ project_id: nil,
138
+ id: EventId.mint,
139
+ session_id: nil,
140
+ event_type: AgentCat::Client::CUSTOM_EVENT_TYPE,
141
+ resource_name: wire_string("resource_name", resource_name) || "",
142
+ parameters: wire_payload("parameters", parameters) || {},
143
+ user_intent: wire_string("message", message),
144
+ response: wire_payload("response", response),
145
+ is_error: wire_bool("is_error", is_error) || false,
146
+ error: wire_error(error),
147
+ duration: wire_integer("duration", duration) || 0,
148
+ timestamp: Time.now.utc.iso8601(3),
149
+ agentcat_version: AgentCat::VERSION,
150
+ tags: Tags.sanitize(wire_hash("tags", tags), "publish_custom_event tags"),
151
+ properties: wire_payload("properties", properties) || {}
152
+ )
153
+ end
154
+ private_class_method :build_event
155
+
156
+ # A value the wire's strict scalar field can hold, or nil. One unusable field is
157
+ # not worth the whole event - log and drop it, never raise.
158
+ sig { params(field: String, value: T.untyped).returns(T.nilable(String)) }
159
+ def self.wire_string(field, value)
160
+ return value if value.nil? || value.is_a?(String)
161
+
162
+ Log.warn("publish_custom_event: dropping '#{field}' - expected String, got #{value.class}")
163
+ nil
164
+ end
165
+ private_class_method :wire_string
166
+
167
+ sig { params(field: String, value: T.untyped).returns(T.nilable(Integer)) }
168
+ def self.wire_integer(field, value)
169
+ return value if value.nil? || value.is_a?(Integer)
170
+
171
+ Log.warn("publish_custom_event: dropping '#{field}' - expected Integer, got #{value.class}")
172
+ nil
173
+ end
174
+ private_class_method :wire_integer
175
+
176
+ sig { params(field: String, value: T.untyped).returns(T.nilable(T::Boolean)) }
177
+ def self.wire_bool(field, value)
178
+ return value if value.nil? || value == true || value == false
179
+
180
+ Log.warn("publish_custom_event: dropping '#{field}' - expected true/false, got #{value.class}")
181
+ nil
182
+ end
183
+ private_class_method :wire_bool
184
+
185
+ sig { params(field: String, value: T.untyped).returns(T.nilable(T::Hash[T.untyped, T.untyped])) }
186
+ def self.wire_hash(field, value)
187
+ return value if value.nil? || value.is_a?(Hash)
188
+
189
+ Log.warn("publish_custom_event: dropping '#{field}' - expected a Hash, got #{value.class}")
190
+ nil
191
+ end
192
+ private_class_method :wire_hash
193
+
194
+ # `parameters`/`response`/`properties` hold whatever the caller wants recorded, so a
195
+ # non-Hash is a plausible payload, not a mistake - wrapped, never dropped.
196
+ sig { params(field: String, value: T.untyped).returns(T.nilable(T::Hash[T.untyped, T.untyped])) }
197
+ def self.wire_payload(field, value)
198
+ return value if value.nil? || value.is_a?(Hash)
199
+
200
+ Log.warn("publish_custom_event: wrapping non-Hash '#{field}' (#{value.class}) as {value: ...}")
201
+ {"value" => value}
202
+ end
203
+ private_class_method :wire_payload
204
+
205
+ # `error` has a known shape consumers read `message` from, so a bare value becomes
206
+ # one rather than a `{value: ...}` payload.
207
+ sig { params(value: T.untyped).returns(T.nilable(T::Hash[T.untyped, T.untyped])) }
208
+ def self.wire_error(value)
209
+ return value if value.nil? || value.is_a?(Hash)
210
+
211
+ {"message" => value.to_s}
212
+ end
213
+ private_class_method :wire_error
214
+ end
215
+ end