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 cost_source tool_calls model agent_provider ].freeze
- USAGE_MEASUREMENT_FIELDS =
%i[ input_tokens output_tokens reasoning_tokens cached_tokens total_tokens cost_usd ].freeze
- USAGE_STATUSES =
%w[observed estimated unsupported missing zero].freeze
- CONTEXT_FIELDS =
%i[ status source terminal_tokens window_tokens terminal_percent peak_tokens peak_percent samples missing_samples latest_sample_status ].freeze
- CONTEXT_MEASUREMENT_FIELDS =
%i[ terminal_tokens terminal_percent peak_tokens peak_percent ].freeze
- CONTEXT_SAMPLE_STATUSES =
%w[observed estimated missing].freeze
- ATTEMPT_KINDS =
%w[initial retry fix review superseding].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
- QUEUE_FIELDS =
%w[project_id queue_id entry_id entry_title issue plan phase tier intent].freeze
- AGENT_FIELDS =
%w[cli provider model_requested model_effective reasoning_effort service_tier adapter_transport].freeze
- ORCHESTRATION_FIELDS =
%w[ run_id generation_id role project_id queue_id session_id rotation_reason ].freeze
- RELIABILITY_FIELDS =
%w[ adapter_close real_disconnections stream_interruptions stalls force_resumes compactions recovered ].freeze
- SUCCESSFUL_TURN_STATUSES =
%w[completed success succeeded].freeze
Instance Attribute Summary collapse
-
#adapter ⇒ Object
readonly
Returns the value of attribute adapter.
-
#artifact_report_path ⇒ Object
readonly
Returns the value of attribute artifact_report_path.
-
#child_cwd ⇒ Object
readonly
Returns the value of attribute child_cwd.
-
#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.
-
#require_artifact_report ⇒ Object
readonly
Returns the value of attribute require_artifact_report.
-
#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, artifact_report_path: nil, require_artifact_report: false, inbox_ttl: Inbox::DEFAULT_TTL, auto_stop: false, launch_cwd: nil, child_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
-
#record_attempt_transition(type:, child_attempt_id: nil, trigger: nil) ⇒ Object
Public seam for structured recovery/fallback owners (#42 / plan 30).
- #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, artifact_report_path: nil, require_artifact_report: false, inbox_ttl: Inbox::DEFAULT_TTL, auto_stop: false, launch_cwd: nil, child_cwd: nil) ⇒ Session
Returns a new instance of Session.
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 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
# File 'lib/harnex/runtime/session.rb', line 92 def initialize(adapter:, command:, repo_root:, host:, port: nil, id: DEFAULT_ID, watch: nil, description: nil, meta: nil, summary_out: nil, artifact_report_path: nil, require_artifact_report: false, 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.(launch_cwd.to_s.empty? ? repo_root : launch_cwd) @child_cwd = child_cwd.to_s.empty? ? nil : File.(child_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? @artifact_report_path = artifact_report_path.to_s.strip @artifact_report_path = nil if @artifact_report_path.empty? @artifact_report_path = File.(@artifact_report_path, repo_root) if @artifact_report_path @require_artifact_report = !!require_artifact_report raise ArgumentError, "require_artifact_report requires artifact_report_path" if @require_artifact_report && !@artifact_report_path @artifact_report_start_fingerprint = Harnex::ArtifactReport.fingerprint(@artifact_report_path) if @artifact_report_path @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 = {} @context_summary = {} @rpc_context_telemetry = nil @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 @completion_outcome_class = nil @completion_report_status = nil @completion_diagnostics = [] @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.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def adapter @adapter end |
#artifact_report_path ⇒ Object (readonly)
Returns the value of attribute artifact_report_path.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def artifact_report_path @artifact_report_path end |
#child_cwd ⇒ Object (readonly)
Returns the value of attribute child_cwd.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def child_cwd @child_cwd end |
#command ⇒ Object (readonly)
Returns the value of attribute command.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def command @command end |
#description ⇒ Object (readonly)
Returns the value of attribute description.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def description @description end |
#ended_at ⇒ Object (readonly)
Returns the value of attribute ended_at.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def ended_at @ended_at end |
#events_log_path ⇒ Object (readonly)
Returns the value of attribute events_log_path.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def events_log_path @events_log_path end |
#exit_code ⇒ Object (readonly)
Returns the value of attribute exit_code.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def exit_code @exit_code end |
#host ⇒ Object (readonly)
Returns the value of attribute host.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def host @host end |
#id ⇒ Object (readonly)
Returns the value of attribute id.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def id @id end |
#inbox ⇒ Object (readonly)
Returns the value of attribute inbox.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def inbox @inbox end |
#launch_cwd ⇒ Object (readonly)
Returns the value of attribute launch_cwd.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def launch_cwd @launch_cwd end |
#meta ⇒ Object (readonly)
Returns the value of attribute meta.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def @meta end |
#output_log_path ⇒ Object (readonly)
Returns the value of attribute output_log_path.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def output_log_path @output_log_path end |
#pid ⇒ Object (readonly)
Returns the value of attribute pid.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def pid @pid end |
#port ⇒ Object (readonly)
Returns the value of attribute port.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def port @port end |
#repo_root ⇒ Object (readonly)
Returns the value of attribute repo_root.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def repo_root @repo_root end |
#require_artifact_report ⇒ Object (readonly)
Returns the value of attribute require_artifact_report.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def require_artifact_report @require_artifact_report end |
#session_id ⇒ Object (readonly)
Returns the value of attribute session_id.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def session_id @session_id end |
#started_at ⇒ Object (readonly)
Returns the value of attribute started_at.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def started_at @started_at end |
#summary_out ⇒ Object (readonly)
Returns the value of attribute summary_out.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def summary_out @summary_out end |
#term_signal ⇒ Object (readonly)
Returns the value of attribute term_signal.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def term_signal @term_signal end |
#token ⇒ Object (readonly)
Returns the value of attribute token.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def token @token end |
#watch ⇒ Object (readonly)
Returns the value of attribute watch.
88 89 90 |
# File 'lib/harnex/runtime/session.rb', line 88 def watch @watch end |
Class Method Details
.validate_binary!(command) ⇒ Object
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
# File 'lib/harnex/runtime/session.rb', line 166 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
324 325 326 |
# File 'lib/harnex/runtime/session.rb', line 324 def auth_ok?(header) header == "Bearer #{token}" end |
#git_end ⇒ Object
320 321 322 |
# File 'lib/harnex/runtime/session.rb', line 320 def git_end @git_end || {} end |
#git_start ⇒ Object
316 317 318 |
# File 'lib/harnex/runtime/session.rb', line 316 def git_start @git_start || {} end |
#inject(text, newline: true) ⇒ Object
328 329 330 331 332 |
# File 'lib/harnex/runtime/session.rb', line 328 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
334 335 336 337 338 339 340 341 342 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 |
# File 'lib/harnex/runtime/session.rb', line 334 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
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
# File 'lib/harnex/runtime/session.rb', line 376 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
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 |
# File 'lib/harnex/runtime/session.rb', line 405 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 |
#record_attempt_transition(type:, child_attempt_id: nil, trigger: nil) ⇒ Object
Public seam for structured recovery/fallback owners (#42 / plan 30). The current session remains the parent attempt; a recovery implementation supplies a new child attempt id when it starts an independently billable arm.
302 303 304 305 306 307 308 309 310 311 312 313 314 |
# File 'lib/harnex/runtime/session.rb', line 302 def record_attempt_transition(type:, child_attempt_id: nil, trigger: nil) unless %w[attempt_retry_scheduled attempt_fallback_switched].include?(type.to_s) raise ArgumentError, "unsupported attempt transition #{type.inspect}" end emit_event( type.to_s, **attempt_lifecycle_context.merge( child_attempt_id: summary_string(child_attempt_id), trigger: summary_string(trigger) ) ) end |
#run(validate_binary: true) ⇒ Object
184 185 186 187 188 189 190 191 192 |
# File 'lib/harnex/runtime/session.rb', line 184 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
194 195 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 232 233 234 235 236 237 238 239 240 |
# File 'lib/harnex/runtime/session.rb', line 194 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 enforce_required_artifact_report! normalize_work_acceptance_exit_code! 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
242 243 244 245 246 247 248 249 250 251 252 253 254 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 242 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[:outcome_class] = @completion_outcome_class payload[:artifact_report_status] = @completion_report_status 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
444 445 446 447 448 449 450 451 |
# File 'lib/harnex/runtime/session.rb', line 444 def sync_window_size return unless STDIN.tty? return unless @writer @writer.winsize = STDIN.winsize rescue StandardError nil end |
#task_complete? ⇒ Boolean
291 292 293 |
# File 'lib/harnex/runtime/session.rb', line 291 def task_complete? !!@last_completed_at && !task_failed? end |
#task_failed? ⇒ Boolean
295 296 297 |
# File 'lib/harnex/runtime/session.rb', line 295 def task_failed? !!@last_failed_at end |
#validate_binary! ⇒ Object
453 454 455 |
# File 'lib/harnex/runtime/session.rb', line 453 def validate_binary! self.class.validate_binary!(command) end |