Class: Harnex::Session

Inherits:
Object
  • Object
show all
Defined in:
lib/harnex/runtime/session.rb

Defined Under Namespace

Classes: EventCounters

Constant Summary collapse

OUTPUT_BUFFER_LIMIT =
64 * 1024
TRANSCRIPT_TAIL_BYTES =
16 * 1024
AUTOSTOP_TEARDOWN_GRACE_SECONDS_DEFAULT =
5.0
USAGE_FIELDS =
%i[
  input_tokens output_tokens reasoning_tokens cached_tokens total_tokens
  agent_session_id cost_usd tool_calls model agent_provider
].freeze
SESSION_SUMMARY_SIGNAL_FIELDS =
%i[
  input_tokens output_tokens reasoning_tokens cached_tokens total_tokens
  agent_session_id cost_usd
].freeze
BUDGET_META_FIELDS =
%w[read_budget_lines output_ceiling_lines].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(adapter:, command:, repo_root:, host:, port: nil, id: DEFAULT_ID, watch: nil, description: nil, meta: nil, summary_out: nil, inbox_ttl: Inbox::DEFAULT_TTL, auto_stop: false, launch_cwd: nil) ⇒ Session

Returns a new instance of Session.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/harnex/runtime/session.rb', line 64

def initialize(adapter:, command:, repo_root:, host:, port: nil, id: DEFAULT_ID, watch: nil, description: nil, meta: nil, summary_out: nil, inbox_ttl: Inbox::DEFAULT_TTL, auto_stop: false, launch_cwd: nil)
  @adapter = adapter
  @command = command
  @repo_root = repo_root
  @launch_cwd = File.expand_path(launch_cwd.to_s.empty? ? repo_root : launch_cwd)
  @host = host
  @id = Harnex.normalize_id(id)
  @watch = watch
  @description = description.to_s.strip
  @description = nil if @description.empty?
  @meta = meta
  @summary_out = summary_out.to_s.strip
  @summary_out = nil if @summary_out.empty?
  @registry_path = Harnex.registry_path(repo_root, @id)
  @output_log_path = Harnex.output_log_path(repo_root, @id)
  @events_log_path = Harnex.events_log_path(repo_root, @id)
  @session_id = SecureRandom.hex(8)
  @token = SecureRandom.hex(16)
  @port = Harnex.allocate_port(repo_root, @id, port, host: host)
  @mutex = Mutex.new
  @inject_mutex = Mutex.new
  @events_mutex = Mutex.new
  @stop_mutex = Mutex.new
  @auto_stop_mutex = Mutex.new
  @injected_count = 0
  @last_injected_at = nil
  @started_at = Time.now
  @server = nil
  @reader = nil
  @output_log = nil
  @events_log = nil
  @events_log_seq = 0
  @event_counters = EventCounters.new
  @git_start = {}
  @git_end = {}
  @usage_summary = {}
  @ended_at = nil
  @exit_reason = nil
  @last_error = nil
  @session_finalized = false
  @turn_started_seen = false
  @last_completed_at = nil
  @pi_streamed_text_by_message = {}
  @auto_stop = !!auto_stop
  @auto_stop_fired = false
  @auto_stop_seen_busy = false
  @auto_stop_threads = []
  @stop_requested = false
  @writer = nil
  @pid = nil
  @term_signal = nil
  @output_buffer = +""
  @output_buffer.force_encoding(Encoding::BINARY)
  @state_machine = SessionState.new(adapter)
  @inbox = Inbox.new(self, @state_machine, ttl: inbox_ttl)
  @rate_limits = nil
  @parent_harnex_id = ENV["HARNEX_ID"].to_s.strip
  @parent_harnex_id = nil if @parent_harnex_id.empty?
end

Instance Attribute Details

#adapterObject (readonly)

Returns the value of attribute adapter.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def adapter
  @adapter
end

#commandObject (readonly)

Returns the value of attribute command.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def command
  @command
end

#descriptionObject (readonly)

Returns the value of attribute description.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def description
  @description
end

#ended_atObject (readonly)

Returns the value of attribute ended_at.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def ended_at
  @ended_at
end

#events_log_pathObject (readonly)

Returns the value of attribute events_log_path.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def events_log_path
  @events_log_path
end

#exit_codeObject (readonly)

Returns the value of attribute exit_code.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def exit_code
  @exit_code
end

#hostObject (readonly)

Returns the value of attribute host.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def host
  @host
end

#idObject (readonly)

Returns the value of attribute id.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def id
  @id
end

#inboxObject (readonly)

Returns the value of attribute inbox.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def inbox
  @inbox
end

#launch_cwdObject (readonly)

Returns the value of attribute launch_cwd.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def launch_cwd
  @launch_cwd
