coolhand 0.11.0 → 0.12.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: 0643c994a7f5032e47c8f5abd9276dafdb6b1dfe74fd9ec0c0b82c4a62fe59a2
4
- data.tar.gz: f1dc8be18a069e2ded6808153db13480df36e11ba03fbbb94dd220531baa055e
3
+ metadata.gz: 02770efbe420009dbffca43e9bddca98dc83948078e6bc4f613d1c2a2778d69c
4
+ data.tar.gz: ef929d84c508a650cd40fbc41a95e53e311ae64543c608e5b7d18a572832483a
5
5
  SHA512:
6
- metadata.gz: 8880da761ef592e427b577676d1699059bbb5705a4e0f7ffe6086cce5d7a7b0fecd3f7f90bba0b4a476f8d75d8938a33a1fe868ade248b4b70a114a8a4f1b3bf
7
- data.tar.gz: aafbecd72485fecb263599ad2370094d0818d6abef830bceaaceb3005cbb165c40f6077b7545ecfc6cb58889bad420f4bd6f5158463efcf8daa1b5d6674897c3
6
+ metadata.gz: feecbb0ca4a341f61d652fa38c8207c967b793d12ffabc005986b8db80d1df8428ad7de05aa51f082d160123ffe8f7e75a6e3ec95358f2119cf4e5a8776ef653
7
+ data.tar.gz: 8aa7e045b006316891ff22ebb67c59b32be8063b232dae7af6c02ef0af0dfbd81f97fd9a4b38dd9931a252806b33ca258df862600c48244b8c389d20c16563be
data/CHANGELOG.md CHANGED
@@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.12.0] - 2026-11-23
11
+
12
+ ### Added
13
+ - `Coolhand.savings_service.get_realized_savings` ([#220](https://github.com/Coolhand-Labs/coolhand-ruby/pull/220)) reads the client's realized savings (`GET /api/v2/savings`): what requests on the current templates cost versus the deprecated versions they replaced, in total and per workload. It takes no parameters and returns one Symbol-keyed Hash. A non-2xx response raises `Coolhand::HttpError`; a `503` means the figure could not be computed right now and is not zero savings. Needs the private API key. See [Reading Realized Savings](docs/savings.md).
14
+ - `Coolhand.with_context(client_unique_id: "abc.1") { ... }` ([#222](https://github.com/Coolhand-Labs/coolhand-ruby/pull/222)) stamps your own id on every log captured in the block, so `create_feedback(client_unique_id: "abc.1")` has a log-side id to match. It nests like the other fields (innermost wins, restored on exit) and works without a workload or template. The id is sent as top-level `llm_request_log.client_unique_id`, not inside `declared`. **Note:** exact matching needs the matching Coolhand server change ([Coolhand-Labs/coolhand#2316](https://github.com/Coolhand-Labs/coolhand/pull/2316)), which stores `client_unique_id` on logs and matches feedback by it before any text matching. Until it is deployed to your Coolhand instance, the id is sent but not stored or matched. See [Declared Workloads](docs/declared_workloads.md).
15
+
16
+ ### Changed
17
+ - An invalid `client_unique_id` (not a String, blank, over 255 characters, or containing control or invisible characters) is ignored and logged rather than raised, so a bad correlation id never breaks your LLM call or risks a 422 on the log ([#222](https://github.com/Coolhand-Labs/coolhand-ruby/pull/222)).
18
+ - Docs: `docs/anthropic.md` "Request Correlation" no longer references the nonexistent `Thread.current[:coolhand_current_request_id]` or `FeedbackService.new(Coolhand.configuration)`, and `docs/feedback.md` documents the `client_unique_id` flow ([#222](https://github.com/Coolhand-Labs/coolhand-ruby/pull/222)).
19
+ - Internal: the "response was not a JSON object" check now lives in `ReadRequests#ensure_json_object!`, shared by the savings and optimization feedback link services ([#220](https://github.com/Coolhand-Labs/coolhand-ruby/pull/220)).
20
+ - The `/finish-release` skill may use `gh pr merge --admin` only to bypass the "only maintainers can merge" ruleset, after a plain merge is refused and every check is green ([#217](https://github.com/Coolhand-Labs/coolhand-ruby/pull/217)).
21
+
22
+ ### Dependencies
23
+ - `ruby/setup-ruby` bumped to 1.338.0 in CI and the publish workflow ([#218](https://github.com/Coolhand-Labs/coolhand-ruby/pull/218)).
24
+
10
25
  ## [0.11.0] - 2026-11-06
11
26
 
12
27
  ### Added
data/README.md CHANGED
@@ -117,6 +117,18 @@ step[:metrics][:notes]
117
117
 
118
118
  For the parameters, `metrics` fields and errors, see [Reading Step Templates →](docs/step-templates.md).
119
119
 
120
+ ### Realized savings
121
+
122
+ `Coolhand.savings_service.get_realized_savings` returns what you saved by switching templates or models, in total and per workload, with the same private API key. It takes no parameters; a `503` means the figure could not be computed right now and is not zero savings.
123
+
124
+ ```ruby
125
+ savings = Coolhand.savings_service.get_realized_savings
126
+ savings[:total] # USD saved against the deprecated versions
127
+ savings[:percent] # share of what they would have cost
128
+ ```
129
+
130
+ For the return value, errors, and joining it with workload metrics, see [Reading Realized Savings →](docs/savings.md).
131
+
120
132
  ### Cost and performance metrics
121
133
 
122
134
  Pass `include_metrics: true` to `search_templates` (or `search_workloads`) for the dashboard's cost and performance numbers, over a rolling `days_back` window or an explicit `since:` / `until:` one. `search_logs` carries each log's `cost` and can sort and filter by it. `failure_summary` rolls failed requests up by error pattern and template, and `search_logs(error_contains:)` lists the logs behind a pattern.
@@ -521,7 +533,7 @@ The monitor handles errors gracefully:
521
533
  - Failed API logging attempts are logged to console but don't interrupt your application
522
534
  - Invalid API keys will be reported but won't crash your app
523
535
  - Network issues are handled with appropriate error messages
524
- - The read methods (`search_templates`, `get_template`, `list_step_templates`, `get_step_template`, `search_workloads`, `search_logs`, `get_log`, `failure_summary`, `search_help_articles`, `get_help_article`, `list_help_categories`), the feedback-link methods and the `upsert` methods are the exception — they raise `Coolhand::Error` (`Coolhand::HttpError` for non-2xx responses); see [Reading Templates →](docs/template-search.md), [Reading Step Templates →](docs/step-templates.md), [Reading Workloads →](docs/workload-search.md), [Reading Logs →](docs/log-search.md), [Linking Feedback →](docs/feedback-links.md) and [Declared Workloads →](docs/declared_workloads.md)
536
+ - The read methods (`search_templates`, `get_template`, `list_step_templates`, `get_step_template`, `search_workloads`, `get_realized_savings`, `search_logs`, `get_log`, `failure_summary`, `search_help_articles`, `get_help_article`, `list_help_categories`), the feedback-link methods and the `upsert` methods are the exception — they raise `Coolhand::Error` (`Coolhand::HttpError` for non-2xx responses); see [Reading Templates →](docs/template-search.md), [Reading Step Templates →](docs/step-templates.md), [Reading Workloads →](docs/workload-search.md), [Reading Realized Savings →](docs/savings.md), [Reading Logs →](docs/log-search.md), [Linking Feedback →](docs/feedback-links.md) and [Declared Workloads →](docs/declared_workloads.md)
525
537
 
526
538
  ## Documentation
527
539
 
@@ -530,6 +542,7 @@ The monitor handles errors gracefully:
530
542
  - **[Reading Templates](docs/template-search.md)** — Search LLM request templates and fetch a single one, prompt patterns included, using the private API key
531
543
  - **[Reading Step Templates](docs/step-templates.md)** — List the skills and recurring steps detected in captured agent sessions, with run and efficiency metrics, using the private API key
532
544
  - **[Reading Workloads](docs/workload-search.md)** — List workloads with optional cost and performance metrics over a rolling or explicit time window
545
+ - **[Reading Realized Savings](docs/savings.md)** — Fetch the saving realized by switching templates or models, in total and per workload, and join it with workload metrics
533
546
  - **[Reading Logs](docs/log-search.md)** — Search logs with per-log cost, filter and sort by cost, and fetch one log with its cost breakdown
534
547
  - **[Reading the Help Center](docs/help-center.md)** — Search and read Coolhand's help center articles and list its sections, with no API key required
535
548
  - **[Linking Feedback](docs/feedback-links.md)** — Link feedback to an optimization as evidence, singly or in bulk, using the private API key
data/docs/anthropic.md CHANGED
@@ -305,32 +305,32 @@ threads.each(&:join)
305
305
 
306
306
  ### Request Correlation
307
307
 
308
- Access the current request ID for correlation:
308
+ Tag a request with your own id, then send feedback against it:
309
309
 
310
310
  ```ruby
311
311
  client = Anthropic::Client.new
312
312
 
313
- response = client.messages(
314
- parameters: {
315
- model: "claude-3-sonnet-20240229",
316
- max_tokens: 1000,
317
- messages: [{ role: "user", content: "Hello" }]
318
- }
319
- )
320
-
321
- # Get the request ID that was logged to Coolhand
322
- request_id = Thread.current[:coolhand_current_request_id]
323
- puts "Logged to Coolhand with ID: #{request_id}"
313
+ Coolhand.with_context(client_unique_id: "support-ticket-123.1") do
314
+ client.messages(
315
+ parameters: {
316
+ model: "claude-3-sonnet-20240229",
317
+ max_tokens: 1000,
318
+ messages: [{ role: "user", content: "Hello" }]
319
+ }
320
+ )
321
+ end
324
322
 
325
- # Use this ID for feedback or debugging
326
- feedback_service = Coolhand::FeedbackService.new(Coolhand.configuration)
327
- feedback_service.create_feedback(
328
- llm_request_log_id: request_id,
323
+ # The log is tagged with the id above, so feedback can be matched to that request
324
+ Coolhand.flush # logs are sent in the background; make sure this one has been delivered
325
+ Coolhand.feedback_service.create_feedback(
326
+ client_unique_id: "support-ticket-123.1",
329
327
  sentiment: "like",
330
328
  explanation: "Great response quality"
331
329
  )
332
330
  ```
333
331
 
332
+ See [Declaring workloads and templates](declared_workloads.md#linking-feedback-to-a-request) for the id rules.
333
+
334
334
  ## Troubleshooting
335
335
 
336
336
  ### Debug Mode
@@ -24,6 +24,7 @@ end
24
24
  | `reporter` | String | Who is making the declaration, e.g. the library or app. Used when a record is first created. |
25
25
  | `workload` | Hash: `id`, `key`, `name`, `description` | Needs an `id` or a `key`. Other keys are ignored. |
26
26
  | `template` | Hash: `id`, `key`, `name` | Needs an `id` or a `key`. Other keys are ignored. |
27
+ | `client_unique_id` | String | Your own id for the request, so feedback can find it. See [Linking feedback to a request](#linking-feedback-to-a-request). |
27
28
 
28
29
  - `id` refers to an existing record. `key` is a stable string of your choosing; Coolhand finds or creates the record with that key. On a template, `id` wins over `key`.
29
30
  - `name`, `description` and `reporter` are used only when a record is **first created**. Declaring never renames or re-attributes an existing record; use `upsert` for that. A display name that is already taken gets a numeric suffix, and names such as "Unmatched" are reserved.
@@ -35,7 +36,7 @@ end
35
36
 
36
37
  ### Nesting
37
38
 
38
- Blocks nest. Each field (`reporter`, `workload`, `template`) is taken from the innermost block that sets it, and fields an inner block leaves out are inherited (with the one exception below):
39
+ Blocks nest. Each field (`reporter`, `workload`, `template`, `client_unique_id`) is taken from the innermost block that sets it, and fields an inner block leaves out are inherited (with the one exception below):
39
40
 
40
41
  ```ruby
41
42
  Coolhand.with_context(reporter: "my-app", workload: { key: "Parser#call" }) do
@@ -49,6 +50,28 @@ A template belongs to a workload, so an inner block that declares a `workload` w
49
50
 
50
51
  A `workload` or `template` Hash is replaced as a whole, not merged key by key. An inner `workload: { key: "b" }` inside an outer `workload: { id: "a" }` declares only `b`, rather than a mix of `id` and `key`.
51
52
 
53
+ ### Linking feedback to a request
54
+
55
+ `client_unique_id` stamps an id of your own on every log captured in the block. Pass the same id to `create_feedback` so the feedback can be matched to that request exactly, instead of by fuzzy `original_output` comparison.
56
+
57
+ ```ruby
58
+ Coolhand.with_context(workload: { key: "Triage#call" }, client_unique_id: "abc.1") do
59
+ client.chat(...) # logged with client_unique_id "abc.1"
60
+ end
61
+
62
+ Coolhand.feedback_service.create_feedback(
63
+ client_unique_id: "abc.1",
64
+ sentiment: "dislike",
65
+ revised_output: "..."
66
+ )
67
+ ```
68
+
69
+ - It must be a non-blank String of at most 255 characters with no control or invisible characters. An invalid value is **ignored** rather than raised: your block still runs and the call is logged, just without the id.
70
+ - Use an id that is unique per request (e.g. `"<call_id>.<n>"`). Every call inside the block carries the same id, so wrap one LLM call per block when you need to tell them apart.
71
+ - Logs are sent in the background by default, so call `Coolhand.flush` before `create_feedback` if the feedback might otherwise arrive before the request it refers to.
72
+ - It travels as `llm_request_log.client_unique_id`, not inside `declared`, and it works without a `workload` or `template`.
73
+ - Matching happens on the Coolhand server, so whether the id is honoured depends on the server version. What happens when two logs share an id is also decided by the server.
74
+
52
75
  ### Threads and background logging
53
76
 
54
77
  The context is thread-local, like `Coolhand.with_capture`. It is also fiber-local, so it does not carry into threads, fibers, `Enumerator#next` blocks or async tasks you start inside the block; calls made there are captured without a declaration. The identity is read on the thread that made the LLM call, before the log is queued, so it survives `async_logging` (the default).
data/docs/feedback.md CHANGED
@@ -27,6 +27,17 @@ feedback_service.create_feedback(
27
27
  )
28
28
  ```
29
29
 
30
+ To link feedback to a specific request without storing the log ID, tag the request with your own id first:
31
+
32
+ ```ruby
33
+ Coolhand.with_context(client_unique_id: 'order-42.1') do
34
+ client.chat(...) # logged with client_unique_id 'order-42.1'
35
+ end
36
+
37
+ Coolhand.flush # logs are sent in the background; make sure this one has been delivered
38
+ feedback_service.create_feedback(client_unique_id: 'order-42.1', sentiment: 'like')
39
+ ```
40
+
30
41
  ---
31
42
 
32
43
  ## Field Reference
@@ -41,7 +52,7 @@ These fields identify which LLM request the feedback refers to. Use the most spe
41
52
  |---|---|---|
42
53
  | `llm_request_log_id` | Exact | Hashid returned when the original request was logged (a raw integer FK is also still accepted for backward compatibility). Most reliable. |
43
54
  | `llm_provider_unique_id` | Exact | The provider's own request ID (e.g. `x-request-id` from Anthropic or OpenAI). |
44
- | `client_unique_id` | Exact | Your own internal identifier for the request (e.g. a database row ID). |
55
+ | `client_unique_id` | Exact | Your own identifier for the request. Stamp it on the log with [`Coolhand.with_context(client_unique_id:)`](declared_workloads.md#linking-feedback-to-a-request), then pass the same value here. |
45
56
  | `original_output` | Fuzzy | The raw text the LLM produced. Used for fuzzy matching when no ID is available — less reliable. |
46
57
 
47
58
  ### Quality Signals
data/docs/savings.md ADDED
@@ -0,0 +1,95 @@
1
+ # Reading Realized Savings
2
+
3
+ `Coolhand::SavingsService#get_realized_savings` returns the saving your client has realized by
4
+ switching templates or models: what the requests served by the current templates cost, versus what the
5
+ same requests would have cost on the deprecated versions they replaced. It is the figure the dashboard
6
+ shows. It wraps `GET /api/v2/savings` and is read-only.
7
+
8
+ **Auth:** requires your **private** API key. The public key is rejected exactly like an invalid key.
9
+
10
+ **Scoping:** the client is always derived from your API key. There is deliberately no `client_id`
11
+ keyword, and no keyword of any kind.
12
+
13
+ **Window:** the comparison covers deprecations from the last three months, fixed server-side. It is
14
+ not tied to a request window, so there is no `days_back`. The result is cached server-side for an hour.
15
+
16
+ ```ruby
17
+ require "coolhand"
18
+
19
+ Coolhand.configure do |config|
20
+ config.api_key = ENV.fetch("COOLHAND_PRIVATE_API_KEY")
21
+ end
22
+
23
+ savings = Coolhand.savings_service.get_realized_savings
24
+ savings[:total] # => 4.5372 (USD)
25
+ savings[:percent] # => 79.7
26
+ ```
27
+
28
+ ## Return value
29
+
30
+ A Symbol-keyed Hash:
31
+
32
+ ```ruby
33
+ {
34
+ total: 4.5372, # the saving, USD
35
+ cost_at_previous_versions: 5.6912, # the baseline the saving is measured against, USD
36
+ percent: 79.7, # total as a share of the baseline, one decimal; 0.0 when the baseline is 0
37
+ workloads: [
38
+ {
39
+ id: "xwjm0lgsdmy4", # workload hashid, same as search_workloads
40
+ name: "Help Center Article Suggester",
41
+ savings: 2.0437,
42
+ cost_at_previous_versions: 3.0402,
43
+ active_requests: 182
44
+ }
45
+ ]
46
+ }
47
+ ```
48
+
49
+ Money values are USD floats rounded to 4 decimals. `workloads` lists only workloads with a template
50
+ deprecated in the last three months, and every row always carries all five keys. A client with nothing
51
+ to compare gets `{ total: 0.0, cost_at_previous_versions: 0.0, percent: 0.0, workloads: [] }`, which is
52
+ real zero savings.
53
+
54
+ ## Errors
55
+
56
+ `Coolhand::HttpError` carries `#status` and `#body` on a non-2xx response.
57
+
58
+ | status | when |
59
+ |---|---|
60
+ | `401` | No API key, an invalid key, or the public key. |
61
+ | `503` | The comparison could not be computed right now. Retryable. |
62
+
63
+ **A `503` is not zero savings.** Do not map it to zeros; show it as an error and retry.
64
+ `Coolhand::Error` covers no API key configured, a transport failure, and a body that is not a JSON
65
+ object.
66
+
67
+ ## Combining it with workload metrics
68
+
69
+ `savings` is **not windowed**, but a workload's `metrics` from
70
+ `search_workloads(include_metrics: true, days_back: N)` are. A workload's `savings` can therefore exceed
71
+ its windowed `metrics[:total_cost]`; do not read the two as a ratio over the same period. Join the two
72
+ on `id` to build a per-workload ROI view:
73
+
74
+ ```ruby
75
+ # Archived and system workloads can still carry realized savings, so include them or their rows go unmatched.
76
+ workloads = Coolhand.workload_service.search_workloads(
77
+ include_metrics: true, days_back: 30, include_archived: true, include_system: true, per: 100
78
+ ).workloads
79
+ savings = Coolhand.savings_service.get_realized_savings
80
+
81
+ savings_by_id = savings[:workloads].to_h { |row| [row[:id], row] }
82
+
83
+ roi = workloads.map do |workload|
84
+ {
85
+ id: workload[:id],
86
+ name: workload[:name],
87
+ spend_last_30_days: workload.dig(:metrics, :total_cost), # windowed
88
+ realized_savings: savings_by_id.dig(workload[:id], :savings) || 0 # not windowed
89
+ }
90
+ end
91
+ ```
92
+
93
+ This reads one page of up to 100 workloads; `search_workloads` is paged (`page`, `per`), so repeat the
94
+ call while `pagination.has_next_page` is true for a client with more. The `get_client_roi_summary` MCP
95
+ tool performs the same join over the two endpoints.
@@ -73,7 +73,7 @@ module Coolhand
73
73
 
74
74
  if key_down == "authorization"
75
75
  sanitized[k] = if v.to_s.match?(/\ABearer\s+/i)
76
- v.to_s.gsub(/\ABearer\s+.+/i, "Bearer [REDACTED]")
76
+ v.to_s.gsub(/\ABearer\s+.+/im, "Bearer [REDACTED]")
77
77
  else
78
78
  "[REDACTED]"
79
79
  end
@@ -267,7 +267,11 @@ module Coolhand
267
267
  raw_request[:stream_incomplete] = true if stream_incomplete
268
268
 
269
269
  request_data = { raw_request: raw_request }
270
+ # client_unique_id rides in the snapshot but is a log attribute, not workload identity.
271
+ client_unique_id = declared&.dig(:client_unique_id)
272
+ declared = declared&.except(:client_unique_id)
270
273
  request_data[:declared] = declared if declared && !declared.empty?
274
+ request_data[:client_unique_id] = client_unique_id if client_unique_id
271
275
 
272
276
  LogQueue.submit do
273
277
  Coolhand::ApiService.new.send_llm_request_log(request_data)
@@ -1,9 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Coolhand
4
- # Ambient workload/template identity for captured calls, set with {Coolhand.with_context}. The
5
- # interceptor snapshots {current} on the calling thread before a log is queued, because the
6
- # background log worker does not inherit thread-locals. See docs/declared_workloads.md.
4
+ # Ambient workload/template identity and caller-supplied `client_unique_id` for captured calls, set
5
+ # with {Coolhand.with_context}. The interceptor snapshots {current} on the calling thread before a
6
+ # log is queued, because the background log worker does not inherit thread-locals. See
7
+ # docs/declared_workloads.md.
7
8
  module DeclaredContext
8
9
  THREAD_KEY = :coolhand_declared_context
9
10
 
@@ -27,12 +28,13 @@ module Coolhand
27
28
  # key by key: `{ id: x }` merged with `{ key: y }` would declare both, and the server prefers `id`.
28
29
  # A template belongs to a workload, so a block that declares a workload without a template does
29
30
  # not inherit the outer one; it would pair the new workload with a template from another.
30
- def with(reporter: nil, workload: nil, template: nil)
31
+ def with(reporter: nil, workload: nil, template: nil, client_unique_id: nil)
31
32
  previous = current
32
33
  declared = {
33
34
  reporter: normalize_reporter(reporter),
34
35
  workload: normalize_part(:workload, workload, WORKLOAD_FIELDS),
35
- template: normalize_part(:template, template, TEMPLATE_FIELDS)
36
+ template: normalize_part(:template, template, TEMPLATE_FIELDS),
37
+ client_unique_id: normalize_client_unique_id(client_unique_id)
36
38
  }.compact
37
39
  inherited = previous || {}
38
40
  inherited = inherited.except(:template) if declared.key?(:workload) && !declared.key?(:template)
@@ -50,6 +52,22 @@ module Coolhand
50
52
  reporter.to_s
51
53
  end
52
54
 
55
+ # The caller's own id for the next logged request(s), so feedback can find them by
56
+ # `create_feedback(client_unique_id:)`. Unlike a workload key, a bad value is dropped rather than
57
+ # raised: a correlation id must never break the caller's LLM call, and a value the server may
58
+ # refuse (over-long, control characters) should not put the whole log at risk.
59
+ MAX_CLIENT_UNIQUE_ID_LENGTH = 255
60
+ CLIENT_UNIQUE_ID_FORMAT = /\A[^\p{Cntrl}\p{Cf}]*[^\p{Cntrl}\p{Cf}[:space:]][^\p{Cntrl}\p{Cf}]*\z/
61
+
62
+ def normalize_client_unique_id(value)
63
+ return nil if value.nil?
64
+ return value.dup.freeze if valid_string?(value, MAX_CLIENT_UNIQUE_ID_LENGTH, CLIENT_UNIQUE_ID_FORMAT)
65
+
66
+ Coolhand.log "Ignoring client_unique_id: expected a non-blank String of at most " \
67
+ "#{MAX_CLIENT_UNIQUE_ID_LENGTH} characters with no control or invisible characters"
68
+ nil
69
+ end
70
+
53
71
  # Mirrors the server's key rules: at most 255 characters, no control or invisible characters, no
54
72
  # leading or trailing whitespace, and no leading, trailing or doubled "/". The server answers a
55
73
  # bad key with a 422 that rejects the whole log, so it is checked here, before the call is made.
@@ -62,9 +80,13 @@ module Coolhand
62
80
  }x
63
81
 
64
82
  def valid_key?(key)
65
- key.is_a?(String) && key.length <= MAX_KEY_LENGTH && KEY_FORMAT.match?(key)
83
+ valid_string?(key, MAX_KEY_LENGTH, KEY_FORMAT)
84
+ end
85
+
86
+ def valid_string?(value, max_length, format)
87
+ value.is_a?(String) && value.length <= max_length && format.match?(value)
66
88
  rescue ArgumentError, EncodingError
67
- false # a string with a broken or incompatible encoding is not a valid key
89
+ false # a string with a broken or incompatible encoding is not valid
68
90
  end
69
91
 
70
92
  # A template given by key, with no workload to create it in, is a 422 that drops the log. A
@@ -22,7 +22,8 @@ module Coolhand
22
22
  def link_feedback(optimization_id, feedback_id, note: nil)
23
23
  validate_id!("link_feedback", "feedback_id", feedback_id)
24
24
  url = links_url("link_feedback", optimization_id)
25
- ensure_object!(request_json(:post, url, ERROR_NOUN, body: { feedback_id: feedback_id.strip, note: note }.compact))
25
+ result = request_json(:post, url, ERROR_NOUN, body: { feedback_id: feedback_id.strip, note: note }.compact)
26
+ ensure_json_object!(result, ERROR_NOUN)
26
27
  end
27
28
 
28
29
  # Lists over 100 ids are sent in batches; a failing batch raises and earlier ones stay applied,
@@ -56,18 +57,12 @@ module Coolhand
56
57
  private
57
58
 
58
59
  def merge_bulk_result!(totals, result)
59
- ensure_object!(result)
60
+ ensure_json_object!(result, ERROR_NOUN)
60
61
 
61
62
  %i[linked already_linked errored].each { |key| totals[key] += result[key].to_i }
62
63
  totals[:not_found].concat(Array(result[:not_found]))
63
64
  end
64
65
 
65
- def ensure_object!(result)
66
- raise Error, "#{ERROR_NOUN} response was not a JSON object" unless result.is_a?(Hash)
67
-
68
- result
69
- end
70
-
71
66
  def links_url(method_name, optimization_id)
72
67
  validate_id!(method_name, "optimization_id", optimization_id)
73
68
  URI.parse("#{api_endpoint}/#{escape_path_segment(optimization_id.strip)}/feedback_links")
@@ -45,6 +45,12 @@ module Coolhand
45
45
  true
46
46
  end
47
47
 
48
+ def ensure_json_object!(result, noun)
49
+ raise Error, "#{noun} response was not a JSON object" unless result.is_a?(Hash)
50
+
51
+ result
52
+ end
53
+
48
54
  private
49
55
 
50
56
  def perform_get(url, noun)
@@ -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
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Coolhand
4
- VERSION = "0.11.0"
4
+ VERSION = "0.12.0"
5
5
  end
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,14 +97,18 @@ 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
@@ -152,6 +157,12 @@ module Coolhand
152
157
  WorkloadService.new
153
158
  end
154
159
 
160
+ # Creates a new SavingsService instance, for reading the client's realized savings. Needs the
161
+ # private API key.
162
+ def savings_service
163
+ SavingsService.new
164
+ end
165
+
155
166
  # Creates a new LogService instance, for reading logs back out of Coolhand. Distinct from
156
167
  # {logger_service}, which writes them. Needs the private API key.
157
168
  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.12.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-24 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
@@ -89,6 +90,7 @@ files:
89
90
  - lib/coolhand/read_query.rb
90
91
  - lib/coolhand/read_requests.rb
91
92
  - lib/coolhand/response_warnings.rb
93
+ - lib/coolhand/savings_service.rb
92
94
  - lib/coolhand/step_template_service.rb
93
95
  - lib/coolhand/stream_read.rb
94
96
  - lib/coolhand/string_body_redactor.rb