coolhand 0.11.0 → 0.13.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.
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "json"
6
+ require_relative "errors"
7
+ require_relative "log_queue"
8
+
9
+ module Coolhand
10
+ # The POST half of {ApiService}: the logging writes (logs and feedback). Failures are logged and
11
+ # swallowed (`nil`) so instrumentation can't break the host app, unless the caller opts in with
12
+ # `raise_on_error:`. Sends made from a {LogQueue} worker retry transient failures and report an
13
+ # unrecovered one to {LogQueue}, so `Coolhand.flush` can say the logs were not delivered. Mix into
14
+ # an {ApiService}: it relies on `api_key`, `log`, `apply_headers`, `format_error_body`,
15
+ # `sanitize_payload_for_json` and {ReadRequests#raise_http_error} from there.
16
+ module PostDelivery
17
+ # Retries after the first attempt, and the base of the linear backoff between them.
18
+ LOG_SEND_RETRIES = 2
19
+ RETRY_BACKOFF = 0.5
20
+ # Failures where the log was most likely not stored: the connection never opened, or a proxy or
21
+ # the server turned the request away. A read timeout, a connection reset or a 504 are ambiguous
22
+ # (the server may have stored the log), so they are not retried: a retry could duplicate it.
23
+ RETRYABLE_ERRORS = [Net::OpenTimeout, SocketError, Errno::ECONNREFUSED].freeze
24
+ RETRYABLE_STATUSES = [429, 502, 503].freeze
25
+ MISSING_KEY_MESSAGE = "Request failed: an API key is required"
26
+
27
+ protected
28
+
29
+ # Returns the parsed response on success. On failure returns nil, or raises {Coolhand::HttpError}
30
+ # (non-2xx) / {Coolhand::Error} (everything else) when `raise_on_error`. `background` marks a
31
+ # send from a queue worker: it is retried and its failure recorded for `Coolhand.flush`.
32
+ def send_request(payload, success_message, raise_on_error: false, background: false)
33
+ return reject_missing_key(raise_on_error) if missing_api_key?
34
+
35
+ attempt_send(payload, success_message, raise_on_error: raise_on_error, background: background)
36
+ end
37
+
38
+ def reject_missing_key(raise_on_error)
39
+ raise Error, MISSING_KEY_MESSAGE if raise_on_error
40
+
41
+ nil
42
+ end
43
+
44
+ private
45
+
46
+ def attempt_send(payload, success_message, raise_on_error:, background:)
47
+ result = deliver(build_post(payload), background ? LOG_SEND_RETRIES : 0)
48
+ rescue StandardError => e
49
+ fail_send(e, raise_on_error: raise_on_error, background: background)
50
+ else
51
+ announce_success(success_message)
52
+ result
53
+ end
54
+
55
+ # Outside the rescue above: a failing log write (a closed stdout) must not turn a delivered
56
+ # request into a failure, nor raise into the host app.
57
+ def announce_success(message)
58
+ log message
59
+ rescue StandardError
60
+ nil
61
+ end
62
+
63
+ def build_post(payload)
64
+ uri = URI.parse(@api_endpoint)
65
+ request = Net::HTTP::Post.new(uri.request_uri)
66
+ apply_headers(request, create_request_options(payload))
67
+ # Clean payload and ensure UTF-8 encoding before JSON generation
68
+ request.body = JSON.generate(sanitize_payload_for_json(payload)).force_encoding("UTF-8")
69
+ [uri, request]
70
+ end
71
+
72
+ def deliver(built, retries)
73
+ attempts = 0
74
+ begin
75
+ post_once(*built)
76
+ rescue StandardError => e
77
+ attempts += 1
78
+ raise unless attempts <= retries && transient?(e)
79
+
80
+ log "⚠️ Request failed (#{e.message}); retrying (#{attempts}/#{retries})"
81
+ sleep(RETRY_BACKOFF * attempts)
82
+ retry
83
+ end
84
+ end
85
+
86
+ def post_once(uri, request)
87
+ http = Net::HTTP.new(uri.host, uri.port)
88
+ http.use_ssl = (uri.scheme == "https")
89
+ # Bound worst-case latency: with async_logging off this call happens inline in
90
+ # the intercepted request's path (otherwise it ties up the background log
91
+ # worker), so a slow/unreachable Coolhand backend must not hang for Ruby's
92
+ # ~60s Net::HTTP defaults (a stalled upload hits write_timeout).
93
+ http.open_timeout = 5
94
+ http.read_timeout = 5
95
+ http.write_timeout = 5
96
+
97
+ # This request goes through the same patched Net::HTTP as the host
98
+ # app's real LLM calls. Without this, a base_url/intercept_addresses
99
+ # configuration that also matches Coolhand's own API host would
100
+ # re-intercept this log-shipping call, generating a second log
101
+ # request that itself gets intercepted, and so on — unbounded
102
+ # request amplification.
103
+ response = Coolhand.without_capture { http.request(request) }
104
+ raise_http_error(response, "Coolhand API") unless response.is_a?(Net::HTTPSuccess)
105
+
106
+ parse_success_body(response.body)
107
+ end
108
+
109
+ # The server already accepted the request, so a blank, non-JSON or `null` 2xx body (a 204, say) is
110
+ # still a delivery: reporting it as a failure would make a retrying caller store it twice.
111
+ def parse_success_body(body)
112
+ JSON.parse(body.to_s, symbolize_names: true) || {}
113
+ rescue JSON::ParserError
114
+ {}
115
+ end
116
+
117
+ def transient?(error)
118
+ return RETRYABLE_STATUSES.include?(error.status) if error.is_a?(HttpError)
119
+
120
+ RETRYABLE_ERRORS.any? { |klass| error.is_a?(klass) }
121
+ end
122
+
123
+ def fail_send(error, raise_on_error:, background:)
124
+ log failure_message(error)
125
+ LogQueue.record_failure if background
126
+ return nil unless raise_on_error
127
+
128
+ raise error if error.is_a?(Error)
129
+
130
+ raise Error, "Request failed: #{error.message}"
131
+ end
132
+
133
+ def failure_message(error)
134
+ return "❌ Request error: #{error.message}" unless error.is_a?(HttpError)
135
+
136
+ "❌ Request failed: #{error.status} - #{format_error_body(error.body)}"
137
+ end
138
+ end
139
+ end
@@ -16,6 +16,8 @@ module Coolhand
16
16
  # and one response runs several. A tighter read timeout pre-empts the 504 callers should retry.
