agent-council 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,10 +14,10 @@ module AgentCouncil
14
14
  # whose rescue calls #shutdown: it sends every agent SIGTERM, waits up to
15
15
  # the grace period for the workers to finish, and SIGKILLs agents still
16
16
  # running. The commands an agent's shell tool started run in process
17
- # groups of their own, which these signals don't reach; pi and Claude
18
- # Code stop them on SIGTERM, but an agent that is SIGKILLed can't, so
19
- # they may keep running. A second trapped signal other
20
- # than HUP SIGKILLs them at once. Any HUP after the first signal is
17
+ # groups of their own, which these signals don't reach; pi, Claude
18
+ # Code, and Codex stop them on SIGTERM, but OpenCode doesn't, and an
19
+ # agent that is SIGKILLed can't, so they may keep running. A second
20
+ # trapped signal other than HUP SIGKILLs them at once. Any HUP after the first signal is
21
21
  # ignored: a closing terminal can deliver two at once (one forwarded by the
22
22
  # shell, one from the kernel), which must not skip the graceful stop. A
23
23
  # signal agent-council was started ignoring (e.g. HUP under nohup) stays
@@ -25,9 +25,9 @@ module AgentCouncil
25
25
  # .exit_by_signal).
26
26
  #
27
27
  # Agents run in worker threads, never the main thread, so the main thread
28
- # is always free to take the Interrupt. Workers report completion through
29
- # a queue and only the main thread prints, so nothing more is printed once
30
- # the Interrupt has been taken.
28
+ # is always free to take the Interrupt. Workers report each agent's spawn
29
+ # and their own completion through a queue and only the main thread
30
+ # prints, so nothing more is printed once the Interrupt has been taken.
31
31
  class WorkerPool
32
32
  # Not QUIT on JRuby: the JVM reserves it for thread dumps, so trapping
33
33
  # it only prints a warning.
@@ -53,7 +53,9 @@ module AgentCouncil
53
53
  def initialize(grace:)
54
54
  @grace = grace
55
55
  @threads = []
56
- @finished = Queue.new # indexes of threads as they finish
56
+ # As they happen: [:spawned, tag, pid] when an agent is spawned
57
+ # (see #capture3) and [:finished, index] when a thread finishes.
58
+ @events = Queue.new
57
59
  @uncollected = 0 # threads not yet #collect'ed
58
60
  @children = {} # agent pids (each also its process group id)
59
61
  @children_lock = Mutex.new
@@ -94,20 +96,27 @@ module AgentCouncil
94
96
  Thread.current.report_on_exception = false
95
97
  Thread.handle_interrupt(Interrupt => :immediate, &block)
96
98
  ensure
97
- @finished << index
99
+ @events << [:finished, index]
98
100
  end
99
101
  end
100
102
  end
101
103
 
102
104
  # Waits for the threads started since the last call, yielding each
103
105
  # one's value as it finishes. Returns their values in start order.
104
- # Re-raises if a worker raised.
105
- def collect
106
+ # Re-raises if a worker raised. on_spawn: called with the tag and pid
107
+ # of each agent the threads spawn (see #capture3), as it's spawned.
108
+ def collect(on_spawn: nil)
106
109
  count = @uncollected
107
110
  @uncollected = 0
108
- finished = Array.new(count) do
109
- index = @finished.pop
110
- [index, @threads[index].value.tap { |value| yield value if block_given? }]
111
+ finished = []
112
+ while finished.size < count
113
+ kind, *args = @events.pop
114
+ if kind == :spawned
115
+ on_spawn&.call(*args)
116
+ else
117
+ index = args.first
118
+ finished << [index, @threads[index].value.tap { |value| yield value if block_given? }]
119
+ end
111
120
  end
112
121
  finished.sort_by(&:first).map(&:last)
113
122
  end
@@ -115,8 +124,10 @@ module AgentCouncil
115
124
  # Open3.capture3, but with the agent in its own process group and
116
125
  # tracked for #shutdown while it runs, and its output read as UTF-8
117
126
  # whatever the locale. An agent spawned after shutdown has started
118
- # signalling gets the same signal at once.
119
- def capture3(env, *argv, stdin_data:)
127
+ # signalling gets the same signal at once. tag: identifies the agent
128
+ # to #collect's on_spawn, which gets it with the agent's pid (an
129
+ # untagged agent isn't reported).
130
+ def capture3(env, *argv, stdin_data:, tag: nil)
120
131
  Open3.popen3(env, *argv, **SPAWN_OPTIONS) do |stdin, stdout, stderr, wait_thr|
121
132
  [stdout, stderr].each { |io| io.set_encoding(Encoding::UTF_8) }
122
133
  pid = wait_thr.pid
@@ -128,6 +139,7 @@ module AgentCouncil
128
139
  @stop_signal
129
140
  end
130
141
  signal_child(pid, signal) if signal
