ruby_llm-ag_ui 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +52 -0
  3. data/README.md +1 -1
  4. data/docs/_advanced/client-example.md +11 -0
  5. data/docs/_advanced/provider-verification.md +70 -0
  6. data/docs/_advanced/rails-integration.md +5 -2
  7. data/docs/_advanced/security-and-deployment.md +2 -2
  8. data/docs/_advanced/worker-recovery.md +104 -0
  9. data/docs/_core_features/approval-and-resume.md +9 -0
  10. data/docs/_core_features/cancellation.md +84 -0
  11. data/docs/_core_features/reconnects.md +22 -1
  12. data/docs/_core_features/streaming-runs.md +14 -0
  13. data/docs/_getting_started/configuration.md +7 -2
  14. data/docs/_getting_started/whats-new-in-0-4.md +57 -0
  15. data/docs/_reference/api-reference.md +2 -1
  16. data/docs/_reference/compatibility.md +121 -11
  17. data/docs/_reference/public-api.md +102 -0
  18. data/docs/_reference/release-history.md +3 -1
  19. data/docs/_reference/releasing.md +10 -0
  20. data/docs/_reference/upgrading.md +17 -16
  21. data/docs/{_getting_started → _reference}/whats-new-in-0-2.md +2 -1
  22. data/docs/_reference/whats-new-in-0-3.md +62 -0
  23. data/lib/ruby_llm/ag_ui/configuration.rb +14 -11
  24. data/lib/ruby_llm/ag_ui/emitter.rb +6 -2
  25. data/lib/ruby_llm/ag_ui/error.rb +13 -2
  26. data/lib/ruby_llm/ag_ui/error_sanitizer.rb +2 -1
  27. data/lib/ruby_llm/ag_ui/immutable.rb +34 -0
  28. data/lib/ruby_llm/ag_ui/input.rb +5 -4
  29. data/lib/ruby_llm/ag_ui/interrupt.rb +10 -10
  30. data/lib/ruby_llm/ag_ui/mapper.rb +8 -0
  31. data/lib/ruby_llm/ag_ui/message_parser.rb +1 -1
  32. data/lib/ruby_llm/ag_ui/persistence.rb +18 -0
  33. data/lib/ruby_llm/ag_ui/rails/active_record_store.rb +21 -11
  34. data/lib/ruby_llm/ag_ui/rails/record.rb +8 -3
  35. data/lib/ruby_llm/ag_ui/rails/streaming.rb +3 -3
  36. data/lib/ruby_llm/ag_ui/reconnect.rb +1 -1
  37. data/lib/ruby_llm/ag_ui/resume.rb +9 -5
  38. data/lib/ruby_llm/ag_ui/resume_entry.rb +3 -3
  39. data/lib/ruby_llm/ag_ui/run.rb +18 -18
  40. data/lib/ruby_llm/ag_ui/run_record.rb +27 -14
  41. data/lib/ruby_llm/ag_ui/sse_writer.rb +16 -4
  42. data/lib/ruby_llm/ag_ui/store/base.rb +24 -1
  43. data/lib/ruby_llm/ag_ui/store/memory_store.rb +6 -10
  44. data/lib/ruby_llm/ag_ui/validation.rb +1 -1
  45. data/lib/ruby_llm/ag_ui/version.rb +1 -1
  46. metadata +31 -3
@@ -69,15 +69,15 @@ module RubyLLM
69
69
  # rubocop:disable Metrics/ParameterLists -- one keyword per field the value object owns
70
70
  def initialize(id:, tool_call_id:, arguments_digest:, expires_at:, reason: REASON_TOOL_CALL,
71
71
  message: nil, status: PENDING, decided_at: nil, created_at: nil)
