agentcat 0.0.1 → 1.0.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 +4 -4
- data/LICENSE +2 -11
- data/README.md +265 -20
- data/lib/agentcat/adapters/base.rb +73 -0
- data/lib/agentcat/adapters/official.rb +194 -0
- data/lib/agentcat/client.rb +171 -0
- data/lib/agentcat/clock.rb +16 -0
- data/lib/agentcat/custom_event.rb +215 -0
- data/lib/agentcat/delivery.rb +58 -0
- data/lib/agentcat/diagnostics.rb +434 -0
- data/lib/agentcat/error_capture.rb +117 -0
- data/lib/agentcat/event_id.rb +19 -0
- data/lib/agentcat/event_pipeline.rb +82 -0
- data/lib/agentcat/event_queue.rb +151 -0
- data/lib/agentcat/exporters/base.rb +135 -0
- data/lib/agentcat/exporters/datadog.rb +137 -0
- data/lib/agentcat/exporters/otlp.rb +157 -0
- data/lib/agentcat/exporters/posthog.rb +185 -0
- data/lib/agentcat/exporters/sentry.rb +242 -0
- data/lib/agentcat/exporters/trace_context.rb +79 -0
- data/lib/agentcat/exporters.rb +108 -0
- data/lib/agentcat/fork_safety.rb +30 -0
- data/lib/agentcat/hooks.rb +190 -0
- data/lib/agentcat/http_post.rb +61 -0
- data/lib/agentcat/interceptor.rb +711 -0
- data/lib/agentcat/log.rb +80 -0
- data/lib/agentcat/options.rb +313 -0
- data/lib/agentcat/payload_limits.rb +71 -0
- data/lib/agentcat/private_members.rb +271 -0
- data/lib/agentcat/redaction.rb +115 -0
- data/lib/agentcat/rejected_calls.rb +147 -0
- data/lib/agentcat/request_context.rb +266 -0
- data/lib/agentcat/sanitization.rb +191 -0
- data/lib/agentcat/schema/prompts.rb +44 -0
- data/lib/agentcat/session_manager.rb +83 -0
- data/lib/agentcat/tags.rb +61 -0
- data/lib/agentcat/test_mode.rb +86 -0
- data/lib/agentcat/testing.rb +153 -0
- data/lib/agentcat/text.rb +68 -0
- data/lib/agentcat/token_estimate.rb +98 -0
- data/lib/agentcat/tool_call.rb +129 -0
- data/lib/agentcat/tool_handle.rb +289 -0
- data/lib/agentcat/tracker.rb +201 -0
- data/lib/agentcat/truncation.rb +265 -0
- data/lib/agentcat/unredacted_event.rb +155 -0
- data/lib/agentcat/user_identity.rb +11 -0
- data/lib/agentcat/version.rb +2 -2
- data/lib/agentcat.rb +391 -21
- metadata +193 -16
- data/agentcat.gemspec +0 -30
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
# typed: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
require "etc"
|
|
5
|
+
require "json"
|
|
6
|
+
require "logger"
|
|
7
|
+
require "socket"
|
|
8
|
+
|
|
9
|
+
require_relative "version"
|
|
10
|
+
require_relative "http_post"
|
|
11
|
+
require_relative "test_mode"
|
|
12
|
+
|
|
13
|
+
module AgentCat
|
|
14
|
+
class << self
|
|
15
|
+
extend T::Sig
|
|
16
|
+
|
|
17
|
+
# Defaults to WARN on $stderr — best-effort failures (publishing, bad config)
|
|
18
|
+
# shouldn't show up in tool results, but they shouldn't vanish either.
|
|
19
|
+
sig { params(logger: Logger).void }
|
|
20
|
+
attr_writer :logger
|
|
21
|
+
|
|
22
|
+
sig { returns(Logger) }
|
|
23
|
+
def logger
|
|
24
|
+
@logger ||= Logger.new($stderr, level: Logger::WARN, progname: "agentcat")
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# When true, also appends to ~/agentcat.log (never $stderr — stdio transports
|
|
28
|
+
# need that clean). Independent of the remote beacon's on/off switch.
|
|
29
|
+
sig { returns(T::Boolean) }
|
|
30
|
+
def debug?
|
|
31
|
+
!!@debug
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
sig { params(debug: T::Boolean).void }
|
|
35
|
+
attr_writer :debug
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Anonymized signal sent back to AgentCat when setup or runtime errors happen.
|
|
39
|
+
# Just operational metadata — project id (or an anonymous install id), SDK/MCP/
|
|
40
|
+
# runtime versions, host shape. Never tool calls, responses, or anything about
|
|
41
|
+
# your users.
|
|
42
|
+
#
|
|
43
|
+
# Ships as an OTLP/HTTP log record to https://otel.agentcat.com/v1/logs (override
|
|
44
|
+
# with AGENTCAT_DIAGNOSTICS_ENDPOINT / AGENTCAT_DIAGNOSTICS_TOKEN). On by default —
|
|
45
|
+
# turn it off with Options#disable_diagnostics or AGENTCAT_DISABLE_DIAGNOSTICS
|
|
46
|
+
# (false/0/no/off forces it back on). The unprefixed DISABLE_DIAGNOSTICS (the TS
|
|
47
|
+
# name) can only turn it off; the unprefixed DIAGNOSTICS_ENDPOINT/DIAGNOSTICS_TOKEN
|
|
48
|
+
# are never read, so an app's own variables never reach AgentCat. Test
|
|
49
|
+
# processes disable themselves unless forced. ~/agentcat.log doesn't care about any
|
|
50
|
+
# of this.
|
|
51
|
+
module Diagnostics
|
|
52
|
+
DEFAULT_ENDPOINT = "https://otel.agentcat.com"
|
|
53
|
+
DEFAULT_TOKEN = "dgk_sdk_diag_3f9a2c7e1b8d4065af2e9c1d7b6a4f80"
|
|
54
|
+
SCOPE_NAME = "agentcat-diagnostics"
|
|
55
|
+
LOGS_PATH = "/v1/logs"
|
|
56
|
+
MAX_BUFFER = 1000
|
|
57
|
+
FLUSH_DELAY = 2
|
|
58
|
+
# A blocked collector costs a flush (and so `AgentCat.flush` / at_exit) at
|
|
59
|
+
# most about a second.
|
|
60
|
+
CONNECT_TIMEOUT = 0.25
|
|
61
|
+
TOTAL_TIMEOUT = 1.0
|
|
62
|
+
LOCAL_LOG_NAME = "agentcat.log"
|
|
63
|
+
# lib/agentcat/../.. - the installed gem's directory.
|
|
64
|
+
GEM_ROOT = T.let(
|
|
65
|
+
begin
|
|
66
|
+
File.realpath(File.expand_path("../..", __dir__))
|
|
67
|
+
rescue SystemCallError
|
|
68
|
+
File.expand_path("../..", __dir__)
|
|
69
|
+
end,
|
|
70
|
+
String
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
SEVERITY = T.let(
|
|
74
|
+
{
|
|
75
|
+
info: [9, "INFO"],
|
|
76
|
+
warn: [13, "WARN"],
|
|
77
|
+
error: [17, "ERROR"]
|
|
78
|
+
}.freeze,
|
|
79
|
+
T::Hash[Symbol, T::Array[T.untyped]]
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
extend T::Sig
|
|
83
|
+
|
|
84
|
+
@mutex = T.let(Mutex.new, Mutex)
|
|
85
|
+
@initialized = T.let(false, T::Boolean)
|
|
86
|
+
@enabled = T.let(false, T::Boolean)
|
|
87
|
+
@buffer = T.let([], T::Array[T::Hash[String, T.untyped]])
|
|
88
|
+
@flush_pending = T.let(false, T::Boolean)
|
|
89
|
+
@static_attrs = T.let([], T::Array[T::Hash[String, T.untyped]])
|
|
90
|
+
@record_attrs = T.let([], T::Array[T::Hash[String, T.untyped]])
|
|
91
|
+
|
|
92
|
+
class << self
|
|
93
|
+
extend T::Sig
|
|
94
|
+
|
|
95
|
+
# Test seam: (url, headers, body) -> [status, body].
|
|
96
|
+
sig { returns(T.untyped) }
|
|
97
|
+
attr_accessor :http_post
|
|
98
|
+
|
|
99
|
+
# Idempotent — only the first call per process does anything. Never raises.
|
|
100
|
+
sig { params(project_id: T.nilable(String), integration: String, disabled: T::Boolean).void }
|
|
101
|
+
def init(project_id:, integration:, disabled:)
|
|
102
|
+
@mutex.synchronize do
|
|
103
|
+
return if @initialized
|
|
104
|
+
|
|
105
|
+
@initialized = true
|
|
106
|
+
@static_attrs = build_static_attributes(project_id, integration)
|
|
107
|
+
@record_attrs = build_record_attributes
|
|
108
|
+
@enabled = compute_enabled?(disabled)
|
|
109
|
+
end
|
|
110
|
+
rescue => e
|
|
111
|
+
AgentCat.logger.debug { "diagnostics init failed: #{e.class}: #{e.message}" }
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# Buffers a message for the next batched send; also writes to agentcat.log
|
|
115
|
+
# when debug? is on. Never raises, never blocks.
|
|
116
|
+
sig { params(level: Symbol, message: String).void }
|
|
117
|
+
def record(level, message)
|
|
118
|
+
file_log(level, message) if AgentCat.debug?
|
|
119
|
+
return unless @enabled
|
|
120
|
+
return if level == :debug
|
|
121
|
+
|
|
122
|
+
flush_already_pending = schedule_record(record: build_record(level, message))
|
|
123
|
+
spawn_flush unless flush_already_pending
|
|
124
|
+
rescue => e
|
|
125
|
+
AgentCat.logger.debug { "diagnostics record failed: #{e.class}: #{e.message}" }
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# Best-effort send of whatever's buffered, bounded by TOTAL_TIMEOUT. AgentCat.flush
|
|
129
|
+
# (and so the at_exit hook) calls this too, so a record never waits for the
|
|
130
|
+
# FLUSH_DELAY batch timer at shutdown.
|
|
131
|
+
sig { void }
|
|
132
|
+
def flush
|
|
133
|
+
records = @mutex.synchronize do
|
|
134
|
+
pending = @buffer
|
|
135
|
+
@buffer = []
|
|
136
|
+
pending
|
|
137
|
+
end
|
|
138
|
+
return if records.empty?
|
|
139
|
+
|
|
140
|
+
post(build_payload(records))
|
|
141
|
+
rescue => e
|
|
142
|
+
AgentCat.logger.debug { "diagnostics flush failed: #{e.class}: #{e.message}" }
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
sig { returns(T::Boolean) }
|
|
146
|
+
def enabled?
|
|
147
|
+
@enabled
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
sig { returns(T::Array[T::Hash[String, T.untyped]]) }
|
|
151
|
+
def static_attributes
|
|
152
|
+
@static_attrs
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
# Node `os.platform()` names for `Etc.uname[:sysname]`: `win32` for Windows,
|
|
156
|
+
# else the name in lower case (`linux`, `darwin`, `freebsd`, `sunos`).
|
|
157
|
+
sig { params(sysname: String).returns(String) }
|
|
158
|
+
def os_type(sysname)
|
|
159
|
+
name = sysname.downcase
|
|
160
|
+
name.start_with?("windows", "mingw", "msys", "cygwin") ? "win32" : name
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
# Node `os.arch()` names for x64 and arm64 (any case); any other machine name as is.
|
|
164
|
+
sig { params(machine: String).returns(String) }
|
|
165
|
+
def arch(machine)
|
|
166
|
+
case machine.downcase
|
|
167
|
+
when "x86_64", "amd64", "x64" then "x64"
|
|
168
|
+
when "aarch64", "arm64" then "arm64"
|
|
169
|
+
else machine
|
|
170
|
+
end
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
sig { returns(Integer) }
|
|
174
|
+
def buffer_size
|
|
175
|
+
@mutex.synchronize { @buffer.size }
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
# Test helper, called from AgentCat.reset!.
|
|
179
|
+
sig { void }
|
|
180
|
+
def reset!
|
|
181
|
+
@mutex.synchronize do
|
|
182
|
+
@initialized = false
|
|
183
|
+
@enabled = false
|
|
184
|
+
@buffer = []
|
|
185
|
+
@flush_pending = false
|
|
186
|
+
@static_attrs = []
|
|
187
|
+
@record_attrs = []
|
|
188
|
+
end
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
private
|
|
192
|
+
|
|
193
|
+
# The option, then AGENTCAT_DISABLE_DIAGNOSTICS, then the test environment. The
|
|
194
|
+
# unprefixed DISABLE_DIAGNOSTICS can only turn diagnostics off, also over a false
|
|
195
|
+
# AGENTCAT_DISABLE_DIAGNOSTICS: a privacy opt-out fails closed.
|
|
196
|
+
sig { params(disabled: T::Boolean).returns(T::Boolean) }
|
|
197
|
+
def compute_enabled?(disabled)
|
|
198
|
+
return false if disabled
|
|
199
|
+
|
|
200
|
+
flag = (env_flag("DISABLE_DIAGNOSTICS") == :disabled) ? :disabled : env_flag("AGENTCAT_DISABLE_DIAGNOSTICS")
|
|
201
|
+
return false if flag == :disabled
|
|
202
|
+
return true if flag == :force_enabled
|
|
203
|
+
|
|
204
|
+
!test_environment?
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
# Mirrors TS `envDiagnosticsFlag`: blank is "unset", false/0/no/off (trimmed, any
|
|
208
|
+
# case) forces it back on, anything else turns it off.
|
|
209
|
+
sig { params(name: String).returns(Symbol) }
|
|
210
|
+
def env_flag(name)
|
|
211
|
+
case ENV[name].to_s.strip.downcase
|
|
212
|
+
when ""
|
|
213
|
+
:unset
|
|
214
|
+
when "false", "0", "no", "off"
|
|
215
|
+
:force_enabled
|
|
216
|
+
else
|
|
217
|
+
:disabled
|
|
218
|
+
end
|
|
219
|
+
end
|
|
220
|
+
|
|
221
|
+
# Off in the same test environments as test mode (TestMode). Not the
|
|
222
|
+
# AGENTCAT_ENABLED answer: forcing the SDK on in tests keeps diagnostics off
|
|
223
|
+
# unless AGENTCAT_DISABLE_DIAGNOSTICS=false forces them on too.
|
|
224
|
+
sig { returns(T::Boolean) }
|
|
225
|
+
def test_environment?
|
|
226
|
+
TestMode.test_environment?
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
sig { returns(String) }
|
|
230
|
+
def endpoint
|
|
231
|
+
base = ENV["AGENTCAT_DIAGNOSTICS_ENDPOINT"].to_s.strip
|
|
232
|
+
base = DEFAULT_ENDPOINT if base.empty?
|
|
233
|
+
base = base.chomp("/")
|
|
234
|
+
base.end_with?(LOGS_PATH) ? base : "#{base}#{LOGS_PATH}"
|
|
235
|
+
end
|
|
236
|
+
|
|
237
|
+
sig { returns(String) }
|
|
238
|
+
def token
|
|
239
|
+
value = ENV["AGENTCAT_DIAGNOSTICS_TOKEN"].to_s.strip
|
|
240
|
+
value.empty? ? DEFAULT_TOKEN : value
|
|
241
|
+
end
|
|
242
|
+
|
|
243
|
+
# Stable per-install id for setups with no project id to attribute telemetry to
|
|
244
|
+
# instead (TS uses `hostname|import.meta.url`): hostname + "|file://" + the
|
|
245
|
+
# gem root, symlinks resolved, hashed. Not the cwd or $0, so every script of one
|
|
246
|
+
# install shares it. The hostname is hashed, never sent.
|
|
247
|
+
sig { returns(String) }
|
|
248
|
+
def install_id
|
|
249
|
+
Digest::SHA256.hexdigest("#{Socket.gethostname}|file://#{GEM_ROOT}").slice(0, 16) || "0" * 16
|
|
250
|
+
rescue => e
|
|
251
|
+
AgentCat.logger.debug { "diagnostics install_id failed: #{e.class}: #{e.message}" }
|
|
252
|
+
"0" * 16
|
|
253
|
+
end
|
|
254
|
+
|
|
255
|
+
sig { returns(T.nilable(String)) }
|
|
256
|
+
def mcp_version
|
|
257
|
+
return nil unless defined?(MCP)
|
|
258
|
+
return nil unless MCP.respond_to?(:const_get) && MCP.const_defined?(:VERSION)
|
|
259
|
+
|
|
260
|
+
MCP::VERSION.to_s
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
sig do
|
|
264
|
+
params(record: T::Hash[String, T.untyped]).returns(T::Boolean)
|
|
265
|
+
end
|
|
266
|
+
def schedule_record(record:)
|
|
267
|
+
@mutex.synchronize do
|
|
268
|
+
@buffer.shift while @buffer.size >= MAX_BUFFER
|
|
269
|
+
@buffer << record
|
|
270
|
+
flush_pending = @flush_pending
|
|
271
|
+
@flush_pending = true
|
|
272
|
+
flush_pending
|
|
273
|
+
end
|
|
274
|
+
end
|
|
275
|
+
|
|
276
|
+
sig do
|
|
277
|
+
params(
|
|
278
|
+
project_id: T.nilable(String),
|
|
279
|
+
integration: String
|
|
280
|
+
).returns(T::Array[T::Hash[String, T.untyped]])
|
|
281
|
+
end
|
|
282
|
+
def build_static_attributes(project_id, integration)
|
|
283
|
+
attrs = []
|
|
284
|
+
if project_id.nil? || project_id.empty?
|
|
285
|
+
add_attr!(attrs, "agentcat.install_id", install_id)
|
|
286
|
+
else
|
|
287
|
+
add_attr!(attrs, "agentcat.project_id", project_id)
|
|
288
|
+
end
|
|
289
|
+
|
|
290
|
+
add_attr!(attrs, "agentcat.sdk.language", "ruby")
|
|
291
|
+
add_attr!(attrs, "agentcat.sdk.version", AgentCat::VERSION)
|
|
292
|
+
add_attr!(attrs, "agentcat.mcp_sdk.version", mcp_version)
|
|
293
|
+
add_attr!(attrs, "agentcat.integration", integration)
|
|
294
|
+
|
|
295
|
+
add_attr!(attrs, "process.runtime.name", "ruby")
|
|
296
|
+
add_attr!(attrs, "process.runtime.version", RUBY_VERSION)
|
|
297
|
+
add_attr!(attrs, "process.pid", Process.pid)
|
|
298
|
+
|
|
299
|
+
# Node vocabulary, and no host.cpu.count.
|
|
300
|
+
uname = self.uname
|
|
301
|
+
sysname = uname[:sysname]
|
|
302
|
+
machine = uname[:machine]
|
|
303
|
+
add_attr!(attrs, "os.type", sysname && os_type(sysname))
|
|
304
|
+
add_attr!(attrs, "os.version", uname[:release])
|
|
305
|
+
add_attr!(attrs, "host.arch", machine && arch(machine))
|
|
306
|
+
|
|
307
|
+
add_attr!(attrs, "deployment.environment", deployment_environment)
|
|
308
|
+
attrs
|
|
309
|
+
end
|
|
310
|
+
|
|
311
|
+
sig { returns(T::Hash[Symbol, T.nilable(String)]) }
|
|
312
|
+
def uname
|
|
313
|
+
Etc.uname
|
|
314
|
+
rescue => e
|
|
315
|
+
AgentCat.logger.debug { "diagnostics uname failed: #{e.class}: #{e.message}" }
|
|
316
|
+
{}
|
|
317
|
+
end
|
|
318
|
+
|
|
319
|
+
# The Rack/Rails names, like NODE_ENV in TS and APP_ENV in PHP. Blank counts as unset.
|
|
320
|
+
sig { returns(T.nilable(String)) }
|
|
321
|
+
def deployment_environment
|
|
322
|
+
%w[RAILS_ENV RACK_ENV].each do |name|
|
|
323
|
+
value = ENV[name].to_s.strip
|
|
324
|
+
return value unless value.empty?
|
|
325
|
+
end
|
|
326
|
+
nil
|
|
327
|
+
end
|
|
328
|
+
|
|
329
|
+
sig { returns(T::Array[T::Hash[String, T.untyped]]) }
|
|
330
|
+
def build_record_attributes
|
|
331
|
+
attrs = []
|
|
332
|
+
add_attr!(attrs, "agentcat.sdk.version", AgentCat::VERSION)
|
|
333
|
+
add_attr!(attrs, "agentcat.mcp_sdk.version", mcp_version)
|
|
334
|
+
add_attr!(attrs, "process.runtime.version", RUBY_VERSION)
|
|
335
|
+
attrs
|
|
336
|
+
end
|
|
337
|
+
|
|
338
|
+
sig { params(level: Symbol, message: String).returns(T::Hash[String, T.untyped]) }
|
|
339
|
+
def build_record(level, message)
|
|
340
|
+
severity, text = SEVERITY.fetch(level, SEVERITY[:info])
|
|
341
|
+
{
|
|
342
|
+
"timeUnixNano" => (Time.now.to_r * 1_000_000_000).to_i.to_s,
|
|
343
|
+
"severityNumber" => severity,
|
|
344
|
+
"severityText" => text,
|
|
345
|
+
"body" => {"stringValue" => message},
|
|
346
|
+
"attributes" => @record_attrs
|
|
347
|
+
}
|
|
348
|
+
end
|
|
349
|
+
|
|
350
|
+
sig { params(records: T::Array[T::Hash[T.untyped, T.untyped]]).returns(T::Hash[String, T.untyped]) }
|
|
351
|
+
def build_payload(records)
|
|
352
|
+
{
|
|
353
|
+
"resourceLogs" => [
|
|
354
|
+
{
|
|
355
|
+
"resource" => {"attributes" => @static_attrs},
|
|
356
|
+
"scopeLogs" => [
|
|
357
|
+
{
|
|
358
|
+
"scope" => {"name" => SCOPE_NAME, "version" => AgentCat::VERSION},
|
|
359
|
+
"logRecords" => records
|
|
360
|
+
}
|
|
361
|
+
]
|
|
362
|
+
}
|
|
363
|
+
]
|
|
364
|
+
}
|
|
365
|
+
end
|
|
366
|
+
|
|
367
|
+
sig { void }
|
|
368
|
+
def spawn_flush
|
|
369
|
+
Thread.new do
|
|
370
|
+
sleep(FLUSH_DELAY)
|
|
371
|
+
@mutex.synchronize { @flush_pending = false }
|
|
372
|
+
flush
|
|
373
|
+
end
|
|
374
|
+
rescue ThreadError
|
|
375
|
+
nil
|
|
376
|
+
end
|
|
377
|
+
|
|
378
|
+
sig { params(payload: T::Hash[String, T.untyped]).void }
|
|
379
|
+
def post(payload)
|
|
380
|
+
sender = http_post || default_http_post
|
|
381
|
+
sender.call(endpoint, build_headers, payload.to_json)
|
|
382
|
+
end
|
|
383
|
+
|
|
384
|
+
sig { returns(T::Hash[String, String]) }
|
|
385
|
+
def build_headers
|
|
386
|
+
{
|
|
387
|
+
"Content-Type" => "application/json",
|
|
388
|
+
"Authorization" => "Bearer #{token}",
|
|
389
|
+
"User-Agent" => "agentcat-ruby/#{AgentCat::VERSION}"
|
|
390
|
+
}
|
|
391
|
+
end
|
|
392
|
+
|
|
393
|
+
# Doesn't raise on non-2xx.
|
|
394
|
+
sig do
|
|
395
|
+
returns(
|
|
396
|
+
T.proc.params(
|
|
397
|
+
url: String,
|
|
398
|
+
headers: T::Hash[String, String],
|
|
399
|
+
body: String
|
|
400
|
+
).returns([Integer, String])
|
|
401
|
+
)
|
|
402
|
+
end
|
|
403
|
+
def default_http_post
|
|
404
|
+
lambda do |url, headers, body|
|
|
405
|
+
HttpPost.call(url, headers, body, open_timeout: CONNECT_TIMEOUT, read_timeout: TOTAL_TIMEOUT, deadline: TOTAL_TIMEOUT)
|
|
406
|
+
end
|
|
407
|
+
end
|
|
408
|
+
|
|
409
|
+
sig { params(level: Symbol, message: String).void }
|
|
410
|
+
def file_log(level, message)
|
|
411
|
+
path = File.join(Dir.home, LOCAL_LOG_NAME)
|
|
412
|
+
File.open(path, "a") do |file|
|
|
413
|
+
file.puts "[agentcat] #{Time.now.utc.iso8601} #{level.to_s.upcase}: #{message}"
|
|
414
|
+
end
|
|
415
|
+
rescue => e
|
|
416
|
+
AgentCat.logger.debug { "diagnostics file log failed: #{e.class}: #{e.message}" }
|
|
417
|
+
end
|
|
418
|
+
|
|
419
|
+
sig do
|
|
420
|
+
params(
|
|
421
|
+
attrs: T::Array[T::Hash[String, T.untyped]],
|
|
422
|
+
key: String,
|
|
423
|
+
value: T.untyped
|
|
424
|
+
).void
|
|
425
|
+
end
|
|
426
|
+
def add_attr!(attrs, key, value)
|
|
427
|
+
return if value.nil?
|
|
428
|
+
return if value.to_s.empty?
|
|
429
|
+
|
|
430
|
+
attrs << {"key" => key, "value" => {"stringValue" => value.to_s}}
|
|
431
|
+
end
|
|
432
|
+
end
|
|
433
|
+
end
|
|
434
|
+
end
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# typed: true
|
|
2
|
+
|
|
3
|
+
require_relative "payload_limits"
|
|
4
|
+
require_relative "truncation"
|
|
5
|
+
|
|
6
|
+
module AgentCat
|
|
7
|
+
# Converts a raised exception into the structured error payload the Go and TypeScript
|
|
8
|
+
# SDKs send: message, type, platform, a raw stack string, structured frames (function/
|
|
9
|
+
# filename/lineno/in_app), and the `#cause` chain. Ruby's `backtrace_locations` already
|
|
10
|
+
# gives structured frames for free - no need to parse a stack-trace string the way the
|
|
11
|
+
# Go SDK does.
|
|
12
|
+
#
|
|
13
|
+
# Never raises: a malformed error (a custom #message that itself raises, for example)
|
|
14
|
+
# falls back to a minimal payload rather than taking the publish pipeline down with it.
|
|
15
|
+
module ErrorCapture
|
|
16
|
+
extend T::Sig
|
|
17
|
+
|
|
18
|
+
PLATFORM = "ruby"
|
|
19
|
+
|
|
20
|
+
sig { params(error: Exception).returns(T::Hash[String, T.untyped]) }
|
|
21
|
+
def self.capture(error)
|
|
22
|
+
{
|
|
23
|
+
"message" => safe_message(error),
|
|
24
|
+
"type" => error.class.name,
|
|
25
|
+
"platform" => PLATFORM
|
|
26
|
+
}.merge(stack_and_frames(error)).merge(chain(error))
|
|
27
|
+
rescue => e
|
|
28
|
+
{
|
|
29
|
+
"message" => "[error capture failed: #{e.class}: #{e.message}]",
|
|
30
|
+
"type" => error.class.name,
|
|
31
|
+
"platform" => PLATFORM
|
|
32
|
+
}
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# The error of an isError tool result with no exception behind it, like the TS
|
|
36
|
+
# SDK's `captureCallToolResultError`: its text blocks joined by a space as the
|
|
37
|
+
# message, no type and no stack. nil for a result that isn't an isError result.
|
|
38
|
+
sig { params(result: T.untyped).returns(T.nilable(T::Hash[String, T.untyped])) }
|
|
39
|
+
def self.capture_result(result)
|
|
40
|
+
return nil unless result.is_a?(Hash)
|
|
41
|
+
|
|
42
|
+
flag = result.key?(:isError) ? result[:isError] : result["isError"]
|
|
43
|
+
content = result.key?(:content) ? result[:content] : result["content"]
|
|
44
|
+
return nil unless flag == true && content.is_a?(Array)
|
|
45
|
+
|
|
46
|
+
texts = content.filter_map do |block|
|
|
47
|
+
next if !block.is_a?(Hash) || (block[:type] || block["type"]) != "text"
|
|
48
|
+
|
|
49
|
+
block.key?(:text) ? block[:text] : block["text"]
|
|
50
|
+
end
|
|
51
|
+
message = texts.join(" ").strip
|
|
52
|
+
{"message" => message.empty? ? "Unknown error" : message, "platform" => PLATFORM}
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
sig { params(error: Exception).returns(T::Hash[String, T.untyped]) }
|
|
56
|
+
def self.stack_and_frames(error)
|
|
57
|
+
backtrace = error.backtrace
|
|
58
|
+
return {} if backtrace.nil? || backtrace.empty?
|
|
59
|
+
|
|
60
|
+
result = T.let({"stack" => backtrace.join("\n")}, T::Hash[String, T.untyped])
|
|
61
|
+
frames = frames_from(error)
|
|
62
|
+
result["frames"] = Truncation.truncate_frames(frames) unless frames.empty?
|
|
63
|
+
result
|
|
64
|
+
end
|
|
65
|
+
private_class_method :stack_and_frames
|
|
66
|
+
|
|
67
|
+
sig { params(error: Exception).returns(T::Array[T::Hash[String, T.untyped]]) }
|
|
68
|
+
def self.frames_from(error)
|
|
69
|
+
locations = error.backtrace_locations
|
|
70
|
+
return [] if locations.nil?
|
|
71
|
+
|
|
72
|
+
locations.map do |location|
|
|
73
|
+
path = location.absolute_path || location.path
|
|
74
|
+
{
|
|
75
|
+
"function" => location.label,
|
|
76
|
+
"filename" => location.path,
|
|
77
|
+
"abs_path" => path,
|
|
78
|
+
"lineno" => location.lineno,
|
|
79
|
+
"in_app" => in_app?(path)
|
|
80
|
+
}
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
private_class_method :frames_from
|
|
84
|
+
|
|
85
|
+
# Library/stdlib frames (this gem included) are noise next to the tool's own code.
|
|
86
|
+
sig { params(path: T.nilable(String)).returns(T::Boolean) }
|
|
87
|
+
def self.in_app?(path)
|
|
88
|
+
return true if path.nil?
|
|
89
|
+
|
|
90
|
+
!(Gem.path.any? { |gem_dir| path.start_with?(gem_dir) } || path.start_with?(RbConfig::CONFIG["rubylibdir"]))
|
|
91
|
+
end
|
|
92
|
+
private_class_method :in_app?
|
|
93
|
+
|
|
94
|
+
sig { params(error: Exception).returns(T::Hash[String, T.untyped]) }
|
|
95
|
+
def self.chain(error)
|
|
96
|
+
chained = []
|
|
97
|
+
seen = Set.new
|
|
98
|
+
current = T.let(error.cause, T.nilable(Exception))
|
|
99
|
+
while current && seen.add?(current.object_id) && chained.size < PayloadLimits::MAX_CHAIN_DEPTH
|
|
100
|
+
entry = T.let({"message" => safe_message(current), "type" => current.class.name}, T::Hash[String, T.untyped])
|
|
101
|
+
entry.merge!(stack_and_frames(current))
|
|
102
|
+
chained << entry
|
|
103
|
+
current = current.cause
|
|
104
|
+
end
|
|
105
|
+
chained.empty? ? {} : {"chained_errors" => chained}
|
|
106
|
+
end
|
|
107
|
+
private_class_method :chain
|
|
108
|
+
|
|
109
|
+
sig { params(error: Exception).returns(String) }
|
|
110
|
+
def self.safe_message(error)
|
|
111
|
+
error.message.to_s
|
|
112
|
+
rescue => e
|
|
113
|
+
"[message capture failed: #{e.class}]"
|
|
114
|
+
end
|
|
115
|
+
private_class_method :safe_message
|
|
116
|
+
end
|
|
117
|
+
end
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# typed: true
|
|
2
|
+
|
|
3
|
+
module AgentCat
|
|
4
|
+
# Mints "evt_<KSUID>" ids, same scheme as session ids ("ses_"). The events API
|
|
5
|
+
# will happily 202 a request with no id and then silently drop it server-side,
|
|
6
|
+
# so don't skip this.
|
|
7
|
+
class EventId
|
|
8
|
+
PREFIX = "evt_"
|
|
9
|
+
|
|
10
|
+
class << self
|
|
11
|
+
extend T::Sig
|
|
12
|
+
|
|
13
|
+
sig { returns(String).checked(:tests) }
|
|
14
|
+
def mint
|
|
15
|
+
SessionManager.mint_id(T.must(PREFIX))
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
end
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# typed: true
|
|
2
|
+
|
|
3
|
+
require_relative "redaction"
|
|
4
|
+
require_relative "sanitization"
|
|
5
|
+
require_relative "truncation"
|
|
6
|
+
require_relative "delivery"
|
|
7
|
+
require_relative "exporters"
|
|
8
|
+
|
|
9
|
+
module AgentCat
|
|
10
|
+
# What happens to an event once it's on the queue's worker thread: redact, sanitize,
|
|
11
|
+
# truncate, deliver, export. Shared by tool calls and tracked custom events so the two
|
|
12
|
+
# can't drift apart.
|
|
13
|
+
module EventPipeline
|
|
14
|
+
extend T::Sig
|
|
15
|
+
|
|
16
|
+
# `label` only goes into debug logs, to say which event failed. `redact_strings:
|
|
17
|
+
# false` skips `redact_sensitive_information`: custom events hold only what the
|
|
18
|
+
# customer chose to send, so TS never runs the string hook on them.
|
|
19
|
+
# `redact_event` still runs, as in TS.
|
|
20
|
+
sig { params(event: UnredactedEvent, tracker: Tracker, epoch: Integer, label: String, redact_strings: T::Boolean).void }
|
|
21
|
+
def self.run(event, tracker, epoch:, label:, redact_strings: true)
|
|
22
|
+
options = tracker.options
|
|
23
|
+
|
|
24
|
+
# The hooks get valid UTF-8, so a regex in them can't raise on a binary string.
|
|
25
|
+
Sanitization.scrub_event(event)
|
|
26
|
+
|
|
27
|
+
# Runs here, not before enqueue: matching Go/TS/Python, a slow or uncached redact
|
|
28
|
+
# hook must never add latency to the caller.
|
|
29
|
+
redacted = Redaction.apply_redact_event(event, options)
|
|
30
|
+
return if redacted.nil?
|
|
31
|
+
|
|
32
|
+
event = redact_strings ? Redaction.apply_sensitive_redaction(redacted, options) : redacted
|
|
33
|
+
return if event.nil?
|
|
34
|
+
|
|
35
|
+
normalize(event, label: label)
|
|
36
|
+
return if record_in_fake(event, epoch)
|
|
37
|
+
|
|
38
|
+
# No project id = export-only, skip AgentCat's own API entirely.
|
|
39
|
+
if tracker.project_id
|
|
40
|
+
Delivery.publish(
|
|
41
|
+
options.client,
|
|
42
|
+
event.to_wire_hash,
|
|
43
|
+
max_retries: options.max_retries,
|
|
44
|
+
base_delay: options.retry_base_delay,
|
|
45
|
+
epoch: epoch
|
|
46
|
+
)
|
|
47
|
+
end
|
|
48
|
+
Exporters.dispatch(options.exporters, event)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# `AgentCat.fake`: the event goes to the fake (as it would be sent) instead of
|
|
52
|
+
# AgentCat and the exporters. Returns whether it did. An event from before a
|
|
53
|
+
# `reset!` is dropped, like Delivery does.
|
|
54
|
+
sig { params(event: UnredactedEvent, epoch: Integer).returns(T::Boolean) }
|
|
55
|
+
def self.record_in_fake(event, epoch)
|
|
56
|
+
fake = AgentCat.active_fake
|
|
57
|
+
return false if fake.nil?
|
|
58
|
+
|
|
59
|
+
fake.record(event.to_wire_hash) if epoch == AgentCat.event_epoch
|
|
60
|
+
true
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Fail open like Go/Python: a bug in either step delivers the event as-is rather
|
|
64
|
+
# than dropping it. The UTF-8 scrub runs first and on its own (it never raises), so
|
|
65
|
+
# even then every string encodes as JSON. It runs again here because a hook can put
|
|
66
|
+
# new strings on the event, and untracked custom events come here without `run`.
|
|
67
|
+
sig { params(event: UnredactedEvent, label: String).void }
|
|
68
|
+
def self.normalize(event, label:)
|
|
69
|
+
Sanitization.scrub_event(event)
|
|
70
|
+
sanitize_and_truncate(event, label: label)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
sig { params(event: UnredactedEvent, label: String).void }
|
|
74
|
+
def self.sanitize_and_truncate(event, label:)
|
|
75
|
+
Sanitization.sanitize_event(event)
|
|
76
|
+
Truncation.truncate_event(event)
|
|
77
|
+
rescue => e
|
|
78
|
+
Log.warn("sanitizing or truncating #{label} failed with #{e.class}; the event goes out as it is")
|
|
79
|
+
AgentCat.logger.debug { "sanitization/truncation failed for #{label}: #{e.class}: #{e.message}" }
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
end
|