Class: Harnex::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/harnex/commands/run.rb

Constant Summary collapse

DEFAULT_TIMEOUT =
5.0
KNOWN_FLAGS =
%w[
  --id --description --detach --tmux --host --port --watch --context --timeout --inbox-ttl --help
].freeze
VALUE_FLAGS =
%w[
  --id --description --host --port --watch --context --timeout --inbox-ttl
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ Runner

Returns a new instance of Runner.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/harnex/commands/run.rb', line 39

def initialize(argv)
  @argv = argv.dup
  @options = {
    id: nil,
    description: nil,
    host: DEFAULT_HOST,
    port: nil,
    watch: nil,
    context: nil,
    detach: false,
    tmux: false,
    tmux_name: nil,
    timeout: DEFAULT_TIMEOUT,
    inbox_ttl: default_inbox_ttl,
    help: false
  }
end

Class Method Details

.usage(program_name = "harnex run") ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/harnex/commands/run.rb', line 15

def self.usage(program_name = "harnex run")
  <<~TEXT
    Usage: #{program_name} <cli> [options] [--] [cli-args...]

    Options:
      --id ID            Session identifier (default: random two-word ID)
      --description TEXT Short description of what this session is doing
      --detach           Start session in background and return JSON on stdout
      --tmux [NAME]      Run in a tmux window (implies --detach)
      --host HOST        Bind host for the local API (default: #{DEFAULT_HOST})
      --port PORT        Force a specific local API port
      --watch PATH       Auto-send a file-change hook on modification
      --context TEXT     Inject as the initial prompt (prepends session header)
      --timeout SECS     Max seconds to wait for detached registration (default: #{DEFAULT_TIMEOUT})
      --inbox-ttl SECS   Expire queued inbox messages after SECS (default: #{Inbox::DEFAULT_TTL})
      -h, --help         Show this help

    Notes:
      CLIs with smart prompt detection: #{Adapters.known.join(', ')}
      Any other CLI name is launched with generic wrapping.
      Wrapper options may appear before or after <cli>.
  TEXT
end

Instance Method Details

#runObject

Raises:

  • (OptionParser::MissingArgument)


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/harnex/commands/run.rb', line 57

def run
  cli_name, child_args = extract_wrapper_options(@argv)
  if @options[:help]
    puts self.class.usage
    return 0
  end

  raise OptionParser::MissingArgument, "cli" if cli_name.nil?

  repo_root = Harnex.resolve_repo_root(adapter_repo_path(cli_name, child_args))
  @options[:id] ||= Harnex.generate_id(repo_root)
  validate_unique_id!(repo_root)
  effective_child_args = apply_context(child_args)
  adapter = Harnex.build_adapter(cli_name, effective_child_args)
  @options[:detach] = true if @options[:tmux]

  if @options[:detach]
    run_detached(adapter, cli_name, child_args, repo_root)
  else
    run_foreground(adapter, repo_root)
  end
end

#run_detached(adapter, cli_name, child_args, repo_root) ⇒ Object



87
88
89
90
91
92
93
94
95
# File 'lib/harnex/commands/run.rb', line 87

def run_detached(adapter, cli_name, child_args, repo_root)
  Session.validate_binary!(adapter.build_command)

  if @options[:tmux]
    run_in_tmux(cli_name, child_args, repo_root)
  else
    run_headless(adapter, repo_root)
  end
end

#run_foreground(adapter, repo_root) ⇒ Object



80
81
82
83
84
85
# File 'lib/harnex/commands/run.rb', line 80

def run_foreground(adapter, repo_root)
  session = build_session(adapter, repo_root)
  session.validate_binary!
  warn("harnex: session #{session.id} on #{session.host}:#{session.port}")
  session.run(validate_binary: false)
end

#run_headless(adapter, repo_root) ⇒ Object



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
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/harnex/commands/run.rb', line 140

def run_headless(adapter, repo_root)
  log_dir = File.join(Harnex::STATE_DIR, "logs")
  FileUtils.mkdir_p(log_dir)
  log_path = File.join(log_dir, "#{@options[:id]}.log")

  child_pid = fork do
    Process.setsid
    STDIN.reopen("/dev/null")
    log_file = File.open(log_path, "a")
    STDOUT.reopen(log_file)
    STDERR.reopen(log_file)
    STDOUT.sync = true
    STDERR.sync = true

    session = build_session(adapter, repo_root)
    exit_code = session.run(validate_binary: false)
    exit(exit_code || 1)
  end

  Process.detach(child_pid)

  registry = wait_for_registration(repo_root)
  return registration_timeout(@options[:id]) unless registry

  payload = {
    ok: true,
    id: @options[:id],
    cli: adapter.key,
    pid: registry["pid"],
    port: registry["port"],
    mode: "headless",
    log: log_path,
    output_log_path: Harnex.output_log_path(repo_root, @options[:id])
  }
  payload[:description] = @options[:description] if @options[:description]
  puts JSON.generate(payload)
  0
end

#run_in_tmux(cli_name, child_args, repo_root) ⇒ Object



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
# File 'lib/harnex/commands/run.rb', line 97

def run_in_tmux(cli_name, child_args, repo_root)
  harnex_bin = File.expand_path("../../../bin/harnex", __dir__)
  tmux_cmd = [harnex_bin, "run", cli_name]
  tmux_cmd += ["--id", @options[:id]]
  tmux_cmd += ["--description", @options[:description]] if @options[:description]
  tmux_cmd += ["--host", @options[:host]]
  tmux_cmd += ["--port", @options[:port].to_s] if @options[:port]
  tmux_cmd += ["--watch", @options[:watch]] if @options[:watch]
  tmux_cmd += ["--context", @options[:context]] if @options[:context]
  tmux_cmd += ["--inbox-ttl", @options[:inbox_ttl].to_s]
  tmux_cmd += ["--"] + child_args unless child_args.empty?

  window_name = @options[:tmux_name] || @options[:id]
  shell_cmd = tmux_cmd.map { |arg| Shellwords.shellescape(arg) }.join(" ")

  started =
    if ENV["TMUX"]
      system("tmux", "new-window", "-n", window_name, "-d", shell_cmd)
    else
      system("tmux", "new-session", "-d", "-s", "harnex", "-n", window_name, shell_cmd)
    end

  raise "tmux failed to start #{cli_name.inspect}" unless started

  registry = wait_for_registration(repo_root)
  return registration_timeout(@options[:id]) unless registry
  registry = annotate_tmux_registry(registry)

  payload = {
    ok: true,
    id: @options[:id],
    cli: cli_name,
    pid: registry["pid"],
    port: registry["port"],
    mode: "tmux",
    window: window_name,
    output_log_path: Harnex.output_log_path(repo_root, @options[:id])
  }
  payload[:description] = @options[:description] if @options[:description]
  puts JSON.generate(payload)
  0
end