142
+ @events << [:spawned, tag, pid] if tag
131
143
  out_reader = Thread.new { stdout.read }
132
144
  err_reader = Thread.new { stderr.read }
133
145
  begin
@@ -198,6 +210,7 @@ module AgentCouncil
198
210
  end
199
211
 
200
212
  # A hung-up terminal can make writing fail; that mustn't stop shutdown.
213
+ # (main's SafeStdout doesn't raise, but a $stdout set otherwise may.)
201
214
  private def flush_stdout
202
215
  $stdout.flush
203
216
  rescue IOError, SystemCallError
data/lib/agent_council.rb CHANGED
@@ -4,9 +4,9 @@
4
4
  # layout, per-agent subprocess execution, and the CLI entry point.
5
5
  # Harness-specific behavior lives under AgentCouncil::Harnesses (e.g.
6
6
  # AgentCouncil::Harnesses::PiHarness), looked up per agent from its config
7
- # entry's 'harness' key with Harnesses.module_for. A harness's
7
+ # entry's 'harness' key with Harnesses.class_for. A harness's
8
8
  # usage(stdout) returns token counts in the shape documented on
9
- # PiHarness.usage, or nil when the harness reports none.
9
+ # Harnesses::Harness.usage, or nil when the harness reports none.
10
10
 
11
11
  require 'json'
12
12
  require 'yaml'
@@ -24,6 +24,9 @@ require_relative 'agent_council/version'
24
24
  require_relative 'agent_council/platform'
25
25
  require_relative 'agent_council/harnesses'
26
26
  require_relative 'agent_council/worker_pool'
27
+ require_relative 'agent_council/progress_printer'
28
+ require_relative 'agent_council/safe_stdout'
29
+ require_relative 'agent_council/plain_line'
27
30
 
28
31
  module AgentCouncil
29
32
  # Runtime data files (prompt templates) ship inside lib/, resolved
@@ -131,22 +134,20 @@ module AgentCouncil
131
134
  end
132
135
 
133
136
  # The variables set for an agent's process: the scratch dir as its
134
- # TMPDIR, which the scaffolding tells agents to use, and as
135
- # CLAUDE_CODE_TMPDIR, the base under which Claude Code's sandbox makes
136
- # the writable TMPDIR it gives commands. Without the latter, a user's
137
- # own CLAUDE_CODE_TMPDIR would put that dir outside the scratch dir,
138
- # shared and never cleaned up. pi ignores it.
139
- module_function def agent_env(scratch_dir)
140
- { 'TMPDIR' => scratch_dir, 'CLAUDE_CODE_TMPDIR' => scratch_dir }
137
+ # TMPDIR, which the scaffolding tells agents to use, and whatever its
138
+ # harness adds (see Harnesses::Harness.env).
139
+ module_function def agent_env(scratch_dir, harness)
140
+ harness.env(scratch_dir).merge('TMPDIR' => scratch_dir)
141
141
  end
142
142
 
143
143
  # Returns [label, ok, detail, usage, warnings]; never raises. detail is
144
144
  # the report's filename on success, the error otherwise. usage is the
145
- # agent's token usage (see Harnesses), or nil; failed agents report it too,
146
- # since their tokens were still spent. warnings: the harness's warnings
147
- # about the agent (see run_warnings), failed or not, since what the harness
148
- # kept the agent from doing may be why it failed; empty if the harness
149
- # never ran. Returned, not printed, since this runs in a worker thread.
145
+ # agent's token usage (see Harnesses::Harness.usage), or nil; failed
146
+ # agents report it too, since their tokens were still spent. warnings:
147
+ # the harness's warnings about the agent (see run_warnings), failed or
148
+ # not, since what the harness kept the agent from doing may be why it
149
+ # failed; empty if the harness never ran. Returned, not printed, since
150
+ # this runs in a worker thread.
150
151
  # index: the agent's 1-based position in the config's agent list, used to
151
152
  # disambiguate repeated provider/model entries in the filename and label;
152
153
  # filename: overrides the output name; meta: becomes YAML front matter,
@@ -157,7 +158,8 @@ module AgentCouncil
157
158
  # and returning it). If the response begins
158
159
  # with an H1 of its own, it is dropped: the header leads the body (and
159
160
  # carries the title, in consolidated reports).
160
- # pool: the WorkerPool to spawn the agent through, so Ctrl-C can stop it;
161
+ # pool: the WorkerPool to spawn the agent through, so Ctrl-C can stop it
162
+ # (and its #collect can report the agent's pid, tagged with its label);
161
163
  # without one it's spawned untracked.
162
164
  module_function def run_agent(agent, prompt, run_dir, file_prefix, index: nil, filename: nil, meta: {},
163
165
  header: nil, pool: nil)
@@ -173,11 +175,16 @@ module AgentCouncil
173
175
  # with errors ignored: a child that is still exiting (e.g. one just
