Class: Harnex::Session
- Inherits:
-
Object
- Object
- Harnex::Session
- 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
-
#adapter ⇒ Object
readonly
Returns the value of attribute adapter.
-
#command ⇒ Object
readonly
Returns the value of attribute command.
-
#description ⇒ Object
readonly
Returns the value of attribute description.
-
#ended_at ⇒ Object
readonly
Returns the value of attribute ended_at.
-
#events_log_path ⇒ Object
readonly
Returns the value of attribute events_log_path.
-
#exit_code ⇒ Object
readonly
Returns the value of attribute exit_code.
-
#host ⇒ Object
readonly
Returns the value of attribute host.
-
#id ⇒ Object
readonly
Returns the value of attribute id.
-
#inbox ⇒ Object
readonly
Returns the value of attribute inbox.
-
#launch_cwd ⇒ Object
readonly
Returns the value of attribute launch_cwd.
-
#meta ⇒ Object
readonly
Returns the value of attribute meta.
-
#output_log_path ⇒ Object
readonly
Returns the value of attribute output_log_path.
-
#pid ⇒ Object
readonly
Returns the value of attribute pid.
-
#port ⇒ Object
readonly
Returns the value of attribute port.
-
#repo_root ⇒ Object
readonly
Returns the value of attribute repo_root.
-
#session_id ⇒ Object
readonly
Returns the value of attribute session_id.
-
#started_at ⇒ Object
readonly
Returns the value of attribute started_at.
-
#summary_out ⇒ Object
readonly
Returns the value of attribute summary_out.
-
#term_signal ⇒ Object
readonly
Returns the value of attribute term_signal.
-
#token ⇒ Object
readonly
Returns the value of attribute token.
-
#watch ⇒ Object
readonly
Returns the value of attribute watch.
Class Method Summary collapse
Instance Method Summary collapse
- #auth_ok?(header) ⇒ Boolean
- #git_end ⇒ Object
- #git_start ⇒ Object
-
#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
constructor
A new instance of Session.
- #inject(text, newline: true) ⇒ Object
- #inject_stop(turn_id: nil, interrupt: true) ⇒ Object
- #inject_via_adapter(text:, submit:, enter_only:, force: false) ⇒ Object
- #inject_via_structured(text:, submit:, enter_only:, force: false) ⇒ Object
- #run(validate_binary: true) ⇒ Object
- #run_pty ⇒ Object
- #status_payload(include_input_state: true) ⇒ Object
- #sync_window_size ⇒ Object
- #task_complete? ⇒ Boolean
- #task_failed? ⇒ Boolean
- #validate_binary! ⇒ Object
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.
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 |
# 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) @adapter = adapter @command = command @repo_root = repo_root @launch_cwd = File.(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 = @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
#adapter ⇒ Object (readonly)
Returns the value of attribute adapter.
61 62 63 |
# File 'lib/harnex/runtime/session.rb', line 61 def adapter @adapter end |
#command ⇒ Object (readonly)
Returns the value of attribute command.
61 62 63 |
# File 'lib/harnex/runtime/session.rb', line 61 def command @command end |
#description ⇒ Object (readonly)
Returns the value of attribute description.
61 62 63 |
# File 'lib/harnex/runtime/session.rb', line 61 def description @description end |
#ended_at ⇒ Object (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_path ⇒ Object (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_code ⇒ Object (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 |
#host ⇒ Object (readonly)
Returns the value of attribute host.
61 62 63 |
# File 'lib/harnex/runtime/session.rb', line 61 def host @host end |
#id ⇒ Object (readonly)
Returns the value of attribute id.
61 62 63 |
# File 'lib/harnex/runtime/session.rb', line 61 def id @id end |
#inbox ⇒ Object (readonly)
Returns the value of attribute inbox.
61 62 63 |
# File 'lib/harnex/runtime/session.rb', line 61 def inbox @inbox end |
#launch_cwd ⇒ Object (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 |
#meta ⇒ Object (readonly)
Returns the value of attribute meta.
61 62 63 |
# File 'lib/harnex/runtime/session.rb', line 61 def @meta end |
#output_log_path ⇒ Object (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 |
#pid ⇒ Object (readonly)
Returns the value of attribute pid.
61 62 63 |
# File 'lib/harnex/runtime/session.rb', line 61 def pid @pid end |
#port ⇒ Object (readonly)
Returns the value of attribute port.
61 62 63 |
# File 'lib/harnex/runtime/session.rb', line 61 def port @port end |
#repo_root ⇒ Object (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_id ⇒ Object (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_at ⇒ Object (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_out ⇒ Object (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_signal ⇒ Object (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 |
#token ⇒ Object (readonly)
Returns the value of attribute token.
61 62 63 |
# File 'lib/harnex/runtime/session.rb', line 61 def token @token end |
#watch ⇒ Object (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
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
# File 'lib/harnex/runtime/session.rb', line 127 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
262 263 264 |
# File 'lib/harnex/runtime/session.rb', line 262 def auth_ok?(header) header == "Bearer #{token}" end |
#git_end ⇒ Object
258 259 260 |
# File 'lib/harnex/runtime/session.rb', line 258 def git_end @git_end || {} end |
#git_start ⇒ Object
254 255 256 |
# File 'lib/harnex/runtime/session.rb', line 254 def git_start @git_start || {} end |
#inject(text, newline: true) ⇒ Object
266 267 268 269 270 |
# File 'lib/harnex/runtime/session.rb', line 266 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
272 273 274 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 |
# File 'lib/harnex/runtime/session.rb', line 272 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
314 315 316 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 |
# File 'lib/harnex/runtime/session.rb', line 314 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
343 344 345 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 |
# File 'lib/harnex/runtime/session.rb', line 343 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] = ["model"] if ["model"] && !dispatch.key?(:model) dispatch[:effort] = ["effort"] if ["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.) 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
145 146 147 148 149 150 151 152 153 |
# File 'lib/harnex/runtime/session.rb', line 145 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_pty ⇒ Object
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 195 196 197 |
# File 'lib/harnex/runtime/session.rb', line 155 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
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 232 233 234 235 236 237 238 239 240 241 242 243 244 |
# File 'lib/harnex/runtime/session.rb', line 199 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] = ["effort"] payload[:auto_disconnects] = @event_counters.snapshot[:disconnections] payload end |
#sync_window_size ⇒ Object
382 383 384 385 386 387 388 389 |
# File 'lib/harnex/runtime/session.rb', line 382 def sync_window_size return unless STDIN.tty? return unless @writer @writer.winsize = STDIN.winsize rescue StandardError nil end |
#task_complete? ⇒ Boolean
246 247 248 |
# File 'lib/harnex/runtime/session.rb', line 246 def task_complete? !!@last_completed_at && !task_failed? end |
#task_failed? ⇒ Boolean
250 251 252 |
# File 'lib/harnex/runtime/session.rb', line 250 def task_failed? !!@last_failed_at end |
#validate_binary! ⇒ Object
391 392 393 |
# File 'lib/harnex/runtime/session.rb', line 391 def validate_binary! self.class.validate_binary!(command) end |