Class: CodexSDK::AgentThread

Inherits:
Object
  • Object
show all
Defined in:
lib/codex_sdk/agent_thread.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options, thread_options:, resume_id: nil) ⇒ AgentThread

Returns a new instance of AgentThread.



9
10
11
12
13
14
# File 'lib/codex_sdk/agent_thread.rb', line 9

def initialize(options, thread_options:, resume_id: nil)
  @options = options
  @thread_options = thread_options
  @id = resume_id
  @exec = nil
end

Instance Attribute Details

#context_snapshotObject (readonly)

Returns the value of attribute context_snapshot.



7
8
9
# File 'lib/codex_sdk/agent_thread.rb', line 7

def context_snapshot
  @context_snapshot
end

#idObject (readonly)

Returns the value of attribute id.



7
8
9
# File 'lib/codex_sdk/agent_thread.rb', line 7

def id
  @id
end

Instance Method Details

#interruptObject

Interrupt the running subprocess.



67
68
69
# File 'lib/codex_sdk/agent_thread.rb', line 67

def interrupt
  @exec&.interrupt
end

#run(input, turn_options: TurnOptions.new) ⇒ Object

Blocking run: sends prompt, collects all events, returns a Turn.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/codex_sdk/agent_thread.rb', line 17

def run(input, turn_options: TurnOptions.new)
  items = []
  final_response = ""
  usage = nil

  run_streamed(input, turn_options: turn_options) do |event|
    case event
    when Events::ItemCompleted
      items << event.item
      final_response = event.item.text if event.item.is_a?(Items::AgentMessage)
    when Events::TurnCompleted
      usage = event.usage
    when Events::TurnFailed
      raise Error, event.error_message
    when Events::Error
      items << Items::Error.new(id: nil, message: event.message)
    end
  end

  Turn.new(items: items, final_response: final_response, usage: usage, context_snapshot: @context_snapshot)
end

#run_streamed(input, turn_options: TurnOptions.new, &block) ⇒ Object

Streaming run: yields each event to the block as it arrives.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/codex_sdk/agent_thread.rb', line 40

def run_streamed(input, turn_options: TurnOptions.new, &block)
  prompt = normalize_input(input)

  output_schema_path = nil
  output_schema_path = write_output_schema(turn_options.output_schema) if turn_options.output_schema

  @exec = Exec.new(
    @options,
    thread_options: @thread_options
  )

  @exec.run(
    prompt,
    resume_thread_id: @id,
    output_schema_path: output_schema_path
  ) do |event|
    # Capture thread ID from first event
    @id = event.thread_id if event.is_a?(Events::ThreadStarted)

    block.call(event)
  end
ensure
  @context_snapshot = @exec&.context_snapshot
  cleanup_output_schema(output_schema_path)
end