174
176
  # killed after the Ctrl-C grace period) can still be writing here
175
177
  # (node's compile cache, say). That must not surface as an error.
176
- harness = Harnesses.module_for(agent)
178
+ harness = Harnesses.class_for(agent)
177
179
  scratch_dir = Dir.mktmpdir('agent-council-')
178
180
  argv = harness.argv(provider, model)
181
+ env = agent_env(scratch_dir, harness)
179
182
  (stdout, stderr, status), elapsed = timed do
180
- (pool || Open3).capture3(agent_env(scratch_dir), *argv, stdin_data: prompt)
183
+ if pool
184
+ pool.capture3(env, *argv, stdin_data: prompt, tag: label)
185
+ else
186
+ Open3.capture3(env, *argv, stdin_data: prompt)
187
+ end
181
188
  end
182
189
  # Harness output is UTF-8. WorkerPool#capture3 already returns it as such,
183
190
  # but Open3.capture3 (used without a pool) returns the locale's encoding.
@@ -194,7 +201,10 @@ module AgentCouncil
194
201
 
195
202
  unless status.success?
196
203
  detail = failure_reason(harness.exit_detail(stdout, stderr))
197
- return [label, false, "#{harness::NAME} exited #{status.exitstatus}: #{detail}", usage, warnings]
204
+ # A signal is reason enough; "no error output" would add nothing.
205
+ detail = nil if status.signaled? && detail == Harnesses::Harness::NO_ERROR_OUTPUT
206
+ reason = [exit_description(status), detail]
207
+ return [label, false, "#{harness::NAME} #{reason.compact.join(': ')}", usage, warnings]
198
208
  end
199
209
 
200
210
  error = harness.error_message(stdout)
@@ -236,10 +246,11 @@ module AgentCouncil
236
246
  end
237
247
 
238
248
  # The harness's warnings about an agent: what the harness kept it
239
- # from doing (see ClaudeCodeHarness.warnings), which a report may lack,
240
- # or which may be why the agent failed. Advisory only: failing to read them
241
- # must not fail an agent whose report is saved, so that becomes a warning
242
- # too.
249
+ # from doing, or errors it hit without failing (see
250
+ # ClaudeCodeHarness.warnings, CodexHarness.warnings, and
251
+ # OpenCodeHarness.warnings), which a report may lack, or which may be
252
+ # why the agent failed. Advisory only: failing to read them must not
253
+ # fail an agent whose report is saved, so that becomes a warning too.
243
254
  # Each is a plain_line, so wherever it goes (console, report, run.json,
244
255
  # and so anything that prints run.json's values) it can't carry a
245
256
  # terminal escape from a command the model wrote.
@@ -252,38 +263,21 @@ module AgentCouncil
252
263
 
253
264
  # A harness's reason for a failure, as run_agent reports it: a
254
265
  # plain_line, since it can quote the model or the CLI, cut to 300
255
- # characters plus "..." so it doesn't swamp the progress line, the Errors
256
- # list, or the consolidation prompt; 'no error output' if nothing is left.
266
+ # characters plus "..." so it doesn't swamp the finish line, the Errors
267
+ # list, or the consolidation prompt; Harnesses::Harness::NO_ERROR_OUTPUT if
268
+ # nothing is left.
257
269
  module_function def failure_reason(text)
258
270
  reason = plain_line(text)
259
- return 'no error output' if reason.empty?
271
+ return Harnesses::Harness::NO_ERROR_OUTPUT if reason.empty?
260
272
 
261
273
  reason.length > 300 ? "#{reason[0, 300]}..." : reason
262
274
  end
263
275
 
264
- # Lines showing an agent's warnings under its progress line or result table.
276
+ # Lines showing an agent's warnings under its finish line or result table.
265
277
  module_function def warning_lines(warnings)
266
278
  Array(warnings).map { |warning| " Warning: #{plain_line(warning)}" }
267
279
  end
268
280
 
269
- # Text on one line with no control characters: every run of whitespace
270
- # or control characters (newlines, carriage returns, the ESC that starts
271
- # a terminal escape sequence) becomes one space; the rest of an escape
272
- # sequence, such as "[2J", stays as harmless text. Warnings can quote a
273
- # model's refused command, so this keeps one from moving the cursor or
274
- # clearing the screen when printed, or from breaking the line it appears
275
- # on in a report. Text in any encoding is read as UTF-8 (a SystemCallError's
276
- # message can be binary). Invisible format characters (Unicode category Cf, such
277
- # as bidirectional overrides and zero-width spaces) are removed, so text
278
- # can't display reordered or hide characters. Invalid bytes become U+FFFD,
279
- # since this also runs in rescue clauses and must not raise.
280
- module_function def plain_line(text)
281
- # Alternation, not one bracket class: the two overlap, which ruby -w
282
- # warns of.
283
- String.new(text.to_s, encoding: ENCODING).scrub.gsub(/\p{Cf}/, '')
284
- .gsub(/(?:[[:space:]]|[[:cntrl:]])+/, ' ').strip
285
- end
286
-
287
281
  # Creates a new run dir in day_dir and returns its name: base, or base-2,