72
- @id = id
73
- @tool_call_id = tool_call_id
74
- @arguments_digest = arguments_digest
75
- @expires_at = expires_at
76
- @reason = reason
77
- @message = message
72
+ @id = Immutable.copy(id)
73
+ @tool_call_id = Immutable.copy(tool_call_id)
74
+ @arguments_digest = Immutable.copy(arguments_digest)
75
+ @expires_at = Immutable.copy(expires_at)
76
+ @reason = Immutable.copy(reason)
77
+ @message = Immutable.copy(message)
78
78
  @status = assert_status!(status)
79
- @decided_at = decided_at
80
- @created_at = created_at
79
+ @decided_at = Immutable.copy(decided_at)
80
+ @created_at = Immutable.copy(created_at)
81
81
  freeze
82
82
  end
83
83
 
@@ -146,7 +146,7 @@ module RubyLLM
146
146
  reason: reason,
147
147
  message: message,
148
148
  tool_call_id: tool_call_id,
149
- expires_at: expires_at&.utc&.iso8601
149
+ expires_at: expires_at&.getutc&.iso8601
150
150
  )
151
151
  end
152
152
 
@@ -194,7 +194,7 @@ module RubyLLM
194
194
  private
195
195
 
196
196
  def iso8601(time)
197
- time&.utc&.iso8601
197
+ time&.getutc&.iso8601
198
198
  end
199
199
 
200
200
  def assert_status!(value)
@@ -60,6 +60,12 @@ module RubyLLM
60
60
  @closed = false
61
61
  end
62
62
 
63
+ # Internal resume bookkeeping: these calls were already reported by the
64
+ # interrupted run. Only their result and progress belong to this run.
65
+ def continue_tool_calls(ids) # :nodoc:
66
+ @continued_tool_call_ids = ids.dup.freeze
67
+ end
68
+
63
69
  # One streamed Chunk from Chat#complete.
64
70
  def chunk(chunk)
65
71
  return [] if @closed
@@ -185,6 +191,8 @@ module RubyLLM
185
191
  return [] if tool_calls.nil? || tool_calls.empty?
186
192
 
187
193
  tool_calls.flat_map do |key, tool_call|
194
+ next [] if @continued_tool_call_ids&.include?(tool_call.id)
195
+
188
196
  record = track(key, tool_call, streamed: streamed)
189
197
  open_tool_call(record) + argument_events(record, tool_call, streamed: streamed)
190
198
  end
@@ -9,7 +9,7 @@ module RubyLLM
9
9
  # gem never trusts a client message as a system instruction or a tool
10
10
  # result. This parser only guarantees the shapes the pinned schema defines,
11
11
  # so a mismatch is a clear InputError instead of a downstream surprise.
12
- class MessageParser
12
+ class MessageParser # :nodoc:
13
13
  include Validation
14
14
 
15
15
  # The roles the pinned schema defines.
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyLLM
4
+ module AgUI
5
+ # Keep uncertain write acknowledgements separate from run outcomes.
6
+ module Persistence # :nodoc:
7
+ module_function
8
+
9
+ def write
10
+ yield
11
+ rescue Error
12
+ raise
13
+ rescue StandardError => e
14
+ raise PersistenceError, "The store write could not be acknowledged: #{e.class}"
15
+ end
16
+ end
17
+ end
18
+ end
@@ -50,10 +50,8 @@ module RubyLLM
50
50
  def save(record)
51
51
  scope_key(record.scope)
52
52
  row = row_for(record.scope, record.thread_id, record.run_id)
53
- raise InvalidRunIdentityError, "run #{record.run_id} was never reserved" if row.nil?
54
- raise RunConflictError, conflict_message(record) if row.digest != record.digest
55
-
56
- row.write_run_record(record)
53
+ updated = next_record(row&.as_run_record, record)
54
+ row.write_run_record(updated)
57
55
  end
58
56
 
59
57
  def find_interrupt(scope:, thread_id:, interrupt_id:)
@@ -62,21 +60,34 @@ module RubyLLM
62
60
  row_for_interrupt(scope, thread_id, interrupt_id)&.as_run_record&.interrupt(interrupt_id)