17
17
  READ_OPEN_TIMEOUT = 5
18
18
  READ_TIMEOUT = 60
19
+ # A GET writes only its request line and headers, so a stalled write is a dead connection.
20
+ READ_WRITE_TIMEOUT = 5
19
21
 
20
22
  # ERROR_BODY_LIMIT caps the message; this caps the body the exception object itself carries.
21
23
  RETAINED_ERROR_BODY_LIMIT = 8_000
@@ -45,6 +47,12 @@ module Coolhand
45
47
  true
46
48
  end
47
49
 
50
+ def ensure_json_object!(result, noun)
51
+ raise Error, "#{noun} response was not a JSON object" unless result.is_a?(Hash)
52
+
53
+ result
54
+ end
55
+
48
56
  private
49
57
 
50
58
  def perform_get(url, noun)
@@ -68,6 +76,7 @@ module Coolhand
68
76
  http.use_ssl = (uri.scheme == "https")
69
77
  http.open_timeout = READ_OPEN_TIMEOUT
70
78
  http.read_timeout = READ_TIMEOUT
79
+ http.write_timeout = READ_WRITE_TIMEOUT
71
80
  http
72
81
  end
73
82
 
@@ -1,7 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Coolhand
4
- # Prints the `warnings` a Coolhand log response carries, for {ApiService}.
4
+ # Prints the `warnings` a Coolhand log response carries, for {ApiService}. Also owns
5
+ # `strip_control_characters`, which {ApiService#format_error_body} (and so every
6
+ # {ReadRequests}/{WriteRequests} caller) uses on the error body.
5
7
  #