288
282
  # base-3, ... if that is taken. Dir.mkdir fails if the dir exists, so the
289
283
  # claim is atomic: runs started in the same second (or whose local time
@@ -320,6 +314,10 @@ module AgentCouncil
320
314
 
321
315
  # --- report front matter ---
322
316
 
317
+ # A report's YAML front matter block, with the YAML itself captured, and
318
+ # the blank line after it, if any.
319
+ FRONT_MATTER_REGEX = /\A---\n(.+?)\n---\n\n?/m
320
+
323
321
  module_function def with_front_matter(fields, body)
324
322
  header = YAML.dump(fields.transform_keys(&:to_s)).delete_prefix("---\n").chomp
325
323
  # Documented format: ISO 8601 timestamps, with or without a UTC offset,
@@ -338,7 +336,7 @@ module AgentCouncil
338
336
  # [fields, body] from a report file, or [nil, nil] if it has no YAML
339
337
  # front matter block (or the block cannot be safe-loaded).
340
338
  module_function def parse_front_matter(text)
341
- match = text.match(/\A---\n(.+?)\n---\n\n?/m)
339
+ match = text.match(FRONT_MATTER_REGEX)
342
340
  return [nil, nil] unless match
343
341
 
344
342
  fields =
@@ -358,7 +356,7 @@ module AgentCouncil
358
356
  "#{prompt.chomp}\n\n#{addendum}"
359
357
  end
360
358
 
361
- # An agent's label in progress lines, report sources, and consolidation
359
+ # An agent's label in start and finish lines, report sources, and consolidation
362
360
  # prompts: "#<index> <provider> / <model>", or without the index when
363
361
  # there is none (the consolidator). missing_agents matches reports by it.
364
362
  module_function def agent_label(provider, model, index = nil)
@@ -421,8 +419,7 @@ module AgentCouncil
421
419
  # <model>", for the findings file's legend.
422
420
  module_function def full_label(fields)
423
421
  index = fields['agent_index']
424
- parts = [Harnesses.name_of(fields), fields['provider'], fields['model']].join(' / ')
425
- index ? "##{index} #{parts}" : parts
422
+ index ? "##{index} #{agent_descriptor(fields)}" : agent_descriptor(fields)
426
423
  end
427
424
 
428
425
  # [[findings, meta], nil] if text can be split on its marker line, else
@@ -482,7 +479,7 @@ module AgentCouncil
482
479
  unsplit_name = consolidated_filename(file_prefix, consolidator)
483
480
  findings_name = consolidated_filename(file_prefix, consolidator, 'findings')
484
481
  content = File.read(path, encoding: ENCODING)
485
- front = content[/\A---\n.+?\n---\n\n?/m] || ''
482
+ front = content[FRONT_MATTER_REGEX] || ''
486
483
  body = content.delete_prefix(front)
487
484
  # The header run_agent put before the model's text must still be there,
488
485
  # or it would end up in the findings file.
@@ -508,10 +505,7 @@ module AgentCouncil
508
505
  "provider, model):\n\n#{legend}\n\n#{findings}")
509
506
  end
510
507
  # Replaced atomically, so the whole report survives a failed write.
511
- temp = "#{path}.tmp"
512
- written << File.basename(temp)
513
- File.write(temp, "#{front}#{head}\n#{meta.lstrip}")
514
- File.rename(temp, path)
508
+ atomic_write(path, "#{front}#{head}\n#{meta.lstrip}")
515
509
  [findings_name, filename]
516
510
  rescue => e
517
511
  # A failed split must not fail the consolidation, whose model call is
@@ -668,9 +662,9 @@ module AgentCouncil
668
662
  format('%02d:%02d:%02d', total / 3600, total % 3600 / 60, total % 60)
669
663
  end
670
664
 
671
- # Token usage (see Harnesses) as e.g. "1.2M in (900.0k cached) / 30.5k out,
672
- # $0.85", where "in" counts all input, cached or not. The cost is left out
673
- # when unknown. nil for nil usage.
665
+ # Token usage (see Harnesses::Harness.usage) as e.g. "1.2M in (900.0k
666
+ # cached) / 30.5k out, $0.85", where "in" counts all input, cached or
667
+ # not. The cost is left out when unknown. nil for nil usage.
674
668
  module_function def format_usage(usage)
675
669
  input, cached, output, cost = usage_figures(usage)
676
670
  return nil unless input
@@ -689,7 +683,7 @@ module AgentCouncil
689
683
  end
690
684
 
691
685
  # [input (cached or not), cached input, output, cost (nil when unknown)]