63
61
  end
64
62
 
65
- # Records +decision+ on the interrupt under a row lock, so two resumes
66
- # that arrive together cannot both record a decision and run the tool.
63
+ # Records +decision+ with a conditional update. Competing writers reload
64
+ # and revalidate, so only one can redeem the approval.
67
65
  def redeem_interrupt(scope:, thread_id:, interrupt_id:, decision:, now:)
68
66
  unless Interrupt::DECISIONS.include?(decision)
69
67
  raise ConfigurationError, "decision must be one of #{Interrupt::DECISIONS.join(', ')}"
70
68
  end
71
69
 
72
- row = row_for_interrupt(scope, thread_id, interrupt_id)
73
- raise ResumeRejectedError, "no interrupt #{interrupt_id}" if row.nil?
70
+ retry_stale do
71
+ row = row_for_interrupt(scope, thread_id, interrupt_id)
72
+ raise ResumeRejectedError, "no interrupt #{interrupt_id}" if row.nil?
74
73
 
75
- row.with_lock { redeem(row.reload.as_run_record, interrupt_id, decision, now) }
74
+ redeem(row.as_run_record, interrupt_id, decision, now)
75
+ end
76
76
  end
77
77
 
78
78
  private
79
79
 
80
+ def retry_stale
81
+ attempts = 0
82
+ begin
83
+ yield
84
+ rescue StaleRecordError
85
+ attempts += 1
86
+ retry if attempts < 3
87
+ raise
88
+ end
89
+ end
90
+
80
91
  # A retry of the same identity attaches; a different input under the
81
92
  # same key is a conflict, because one run id may not mean two requests.
82
93
  def attach(row, digest)
@@ -91,8 +102,7 @@ module RubyLLM
91
102
  raise ResumeRejectedError, "interrupt #{interrupt_id} expired" if interrupt.expired?(now)
92
103
 
93
104
  answered = interrupt.decide(decision, now: now)
94
- row = row_for(record.scope, record.thread_id, record.run_id)
95
- row.write_run_record(record.replace_interrupt(answered, now: now))
105
+ save(record.replace_interrupt(answered, now: now))
96
106
  Redemption.new(interrupt: answered, replayed: false)
97
107
  end
98
108
 
@@ -28,13 +28,18 @@ module RubyLLM
28
28
  ::RubyLLM::AgUI::RunRecord.from_storage(::JSON.parse(payload))
29
29
  end
30
30
 
31
- # Writes +record+ onto this row and returns the record.
31
+ # Writes +record+ only if this row's observed payload is still current.
32
+ # Returns the record or raises StaleRecordError on a competing update.
32
33
  #
33
34
  # The identity columns are not writable: a row keeps the identity it was
34
35
  # reserved with, so a record cannot be stored under another run's key.
35
36
  def write_run_record(record)
36
- update!(digest: record.digest, status: record.status.to_s, sequence: record.sequence,
37
- payload: ::JSON.generate(record.to_storage))
37
+ changed = self.class.where(id: id, payload: payload).update_all(
38
+ digest: record.digest, status: record.status.to_s, sequence: record.sequence,
39
+ payload: ::JSON.generate(record.to_storage)
40
+ )
41
+ raise StaleRecordError, "run #{record.run_id} changed before it could be saved" unless changed == 1
42
+
38
43
  record
39
44
  end
40
45
 
@@ -45,9 +45,9 @@ module RubyLLM
45
45
  include ::ActionController::Live
46
46
  end
47
47
 
48
- # Streams one run and returns the run's record, or nil when the client
49
- # disconnected. The block receives the parsed input and returns the chat
50
- # for it.
48
+ # Streams one run and returns its record. A disconnected transport does
49
+ # not stop its worker from completing and storing the real outcome.
50
+ # The block receives the parsed input and returns the authorized chat.
51
51
  def stream_ag_ui_run(&resolve_chat)