6
8
  # Warnings come from the response body and are written to the host app's stdout, so they are
7
9
  # untrusted: each is coerced to a string, stripped of control characters and length-capped, and
@@ -27,10 +29,15 @@ module Coolhand
27
29
  # Control characters and line/paragraph separators are replaced with a space, not dropped: a
28
30
  # newline would forge a log line and ESC starts a terminal escape sequence. Unicode format
29
31
  # characters (bidi overrides, zero-width) are invisible and can reorder or hide text in a
30
- # terminal, so they are removed outright.
32
+ # terminal, so they are removed outright. Shared with ApiService#format_error_body, which
33
+ # prints another server-controlled string.
34
+ def strip_control_characters(value)
35
+ text = value.to_s.dup.force_encoding("UTF-8").scrub
36
+ text.gsub(/\p{Cf}+/, "").gsub(/[[:cntrl:]\p{Zl}\p{Zp}]+/, " ").strip
37
+ end
38
+
31
39
  def sanitize_warning(warning)
32
- text = warning.to_s.dup.force_encoding("UTF-8").scrub
33
- text = text.gsub(/\p{Cf}+/, "").gsub(/[[:cntrl:]\p{Zl}\p{Zp}]+/, " ").strip
40
+ text = strip_control_characters(warning)
34
41
  return text if text.length <= MAX_WARNING_LENGTH
35
42
 
36
43
  "#{text[0, MAX_WARNING_LENGTH]}... [truncated]"
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "api_service"
4
+
5
+ module Coolhand
6
+ # Reads the client's realized savings: a singleton keyed by the authenticating API key, with no id
7
+ # and no filters. Requires the **private** key; the public key is rejected like an invalid one.
8
+ # See docs/savings.md.
9
+ class SavingsService < ApiService
10
+ ERROR_NOUN = "Savings"
11
+
12
+ def initialize
13
+ super("v2/savings")
14
+ end
15
+
16
+ # What this client saved by switching templates or models: the cost of requests served by the
17
+ # current templates versus the deprecated versions they replaced (deprecations in the last three
18
+ # months, fixed server-side).
19
+ #
20
+ # Returns a Symbol-keyed Hash: `:total`, `:cost_at_previous_versions`, `:percent` and `:workloads`
21
+ # (each row `:id`, `:name`, `:savings`, `:cost_at_previous_versions`, `:active_requests`). A client
22
+ # with nothing to compare gets zeros and an empty `:workloads`, which is real zero savings.
23
+ #
24
+ # Raises {Coolhand::HttpError} on a non-2xx response: `401` for a missing, invalid or public key,
25
+ # and `503` when the comparison could not be computed. A `503` is NOT zero savings; it is
26
+ # retryable, so never map it to zeros.
27
+ #
28
+ # The name is the API definition's operationId; this is a network read, not an accessor.
29
+ def get_realized_savings # rubocop:disable Naming/AccessorMethodName
30
+ ensure_json_object!(get_json(api_endpoint, ERROR_NOUN), ERROR_NOUN)
31
+ end
32
+ end
33
+ end
@@ -4,10 +4,13 @@ module Coolhand
4
4
  # Redacts credentials in raw String bodies, which BodyRedactor's tree walk never sees: a streamed
5
5
  # (server-sent event) response arrives as one String of `data: {...}` lines, and a webhook body
6
6
  # may be raw JSON text. Each JSON object/array payload is parsed, run through BodyRedactor and
