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
USAGE_FIELDS =
%i[
  input_tokens output_tokens reasoning_tokens cached_tokens total_tokens agent_session_id
].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) ⇒ Session

Returns a new instance of Session.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/harnex/runtime/session.rb', line 42

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)
  @adapter = adapter
  @command = command
  @repo_root = repo_root
  @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
  @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_completed_at = nil
  @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)
end

Instance Attribute Details

#adapterObject (readonly)

Returns the value of attribute adapter.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def adapter
  @adapter
end

#commandObject (readonly)

Returns the value of attribute command.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def command
  @command
end

#descriptionObject (readonly)

Returns the value of attribute description.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def description
  @description
end

#events_log_pathObject (readonly)

Returns the value of attribute events_log_path.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def events_log_path
  @events_log_path
end

#hostObject (readonly)

Returns the value of attribute host.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def host
  @host
end

#idObject (readonly)

Returns the value of attribute id.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def id
  @id
end

#inboxObject (readonly)

Returns the value of attribute inbox.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def inbox
  @inbox
end

#metaObject (readonly)

Returns the value of attribute meta.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def meta
  @meta
end

#output_log_pathObject (readonly)

Returns the value of attribute output_log_path.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def output_log_path
  @output_log_path
end

#pidObject (readonly)

Returns the value of attribute pid.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def pid
  @pid
end

#portObject (readonly)

Returns the value of attribute port.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def port
  @port
end

#repo_rootObject (readonly)

Returns the value of attribute repo_root.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def repo_root
  @repo_root
end

#session_idObject (readonly)

Returns the value of attribute session_id.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def session_id
  @session_id
end

#summary_outObject (readonly)

Returns the value of attribute summary_out.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def summary_out
  @summary_out
end

#tokenObject (readonly)

Returns the value of attribute token.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def token
  @token
end

#watchObject (readonly)

Returns the value of attribute watch.



40
41
42
# File 'lib/harnex/runtime/session.rb', line 40

def watch
  @watch
end

Class Method Details

.validate_binary!(command) ⇒ Object

Raises:



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/harnex/runtime/session.rb', line 87

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)


197
198
199
# File 'lib/harnex/runtime/session.rb', line 197

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

#inject(text, newline: true) ⇒ Object



201
202
203
204
205
# File 'lib/harnex/runtime/session.rb', line 201

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

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

#inject_stopObject



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/harnex/runtime/session.rb', line 207

def inject_stop
  if adapter.transport == :stdio_jsonrpc
    @inject_mutex.synchronize do
      begin
        adapter.interrupt
      rescue StandardError
        nil
      end
      @state_machine.force_busy!
    end
    return { ok: true, signal: "interrupt_sent" }
  end

  raise "session is not running" unless pid && Harnex.alive_pid?(pid)

  @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



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/harnex/runtime/session.rb', line 230

def inject_via_adapter(text:, submit:, enter_only:, force: false)
  if adapter.transport == :stdio_jsonrpc
    return inject_via_jsonrpc(text: text, 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_jsonrpc(text:, force: false) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/harnex/runtime/session.rb', line 259

def inject_via_jsonrpc(text:, force: false)
  turn_id = nil
  @inject_mutex.synchronize do
    turn_id = adapter.dispatch(prompt: text)
    @state_machine.force_busy!
    @injected_count += 1
    @last_injected_at = Time.now
    persist_registry
  end

  emit_send_event(text, force: force)
  {
    ok: true,
    cli: adapter.key,
    bytes_written: text.to_s.bytesize,
    injected_count: @injected_count,
    newline: false,
    input_state: adapter.input_state(nil),
    force: force,
    turn_id: turn_id
  }
end

#run(validate_binary: true) ⇒ Object



105
106
107
108
109
110
111
112
113
# File 'lib/harnex/runtime/session.rb', line 105

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

  return run_jsonrpc if adapter.transport == :stdio_jsonrpc

  run_pty
end

#run_ptyObject



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

def run_pty
  @reader, @writer, @pid = PTY.spawn(child_env, *command)
  @writer.sync = true
  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

  output_thread.join(1)
  emit_session_end_telemetry
  @exit_reason = classify_exit
  summary_record = build_summary_record
  append_summary_record(summary_record)
  emit_summary_event
  emit_exit_event
  input_thread&.kill
  watch_thread&.kill
  @exit_code
ensure
  @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



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

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] = meta_hash["model"]
  payload[:effort] = meta_hash["effort"]
  payload[:auto_disconnects] = @event_counters.snapshot[:disconnections]
  payload
end

#sync_window_sizeObject



282
283
284
285
286
287
288
289
# File 'lib/harnex/runtime/session.rb', line 282

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

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

#validate_binary!Object



291
292
293
# File 'lib/harnex/runtime/session.rb', line 291

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