52
52
  if resolve_chat.nil?
53
53
  raise ConfigurationError, 'stream_ag_ui_run needs a block that returns the chat for the input'
@@ -12,7 +12,7 @@ module RubyLLM
12
12
  # What cannot be served this way is a run that has not ended: attaching a
13
13
  # second stream to a live run needs a relay the gem does not own, and a
14
14
  # silent second stream would duplicate the work. Those are refused.
15
- class Reconnect
15
+ class Reconnect # :nodoc:
16
16
  # The failure reported for a run that failed before its sanitized error
17
17
  # was recorded — a record from an older release, or one whose write was
18
18
  # interrupted.
@@ -15,7 +15,7 @@ module RubyLLM
15
15
  #
16
16
  # An approval answers an interrupt. The host still re-authorizes the actor
17
17
  # before the tool executes.
18
- class Resume
18
+ class Resume # :nodoc:
19
19
  # One entry's effect: the interrupt it answers and the decision to record.
20
20
  Decision = Struct.new(:interrupt, :decision, keyword_init: true)
21
21
 
@@ -88,15 +88,19 @@ module RubyLLM
88
88
  # The store's redemption is atomic: the first answer record wins, and a
89
89
  # repeat comes back as a replay that must not execute anything.
90
90
  def redeem(planned, now:)
91
- redemption = @store.redeem_interrupt(
92
- scope: @scope, thread_id: @input.thread_id,
93
- interrupt_id: planned.interrupt.id, decision: planned.decision, now: now
94
- )
91
+ redemption = persist_decision(planned, now: now)
95
92
  raise ResumeRejectedError, "interrupt #{planned.interrupt.id} was already answered" if redemption.replayed?
96
93
 
97
94
  redemption.approved? ? @chat.approve(redemption.tool_call_id) : @chat.deny(redemption.tool_call_id)
98
95
  end
99
96
 
97
+ def persist_decision(planned, now:)
98
+ Persistence.write do
99
+ @store.redeem_interrupt(scope: @scope, thread_id: @input.thread_id,
100
+ interrupt_id: planned.interrupt.id, decision: planned.decision, now: now)
101
+ end
102
+ end
103
+
100
104
  # The protocol's resume vocabulary is resolved or cancelled; the interrupt
101
105
  # records the truthful decision, and a cancelled answer denies the call
102
106
  # rather than approving it.
@@ -25,9 +25,9 @@ module RubyLLM
25
25
  attr_reader :payload
26
26
 
27
27
  def initialize(interrupt_id:, status:, payload: nil)
28
- @interrupt_id = interrupt_id
29
- @status = status
30
- @payload = payload
28
+ @interrupt_id = Immutable.copy(interrupt_id)
29
+ @status = Immutable.copy(status)
30
+ @payload = Immutable.copy(payload)
31
31
  freeze
32
32
  end
33
33
 
@@ -20,7 +20,8 @@ module RubyLLM
20
20
  # input, because a scope derived from anything the client sent would let one
21
21
  # client attach to another's run.
22
22
  class Run
23
- # The run's authoritative record, once it has been reserved.
23
+ # The reserved record or final outcome observed by this run, including a
24
+ # reconnect. Nil before the run obtains its reservation.
24
25
  attr_reader :record
25
26
 
26
27
  # rubocop:disable-next Metrics/ParameterLists -- one keyword per host-supplied or overridable value
@@ -52,21 +53,20 @@ module RubyLLM
52
53
  def stream(to:)
53
54
  resume.plan(now: @clock.call) if resume.needed?
54
55
  reservation = reserve
55
- return execute(reservation.record, to) if reservation.created?
56
+ @record = reservation.record
57
+ return execute(@record, to) if reservation.created?
56
58
 
57
- reconnect(reservation.record, to)
59
+ reconnect(@record, to)
58
60
  end
59
61
 
60
62
  private
61
63
 