7
- # re-serialized; text that is not JSON (plain text, `[DONE]`, `event:` and comment lines, a
8
- # payload that fails to parse) is left byte for byte. A JSON payload is always re-serialized, even
9
- # when nothing in it needed redacting: JSON.parse keeps only the last of a repeated key, so
10
- # "nothing changed" cannot be trusted to mean "no credential in the original text".
7
+ # re-serialized; text that is not JSON (plain text, `[DONE]`, `event:` and comment lines) is left
8
+ # byte for byte. JSON that fails to parse (typically a stream cut off mid-line) cannot be
9
+ # re-serialized, so each credential-named string value in it is scrubbed in place instead: the
10
+ # rest of the partial text is kept, and an unterminated value is scrubbed to the end of the text.
11
+ # A JSON payload is always re-serialized, even when nothing in it needed redacting: JSON.parse
12
+ # keeps only the last of a repeated key, so "nothing changed" cannot be trusted to mean "no
13
+ # credential in the original text".
11
14
  module StringBodyRedactor
12
15
  module_function
13
16
 
@@ -19,6 +22,13 @@ module Coolhand
19
22
  # a rewritten line keeps its own.
20
23
  DATA_LINE = /(?<![^\r\n\uFEFF])data:([ \t]*)([^\r\n]*)/
