nitro_intelligence 4.4.0 → 4.5.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: 6487f455691ffd262370d81066b51e5b4cf6dad688e6002a5f9b02c29253e2cc
4
- data.tar.gz: 372209bb82930b56c163780e2ccc87371fbcbff21b3cb715d8d2acde2dca4d37
3
+ metadata.gz: f6f8744bf383b1384818c1a6c46cff6ef7b8bdb6ff7d00b997ac3f0032965389
4
+ data.tar.gz: 60d960e0cc271d2e6f893ebcbedeed584e4f80eb0dd3c57deba073bd9ab3bc41
5
5
  SHA512:
6
- metadata.gz: 692009dc4963b15df7a749c7aa10cf15c6d959e3575abd1d7cd07f292300010a70b91fdaca7bf90d48463c7b30672243f94769b2473c807a27a280cf5fda91ac
7
- data.tar.gz: 4181e4fa302350c9c1210d726bf880435f8c1205f92397cbfb55b83e8f8c9f6cde4e421f6dd95569eae19d35ae8f9d34b7eda92fbf7d84307ca1b684e800aec4
6
+ metadata.gz: 791abbfaa49a80adb1b239bb2b0925ef1b0d71973723de5d9c51477b82c8509a3f11a805aa352a69d9bc45259f714a7acc6952cd0ffaa28ea5da635e7afc7573
7
+ data.tar.gz: 43faaecea7befe2d80f009dcfe5c812a67c59a8ae12e08f95cbf25324b91baaaeeb4f557b1baba410a7fe9631e77d8048230cb63b75447ed8827f72e88ca709e
data/docs/ASSISTANTS.md CHANGED
@@ -16,6 +16,7 @@ An assistant can be set up so that a person checks its work before it takes effe
16
16
 
17
17
  - **Tool-call review.** The assistant holds the calls to tools listed in its prompt config's `interrupt_on`, and the run pauses until a reviewer approves, edits, rejects or answers each one. Nothing the held calls would do happens before then. See [Make it pause for review](https://github.com/powerhome/nip-assistants/blob/main/docs/tools-and-review.md#make-it-pause-for-review).