62
- def resume
63
- @resume ||= Resume.new(input: @input, store: @store, scope: @scope, chat: @chat)
64
- end
64
+ def resume = @resume ||= Resume.new(input: @input, store: @store, scope: @scope, chat: @chat)
65
65
 
66
66
  def reserve
67
- @store.reserve(
68
- scope: @scope, thread_id: @input.thread_id, run_id: @input.run_id, digest: @input.digest
69
- )
67
+ Persistence.write do
68
+ @store.reserve(scope: @scope, thread_id: @input.thread_id, run_id: @input.run_id, digest: @input.digest)
69
+ end
70
70
  end
71
71
 
72
72
  # An identity that is already reserved is never executed a second time.
@@ -92,20 +92,25 @@ module RubyLLM
92
92
  @record = finalize { finish }
93
93
  rescue RubyLLM::CancelledError
94
94
  @record = finalize { @emitter.cancel }
95
+ rescue PersistenceError, RunConflictError
96
+ raise
95
97
  rescue StandardError => e
96
98
  @record = finalize { @emitter.fail(e) }
99
+ ensure
100
+ finalize { @mapper&.close }
97
101
  end
98
102
 
99
103
  def start_execution(record, to)
100
104
  @mapper = build_mapper(record)
105
+ @mapper.continue_tool_calls(@chat.pending_approvals.map(&:id)) if resume.needed?
101
106
  @emitter = build_emitter(record, to, mapper: @mapper)
102
107
  @emitter.start(run_started_event(record), state: @state)
103
108
  end
104
109
 
105
110
  def build_emitter(record, to, mapper: build_mapper(record))
106
111
  Emitter.new(
107
- writer: SSEWriter.new(to, logger: @logger), mapper: mapper,
108
- store: @store, record: record, clock: @clock, logger: @logger
112
+ writer: SSEWriter.new(to, logger: @logger), mapper: mapper, store: @store,
113
+ record: record, clock: @clock, logger: @logger
109
114
  )
110
115
  end
111
116
 
@@ -164,8 +169,7 @@ module RubyLLM
164
169
 
165
170
  def run_started_event(record)
166
171
  Protocol.run_started(
167
- thread_id: record.thread_id, run_id: record.run_id,
168
- parent_run_id: @input.parent_run_id, input: @input.to_h
172
+ thread_id: record.thread_id, run_id: record.run_id, parent_run_id: @input.parent_run_id, input: @input.to_h
169
173
  )
170
174
  end
171
175
 
@@ -175,13 +179,9 @@ module RubyLLM
175
179
  end
176
180
  raise ConfigurationError, 'input must be a RubyLLM::AgUI::Input' unless @input.is_a?(Input)
177
181
 
178
- validate_scope!
179
- end
180
-
181
- def validate_scope!
182
182
  return if @scope.is_a?(String) && !@scope.empty?
183
183
 
184
- raise ConfigurationError, 'scope must be a non-empty String built from authenticated identity'
184
+ raise ConfigurationError, Store::Base::SCOPE_MESSAGE
185
185
  end
186
186
  end
187
187
  end
@@ -52,6 +52,10 @@ module RubyLLM
52
52
  # reconnect are ordered by it rather than by wall-clock time.
53
53
  attr_reader :sequence
54
54
 
55
+ # Storage revision, distinct from the event sequence. Stores increment it
56
+ # atomically and reject writes from older snapshots.
57
+ attr_reader :revision
58
+
55
59
  # The host-owned run state kept for a reconnect snapshot, or nil.
56
60
  attr_reader :snapshot
57
61
 
@@ -67,18 +71,19 @@ module RubyLLM
67
71
 
68
72
  # rubocop:disable-next Metrics/ParameterLists -- one keyword per field the record owns
