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
SUCCESSFUL_TURN_STATUSES =
%w[completed success succeeded].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, child_cwd: nil) ⇒ Session

Returns a new instance of Session.



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
123
124
125
126
# File 'lib/harnex/runtime/session.rb', line 65

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, child_cwd: nil)
  @adapter = adapter
  @command = command
  @repo_root = repo_root
  @launch_cwd = File.expand_path(launch_cwd.to_s.empty? ? repo_root : launch_cwd)
  @child_cwd = child_cwd.to_s.empty? ? nil : File.expand_path(child_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
  @last_failed_at = nil
  @last_failed_status = 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.



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

def adapter
  @adapter
end

#child_cwdObject (readonly)

Returns the value of attribute child_cwd.



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

def child_cwd
  @child_cwd
end

#commandObject (readonly)

Returns the value of attribute command.



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

def command
  @command
end

#descriptionObject (readonly)

Returns the value of attribute description.



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

def description
  @description
end

#ended_atObject (readonly)

Returns the value of attribute ended_at.



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

def ended_at
  @ended_at
end

#events_log_pathObject (readonly)

Returns the value of attribute events_log_path.



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

def events_log_path
  @events_log_path
end

#exit_codeObject (readonly)

Returns the value of attribute exit_code.



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

def exit_code
  @exit_code
end

#hostObject (readonly)

Returns the value of attribute host.



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

def host
  @host
end

#idObject (readonly)

Returns the value of attribute id.



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

def id
  @id
end

#inboxObject (readonly)

Returns the value of attribute inbox.



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

def inbox
  @inbox
end

#launch_cwdObject (readonly)

Returns the value of attribute launch_cwd.



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

def launch_cwd
  @launch_cwd
end

#metaObject (readonly)

Returns the value of attribute meta.



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

def meta
  @meta
end

#output_log_pathObject (readonly)

Returns the value of attribute output_log_path.



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

def output_log_path
  @output_log_path
end

#pidObject (readonly)

Returns the value of attribute pid.



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

def pid
  @pid
end

#portObject (readonly)

Returns the value of attribute port.



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

def port
  @port
end

#repo_rootObject (readonly)

Returns the value of attribute repo_root.



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

def repo_root
  @repo_root
end

#session_idObject (readonly)

Returns the value of attribute session_id.



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

def session_id
  @session_id
end

#started_atObject (readonly)

Returns the value of attribute started_at.



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

def started_at
  @started_at
end

#summary_outObject (readonly)

Returns the value of attribute summary_out.



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

def summary_out
  @summary_out
end

#term_signalObject (readonly)

Returns the value of attribute term_signal.



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

def term_signal
  @term_signal
end

#tokenObject (readonly)

Returns the value of attribute token.



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

def token
  @token
end

#watchObject (readonly)

Returns the value of attribute watch.



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

def watch
  @watch
end

Class Method Details

.validate_binary!(command) ⇒ Object

Raises:



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/harnex/runtime/session.rb', line 128

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)


265
266
267
# File 'lib/harnex/runtime/session.rb', line 265

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

#git_endObject



261
262
263
# File 'lib/harnex/runtime/session.rb', line 261

def git_end
  @git_end || {}
end

#git_startObject



257
258
259
# File 'lib/harnex/runtime/session.rb', line 257

def git_start
  @git_start || {}
end

#inject(text, newline: true) ⇒ Object



269
270
271
272
273
# File 'lib/harnex/runtime/session.rb', line 269

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, interrupt: true) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
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
# File 'lib/harnex/runtime/session.rb', line 275

def inject_stop(turn_id: nil, interrupt: true)
  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
    if interrupt
      @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

    @state_machine.force_busy!
    signal_rpc_done! unless @pid
    return { ok: true, signal: "terminate_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



317
318
319
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
# File 'lib/harnex/runtime/session.rb', line 317

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



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/harnex/runtime/session.rb', line 346

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
    begin
      turn_id = adapter.dispatch(**dispatch)
    rescue StandardError => e
      mark_task_failed(status: "dispatch_error", error: e.message)
      raise
    end
    @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



146
147
148
149
150
151
152
153
154
# File 'lib/harnex/runtime/session.rb', line 146

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



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
195
196
197
198
199
200
# File 'lib/harnex/runtime/session.rb', line 156

def run_pty
  spawn_args = [child_env, *command]
  spawn_args << { chdir: child_cwd } if child_cwd
  @reader, @writer, @pid = PTY.spawn(*spawn_args)
  @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



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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/harnex/runtime/session.rb', line 202

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
  task_complete = task_complete?
  task_failed = task_failed?
  work_state = task_failed ? "failed" : Harnex.work_state_for("running", task_complete: task_complete)
  payload[:agent_state] = @state_machine.to_s
  payload[:process_state] = "running"
  payload[:inbox] = @inbox.stats
  payload[:last_completed_at] = @last_completed_at&.iso8601
  payload[:last_failed_at] = @last_failed_at&.iso8601
  payload[:task_complete] = task_complete
  payload[:task_failed] = task_failed
  payload[:done] = Harnex.work_done_for("running", task_complete: task_complete)
  payload[:work_state] = work_state
  payload[:last_error] = @last_error
  payload[:model] = summary_model
  payload[:effort] = meta_hash["effort"]
  payload[:auto_disconnects] = @event_counters.snapshot[:disconnections]
  payload
end

#sync_window_sizeObject



385
386
387
388
389
390
391
392
# File 'lib/harnex/runtime/session.rb', line 385

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

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

#task_complete?Boolean

Returns:

  • (Boolean)


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

def task_complete?
  !!@last_completed_at && !task_failed?
end

#task_failed?Boolean

Returns:

  • (Boolean)


253
254
255
# File 'lib/harnex/runtime/session.rb', line 253

def task_failed?
  !!@last_failed_at
end

#validate_binary!Object



394
395
396
# File 'lib/harnex/runtime/session.rb', line 394

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