692
- # from a usage hash (see Harnesses), or nil for unknown usage.
686
+ # from a usage hash (see Harnesses::Harness.usage), or nil for unknown usage.
693
687
  module_function def usage_figures(usage)
694
688
  return nil unless usage.is_a?(Hash)
695
689
 
@@ -709,8 +703,8 @@ module AgentCouncil
709
703
  dollars < 0.01 ? '<$0.01' : format('$%.2f', dollars)
710
704
  end
711
705
 
712
- # The sum of usage hashes (see Harnesses), ignoring nils (and anything else
713
- # not a hash); nil if there are none.
706
+ # The sum of usage hashes (see Harnesses::Harness.usage), ignoring nils
707
+ # (and anything else not a hash); nil if there are none.
714
708
  # The cost is summed only if every usage has one, so a partial total
715
709
  # isn't presented as the whole.
716
710
  module_function def sum_usage(usages)
@@ -722,6 +716,14 @@ module AgentCouncil
722
716
  costs.all?(Numeric) ? total.merge('cost' => costs.sum.round(6)) : total
723
717
  end
724
718
 
719
+ # The summed cost of the usages whose cost is known, and how many those
720
+ # are, for when sum_usage leaves the cost out because some are unknown
721
+ # (e.g. a Codex agent's, which Codex doesn't price). [nil, 0] if none is.
722
+ module_function def known_cost(usages)
723
+ costs = usages.grep(Hash).map { |u| u['cost'] }.grep(Numeric)
724
+ [costs.empty? ? nil : costs.sum.round(6), costs.size]
725
+ end
726
+
725
727
  # The run dir's machine-readable record of its analysts and consolidations.
726
728
  RUN_FILENAME = 'run.json'
727
729
 
@@ -743,23 +745,36 @@ module AgentCouncil
743
745
  end
744
746
 
745
747
  # Writes the run dir's run.json: every analyst's and consolidation's
746
- # entry (see run_entry), their total usage, and how many entries it covers
747
- # (those that reported usage). Replaced atomically, so a
748
- # reader or a Ctrl-C never sees it half written. A failure to write it is
749
- # only warned about: the reports are what matter.
748
+ # entry (see run_entry), their total usage, how many entries it covers
749
+ # (those that reported usage), and the summed cost of the entries whose
750
+ # cost is known, with how many they are (see known_cost). Replaced
751
+ # atomically (see atomic_write). A failure to write it is only warned
752
+ # about: the reports are what matter.
750
753
  module_function def write_run_file(run_dir, analysts, consolidations)
751
754
  usages = (analysts + consolidations).map { |entry| entry['usage'] }
755
+ cost, cost_runs = known_cost(usages)
752
756
  data = { 'analysts' => analysts, 'consolidations' => consolidations,
753
- 'total_usage' => sum_usage(usages), 'total_usage_runs' => usages.grep(Hash).size }
757
+ 'total_usage' => sum_usage(usages), 'total_usage_runs' => usages.grep(Hash).size,
758
+ 'known_cost' => cost, 'known_cost_runs' => cost_runs }
754
759
  path = File.join(run_dir, RUN_FILENAME)
755
- temp = "#{path}.#{Process.pid}.tmp"
756
- File.write(temp, "#{JSON.pretty_generate(data)}\n")
757
- File.rename(temp, path)
760
+ atomic_write(path, "#{JSON.pretty_generate(data)}\n")
758
761
  rescue SystemCallError => e
759
- FileUtils.rm_f(temp) if temp
760
762
  warn "Could not write #{relative_path(path)}: #{e.message}"
761
763
  end
762
764
 
765
+ # Writes content to path by way of a temporary file beside it, renamed
766
+ # into place, so a reader or a Ctrl-C never sees it half written and a
767
+ # failed write leaves what was there before. The temporary file is
768
+ # removed if the write or rename fails, and the error raised.
769
+ module_function def atomic_write(path, content)
770
+ temp = "#{path}.#{Process.pid}.tmp"
771
+ File.write(temp, content)
772
+ File.rename(temp, path)
773
+ rescue
774
+ FileUtils.rm_f(temp)
775
+ raise
776
+ end
777
+
763
778
  # [analysts, consolidations] from a run dir's run.json, or nil if it is
764
779
  # missing or malformed.
765
780
  module_function def read_run_file(run_dir)
@@ -806,13 +821,20 @@ module AgentCouncil
806
821
  end
807
822
 
808
823
  # "; <total usage>" for a summary line, noting how many of the agents it
809
- # covers when some reported no usage; "" when none reported any.
824
+ # covers when some reported no usage; "" when none reported any. When
825
+ # only some agents' cost is known, the total leaves the cost out, so the
826
+ # known agents' cost follows, with how many they are.
810
827
  module_function def usage_summary(usages)