69
73
  def initialize(scope:, thread_id:, run_id:, digest:, created_at:, status: RESERVED, sequence: 0,
70
- snapshot: nil, interrupts: [], failure: nil, updated_at: nil)
71
- @scope = scope
72
- @thread_id = thread_id
73
- @run_id = run_id
74
- @digest = digest
74
+ snapshot: nil, interrupts: [], failure: nil, updated_at: nil, revision: 0)
75
+ @scope = Immutable.copy(scope)
76
+ @thread_id = Immutable.copy(thread_id)
77
+ @run_id = Immutable.copy(run_id)
78
+ @digest = Immutable.copy(digest)
75
79
  @status = assert_status!(status)
76
80
  @sequence = sequence
77
- @snapshot = snapshot
78
- @interrupts = interrupts.freeze
79
- @failure = failure
80
- @created_at = created_at
81
- @updated_at = updated_at || created_at
81
+ @revision = revision
82
+ @snapshot = Immutable.copy(snapshot)
83
+ @interrupts = Immutable.copy(interrupts)
84
+ @failure = Immutable.copy(failure)
85
+ @created_at = Immutable.copy(created_at)
86
+ @updated_at = Immutable.copy(updated_at || created_at)
82
87
  freeze
83
88
  end
84
89
 
@@ -122,6 +127,11 @@ module RubyLLM
122
127
  with(now: now, sequence: sequence + 1)
123
128
  end
124
129
 
130
+ # Storage bookkeeping; hosts retain the record returned by save.
131
+ def next_revision # :nodoc:
132
+ with(now: updated_at, revision: revision + 1)
133
+ end
134
+
125
135
  # Closes the run with +status+: :succeeded, :interrupted, :cancelled or
126
136
  # :failed, and, for a failure, the sanitized error a reconnect reports.
127
137
  # Re-applying the same terminal status is an idempotent no-op — so the
@@ -158,6 +168,7 @@ module RubyLLM
158
168
  with(now: now, interrupts: replaced)
159
169
  end
160
170
 
171
+ # rubocop:disable-next Metrics/AbcSize -- one entry per serialized record field
161
172
  def to_h