end

#metaObject (readonly)

Returns the value of attribute meta.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def meta
  @meta
end

#output_log_pathObject (readonly)

Returns the value of attribute output_log_path.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def output_log_path
  @output_log_path
end

#pidObject (readonly)

Returns the value of attribute pid.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def pid
  @pid
end

#portObject (readonly)

Returns the value of attribute port.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def port
  @port
end

#repo_rootObject (readonly)

Returns the value of attribute repo_root.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def repo_root
  @repo_root
end

#session_idObject (readonly)

Returns the value of attribute session_id.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def session_id
  @session_id
end

#started_atObject (readonly)

Returns the value of attribute started_at.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def started_at
  @started_at
end

#summary_outObject (readonly)

Returns the value of attribute summary_out.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def summary_out
  @summary_out
end

#term_signalObject (readonly)

Returns the value of attribute term_signal.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def term_signal
  @term_signal
end

#tokenObject (readonly)

Returns the value of attribute token.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def token
  @token
end

#watchObject (readonly)

Returns the value of attribute watch.



60
61
62
# File 'lib/harnex/runtime/session.rb', line 60

def watch
  @watch
end

Class Method Details

.validate_binary!(command) ⇒ Object

Raises:



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/harnex/runtime/session.rb', line 124

def self.validate_binary!(command)
  binary = Array(command).first.to_s
  raise BinaryNotFound, "\"\" not found — is it installed and on your PATH?" if binary.empty?

  if binary.include?("/")
    return binary if File.executable?(binary) && !File.directory?(binary)

    raise BinaryNotFound, "\"#{binary}\" not found — is it installed and on your PATH?"
  end

  ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).each do |dir|
    path = File.join(dir, binary)
    return path if File.executable?(path) && !File.directory?(path)
  end

  raise BinaryNotFound, "\"#{binary}\" not found — is it installed and on your PATH?"
end

Instance Method Details

#auth_ok?(header) ⇒ Boolean

Returns:

  • (Boolean)


245
246
247
# File 'lib/harnex/runtime/session.rb', line 245

def auth_ok?(header)
  header == "Bearer #{token}"
end

#git_endObject



241
242
243
# File 'lib/harnex/runtime/session.rb', line 241

def git_end
  @git_end || {}
end

#git_startObject



237
238
239
# File 'lib/harnex/runtime/session.rb', line 237

def git_start
  @git_start || {}
end

#inject(text, newline: true) ⇒ Object



249
250
251
252
253
# File 'lib/harnex/runtime/session.rb', line 249

def inject(text, newline: true)
  raise "session is not running" unless pid && Harnex.alive_pid?(pid)

  inject_sequence([{ text: text, newline: newline }])
end

#inject_stop(turn_id: nil) ⇒ Object



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/harnex/runtime/session.rb', line 255

def inject_stop(turn_id: nil)
  unless structured_transport?
    raise "session is not running" unless pid && Harnex.alive_pid?(pid)
  end

  return { ok: true, signal: "already_requested" } if stop_requested!

  if structured_transport?
    if adapter.respond_to?(:terminate_subprocess)
      Thread.new do
        begin
          adapter.terminate_subprocess
        rescue Errno::ESRCH, StandardError
          nil
        end
      end
    end
    @inject_mutex.synchronize do
      begin
        adapter.interrupt(turn_id: turn_id)
      rescue StandardError
        nil
      end
      @state_machine.force_busy!
    end
    return { ok: true, signal: "interrupt_sent" }
  end

  @inject_mutex.synchronize do
    adapter.inject_exit(@writer)
    @state_machine.force_busy!
  end

  { ok: true, signal: "exit_sequence_sent" }
end

#inject_via_adapter(text:, submit:, enter_only:, force: false) ⇒ Object



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/harnex/runtime/session.rb', line 291

def inject_via_adapter(text:, submit:, enter_only:, force: false)
  if structured_transport?
    return inject_via_structured(text: text, submit: submit, enter_only: enter_only, force: force)
  end

  snapshot = adapter.wait_for_sendable(method(:screen_snapshot), submit: submit, enter_only: enter_only, force: force)
  payload = adapter.build_send_payload(
    text: text,
    submit: submit,
    enter_only: enter_only,
    screen_text: snapshot,
    force: force
  )

  result =
    if payload[:steps]
      inject_sequence(payload.fetch(:steps))
    else
      inject(payload.fetch(:text), newline: payload.fetch(:newline, false))
    end

  result.merge(
    cli: adapter.key,
    input_state: payload[:input_state],
    force: payload[:force]
  )
    .tap { emit_send_event(text, force: payload[:force]) }
end

#inject_via_structured(text:, submit:, enter_only:, force: false) ⇒ Object



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/harnex/runtime/session.rb', line 320

