Class: PiAgent::Event

Inherits:
Object
  • Object
show all
Defined in:
lib/pi_agent/event.rb

Overview

Thin typed wrapper over a pi RPC event message. The native JSON payload is preserved on ‘#raw` so callers can reach fields we haven’t given a dedicated accessor yet.

Event types are exposed as Ruby symbols (e.g. ‘:text_delta`, `:agent_end`) matching the upstream protocol’s ‘type` field.

Constant Summary collapse

TERMINAL_TYPES =

Event types that terminate a single prompt’s event stream. ‘agent_end` fires when the agent finishes processing the current prompt cycle; we stop iterating then.

%i[agent_end].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw) ⇒ Event

Returns a new instance of Event.



18
19
20
21
# File 'lib/pi_agent/event.rb', line 18

def initialize(raw)
  @raw = raw
  @type = raw["type"]&.to_sym
end

Instance Attribute Details

#rawObject (readonly)

Returns the value of attribute raw.



16
17
18
# File 'lib/pi_agent/event.rb', line 16

def raw
  @raw
end

#typeObject (readonly)

Returns the value of attribute type.



16
17
18
# File 'lib/pi_agent/event.rb', line 16

def type
  @type
end

Instance Method Details

#[](key) ⇒ Object



27
28
29
# File 'lib/pi_agent/event.rb', line 27

def [](key)
  @raw[key.to_s]
end

#deltaObject

Common shorthand for streaming text deltas. ‘message_update` with `assistantMessageEvent.type == “text_delta”`.



33
34
35
# File 'lib/pi_agent/event.rb', line 33

def delta
  assistant_event&.[]("delta")
end

#error?Boolean

True for an ‘extension_error` event, or a `message_update` whose assistant event is an error (agent turn errored or was aborted).

Returns:

  • (Boolean)


39
40
41
# File 'lib/pi_agent/event.rb', line 39

def error?
  @type == :extension_error || assistant_event_type == :error
end

#error_messageObject

Best-effort error text for an error event; nil if not an error.



44
45
46
47
48
49
# File 'lib/pi_agent/event.rb', line 44

def error_message
  return @raw["error"] if @type == :extension_error
  return nil unless assistant_event_type == :error

  assistant_event["error"] || assistant_event["message"]
end

#error_reasonObject

Reason for an assistant-event error: “aborted” or “error”. nil otherwise. Use this to distinguish a user abort from a real failure.



53
54
55
56
57
# File 'lib/pi_agent/event.rb', line 53

def error_reason
  return nil unless assistant_event_type == :error

  assistant_event["reason"]
end

#inspectObject



63
64
65
# File 'lib/pi_agent/event.rb', line 63

def inspect
  "#<#{self.class.name} type=#{@type.inspect}>"
end

#terminal?Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/pi_agent/event.rb', line 23

def terminal?
  TERMINAL_TYPES.include?(@type)
end

#to_hObject



59
60
61
# File 'lib/pi_agent/event.rb', line 59

def to_h
  @raw
end