18
18
  - **Reply review.** With the reserved entry `"__reply__": true` in the same `interrupt_on`, the assistant also holds its final reply, the message a customer would read, as a draft. The run pauses with the draft in [`#run`](#run)'s `review.reply`, and `reply` is `nil` until a reviewer approves, edits or rejects it with [`#review`](#review). Turn it on when a person should read what the assistant says before a customer does. See [Reviewing replies](https://github.com/powerhome/nip-assistants/blob/main/docs/README.md#reviewing-replies).
19
+ - **Escalation.** An assistant can hand a conversation to a person: the model asks for one, a decision model (the judge) reading its outputs asks for one, or a tool or model call fails. The platform calls the escalation tool the application names, and the run ends with no reply and an [`escalation`](#escalations) on its result. The thread then refuses runs, raising `ThreadEscalatedError`, until a person hands it back or closes it with [`#hand_back_escalation`](#hand_back_escalation) or [`#close_escalation`](#close_escalation). See [Escalating to a person](https://github.com/powerhome/nip-assistants/blob/main/docs/escalation.md).
19
20
  - **Delivery tool.** The assistant's `mcp-config.json` can name a tool, on a server the application runs, that sends a reply to the customer -- an SMS, a chat message. The platform calls it with every settled reply: one that was approved, edited, or never under review. A reply approved hours later from a reviewer's screen is then sent by the run that approved it, without the application tracking which drafts are still waiting. The outcome is stamped on the reply and read as [`#run`](#run)'s `delivery`. With a delivery tool the application no longer sends replies: the reply it gets back has already gone out. See [Delivering replies](https://github.com/powerhome/nip-assistants/blob/main/docs/README.md#delivering-replies).
20
21
 
21
22
  ## Review flow walkthrough
@@ -89,7 +90,7 @@ assistant.review(thread_id:, reviewer_id: "jane@example.com", interrupt_id: draf
89
90
 
90
91
  ## Upgrading to 4.0
91
92
 
92
- 4.0 replaces the reply-only calls with ones that report what a run is waiting on. The old ones still work, warn through `NitroIntelligence.deprecator` (registered with a Rails application's deprecators, so `config.active_support` deprecation settings apply), and are removed in 5.0:
93
+ 4.0 replaces the reply-only calls with ones that report what a run is waiting on. The old ones still work, warn through `NitroIntelligence.deprecator` (registered with a Rails application's deprecators, so `config.active_support` deprecation settings apply), and are removed in the next major release:
93
94
 
94
95
  | Deprecated | Use instead |
95
96
  | --- | --- |
@@ -134,6 +135,7 @@ This is the main entry point when the host application wants to continue a threa
134
135
  | `interrupted?` | Whether the run paused for review |
135
136
  | `review` | What the paused run is waiting on, a `NitroIntelligence::PendingReview`; `nil` when it did not pause |
136
137
  | `delivery` | How the platform delivered the reply through the assistant's delivery tool; `nil` when the reply carries no delivery stamp: no reply, or no delivery tool. Read it with `&.` |
138
+ | `escalation` | The escalation the run ended on, a `NitroIntelligence::Escalation`; `nil` when it did not escalate. `escalated?` tests for it. See [Escalations](#escalations) |
137
139
  | `messages` | The run's messages as Assistants reports them |
138
140
  | `raw` | The `/runs/wait` response, unformatted |
139
141
 
@@ -192,6 +194,8 @@ Error: KeyError: missing variables {'first_name'}
192
194
  IncompleteRun: Wait ended before the run completed (status: running)
193
195
  ```
194
196
 
197
+ A run on a thread escalated to a person raises `ThreadEscalatedError`, a `RunError`, whose `escalation` says which escalation refused it. See [Escalations](#escalations).
198
+
195
199
  A run that pauses for review is not a failure: `interrupted?` is true, `reply` is `nil` whether or not it drafted text, and `review` reports what it is waiting on.
196
200
 
197
201
  ### Thread initialization
@@ -206,7 +210,7 @@ Because `ifExists` is `raise`, Assistants answers with a `409` when the thread i
206
210
 
207
211
  ## `#await_run`
208
212
 
209
- > **Deprecated** in 4.0 and removed in 5.0. Use [`#run`](#run)`(...).reply`.
213
+ > **Deprecated** in 4.0, and removed in the next major release. Use [`#run`](#run)`(...).reply`.
210
214
 
211
215
  [`#run`](#run)'s reply: initializes a thread if needed, seeds it with the prior messages in the conversation, sends the latest message to the agent, and waits for the run to end or pause.
212
216
 
@@ -310,7 +314,7 @@ messages = assistants.thread_messages(thread_id: "thread-456")
310
314
 
311
315
  ## `#tool_calls_pending_review`
312
316
 
313
- > **Deprecated** in 4.0 and removed in 5.0. Use [`#under_review`](#under_review)`(thread_id:)&.tool_calls.to_a`, which reports only the calls a reviewer has to decide.
317
+ > **Deprecated** in 4.0, and removed in the next major release. Use [`#under_review`](#under_review)`(thread_id:)&.tool_calls.to_a`, which reports only the calls a reviewer has to decide.
314
318
 
315
319
  Returns every tool call in a thread that has no result yet, across every AI message that made one.
316
320
 
@@ -359,7 +363,7 @@ tool_calls = assistants.tool_calls_pending_review(
359
363
 
360
364
  ## `#tool_calls_under_review`
361
365
 
362
- > **Deprecated** in 4.0 and removed in 5.0. Use [`#under_review`](#under_review)`(thread_id:)&.tool_calls.to_a`.
366
+ > **Deprecated** in 4.0, and removed in the next major release. Use [`#under_review`](#under_review)`(thread_id:)&.tool_calls.to_a`.
363
367
 
364
368
  Returns the tool calls the thread's interrupt is holding, in the order the platform wants decisions for them, each with the `allowed_decisions` a reviewer may take on it. Empty when the thread is not waiting on a review, or is paused on its reply; [`#under_review`](#under_review) reports either. It reads the same as `under_review(...)&.tool_calls || []`, except that it raises `ThreadResumptionError` rather than `ThreadStateError`.
365
369
 
@@ -508,9 +512,95 @@ rescue NitroIntelligence::Assistants::ReviewSupersededError
508
512
  end
509
513
  ```
510
514
 
515
+ ## Escalations
516
+
517
+ A run that hands the conversation to a person ends with no reply and no pause, and its result's `escalation` describes it. From then on the thread refuses every run, until a person resolves the escalation. Assistants keeps the escalation on the thread's metadata, under `escalation`, so the threads waiting for a person can be found by searching thread metadata for `{"escalation": {"status": "open"}}`.
518
+
519
+ | `Escalation` | What it is |
520
+ | --- | --- |
521
+ | `id` | The escalation's id, which a resolution names |
522
+ | `status` | `"open"`, then `"handed_back"` or `"closed"`; `open?`, `handed_back?` and `closed?` test for each |
523
+ | `source` | What escalated: `"model"`, `"judge"` or `"error"` |
524
+ | `reason` | The model's own sentence, the judge's reason name, or `tool_failed`, `model_failed` or `judge_unavailable`. The model's can repeat what the customer wrote: treat it as untrusted input |
525
+ | `details` | The judge reason's description, or what failed; empty for the model |
526
+ | `message_id` | The latest customer message when it escalated |
527
+ | `tool_call_id`, `at` | The escalation tool call the platform wrote, and when |
528
+ | `judge` | The judge's verdict (`verdict`, `reason`, `confidence`), `{"error" => ...}` when it could not answer, or `nil` |
529
+ | `delivery` | How the platform delivered the escalation to the escalation tool, read as a [reply's `delivery`](#run) is |
530
+ | `resolved_by`, `resolved_at` | Who resolved it and when, once resolved |
531
+ | `sandbox?` | Whether a sandbox run escalated. The thread refuses runs of either kind |
532
+ | `raw` | The escalation as Assistants returned it |
533
+
534
+ The escalation is read in three places, and each carries a different amount of it. A run's `escalation` carries all of it. A `ThreadEscalatedError`, and what a resolution returns, carry a summary (a `ThreadEscalatedError` raised when the platform could not read the stamp carries only `id` and `status`): `id`, `status`, `source`, `reason`, `at`, the delivery's `status`, and `resolved_by` and `resolved_at` once resolved; the other fields are `nil`. An `EscalationNotOpenError` carries only `id` and `status`.
535
+
536
+ **Act on a `failed` or `pending` delivery.** The platform sends an escalation once and never again, so if its `delivery` is `failed`, or `pending` for more than a few minutes, the escalation tool may never have recorded it: queue the conversation for a person yourself. The run's result is the first place to see it, and a `ThreadEscalatedError` the next time the customer writes is the second.
537
+
538
+ ```ruby
539
+ result = assistant.run(thread_id:, messages:, context:)
540
+
541
+ if result.escalated?
542
+ escalation = result.escalation
543
+ escalation.reason # => "asked_for_person"
544
+ escalation.delivery&.status # => "delivered"
545
+ end
546
+
547
+ # Later, the customer writes again while a person has the conversation.
548
+ begin
549
+ assistant.run(thread_id:, messages:, context:)
550
+ rescue NitroIntelligence::Assistants::ThreadEscalatedError => e
551
+ e.escalation.id # => "esc-7f3a91c2d4e5"
552
+ e.escalation.delivery&.status # => "delivered"
553
+ # Pass the customer's message to whoever has the conversation.
554
+ end
555
+ ```
556
+
557
+ A run admitted before its thread was stamped, such as one that waited behind the run that escalated, fails instead of being refused; it raises `ThreadEscalatedError` too, with the same summary.
558
+
559
+ ### `#hand_back_escalation`
560
+
561
+ Hands the conversation back to the assistant, from the person who had it, and returns the handed-back `Escalation`. No run starts: the person answered the customer while they had the conversation. The customer's next message starts an ordinary run with [`#run`](#run), and the assistant answers it knowing what the person did and said.
562
+
563
+ | Argument | What it is |
564
+ | --- | --- |
565
+ | `thread_id` | The thread |
566
+ | `escalation_id` | The open escalation's `id` |
567
+ | `reviewer_id` | Who resolved it, as the host identifies them |
568
+ | `note` | Optional, up to 2,000 characters: what the person did, for the model |
569
+ | `messages` | Optional: what was said meanwhile, oldest first, each `{ "type" => "human" \| "ai", "content" => "...", "name" => "..." }`, `name` optional |
570
+ | `reviewed_at` | Optional, default now |
571
+
572
+ The next run on the thread writes the note, as a person's note, and then the messages into the conversation, straight after the escalation and before the customer's new message.
573
+
574
+ Of two people resolving at once, the first wins, and the other gets `EscalationNotOpenError`. The same decision sent again by the same `reviewer_id` is accepted as a retry.
575
+
576
+ ```ruby
577
+ assistant.hand_back_escalation(
578
+ thread_id:,
579
+ escalation_id: escalation.id,
580
+ reviewer_id: "jane@sunbeam.example",
581
+ note: "Called Ana and moved the visit to Friday at 9. She wants a text reminder the day before.",
582
+ messages: [
583
+ { "type" => "human", "content" => "Fine, Friday morning then." },
584
+ { "type" => "ai", "name" => "agent:jane", "content" => "Booked you for Friday at 9." },
585
+ ]
586
+ )
587
+ # => #<NitroIntelligence::Escalation status="handed_back" ...>
588
+
589
+ # Ana's next text runs as usual, with the note and messages in the conversation.
590
+ result = assistant.run(thread_id:, messages: [{ role: "user", content: "Can it be 10 instead?" }], context:)
591
+ ```
592
+
593
+ ### `#close_escalation`
594
+
595
+ Closes the conversation for good: the thread refuses every run after it. Takes `thread_id`, `escalation_id`, `reviewer_id` and an optional `reviewed_at`, and returns the closed `Escalation`.
596
+
597
+ ```ruby
598
+ assistant.close_escalation(thread_id:, escalation_id: escalation.id, reviewer_id: "jane@sunbeam.example")
599
+ ```
600
+
511
601
  ## `#review_tool_calls`
512
602
 
513
- > **Deprecated** in 4.0 and removed in 5.0. Use [`#review`](#review)`(tool_calls:, reviewer_id:, interrupt_id:)`.
603
+ > **Deprecated** in 4.0, and removed in the next major release. Use [`#review`](#review)`(tool_calls:, reviewer_id:, interrupt_id:)`.
514
604
 
515
605
  Resumes an interrupted thread after a human has reviewed the tool calls it is holding.
516
606
 
@@ -579,6 +669,9 @@ Every error is a `StandardError` raised by the call that hits it.
579
669
  | `Assistants::ThreadStateError` | A thread's state cannot be read by [`#thread_state`](#thread_state), [`#thread_messages`](#thread_messages) or [`#under_review`](#under_review); the message is the response body |
580
670
  | `Assistants::ThreadResumptionError` | A review cannot be applied (see [`#review`](#review) and [`#review_tool_calls`](#review_tool_calls)) |
581
671
  | `Assistants::ReviewSupersededError` | A `ThreadResumptionError`: the thread is no longer paused on the review answered |
672
+ | `Assistants::ThreadEscalatedError` | A `RunError`: [`#run`](#run) is refused because the thread is escalated to a person; `escalation` carries the escalation's summary (see [Escalations](#escalations)) |
673
+ | `Assistants::EscalationResolutionError` | Assistants refuses [`#hand_back_escalation`](#hand_back_escalation) or [`#close_escalation`](#close_escalation), as it does a malformed one; the message is the response body |
674
+ | `Assistants::EscalationNotOpenError` | An `EscalationResolutionError`: the thread has no open escalation with that id, because another person resolved it first or it never existed; `escalation` carries the thread's current `id` and `status`, or is `nil` |
582
675
  | `AssistantRegistry::UnknownAssistantError` | `NitroIntelligence.assistants[key]` names a key `definitions` does not configure |
583
676
  | `Assistant::ConfigurationError` | An assistant's entry lacks its `api_key` or `assistant_id` |
584
677
 
data/docs/CHANGELOG.md CHANGED
@@ -5,6 +5,23 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [4.5.0](https://github.com/powerhome/nitro-intelligence.rb/compare/v4.4.0...v4.5.0) (2026-12-03)
9
+
10
+
11
+ ### Added
12
+
13
+ * **assistants:** Assistants#hand_back_escalation and #close_escalation ([d4663c5](https://github.com/powerhome/nitro-intelligence.rb/commit/d4663c5a2c0e7934d1b6e4d9657ea0ed35086ef6))
14
+ * **assistants:** read and resolve escalations to a person ([#232](https://github.com/powerhome/nitro-intelligence.rb/issues/232)) ([d4663c5](https://github.com/powerhome/nitro-intelligence.rb/commit/d4663c5a2c0e7934d1b6e4d9657ea0ed35086ef6))
15
+ * **deps:** support Active Support 8 [security] ([#209](https://github.com/powerhome/nitro-intelligence.rb/issues/209)) ([2da6425](https://github.com/powerhome/nitro-intelligence.rb/commit/2da642581dcc402e79d2e91b31d20ee9a151ae64))
16
+ * **deps:** support MiniMagick 5 while retaining 4.x compatibility ([#215](https://github.com/powerhome/nitro-intelligence.rb/issues/215)) ([2775ced](https://github.com/powerhome/nitro-intelligence.rb/commit/2775ced7bcec66f06fadcb2e1243271ce585339f))
17
+
18
+
19
+ ### Fixed
20
+
21
+ * **deps:** use langfuse-rb 0.12.4's seeded roots instead of our copy ([#165](https://github.com/powerhome/nitro-intelligence.rb/issues/165)) ([c58feb3](https://github.com/powerhome/nitro-intelligence.rb/commit/c58feb336d297640ca91a21be4c280d64e01c33a))
22
+ * pin `benchmark` to `0.5.0` so MiniMagick 4 loads on Ruby 4. ([2da6425](https://github.com/powerhome/nitro-intelligence.rb/commit/2da642581dcc402e79d2e91b31d20ee9a151ae64))
23
+ * require `json < 3` because Active Support 7.1 through 8.0 pass the obsolete `quirks_mode` option to the JSON encoder. ([2da6425](https://github.com/powerhome/nitro-intelligence.rb/commit/2da642581dcc402e79d2e91b31d20ee9a151ae64))
24
+
8
25
  ## [4.4.0](https://github.com/powerhome/nitro-intelligence.rb/compare/v4.3.2...v4.4.0) (2026-12-02)
9
26
 
10
27
 
data/docs/README.md CHANGED
@@ -859,7 +859,7 @@ On an observed client whose project does not mask content, pass an open `File` a
859
859
 
860
860
  ## Nitro Intelligence Assistants
861
861
 
862
- `NitroIntelligence::Assistants` is Nitro Intelligence's lightweight SDK for working with hosted agent threads, runs, and human review flows. It is mainly used to initialize conversation threads, trigger agent runs, inspect what a paused run is waiting on (tool calls or a reply held for review), and resume paused threads after human reviews.
862
+ `NitroIntelligence::Assistants` is Nitro Intelligence's lightweight SDK for working with hosted agent threads, runs, and human review flows. It is mainly used to initialize conversation threads, trigger agent runs, inspect what a paused run is waiting on (tool calls or a reply held for review), resume paused threads after human reviews, and hand back or close conversations an assistant escalated to a person.
863
863
 
864
864
  For the full guide, see [ASSISTANTS.md](https://github.com/powerhome/nitro-intelligence.rb/blob/main/docs/ASSISTANTS.md). For the service this SDK talks to, see the [Nitro Intelligence Assistants documentation](https://portal.powerapp.cloud/docs/default/system/nip-assistants).
865
865
 
@@ -79,7 +79,7 @@ module NitroIntelligence
79
79
 
80
80
  # {Assistants#await_run} for this assistant.
81
81
  #
82
- # @deprecated Use {#run}`(...).reply`. Removed in 5.0.
82
+ # @deprecated Use {#run}`(...).reply`. Removed in the next major release.
83
83
  # @param (see #run)
84
84
  # @return [String, nil]
85
85
  # @raise (see #run)
@@ -100,9 +100,28 @@ module NitroIntelligence
100
100
  client.review(thread_id:, assistant_id:, **kwargs)
101
101
  end
102
102
 
103
+ # {Assistants#hand_back_escalation} on this assistant's client, with the same arguments.
104
+ #
105
+ # @param thread_id [String]
106
+ # @return [Escalation]
107
+ # @raise (see Assistants#hand_back_escalation)
108
+ def hand_back_escalation(thread_id:, **)
109
+ client.hand_back_escalation(thread_id:, **)
110
+ end
111
+
112
+ # {Assistants#close_escalation} on this assistant's client, with the same arguments.
113
+ #
114
+ # @param thread_id [String]
115
+ # @return [Escalation]
116
+ # @raise (see Assistants#close_escalation)
117
+ def close_escalation(thread_id:, **)
118
+ client.close_escalation(thread_id:, **)
119
+ end
120
+
103
121
  # {Assistants#review_tool_calls} for this assistant.
104
122
  #
105
- # @deprecated Use {#review}`(tool_calls:, reviewer_id:, interrupt_id:)`. Removed in 5.0.
123
+ # @deprecated Use {#review}`(tool_calls:, reviewer_id:, interrupt_id:)`. Removed in the next
124
+ # major release.
106
125
  # @param thread_id [String]
107
126
  # @param tool_calls [Hash, Array<Hash>]
108
127
  # @param kwargs [Hash] the rest of {Assistants#review_tool_calls}'s arguments, except
@@ -0,0 +1,148 @@
1
+ require "json"
2
+ require "nitro_intelligence/escalation"
3
+
4
+ module NitroIntelligence
5
+ # Escalations: reading the refusal of a run on an escalated thread, and resolving an
6
+ # escalation. See `docs/ASSISTANTS.md`.
7
+ class Assistants
8
+ # Raised by {#run} when the thread is escalated to a person: Assistants refuses every run on it
9
+ # while the escalation is open, and after it is closed. A RunError, so that callers rescuing
10
+ # RunError still catch it. Pass the customer's message to whoever has the conversation.
11
+ class ThreadEscalatedError < RunError
12
+ # The escalation refusing the run: the stamp's summary, from the `409` or from the failure of a
13
+ # run admitted before the thread was stamped; only its `id` and `status` when the failure
14
+ # carries no summary. Its
15
+ # `delivery&.status` says whether the application received the escalation.
16
+ #
17
+ # @return [Escalation, nil]
18
+ attr_reader :escalation
19
+
20
+ # @param message [String]
21
+ # @param escalation [Escalation, nil]
22
+ def initialize(message = nil, escalation: nil)
23
+ super(message)
24
+ @escalation = escalation
25
+ end
26
+ end
27
+
28
+ # Raised by {#hand_back_escalation} and {#close_escalation} when Assistants refuses the
29
+ # resolution, as it does a malformed one with a `422`. The message is the response body.
30
+ class EscalationResolutionError < StandardError; end
31
+
32
+ # Raised by {#hand_back_escalation} and {#close_escalation} when the thread has no open
33
+ # escalation with that id: another person resolved it first, with a different decision, or it
34
+ # never existed. An EscalationResolutionError.
35
+ class EscalationNotOpenError < EscalationResolutionError
36
+ # The thread's escalation as it stands, only its `id` and `status`; nil when the thread has
37
+ # none.
38
+ #
39
+ # @return [Escalation, nil]
40
+ attr_reader :escalation
41
+
42
+ # @param message [String]
43
+ # @param escalation [Escalation, nil]
44
+ def initialize(message = nil, escalation: nil)
45
+ super(message)
46
+ @escalation = escalation
47
+ end
48
+ end
49
+
50
+ # @api private
51
+ # The `details.code` of a run refused because its thread is escalated.
52
+ THREAD_ESCALATED = "thread_escalated".freeze
53
+
54
+ # @api private
55
+ # The `details.code` of a resolution of no open escalation.
56
+ ESCALATION_NOT_OPEN = "escalation_not_open".freeze
57
+
58
+ # @api private
59
+ # The error of a run admitted before its thread was stamped, which fails instead of running.
60
+ THREAD_ESCALATED_FAILURE = /thread_escalated: escalation (\S+) is (\w+)/
61
+
62
+ # Hands an escalated conversation back to the assistant, from the person who had it. No run
63
+ # starts: the person answered the customer while they had the conversation, and the customer's
64
+ # next message starts an ordinary run.
65
+ #
66
+ # That run writes `note`, as a person's note, and then `messages` into the conversation, straight
67
+ # after the escalation, so the assistant answers knowing what the person did and said. The same
68
+ # hand-back sent again by the same `reviewer_id` is accepted as a retry.
69
+ #
70
+ # @param thread_id [String]
71
+ # @param escalation_id [String] the open escalation's id ({Escalation#id})
72
+ # @param reviewer_id [String] who resolved it, as the host identifies them
73
+ # @param note [String, nil] up to 2,000 characters: what the person did, for the model
74
+ # @param messages [Array<Hash>] what was said meanwhile, oldest first, each
75
+ # `{ "type" => "human" | "ai", "content" => "...", "name" => "..." }`, `name` optional
76
+ # @param reviewed_at [Time, String, nil] when they resolved it. Defaults to now.
77
+ # @return [Escalation] the handed-back escalation
78
+ # @raise [ArgumentError] without an `escalation_id` or `reviewer_id`
79
+ # @raise [EscalationNotOpenError] when the thread has no open escalation `escalation_id`
80
+ # @raise [EscalationResolutionError] when Assistants refuses the hand-back
81
+ # @example
82
+ # assistants.hand_back_escalation(thread_id:, escalation_id: escalation.id,
83
+ # reviewer_id: "jane@example.com",
84
+ # note: "Moved the visit to Friday at 9 by phone.")
85
+ def hand_back_escalation(thread_id:, escalation_id:, reviewer_id:, note: nil, messages: [], reviewed_at: nil)
86
+ decision = { type: "hand_back", note:, messages: Array(messages) }.compact
87
+ resolve_escalation(thread_id:, escalation_id:, reviewer_id:, reviewed_at:, decision:)
88
+ end
89
+
90
+ # Closes an escalated conversation for good: the thread refuses every run after it.
91
+ #
92
+ # @param thread_id [String]
93
+ # @param escalation_id [String] the open escalation's id ({Escalation#id})
94
+ # @param reviewer_id [String] who closed it, as the host identifies them
95
+ # @param reviewed_at [Time, String, nil] when they closed it. Defaults to now.
96
+ # @return [Escalation] the closed escalation
97
+ # @raise [ArgumentError] without an `escalation_id` or `reviewer_id`
98
+ # @raise [EscalationNotOpenError] when the thread has no open escalation `escalation_id`
99
+ # @raise [EscalationResolutionError] when Assistants refuses the close
100
+ def close_escalation(thread_id:, escalation_id:, reviewer_id:, reviewed_at: nil)
101
+ resolve_escalation(thread_id:, escalation_id:, reviewer_id:, reviewed_at:, decision: { type: "close" })
102
+ end
103
+
104
+ private
105
+
106
+ def resolve_escalation(thread_id:, escalation_id:, reviewer_id:, reviewed_at:, decision:)
107
+ raise ArgumentError, "escalation_id is required" if escalation_id.blank?
108
+ raise ArgumentError, "reviewer_id is required" if reviewer_id.blank?
109
+
110
+ body = { escalation_id:, decision:, **reviewer_stamp(reviewer_id, reviewed_at) }
111
+ response = post(path: "/threads/#{thread_id}/escalation", body:)
112
+ refused!(response, EscalationNotOpenError, ESCALATION_NOT_OPEN)
113
+ Escalation.wrap(parse!(response, EscalationResolutionError)["escalation"])
114
+ end
115
+
116
+ # Raises `error`, carrying the escalation the refusal names, when `response` is a `409` for
117
+ # `code`.
118
+ def refused!(response, error, code)
119
+ details = refusal(response, code)
120
+ raise error.new(response.body, escalation: Escalation.wrap(details["escalation"])) if details
121
+ end
122
+
123
+ # The `details` of a `409` whose `details.code` is `code`, in Assistants' error shape
124
+ # (`{"error", "message", "details"}`), or nil.
125
+ def refusal(response, code)
126
+ return nil unless response.code.to_i == CONFLICT_CODE
127
+
128
+ body = JSON.parse(response.body.to_s)
129
+ details = body["details"] if body.is_a?(Hash)
130
+ details.is_a?(Hash) && details["code"] == code ? details : nil
131
+ rescue JSON::ParserError
132
+ nil
133
+ end
134
+
135
+ # Raises ThreadEscalatedError when a run's failure is a refusal on an escalated thread: a run
136
+ # admitted before the thread was stamped. Its `details` carry the stamp's summary, or null when
137
+ # the platform could not read the stamp, and then the `id` and `status` come from the message.
138
+ def escalated_failure!(failure, detail)
139
+ details = failure.is_a?(Hash) ? failure["details"] : nil
140
+ return unless details.is_a?(Hash) && details["code"] == THREAD_ESCALATED
141
+
142
+ named = detail.match(THREAD_ESCALATED_FAILURE)
143
+ escalation = Escalation.wrap(details["escalation"])
144
+ escalation ||= Escalation.new("id" => named[1], "status" => named[2]) if named
145
+ raise ThreadEscalatedError.new(detail, escalation:)
146
+ end
147
+ end
148
+ end
@@ -2,6 +2,7 @@ require "json"
2
2
  require "net/http"
3
3
  require "uri"
4
4
  require "nitro_intelligence/deprecator"
5
+ require "nitro_intelligence/escalation"
5
6
  require "nitro_intelligence/pending_review"
6
7
  require "nitro_intelligence/run_result"
7
8
 
@@ -33,8 +34,9 @@ module NitroIntelligence
33
34
  NOT_INTERRUPTED_REFUSAL = "thread is not in interrupted state".freeze
34
35
 
35
36
  # @api private
36
- # Assistants answers with a conflict when `ifExists: "raise"` is sent for a thread that already exists.
37
- THREAD_CONFLICT_CODE = 409
37
+ # What Assistants answers with when `ifExists: "raise"` is sent for a thread that already exists, and
38
+ # when it refuses a run or an escalation's resolution, its `details.code` saying why.
39
+ CONFLICT_CODE = 409
38
40
 
39
41
  # @api private
40
42
  # Where a `/runs/wait` response says which run it waited on.
@@ -79,6 +81,7 @@ module NitroIntelligence
79
81
  # before it seed a new thread
80
82
  # @param context [Hash] the run's context, such as the variables its prompt needs
81
83
  # @return [RunResult]
84
+ # @raise [ThreadEscalatedError] when the thread is escalated to a person
82
85
  # @raise [RunError] when `messages` is empty, Assistants rejects the run, or the run fails
83
86
  # @raise [ThreadInitializationError] when a new thread cannot be created or seeded
84
87
  def run(thread_id:, assistant_id:, messages:, context: {})
@@ -94,14 +97,15 @@ module NitroIntelligence
94
97
  # The run's reply, or nil when it paused for review or ended without one.
95
98
  #
96
99
  # @deprecated Use {#run}`(...).reply`, which also says why there is no reply, and how the
97
- # platform delivered the one there is. Removed in 5.0.
100
+ # platform delivered the one there is. Removed in the next major release.
98
101
  # @param (see #run)
99
102
  # @return [String, nil]
100
103
  # @raise (see #run)
101
104
  def await_run(thread_id:, assistant_id:, messages:, context: {})
102
105
  NitroIntelligence.deprecator.warn(
103
- "#await_run is deprecated and is removed in 5.0; use #run(...).reply, and read #run's " \
104
- "interrupted? and review for a run paused for review"
106
+ "#await_run is deprecated and is removed in " \
107
+ "#{NitroIntelligence.deprecator.deprecation_horizon}; use #run(...).reply, " \
108
+ "and read #run's interrupted? and review for a run paused for review"
105
109
  )
106
110
  run(thread_id:, assistant_id:, messages:, context:).reply
107
111
  end
@@ -133,13 +137,14 @@ module NitroIntelligence
133
137
  # in the platform's shape; it goes when the VCA moves onto the platform.
134
138
  #
135
139
  # @deprecated A reviewer decides only the calls the interrupt holds, which {#under_review}
136
- # reports. Removed in 5.0.
140
+ # reports. Removed in the next major release.
137
141
  # @param thread_id [String]
138
142
  # @return [Array<Hash>] each with `previous_message_id`, `id`, `name` and `args`
139
143
  # @raise [ThreadResumptionError] when the state cannot be read
140
144
  def tool_calls_pending_review(thread_id:)
141
145
  NitroIntelligence.deprecator.warn(
142
- "#tool_calls_pending_review is deprecated and is removed in 5.0; use " \
146
+ "#tool_calls_pending_review is deprecated and is removed in " \
147
+ "#{NitroIntelligence.deprecator.deprecation_horizon}; use " \
143
148
  "#under_review(thread_id:)&.tool_calls for the tool calls awaiting a reviewer's decision"
144
149
  )
145
150
  thread_state = get_thread_state(thread_id:)
@@ -172,14 +177,15 @@ module NitroIntelligence
172
177
  # the plain read.
173
178
  #
174
179
  # @deprecated Use {#under_review}`(thread_id:)&.tool_calls.to_a`, which reports a pause on the
175
- # reply as well. Removed in 5.0.
180
+ # reply as well. Removed in the next major release.
176
181
  # @param thread_id [String]
177
182
  # @return [Array<Hash>] each with `previous_message_id`, `id`, `name`, `args` and
178
183
  # `allowed_decisions`
179
184
  # @raise [ThreadResumptionError] when the state cannot be read
180
185
  def tool_calls_under_review(thread_id:)
181
186
  NitroIntelligence.deprecator.warn(
182
- "#tool_calls_under_review is deprecated and is removed in 5.0; use " \
187
+ "#tool_calls_under_review is deprecated and is removed in " \
188
+ "#{NitroIntelligence.deprecator.deprecation_horizon}; use " \
183
189
  "#under_review(thread_id:)&.tool_calls.to_a"
184
190
  )
185
191
  PendingReview.from_thread_state(get_thread_state(thread_id:))&.tool_calls || []
@@ -268,7 +274,7 @@ module NitroIntelligence
268
274
  # ThreadResumptionError carrying the response body, which nitro-web parses. Returns nil.
269
275
  #
270
276
  # @deprecated Use {#review}`(tool_calls:, reviewer_id:, interrupt_id:)`, which requires the
271
- # reviewer and returns the resumed run. Removed in 5.0.
277
+ # reviewer and returns the resumed run. Removed in the next major release.
272
278
  # @param thread_id [String]
273
279
  # @param assistant_id [String]
274
280
  # @param tool_calls [Hash, Array<Hash>] the reviews
@@ -281,7 +287,8 @@ module NitroIntelligence
281
287
  # the pause allows, or the resume fails
282
288
  def review_tool_calls(thread_id:, assistant_id:, tool_calls:, context: {}, reviewer_id: nil, reviewed_at: nil)
283
289
  NitroIntelligence.deprecator.warn(
284
- "#review_tool_calls is deprecated and is removed in 5.0; use " \
290
+ "#review_tool_calls is deprecated and is removed in " \
291
+ "#{NitroIntelligence.deprecator.deprecation_horizon}; use " \
285
292
  "#review(tool_calls:, reviewer_id:, interrupt_id:), which returns the resumed run's RunResult"
286
293
  )
287
294
  thread = get_thread(thread_id:)
@@ -419,7 +426,7 @@ module NitroIntelligence
419
426
  end
420
427
 
421
428
  def thread_already_exists?(response)
422
- response.code.to_i == THREAD_CONFLICT_CODE
429
+ response.code.to_i == CONFLICT_CODE
423
430
  end
424
431
 
425
432
  def trigger_run(thread_id:, assistant_id:, last_message:, context: {})
@@ -433,6 +440,7 @@ module NitroIntelligence
433
440
  # `Content-Location` (`/threads/{thread_id}/runs/{run_id}`); nil without one.
434
441
  def wait_for_run(thread_id:, body:, error:)
435
442
  response = post(path: "/threads/#{thread_id}/runs/wait", body:)
443
+ refused!(response, ThreadEscalatedError, THREAD_ESCALATED) if error <= RunError
436
444
  run = parse!(response, error)
437
445
  raise_run_error!(run, error)
438
446
 
@@ -444,6 +452,8 @@ module NitroIntelligence
444
452
  return if failure.blank?
445
453
 
446
454
  detail = failure.is_a?(Hash) ? [failure["error"], failure["message"]].compact.join(": ") : failure.to_s
455
+ escalated_failure!(failure, detail) if error <= RunError
456
+
447
457
  raise error, detail
448
458
  end
449
459
 
@@ -563,3 +573,5 @@ module NitroIntelligence
563
573
  end
564
574
  end
565
575
  end
576
+
577
+ require "nitro_intelligence/assistants/escalations"
@@ -1,10 +1,16 @@
1
1
  require "active_support/deprecation"
2
+ require "nitro_intelligence/version"
2
3
 
3
4
  module NitroIntelligence
4
5
  # Removed in the next major release. A Rails host has it registered with its own deprecators by
5
6
  # the Railtie, so its `config.active_support` deprecation settings (log, raise, silence) apply;
6
7
  # elsewhere it warns on stderr.
8
+ #
9
+ # Its horizon is the major after this gem's own version, the release that removes whatever this
10
+ # one deprecates (decision 1), so a warning interpolating it names that release.
7
11
  def self.deprecator
8
- @deprecator ||= ActiveSupport::Deprecation.new("5.0", "nitro_intelligence")
12
+ @deprecator ||= ActiveSupport::Deprecation.new(
13
+ "#{Gem::Version.new(VERSION).segments.first + 1}.0", "nitro_intelligence"
14
+ )
9
15
  end
10
16
  end
@@ -0,0 +1,146 @@
1
+ module NitroIntelligence
2
+ # An escalation: the assistant handed the conversation to a person, and the thread refuses runs
3
+ # until a person hands it back or closes it.
4
+ #
5
+ # Read from three places, each carrying a different amount of it:
6
+ #
7
+ # - a run's output ({RunResult#escalation}): the whole record, with `details`, `judge` and the
8
+ # full `delivery`;
9
+ # - a refused run ({Assistants::ThreadEscalatedError#escalation}) and a resolution
10
+ # ({Assistants#hand_back_escalation}, {Assistants#close_escalation}): the stamp's summary, `id`,
11
+ # `status`, `source`, `reason`, `at` and the delivery's `status`, plus `resolved_by` and
12
+ # `resolved_at` once resolved;
13
+ # - a resolution that lost to another ({Assistants::EscalationNotOpenError#escalation}): only
14
+ # `id` and `status`.
15
+ #
16
+ # A field the response does not carry, or carries as the wrong type, is nil.
17
+ class Escalation
18
+ # @api private
19
+ OPEN = "open".freeze
20
+ # @api private
21
+ HANDED_BACK = "handed_back".freeze
22
+ # @api private
23
+ CLOSED = "closed".freeze
24
+
25
+ # The escalation as Assistants returned it.
26
+ #
27
+ # @return [Hash]
28
+ attr_reader :raw
29
+
30
+ # @api private
31
+ # @param value [Object] an `escalation` block from a response
32
+ # @return [Escalation, nil] nil unless `value` is a Hash
33
+ def self.wrap(value)
34
+ value.is_a?(Hash) ? new(value) : nil
35
+ end
36
+
37
+ # @api private
38
+ def initialize(escalation)
39
+ @raw = escalation.to_h.deep_stringify_keys
40
+ end
41
+
42
+ # @return [String, nil] the escalation's id, which a resolution names
43
+ def id
44
+ string("id")
45
+ end
46
+
47
+ # @return [String, nil] `"open"`, `"handed_back"` or `"closed"`
48
+ def status
49
+ string("status")
50
+ end
51
+
52
+ # @return [String, nil] what escalated: `"model"`, `"judge"` or `"error"`
53
+ def source
54
+ string("source")
55
+ end
56
+
57
+ # The model's own sentence, the judge's reason name, or `tool_failed`, `model_failed` or
58
+ # `judge_unavailable`. A model's reason can repeat what the customer wrote: treat it as
59
+ # untrusted input.
60
+ #
61
+ # @return [String, nil]
62
+ def reason
63
+ string("reason")
64
+ end
65
+
66
+ # @return [String, nil] the judge reason's description, or what failed. Empty for the model.
67
+ def details
68
+ string("details")
69
+ end
70
+
71
+ # @return [String, nil] the latest customer message when the conversation escalated
72
+ def message_id
73
+ string("message_id")
74
+ end
75
+
76
+ # @return [String, nil] the id of the escalation tool call the platform wrote
77
+ def tool_call_id
78
+ string("tool_call_id")
79
+ end
80
+
81
+ # @return [String, nil] when it escalated, as an ISO 8601 timestamp
82
+ def at
83
+ string("at")
84
+ end
85
+
86
+ # The judge's verdict on the output that escalated: `verdict`, `reason` and `confidence`;
87
+ # `{"error" => ...}` when the judge could not answer; nil for a failed tool or model call, which
88
+ # escalates without asking it, and in a summary.
89
+ #
90
+ # @return [Hash, nil]
91
+ def judge
92
+ value = raw["judge"]
93
+ value.is_a?(Hash) ? value : nil
94
+ end
95
+
96
+ # How the platform delivered the escalation through the assistant's escalation tool, in the
97
+ # shape of a reply's delivery. Act on a `failed` delivery, or one `pending` for more than a few
98
+ # minutes: the application may never have recorded the escalation, and the platform never
99
+ # sends it again. A summary carries only its `status`.
100
+ #
101
+ # @return [RunResult::Delivery, nil]
102
+ def delivery
103
+ return @delivery if defined?(@delivery)
104
+
105
+ @delivery = RunResult::Delivery.from_stamp(raw["delivery"])
106
+ end
107
+
108
+ # @return [String, nil] who resolved it, as the resolution's `reviewer_id` named them
109
+ def resolved_by
110
+ string("resolved_by")
111
+ end
112
+
113
+ # @return [String, nil] when it was resolved, as an ISO 8601 timestamp
114
+ def resolved_at
115
+ string("resolved_at")
116
+ end
117
+
118
+ # @return [Boolean] whether a person still has the conversation
119
+ def open?
120
+ status == OPEN
121
+ end
122
+
123
+ # @return [Boolean] whether a person handed the conversation back
124
+ def handed_back?
125
+ status == HANDED_BACK
126
+ end
127
+
128
+ # @return [Boolean] whether a person closed the conversation; the thread refuses runs for good
129
+ def closed?
130
+ status == CLOSED
131
+ end
132
+
133
+ # @return [Boolean] whether a sandbox run escalated. For information only: the thread refuses
134
+ # runs of either kind.
135
+ def sandbox?
136
+ raw["sandbox"] == true
137
+ end
138
+
139
+ private
140
+
141
+ def string(key)
142
+ value = raw[key]
143
+ value.is_a?(String) ? value : nil
144
+ end
145
+ end
146
+ end
@@ -4,9 +4,6 @@
4
4
  # The content of this file should eventually make its way upstream. Setting a custom trace ID is
5
5
  # already awaiting approval in https://github.com/simplepractice/langfuse-rb/pull/69.
6
6
  #
7
- # Explicit trace IDs create real roots here while the upstream fix awaits approval:
8
- # https://github.com/simplepractice/langfuse-rb/pull/128.
9
- #
10
7
 
11
8
  require "nitro_intelligence/langfuse_tracer_provider"
12
9
 
@@ -100,15 +97,14 @@ module NitroIntelligence
100
97
  Langfuse.send(:validate_observation_type!, as_type, type_str) unless skip_validation
101
98
 
102
99
  otel_tracer = @tracer_provider.tracer
103
- otel_span = if trace_id
104
- @tracer_provider.start_root_span(name, trace_id: parent_span_context.trace_id, start_time:)
105
- else
106
- Langfuse.send(:create_otel_span,
107
- name:,
108
- start_time:,
109
- parent_span_context:,
110
- otel_tracer:)
111
- end
100
+ otel_span = Langfuse.send(:create_otel_span,
101
+ name:,
102
+ start_time:,
103
+ parent_span_context:,
104
+ otel_tracer:,
105
+ trace_id: trace_id && parent_span_context.trace_id,
106
+ id_generator: @tracer_provider.id_generator)
107
+ otel_span.set_attribute(Langfuse::OtelAttributes::AS_ROOT, true) if trace_id
112
108
 
113
109
  # Serialize attributes
114
110
  # Only set attributes if span is still recording (should always be true here, but guard for safety)
@@ -9,8 +9,10 @@ module NitroIntelligence
9
9
  #
10
10
  # @api private
11
11
  class LangfuseTracerProvider
12
+ attr_reader :id_generator
13
+
12
14
  def initialize(config)
13
- @trace_id_key = OpenTelemetry::Context.create_key("nitro-intelligence-trace-id")
15
+ @id_generator = Langfuse::RootSpanIdGenerator.new
14
16
  @tracer_provider = create_tracer_provider(config)
15
17
  end
16
18
 
@@ -20,8 +22,7 @@ module NitroIntelligence
20
22
 
21
23
  # @api private
22
24
  def force_flush(timeout: 30)
23
- # Langfuse's other span processor only adds attributes; its flush is a no-op.
24
- # Calling our processor directly also avoids the provider's unbounded flush mutex.
25
+ # Calling our only processor directly avoids the provider's unbounded flush mutex.
25
26
  @batch_processor.force_flush(timeout:)
26
27
  end
27
28
 
@@ -29,25 +30,6 @@ module NitroIntelligence
29
30
  @tracer_provider.shutdown(timeout:)
30
31
  end
31
32
 
32
- def start_root_span(name, trace_id:, start_time: nil)
33
- # A seed identifies the trace, not a missing parent. Preserve propagated
34
- # attributes while clearing the ambient span for this explicit root.
35
- context = OpenTelemetry::Trace.context_with_span(OpenTelemetry::Trace::Span::INVALID)
36
- context = context.set_value(@trace_id_key, trace_id)
37
- # generate_trace_id has no context argument, so expose the seed through Context.current.
38
- OpenTelemetry::Context.with_current(context) do
39
- tracer.start_span(name, with_parent: context, start_timestamp: start_time)
40
- end
41
- end
42
-
43
- def generate_trace_id
44
- OpenTelemetry::Context.value(@trace_id_key) || OpenTelemetry::Trace.generate_trace_id
45
- end
46
-
47
- def generate_span_id
48
- OpenTelemetry::Trace.generate_span_id
49
- end
50
-
51
33
  private
52
34
 
53
35
  def create_tracer_provider(config)
@@ -59,17 +41,10 @@ module NitroIntelligence
59
41
  compression: "gzip"
60
42
  )
61
43
 
62
- @batch_processor = Observability::BatchSpanProcessor.new(
63
- exporter,
64
- max_queue_size: config.batch_size * 2,
65
- schedule_delay: config.flush_interval * 1000,
66
- max_export_batch_size: config.batch_size
67
- )
44
+ @batch_processor = Observability::BatchSpanProcessor.new(config:, exporter:)
68
45
 
69
- tracer_provider = OpenTelemetry::SDK::Trace::TracerProvider.new(id_generator: self)
46
+ tracer_provider = OpenTelemetry::SDK::Trace::TracerProvider.new(id_generator: @id_generator)
70
47
  tracer_provider.add_span_processor(@batch_processor)
71
- span_processor = Langfuse::SpanProcessor.new(config:)
72
- tracer_provider.add_span_processor(span_processor)
73
48
 
74
49
  OpenTelemetry.propagation = OpenTelemetry::Trace::Propagation::TraceContext::TextMapPropagator.new
75
50
 
@@ -33,7 +33,7 @@ module NitroIntelligence
33
33
 
34
34
  image = MiniMagick::Image.read(StringIO.new(file))
35
35
 
36
- @mime_type = image.mime_type
36
+ @mime_type = "image/#{image.type.downcase}"
37
37
  @height = image.height
38
38
  @width = image.width
39
39
 
@@ -1,6 +1,7 @@
1
1
  module NitroIntelligence
2
2
  module Observability
3
- # Coordinates flush with the existing export worker instead of exporting a separate
3
+ # Langfuse's span processor, which enriches, filters and batches spans, with a flush
4
+ # coordinated with the existing export worker instead of exporting a separate
4
5
  # queue snapshot. OpenTelemetry Ruby 1.13.1's force_flush misses in-flight batches
5
6
  # and waits for export locks without a deadline. Keep its queue, exporter and metrics;
6
7
  # wake its worker and wait for the work captured at the call's start with a deadline.
@@ -8,10 +9,10 @@ module NitroIntelligence
8
9
  # the worker's export also finishes that batch's delivery attempt.
9
10
  #
10
11
  # Upstream fix requested in https://github.com/open-telemetry/opentelemetry-ruby/issues/2497;
11
- # once it ships, this subclass can be replaced by the SDK's own force_flush.
12
+ # once it ships, these flush overrides can give way to the SDK's own force_flush.
12
13
  #
13
14
  # @api private
14
- class BatchSpanProcessor < OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor
15
+ class BatchSpanProcessor < Langfuse::SpanProcessor
15
16
  # Each call captures a prefix of the FIFO queue and the current export, if any.
16
17
  # Counts shrink on dequeue or overflow; later spans never extend a call's work.
17
18
  #
@@ -27,6 +28,13 @@ module NitroIntelligence
27
28
  alias flush_at_shutdown force_flush
28
29
  private :flush_at_shutdown
29
30
 
31
+ # Langfuse::SpanProcessor sets the SDK's other options itself; start_thread_on_boot
32
+ # is kept so a processor can be built without its export worker.
33
+ def initialize(config:, exporter:, metrics_reporter: nil, start_thread_on_boot: true)
34
+ @start_thread_on_boot = start_thread_on_boot
35
+ super(config:, exporter:, metrics_reporter:)
36
+ end
37
+
30
38
  def force_flush(timeout: nil)
31
39
  start_time = OpenTelemetry::Common::Utilities.timeout_timestamp
32
40
  startup_error = nil
@@ -190,6 +198,8 @@ module NitroIntelligence
190
198
  def reset_on_fork(restart_thread: true)
191
199
  return if @pid == Process.pid
192
200
 
201
+ # The SDK's constructor makes the first call, before any pid is recorded.
202
+ restart_thread = false if @pid.nil? && !@start_thread_on_boot
193
203
  @flush_condition = ConditionVariable.new
194
204
  @flush_waiters = Set.new.compare_by_identity
195
205
  @exporting = false
@@ -1,3 +1,4 @@
1
+ require "nitro_intelligence/escalation"
1
2
  require "nitro_intelligence/pending_review"
2
3
 
3
4
  module NitroIntelligence
@@ -33,6 +34,21 @@ module NitroIntelligence
33
34
  # @return [String, nil] when delivery gave up, as an ISO 8601 timestamp
34
35
  Delivery = Struct.new(:status, :tool, :attempts, :error, :result, :delivered_at, :failed_at,
35
36
  keyword_init: true) do
37
+ # @api private
38
+ # @param stamp [Object] a delivery stamp
39
+ # @return [Delivery, nil] nil unless `stamp` is a Hash
40
+ def self.from_stamp(stamp)
41
+ return nil unless stamp.is_a?(Hash)
42
+
43
+ string = ->(key) { stamp[key].is_a?(String) ? stamp[key] : nil }
44
+ new(
45
+ status: string["status"], tool: string["tool"],
46
+ attempts: stamp["attempts"].is_a?(Integer) ? stamp["attempts"] : nil,
47
+ error: string["error"], result: stamp["result"],
48
+ delivered_at: string["delivered_at"], failed_at: string["failed_at"]
49
+ )
50
+ end
51
+
36
52
  # @return [Boolean] whether the platform delivered the reply
37
53
  def delivered?
38
54
  status == "delivered"
@@ -101,8 +117,23 @@ module NitroIntelligence
101
117
  def delivery
102
118
  return @delivery if defined?(@delivery)
103
119
 
104
- stamp = reply_message&.dig("response_metadata", "delivery")
105
- @delivery = stamp.is_a?(Hash) ? build_delivery(stamp) : nil
120
+ @delivery = Delivery.from_stamp(reply_message&.dig("response_metadata", "delivery"))
121
+ end
122
+
123
+ # The escalation the run ended on, or nil when it did not escalate. A run that escalates ends
124
+ # with no reply and no pause: the thread refuses runs until a person resolves the escalation
125
+ # with {Assistants#hand_back_escalation} or {Assistants#close_escalation}.
126
+ #
127
+ # @return [Escalation, nil]
128
+ def escalation
129
+ return @escalation if defined?(@escalation)
130
+
131
+ @escalation = Escalation.wrap(raw["escalation"])
132
+ end
133
+
134
+ # @return [Boolean] whether the run handed the conversation to a person
135
+ def escalated?
136
+ !escalation.nil?
106
137
  end
107
138
 
108
139
  private
@@ -140,21 +171,5 @@ module NitroIntelligence
140
171
  block["text"] if block.is_a?(Hash) && block["type"] == "text" && block["text"].is_a?(String)
141
172
  end.join
142
173
  end
143
-
144
- def build_delivery(stamp)
145
- Delivery.new(
146
- status: string_or_nil(stamp["status"]),
147
- tool: string_or_nil(stamp["tool"]),
148
- attempts: stamp["attempts"].is_a?(Integer) ? stamp["attempts"] : nil,
149
- error: string_or_nil(stamp["error"]),
150
- result: stamp["result"],
151
- delivered_at: string_or_nil(stamp["delivered_at"]),
152
- failed_at: string_or_nil(stamp["failed_at"])
153
- )
154
- end
155
-
156
- def string_or_nil(value)
157
- value.is_a?(String) ? value : nil
158
- end
159
174
  end
160
175
  end
@@ -1,4 +1,4 @@
1
1
  module NitroIntelligence
2
2
  # The gem's version.
3
- VERSION = "4.4.0".freeze
3
+ VERSION = "4.5.0".freeze
4
4
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: nitro_intelligence
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.4.0
4
+ version: 4.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Igor Artemenko
@@ -13,44 +13,84 @@ dependencies:
13
13
  name: activesupport
14
14
  requirement: !ruby/object:Gem::Requirement
15
15
  requirements:
16
- - - "~>"
16
+ - - ">="
17
17
  - !ruby/object:Gem::Version
18
18
  version: '7.1'
19
+ - - "<"
20
+ - !ruby/object:Gem::Version
21
+ version: '8.2'
19
22
  type: :runtime
20
23
  prerelease: false
21
24
  version_requirements: !ruby/object:Gem::Requirement
22
25
  requirements:
23
- - - "~>"
26
+ - - ">="
24
27
  - !ruby/object:Gem::Version
25
28
  version: '7.1'
29
+ - - "<"
30
+ - !ruby/object:Gem::Version
31
+ version: '8.2'
32
+ - !ruby/object:Gem::Dependency
33
+ name: benchmark
34
+ requirement: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - '='
37
+ - !ruby/object:Gem::Version
38
+ version: 0.5.0
39
+ type: :runtime
40
+ prerelease: false
41
+ version_requirements: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - '='
44
+ - !ruby/object:Gem::Version
45
+ version: 0.5.0
46
+ - !ruby/object:Gem::Dependency
47
+ name: json
48
+ requirement: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - "<"
51
+ - !ruby/object:Gem::Version
52
+ version: '3'
53
+ type: :runtime
54
+ prerelease: false
55
+ version_requirements: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - "<"
58
+ - !ruby/object:Gem::Version
59
+ version: '3'
26
60
  - !ruby/object:Gem::Dependency
27
61
  name: langfuse-rb
28
62
  requirement: !ruby/object:Gem::Requirement
29
63
  requirements:
30
64
  - - '='
31
65
  - !ruby/object:Gem::Version
32
- version: 0.7.0
66
+ version: 0.12.4
33
67
  type: :runtime
34
68
  prerelease: false
35
69
  version_requirements: !ruby/object:Gem::Requirement
36
70
  requirements:
37
71
  - - '='
38
72
  - !ruby/object:Gem::Version
39
- version: 0.7.0
73
+ version: 0.12.4
40
74
  - !ruby/object:Gem::Dependency
41
75
  name: mini_magick
42
76
  requirement: !ruby/object:Gem::Requirement
43
77
  requirements:
44
- - - "~>"
78
+ - - ">="
45
79
  - !ruby/object:Gem::Version
46
80
  version: '4.10'
81
+ - - "<"
82
+ - !ruby/object:Gem::Version
83
+ version: '6'
47
84
  type: :runtime
48
85
  prerelease: false
49
86
  version_requirements: !ruby/object:Gem::Requirement
50
87
  requirements:
51
- - - "~>"
88
+ - - ">="
52
89
  - !ruby/object:Gem::Version
53
90
  version: '4.10'
91
+ - - "<"
92
+ - !ruby/object:Gem::Version
93
+ version: '6'
54
94
  - !ruby/object:Gem::Dependency
55
95
  name: openai
56
96
  requirement: !ruby/object:Gem::Requirement
@@ -107,6 +147,7 @@ files:
107
147
  - lib/nitro_intelligence/assistant.rb
108
148
  - lib/nitro_intelligence/assistant_registry.rb
109
149
  - lib/nitro_intelligence/assistants.rb
150
+ - lib/nitro_intelligence/assistants/escalations.rb
110
151
  - lib/nitro_intelligence/client/base.rb
111
152
  - lib/nitro_intelligence/client/client.rb
112
153
  - lib/nitro_intelligence/client/factory.rb
@@ -132,6 +173,7 @@ files:
132
173
  - lib/nitro_intelligence/decision.rb
133
174
  - lib/nitro_intelligence/deprecator.rb
134
175
  - lib/nitro_intelligence/embeddings.rb
176
+ - lib/nitro_intelligence/escalation.rb
135
177
  - lib/nitro_intelligence/langfuse_extension.rb
136
178
  - lib/nitro_intelligence/langfuse_tracer_provider.rb
137
179
  - lib/nitro_intelligence/media/audio.rb