162
173
  {
163
174
  'scope' => scope.to_s,
@@ -166,6 +177,7 @@ module RubyLLM
166
177
  'digest' => digest,
167
178
  'status' => status.to_s,
168
179
  'sequence' => sequence,
180
+ 'revision' => revision,
169
181
  'snapshot' => snapshot,
170
182
  'failure' => failure,
171
183
  'interrupts' => interrupts.map(&:to_h),
@@ -186,7 +198,8 @@ module RubyLLM
186
198
  new(
187
199
  scope: hash.fetch('scope'), thread_id: hash.fetch('threadId'), run_id: hash.fetch('runId'),
188
200
  digest: hash.fetch('digest'), status: hash.fetch('status').to_sym,
189
- sequence: hash.fetch('sequence'), snapshot: hash['snapshot'], failure: hash['failure'],
201
+ sequence: hash.fetch('sequence'), revision: hash.fetch('revision', 0),
202
+ snapshot: hash['snapshot'], failure: hash['failure'],
190
203
  interrupts: interrupts_from_storage(hash['interrupts']),
191
204
  created_at: Interrupt.parse_time(hash.fetch('createdAt')),
192
205
  updated_at: Interrupt.parse_time(hash.fetch('updatedAt'))
@@ -201,10 +214,10 @@ module RubyLLM
201
214
 
202
215
  # rubocop:disable-next Metrics/ParameterLists -- one keyword per field, each defaulted to the record's own
203
216
  def with(now:, status: self.status, sequence: self.sequence, snapshot: self.snapshot,
204
- interrupts: self.interrupts, failure: self.failure)
217
+ interrupts: self.interrupts, failure: self.failure, revision: self.revision)
205
218
  self.class.new(
206
219
  scope: scope, thread_id: thread_id, run_id: run_id, digest: digest, status: status,
207
- sequence: sequence, snapshot: snapshot, interrupts: interrupts, failure: failure,
220
+ sequence: sequence, revision: revision, snapshot: snapshot, interrupts: interrupts, failure: failure,
208
221
  created_at: created_at, updated_at: now
209
222
  )
210
223
  end
@@ -216,7 +229,7 @@ module RubyLLM
216
229
  end
217
230
 
218
231
  def iso8601(time)
219
- time&.utc&.iso8601
232
+ time&.getutc&.iso8601
220
233
  end
221
234
 
222
235
  def assert_status!(value)
@@ -10,7 +10,7 @@ module RubyLLM
10
10
  # buffer frames or choose how a host relays a background job to a client.
11
11
  # What it does own is the ordering and the framing of the events it writes.
12
12
  #
13
- # A dead stream is reported as a StreamError and the writer stays closed.
13
+ # A dead stream is reported as a TransportError and the writer stays closed.
14
14
  # The reason is a transport truncation, not a run outcome: it is never
15
15
  # evidence that the work finished, succeeded or was cancelled.
16
16
  class SSEWriter
@@ -82,7 +82,7 @@ module RubyLLM
82
82
  # Encodes +event+ and writes it, then flushes so the client sees it now.
83
83
  # Returns the encoded frame.
84
84
  def write(event)
85
- raise StreamError, 'The event stream is closed.' if @closed
85
+ raise TransportError, 'The event stream is closed.' if @closed
86
86
 
87
87
  frame = @encoder.encode(event)
88
88
  @stream.write(frame)
@@ -90,12 +90,14 @@ module RubyLLM
90
90
  @events_written += 1
91
91
  @bytes_written += frame.bytesize
92
92
  frame
93
- rescue IOError, SystemCallError => e
93
+ rescue StandardError => e
94
+ raise unless transport_error?(e)
95
+
94
96
  # The client is gone. The class name is enough for the host log; the
95
97
  # message may embed a path or a socket address and is not echoed.
96
98
  @logger&.warn("[ruby_llm_ag_ui] the event stream failed: #{e.class}")
97
99
  @closed = true
98
- raise StreamError, "The event stream failed: #{e.class}"
100
+ raise TransportError, "The event stream failed: #{e.class}"
99
101
  end
100
102
 
101
103
  # Pushes buffered bytes to the client. A no-op for a stream that cannot
@@ -114,6 +116,16 @@ module RubyLLM
114
116
  def closed?
115
117
  @closed
116
118
  end
119
+
120
+ private
121
+
122
+ def transport_error?(error)
123
+ return true if error.is_a?(IOError) || error.is_a?(SystemCallError)
124
+ return true if defined?(::Puma::ConnectionError) && error.is_a?(::Puma::ConnectionError)
125
+
126
+ defined?(::ActionController::Live::ClientDisconnected) &&
127
+ error.is_a?(::ActionController::Live::ClientDisconnected)
128
+ end
117
129
  end
118
130
  end
119
131
  end
@@ -63,11 +63,24 @@ module RubyLLM
63
63
  raise NotImplementedError
64
64
  end
65
65
 
66
- # Persists an updated record and returns it.
66
+ # Atomically persists a record only if its revision is still current.
67
+ # Returns a new record with its revision incremented. Retain this return
68
+ # value for later writes. A stale write raises StaleRecordError.
67
69
  def save(record)
68
70
  raise NotImplementedError
69
71
  end
70
72
 
73
+ # Closes an observed non-terminal run after the host confirms its worker
74
+ # has stopped. Does not cancel a worker, undo effects, release identity,
75
+ # or execute anything. A newer revision or terminal run is refused.
76
+ def recover(record)
77
+ raise RunConflictError, 'only a non-terminal run can be recovered' if record.terminal?
78
+
79
+ failure = { 'code' => 'worker_lost',
80
+ 'message' => 'The worker stopped before recording an outcome. Tool effects may be incomplete.' }
81
+ save(record.finish(RunRecord::FAILED, now: now, failure: failure))
82
+ end
83
+
71
84
  # The interrupt with +id+ anywhere on the thread, or nil.
72
85
  def find_interrupt(scope:, thread_id:, interrupt_id:)
73
86
  raise NotImplementedError
@@ -88,6 +101,16 @@ module RubyLLM
88
101
 
89
102
  private
90
103
 
104
+ def next_record(stored, candidate)
105
+ raise InvalidRunIdentityError, "run #{candidate.run_id} was never reserved" if stored.nil?
106
+ raise RunConflictError, conflict_message(candidate) if stored.digest != candidate.digest
107
+ if stored.revision != candidate.revision || (stored.terminal? && stored.status != candidate.status)
108
+ raise StaleRecordError, "run #{candidate.run_id} changed; reload its record before writing"
109
+ end
110
+
111
+ candidate.next_revision
112
+ end
113
+
91
114
  # The host's scope must be a canonical string. An arbitrary object would
92
115
  # make two requests from the same tenant hash differently, so a retry
93
116
  # would not attach and the run would execute twice.
@@ -34,7 +34,7 @@ module RubyLLM
34
34
  )