21
24
  JSON_CONTAINER = /\A\uFEFF?\s*[\[{]/
25
+ # Scans JSON text that may not parse, one string literal at a time: a `"key": "value"` pair
26
+ # (first alternative; the key is group 1, the separator group 2) or any other string literal
27
+ # (second alternative, consumed whole so a quote inside it never starts a new match and the
28
+ # scan stays linear even when a regex engine does not memoize, as before Ruby 3.2). A string
29
+ # ends at its closing quote, or at the end of the text when it was cut off (possibly right
30
+ # after a backslash).
31
+ STRING_PAIR = /("(?:[^"\\]|\\.)*")(\s*:\s*)"(?:[^"\\]|\\.)*(?:"|\\?\z)|"(?:[^"\\]|\\.)*(?:"|\\?\z)/m
22
32
 
23
33
  def redact(body)
24
34
  text = utf8_text(body)
@@ -45,22 +55,61 @@ module Coolhand
45
55
 
46
56
  # One pass with gsub (linear in the body); the original String is returned when no line differs
47
57
  # once re-serialized (providers emit compact JSON, so a clean stream usually round-trips as is).
58
+ # Text that starts like JSON but did not parse as one document (a body cut off mid-value) also
59
+ # has its credential-named string values scrubbed.
48
60
  def redact_stream(body, text)
49
- changed = false
50
61
  redacted = text.gsub(DATA_LINE) do |line|
51
62
  match = Regexp.last_match
52
- payload = match[2].match?(JSON_CONTAINER) ? redacted_json(match[2]) : nil
63
+ payload = redact_payload(match[2])
53
64
  next line if payload.nil? || payload == match[2]
54
65
 
55
- changed = true
56
66
  "data:#{match[1]}#{payload}"
57
67
  end
58
- changed ? redacted : body
68
+ redacted = scrub_credential_strings(redacted) if text.match?(JSON_CONTAINER)
69
+ redacted == text ? body : redacted
59
70
  end
60
71
 
61
- # The redacted, re-serialized JSON; nil when the text should stay as is (not a JSON
62
- # object/array, or unparsable). Anything else that goes wrong yields a `redaction_failed`
63
- # marker rather than the unchecked text.
72
+ # The redacted text of a `data:` payload, or nil when it is not JSON-looking and stays as is.
73
+ def redact_payload(payload)
74
+ return unless payload.match?(JSON_CONTAINER)
75
+
76
+ redacted_json(payload) || scrub_credential_strings(payload)
77
+ end
78
+
79
+ # Fallback for JSON text that did not parse: replaces the value of every credential-named
80
+ # string pair (see BodyRedactor::CREDENTIAL_BODY_KEYS) without needing a valid document.
81
+ # URL-valued keys and `client_secret` objects are only handled for parsed JSON.
82
+ def scrub_credential_strings(text)
83
+ text.gsub(STRING_PAIR) do |pair|
84
+ match = Regexp.last_match
85
+ next pair unless match[1] && credential_key?(match[1])
86
+
87
+ "#{match[1]}#{match[2]}#{JSON.generate(BaseInterceptor::REDACTED)}"
88
+ end
89
+ end
90
+
91
+ # `quoted_key` is a JSON string literal, so decode it (`"\u0061pi_key"` names `api_key`).
92
+ def credential_key?(quoted_key)
93
+ BodyRedactor::CREDENTIAL_BODY_KEYS.include?(BodyRedactor.normalize_body_key(decode_key(quoted_key)))
94
+ end
95
+
96
+ # A literal the JSON parser rejects (an invalid escape such as `\_`, a raw control character)
97
+ # is decoded leniently, the way older JSON versions did: `\uXXXX` becomes its character and any
98
+ # other backslash is dropped, so `"api\_key"` still names `api_key` and its value is scrubbed.
99
+ # `scrub` because a lone low surrogate (`"\udc00"`) parses to an invalid UTF-8 String, which
100
+ # String#delete would reject and fail the whole body closed instead of just this one key.
101
+ def decode_key(quoted_key)
102
+ JSON.parse(quoted_key).scrub
103
+ rescue JSON::ParserError
104
+ quoted_key[1..-2].gsub(/\\(?:u(\h{4})|(.))/m) do
105
+ hex, char = Regexp.last_match.captures
106
+ hex ? [hex.hex].pack("U") : char
107
+ end.scrub
108
+ end
109
+
110
+ # The redacted, re-serialized JSON; nil when the text is not a parseable JSON object/array
111
+ # (callers fall back to scrub_credential_strings for the unparseable case). Anything else that
112
+ # goes wrong yields a `redaction_failed` marker rather than the unchecked text.
64
113
  def redacted_json(text)
65
114
  # NaN/Infinity are not JSON, but some servers emit them; a payload that failed to parse
66
115
  # would be logged unredacted next to its credential-named fields.
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Coolhand
4
- VERSION = "0.11.0"
4
+ VERSION = "0.13.0"
5
5
  end
@@ -8,10 +8,10 @@ require_relative "read_requests"
8
8
 
9
9
  module Coolhand
10
10
  # POST/DELETE counterpart of {ReadRequests} for callers that act on the response: raises on any
11
- # failure where {ApiService#send_request} logs and returns nil. Timeouts are the read ones, for
11
+ # failure where {PostDelivery#send_request} logs and returns nil by default. Timeouts are the read ones, for
12
12
  # the same server-side statement-bound reason. Mix into an {ApiService} subclass: it relies on
13
- # `api_key`, `apply_headers` and `format_error_body` from there and the shared HTTP helpers from
14
- # {ReadRequests}.
13
+ # `api_key`, `apply_headers` and `format_error_body` (which in turn needs {ResponseWarnings}'
14
+ # `strip_control_characters`) from there and the shared HTTP helpers from {ReadRequests}.
15
15
  module WriteRequests
16
16
  DOT_SEGMENTS = [".", ".."].freeze
17
17
 
data/lib/coolhand.rb CHANGED
@@ -26,6 +26,7 @@ require_relative "coolhand/template_service"
26
26
  require_relative "coolhand/step_template_service"
27
27
  require_relative "coolhand/optimization_feedback_link_service"
28
28
  require_relative "coolhand/workload_service"
29
+ require_relative "coolhand/savings_service"
29
30
  require_relative "coolhand/help_center_service"
30
31
  require_relative "coolhand/log_service"
31
32
  require_relative "coolhand/webhook_interceptor"
@@ -96,19 +97,25 @@ module Coolhand
96
97
  # Declares the workload/template that LLM calls captured inside the block belong to. Nested
97
98
  # blocks override per field (`reporter`, `workload`, `template`), innermost wins. `workload` and
98
99
  # `template` are Hashes with `id:` (an existing record) or `key:` (find-or-created), plus optional
99
- # `name:` (and `description:` on a workload). See docs/declared_workloads.md.
100
+ # `name:` (and `description:` on a workload). `client_unique_id:` is your own id (a non-blank String
101
+ # of at most 255 characters, no control or invisible characters) stamped on the logs captured in the block, so
102
+ # `FeedbackService#create_feedback(client_unique_id:)` can find them; an invalid one is ignored.
103
+ # See docs/declared_workloads.md.
100
104
  #
101
105
  # Example:
102
106
  # Coolhand.with_context(reporter: "squishling", workload: { key: "Parser#call" }) { client.chat(...) }
103
- def with_context(reporter: nil, workload: nil, template: nil, &block)
107
+ def with_context(reporter: nil, workload: nil, template: nil, client_unique_id: nil, &block)
104
108
  raise ArgumentError, "Coolhand.with_context requires a block" unless block
105
109
 
106
- DeclaredContext.with(reporter: reporter, workload: workload, template: template, &block)
110
+ DeclaredContext.with(reporter: reporter, workload: workload, template: template,
111
+ client_unique_id: client_unique_id, &block)
107
112
  end
108
113
 
109
114
  # Blocks until log requests queued by async logging have been sent, or the timeout (in
110
- # seconds) elapses. Returns true if everything was sent. Pending logs are also flushed
111
- # automatically at process exit.
115
+ # seconds) elapses. Returns true if everything was sent, false on a timeout or if a log was
116
+ # not delivered (a send that failed after retrying transient errors, a job that raised, or a
117
+ # log dropped from a full queue) since the previous flush that drained.
118
+ # Pending logs are also flushed automatically at process exit.
112
119
  def flush(timeout: LogQueue::DEFAULT_FLUSH_TIMEOUT)
113
120
  LogQueue.flush(timeout)
114
121
  end
@@ -152,6 +159,12 @@ module Coolhand
152
159
  WorkloadService.new
153
160
  end
154
161
 
162
+ # Creates a new SavingsService instance, for reading the client's realized savings. Needs the
163
+ # private API key.
164
+ def savings_service
165
+ SavingsService.new
166
+ end
167
+
155
168
  # Creates a new LogService instance, for reading logs back out of Coolhand. Distinct from
156
169
  # {logger_service}, which writes them. Needs the private API key.
157
170
  def log_service
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: coolhand
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.11.0
4
+ version: 0.13.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Michael Carroll
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: exe
11
11
  cert_chain: []
12
- date: 2026-11-08 00:00:00.000000000 Z
12
+ date: 2026-11-25 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: base64
@@ -54,6 +54,7 @@ files:
54
54
  - docs/help-center.md
55
55
  - docs/log-search.md
56
56
  - docs/openai.md
57
+ - docs/savings.md
57
58
  - docs/step-templates.md
58
59
  - docs/template-search.md
59
60
  - docs/vertex.md
@@ -84,11 +85,13 @@ files:
84
85
  - lib/coolhand/optimization_feedback_link_service.rb
85
86
  - lib/coolhand/pagination.rb
86
87
  - lib/coolhand/path_normalizer.rb
88
+ - lib/coolhand/post_delivery.rb
87
89
  - lib/coolhand/rails_auto_declare.rb
88
90
  - lib/coolhand/railtie.rb
89
91
  - lib/coolhand/read_query.rb
90
92
  - lib/coolhand/read_requests.rb
91
93
  - lib/coolhand/response_warnings.rb
94
+ - lib/coolhand/savings_service.rb
92
95
  - lib/coolhand/step_template_service.rb
93
96
  - lib/coolhand/stream_read.rb
94
97
  - lib/coolhand/string_body_redactor.rb