811
- total = format_usage(sum_usage(usages))
828
+ sum = sum_usage(usages)
829
+ total = format_usage(sum)
812
830
  return '' unless total
813
831
 
814
832
  reported = usages.grep(Hash).size
815
- "; #{total}#{" (from #{reported} of #{usages.size} agents)" if reported < usages.size}"
833
+ text = "; #{total}#{" (from #{reported} of #{usages.size} agents)" if reported < usages.size}"
834
+ cost, cost_runs = known_cost(usages)
835
+ return text if sum.key?('cost') || cost.nil? || !cost.positive?
836
+
837
+ "#{text}; #{format_cost(cost)} for the #{cost_runs} of #{usages.size} agents with a known cost"
816
838
  end
817
839
 
818
840
  # East Asian wide and fullwidth characters (CJK, Hangul, fullwidth forms,
@@ -833,6 +855,31 @@ module AgentCouncil
833
855
  text.length + text.scan(WIDE_CHAR).size - text.scan(ZERO_WIDTH_CHAR).size
834
856
  end
835
857
 
858
+ # How an agent's process ended, for a failure's reason: "exited N", or
859
+ # "was stopped by SIGNAME" for one a signal stopped (e.g. the user's
860
+ # kill -TERM -PID), which has no exit status.
861
+ module_function def exit_description(status)
862
+ return "exited #{status.exitstatus}" unless status.signaled?
863
+
864
+ name =
865
+ begin
866
+ Signal.signame(status.termsig)
867
+ rescue ArgumentError # JRuby, for a signal with no name; MRI returns nil
868
+ nil
869
+ end
870
+ "was stopped by #{name ? "SIG#{name}" : "signal #{status.termsig}"}"
871
+ end
872
+
873
+ # Prints how to see what the agents are doing while they run.
874
+ module_function def puts_ps_hint
875
+ puts "\nRun this in another terminal to see (sub)process statuses:\nagent-council-ps #{Process.pid}"
876
+ end
877
+
878
+ # Prints the consolidator's pid line as it starts (see ProgressPrinter).
879
+ module_function def puts_spawned(label, pid)
880
+ ProgressPrinter.puts_live([ProgressPrinter.spawned_line(label, pid)])
881
+ end
882
+
836
883
  # Prints the "--- Consolidation complete ---" (or error) marker.
837
884
  module_function def puts_consolidation_status(ok)
838
885
  puts "\n--- Consolidation #{ok ? 'complete' : 'error'} ---"
@@ -950,7 +997,8 @@ module AgentCouncil
950
997
  end
951
998
 
952
999
  # "harness / provider / model" for a validated config entry, printed at
953
- # startup so it is clear which agents are still running later.
1000
+ # startup so it is clear which agents are still running later (or for a
1001
+ # report's front matter, which has the same keys; see full_label).
954
1002
  module_function def agent_descriptor(entry)
955
1003
  "#{Harnesses.name_of(entry)} / #{entry['provider']} / #{entry['model']}"
956
1004
  end
@@ -1047,6 +1095,7 @@ module AgentCouncil
1047
1095
  end
1048
1096
 
1049
1097
  module_function def main(argv)
1098
+ $stdout = SafeStdout.new($stdout) unless $stdout.is_a?(SafeStdout)
1050
1099
  abort_if_native_windows
1051
1100
  options = {}
1052
1101
  parser = option_parser(options)
@@ -1135,12 +1184,7 @@ module AgentCouncil
1135
1184
  end
1136
1185
  analyst_prompt = compose_analyst_prompt(prompt, File.read(ANALYST_FORMAT_PATH, encoding: ENCODING))
1137
1186
 
1138
- config =
1139
- begin
1140
- YAML.safe_load_file(config_path)
1141
- rescue Psych::Exception => e
1142
- abort "Invalid YAML in #{config_path}: #{e.message}"
1143
- end
1187
+ config = load_config(config_path)
1144
1188
  abort "Config file must be a YAML mapping: #{config_path}" unless config.is_a?(Hash)
1145
1189
 
1146
1190
  agents = config['agents']
@@ -1197,16 +1241,14 @@ module AgentCouncil
1197
1241
  # A default config's path is absolute (resolve_config_path makes it
1198
1242
  # so), to show which of the defaults was picked up.
1199
1243
  puts
1200
- puts "Working Dir: #{Dir.pwd}"
1201
- puts(argv[1] ? "Config: #{relative_path(config_path)}" : "Config: [default] #{config_path}")
1202
- puts "Prompt: #{relative_path(prompt_path)}"
1203
- puts "Run Dir: #{relative_path(run_dir)}"
1204
- puts "\nReview Agents (#{agents.size}):"
1244
+ puts_paths(argv[1] ? relative_path(config_path) : "[default] #{config_path}", prompt_path, run_dir)
1245
+ puts "\nConfigured Review Agents (#{agents.size}):"
1205
1246
  agents.each_with_index do |agent, i|
1206
1247
  puts " ##{i + 1} #{agent_descriptor(agent)}"
1207
1248
  end
1208
- puts "\nConsolidator Agent:\n #{agent_descriptor(consolidator)}" if consolidator
1209
- puts "\nReview Progress:"
1249
+ puts "\nConfigured Consolidator Agent:\n #{agent_descriptor(consolidator)}" if consolidator
1250
+ puts_ps_hint
1251
+ puts "\nStarted Agents:"
1210
1252
  pool = WorkerPool.new(grace: INTERRUPT_GRACE_SECONDS)
1211
1253
  pool.trap_signals
1212
1254
  agents.each_with_index do |agent, i|
@@ -1224,11 +1266,18 @@ module AgentCouncil
1224
1266
  end
1225
1267
  end
1226
1268
  # Printed here, in the main thread, as everything is (see WorkerPool).
1227
- results = pool.collect do |label, ok, detail, elapsed, _usage, warnings|
1228
- duration = format_duration(elapsed)
1229
- puts(ok ? " ✓ #{duration} #{label}" : " ✗ #{duration} #{label}\n #{detail}")
1230
- puts warning_lines(warnings)
1231
- end
1269
+ progress = ProgressPrinter.new(agents.size)
1270
+ results =
1271
+ begin
1272
+ pool.collect(on_spawn: progress.method(:started)) do |label, ok, detail, elapsed, _usage, warnings|
1273
+ duration = format_duration(elapsed)
1274
+ line = ok ? " ✓ #{duration} #{label}" : " ✗ #{duration} #{label}\n #{detail}"
1275
+ progress.finished(label, [line, *warning_lines(warnings)])
1276
+ end
1277
+ rescue
1278
+ progress.flush_held # a worker raised; not after Ctrl-C, which prints nothing more
1279
+ raise
1280
+ end
1232
1281
 
1233
1282
  failed = results.count { |_, ok, _| !ok }
1234
1283
  puts "\nReviews (in #{relative_path(reviews_dir)}):"
@@ -1248,19 +1297,10 @@ module AgentCouncil
1248
1297
  label, _, detail, _, _, warnings = result
1249
1298
  [label, failure_with_warnings(detail, warnings), Harnesses.name_of(agent)]
1250
1299
  end
1251
- pool.start do
1252
- timed do
1253
- run_consolidation(consolidator, prompt, run_dir, file_prefix,
1254
- meta: report_meta, prompt_path: prompt_path, failures: failures, analyst_runs: analyst_runs,
1255
- pool: pool)
1256
- end
1257
- end
1258
- (label, ok, detail, usage, meta_name, warnings), elapsed = pool.collect.first
1259
- puts format_result_table([[label, ok, detail, elapsed, usage]])
1260
- puts warning_lines(warnings)
1261
- entry = run_entry(consolidator, ok, detail, elapsed, usage, meta_report: meta_name, warnings: warnings)
1300
+ entry = run_and_show_consolidation(pool, consolidator, prompt, run_dir, file_prefix,
1301
+ meta: report_meta, prompt_path: prompt_path, failures: failures, analyst_runs: analyst_runs)
1262
1302
  write_run_file(run_dir, analyst_runs, [entry])
1263
- puts_consolidation_status(ok)
1303
+ puts_consolidation_status(entry['ok'])
1264
1304
  end
1265
1305
 
1266
1306
  exit(failed.zero? ? 0 : 1)
@@ -1297,12 +1337,7 @@ module AgentCouncil
1297
1337
  abort "Prompt copy not found: #{prompt_path}" unless File.file?(prompt_path)
1298
1338
  abort "Config copy not found: #{config_path}" unless File.file?(config_path)
1299
1339
 
1300
- config =
1301
- begin
1302
- YAML.safe_load_file(config_path)
1303
- rescue Psych::Exception => e
1304
- abort "Invalid YAML in #{config_path}: #{e.message}"
1305
- end
1340
+ config = load_config(config_path)
1306
1341
  consolidator = config['consolidator'] if config.is_a?(Hash)
1307
1342
  abort "No consolidator in #{config_path}; add one to consolidate" unless consolidator
1308
1343
  abort_on_entry_errors({ "'consolidator'" => consolidator }, config_path,
@@ -1337,43 +1372,62 @@ module AgentCouncil
1337
1372
  'run_stamp')
1338
1373
  meta['timestamp'] = iso_timestamp(meta['timestamp']) if meta['timestamp'].is_a?(Time)
1339
1374
 
1340
- puts "Working Dir: #{Dir.pwd}"
1341
- puts "Config: #{relative_path(config_path)}"
1342
- puts "Prompt: #{relative_path(prompt_path)}"
1343
- puts "Run Dir: #{relative_path(run_dir)}"
1344
- puts "\nConsolidator Agent:\n #{agent_descriptor(consolidator)}"
1375
+ puts_paths(relative_path(config_path), prompt_path, run_dir)
1376
+ puts "\nConfigured Consolidator Agent:\n #{agent_descriptor(consolidator)}"
1377
+ puts_ps_hint
1345
1378
  puts "\nConsolidation Report (in #{relative_path(run_dir)}, " \
1346
1379
  "from #{reports.size} review#{'s' unless reports.size == 1}):"
1347
1380
  analysts, consolidations = read_run_file(run_dir)
1348
1381
  failures = missing_agents(config, reports, analysts)
1349
1382
  pool = WorkerPool.new(grace: INTERRUPT_GRACE_SECONDS)
1350
1383
  pool.trap_signals
1351
- pool.start do
1352
- timed do
1353
- run_consolidation(consolidator, prompt, run_dir, file_prefix,
1354
- meta: meta, prompt_path: relative_path(prompt_path), failures: failures,
1355
- analyst_runs: analysts || [], pool: pool)
1356
- end
1357
- end
1358
- (label, ok, detail, usage, meta_name, warnings), elapsed = pool.collect.first
1359
- puts format_result_table([[label, ok, detail, elapsed, usage]])
1360
- puts warning_lines(warnings)
1384
+ entry = run_and_show_consolidation(pool, consolidator, prompt, run_dir, file_prefix,
1385
+ meta: meta, prompt_path: relative_path(prompt_path), failures: failures, analyst_runs: analysts || [])
1361
1386
  # Added to the run's run.json. Without one (deleted, or unreadable),
1362
1387
  # none is written: a total covering only this consolidation would
1363
1388
  # pass for the run's.
1364
1389
  if analysts
1365
- entry = run_entry(consolidator, ok, detail, elapsed, usage, meta_report: meta_name, warnings: warnings)
1366
1390
  write_run_file(run_dir, analysts, consolidations + [entry])
1367
1391
  else
1368
1392
  warn "No readable #{RUN_FILENAME} in #{relative_path(run_dir)}, " \
1369
1393
  "so this consolidation won't be recorded in one"
1370
1394
  end
1371
- puts_consolidation_status(ok)
1372
- exit(ok ? 0 : 1)
1395
+ puts_consolidation_status(entry['ok'])
1396
+ exit(entry['ok'] ? 0 : 1)
1373
1397
  rescue Interrupt
1374
1398
  exit_interrupted(pool)
1375
1399
  end
1376
1400
 
1401
+ # The parsed YAML of config_path, aborting if it isn't valid YAML.
1402
+ module_function def load_config(config_path)
1403
+ YAML.safe_load_file(config_path)
1404
+ rescue Psych::Exception => e
1405
+ abort "Invalid YAML in #{config_path}: #{e.message}"
1406
+ end
1407
+
1408
+ # Prints the paths a run, or --consolidate, works with; config is the
1409
+ # Config line's text.
1410
+ module_function def puts_paths(config, prompt_path, run_dir)
1411
+ puts "Working Dir: #{Dir.pwd}"
1412
+ puts "Config: #{config}"
1413
+ puts "Prompt: #{relative_path(prompt_path)}"
1414
+ puts "Run Dir: #{relative_path(run_dir)}"
1415
+ end
1416
+
1417
+ # Runs consolidator in pool, as the only agent it has running (options
1418
+ # are run_consolidation's), prints its result row and any warnings, and
1419
+ # returns its run.json entry (see run_entry).
1420
+ module_function def run_and_show_consolidation(pool, consolidator, prompt, run_dir, file_prefix, **options)
1421
+ pool.start do
1422
+ timed { run_consolidation(consolidator, prompt, run_dir, file_prefix, pool: pool, **options) }
1423
+ end
1424
+ (label, ok, detail, usage, meta_name, warnings), elapsed =
1425
+ pool.collect(on_spawn: method(:puts_spawned)).first
1426
+ puts format_result_table([[label, ok, detail, elapsed, usage]])
1427
+ puts warning_lines(warnings)
1428
+ run_entry(consolidator, ok, detail, elapsed, usage, meta_report: meta_name, warnings: warnings)
1429
+ end
1430
+
1377
1431
  # True if name is a plain file name: no directory part or null byte, and
1378
1432
  # not empty, "." or "..".
1379
1433
  # Applied to every front matter value that becomes part of a path, so a
@@ -1433,7 +1487,7 @@ module AgentCouncil
1433
1487
  # executable of every harness the config entries use (validated ones, so
1434
1488
  # each harness is known).
1435
1489
  module_function def abort_unless_harnesses_installed(entries)
1436
- names = entries.map { |entry| Harnesses.module_for(entry)::NAME }.uniq
1490
+ names = entries.map { |entry| Harnesses.class_for(entry)::NAME }.uniq
1437
1491
  missing = names.reject { |name| executable_on_path?(name) }
1438
1492
  return if missing.empty?
1439
1493