35
35
  @records[key] = record
36
36
  thread = thread_key(scope, thread_id)
37
- @threads[thread] = (@threads[thread] || []) + [run_id]
37
+ @threads[thread] = (@threads[thread] || []) + [record.run_id]
38
38
  Reservation.new(record: record, status: Reservation::CREATED)
39
39
  end
40
40
  end
@@ -55,13 +55,8 @@ module RubyLLM
55
55
  def save(record)
56
56
  key = key_for(record.scope, record.thread_id, record.run_id)
57
57
  @lock.synchronize do
58
- stored = @records[key]
59
- raise InvalidRunIdentityError, "run #{record.run_id} was never reserved" if stored.nil?
60
- raise RunConflictError, conflict_message(record) if stored.digest != record.digest
61
-
62
- @records[key] = record
58
+ @records[key] = next_record(@records[key], record)
63
59
  end
64
- record
65
60
  end
66
61
 
67
62
  def find_interrupt(scope:, thread_id:, interrupt_id:)
@@ -89,7 +84,8 @@ module RubyLLM
89
84
  raise ResumeRejectedError, "interrupt #{interrupt_id} expired" if interrupt.expired?(now)
90
85
 
91
86
  answered = interrupt.decide(decision, now: now)
92
- @records[key_for(scope, thread_id, record.run_id)] = record.replace_interrupt(answered, now: now)
87
+ @records[key_for(scope, thread_id, record.run_id)] =
88
+ record.replace_interrupt(answered, now: now).next_revision
93
89
  Redemption.new(interrupt: answered, replayed: false)
94
90
  end
95
91
 
@@ -111,11 +107,11 @@ module RubyLLM
111
107
  end
112
108
 
113
109
  def key_for(scope, thread_id, run_id)
114
- [scope_key(scope), thread_id, run_id]
110
+ Immutable.copy([scope_key(scope), thread_id, run_id])
115
111
  end
116
112
 
117
113
  def thread_key(scope, thread_id)
118
- [scope_key(scope), thread_id]
114
+ Immutable.copy([scope_key(scope), thread_id])
119
115
  end
120
116
  end
121
117
  end
@@ -9,7 +9,7 @@ module RubyLLM
9
9
  # the client without echoing request bytes back.
10
10
  #
11
11
  # Included by RubyLLM::AgUI::Input::Parser and RubyLLM::AgUI::MessageParser.
12
- module Validation
12
+ module Validation # :nodoc:
13
13
  # The longest accepted id (threadId, runId, message id, interrupt id).
14
14
  MAX_ID_LENGTH = 255
15
15
 
@@ -3,6 +3,6 @@
3
3
  module RubyLLM
4
4
  module AgUI
5
5
  # The version of the ruby_llm-ag_ui gem, as a string.
6
- VERSION = '0.2.0'
6
+ VERSION = '0.4.0'
7
7
  end
8
8
  end