def inject_via_structured(text:, submit:, enter_only:, force: false)
  payload = adapter.build_send_payload(
    text: text,
    submit: submit,
    enter_only: enter_only,
    screen_text: nil,
    force: force
  )
  dispatch = payload.fetch(:dispatch).dup
  dispatch[:model] = meta_hash["model"] if meta_hash["model"] && !dispatch.key?(:model)
  dispatch[:effort] = meta_hash["effort"] if meta_hash["effort"] && !dispatch.key?(:effort)

  turn_id = nil
  @inject_mutex.synchronize do
    turn_id = adapter.dispatch(**dispatch)
    @state_machine.force_busy!
    @injected_count += 1
    @last_injected_at = Time.now
    persist_registry
  end

  emit_send_event(dispatch.fetch(:prompt, text), force: payload[:force])
  {
    ok: true,
    cli: adapter.key,
    bytes_written: dispatch.fetch(:prompt, text).to_s.bytesize,
    injected_count: @injected_count,
    newline: false,
    input_state: payload[:input_state],
    force: payload[:force],
    turn_id: turn_id
  }
end

#run(validate_binary: true) ⇒ Object



142
143
144
145
146
147
148
149
150
# File 'lib/harnex/runtime/session.rb', line 142

def run(validate_binary: true)
  validate_binary! if validate_binary
  prepare_output_log
  prepare_events_log

  return run_structured if structured_transport?

  run_pty
end

#run_ptyObject



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/harnex/runtime/session.rb', line 152

def run_pty
  @reader, @writer, @pid = PTY.spawn(child_env, *command)
  @writer.sync = true
  arm_auto_stop_after_initial_context
  emit_started_event
  emit_git_start_event

  install_signal_handlers
  sync_window_size
  @server = ApiServer.new(self)
  @server.start
  persist_registry

  stdin_state = STDIN.tty? ? STDIN.raw! : nil
  watch_thread = start_watch_thread
  @inbox.start
  input_thread = start_input_thread
  output_thread = start_output_thread

  _, status = Process.wait2(pid)
  @term_signal = status.signaled? ? status.termsig : nil
  @exit_code = status.exited? ? status.exitstatus : 128 + status.termsig
  @ended_at = Time.now

  normalize_auto_stop_exit_code!
  drain_auto_stop_threads
  output_thread.join(1)
  finalize_session!
  input_thread&.kill
  watch_thread&.kill
  @exit_code
ensure
  finalize_session!
  @inbox.stop
  STDIN.cooked! if STDIN.tty? && stdin_state
  @server&.stop
  persist_exit_status
  cleanup_registry
  @reader&.close unless @reader&.closed?
  @output_log&.close unless @output_log&.closed?
  @events_log&.close unless @events_log&.closed?
  @writer&.close unless @writer&.closed?
end

#status_payload(include_input_state: true) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/harnex/runtime/session.rb', line 196

def status_payload(include_input_state: true)
  payload = {
    ok: true,
    session_id: session_id,
    repo_root: repo_root,
    repo_key: Harnex.repo_key(repo_root),
    cli: adapter.key,
    id: id,
    pid: pid,
    host: host,
    port: port,
    command: command,
    started_at: @started_at.iso8601,
    last_injected_at: @last_injected_at&.iso8601,
    injected_count: @injected_count,
    output_log_path: output_log_path,
    events_log_path: events_log_path
  }
  payload.merge!(log_activity_snapshot)
  payload[:description] = description if description

  if watch
    payload[:watch_path] = watch.display_path
    payload[:watch_absolute_path] = watch.absolute_path
    payload[:watch_debounce_seconds] = watch.debounce_seconds
  end

  payload[:input_state] = adapter.input_state(screen_snapshot) if include_input_state
  payload[:agent_state] = @state_machine.to_s
  payload[:inbox] = @inbox.stats
  payload[:last_completed_at] = @last_completed_at&.iso8601
  payload[:model] = summary_model
  payload[:effort] = meta_hash["effort"]
  payload[:auto_disconnects] = @event_counters.snapshot[:disconnections]
  payload
end

#sync_window_sizeObject



354
355
356
357
358
359
360
361
# File 'lib/harnex/runtime/session.rb', line 354

def sync_window_size
  return unless STDIN.tty?
  return unless @writer

  @writer.winsize = STDIN.winsize
rescue StandardError
  nil
end

#task_complete?Boolean

Returns:

  • (Boolean)


233
234
235
# File 'lib/harnex/runtime/session.rb', line 233

def task_complete?
  !!@last_completed_at
end

#validate_binary!Object



363
364
365
# File 'lib/harnex/runtime/session.rb', line 363

def validate_binary!
  self.class.validate_binary!(command)
end