agent-council 0.3.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.
@@ -5,15 +5,18 @@
5
5
  # its tool allowlist and the shared read-only scaffolding, and how to read
6
6
  # pi's JSONL event stream afterward.
7
7
  #
8
- # AgentCouncil is harness-agnostic and finds this module through
8
+ # AgentCouncil is harness-agnostic and finds this class through
9
9
  # AgentCouncil::Harnesses (lib/agent_council/harnesses.rb), by its NAME.
10
10
 
11
- require 'json'
12
- require_relative 'scaffold'
11
+ require_relative 'harness'
13
12
 
14
13
  module AgentCouncil
15
14
  module Harnesses
16
- module PiHarness
15
+ # env, exit_detail, and warnings are Harness's defaults: pi needs no
16
+ # variables beyond TMPDIR, explains a nonzero exit on stderr, and gives
17
+ # no warnings, since a failed tool call, MCP calls included, is an
18
+ # ordinary tool error the agent sees, not a refusal (DESIGN.md §11).
19
+ class PiHarness < Harness
17
20
  NAME = 'pi'
18
21
 
19
22
  # Analysis toolset (pi's built-in tool names): edit/write (and the
@@ -34,7 +37,7 @@ module AgentCouncil
34
37
  # Invocation for one agent. The substantive prompt is not part of argv;
35
38
  # it is piped to stdin (byte-identical for every analyst; the
36
39
  # consolidator gets its own).
37
- module_function def argv(provider, model)
40
+ def self.argv(provider, model)
38
41
  [
39
42
  NAME,
40
43
  '-p', # non-interactive: process prompt and exit
@@ -49,56 +52,43 @@ module AgentCouncil
49
52
 
50
53
  # --- event stream reading ---
51
54
 
52
- # The assistant message from a single pi JSONL line, or nil if the line
53
- # is not an assistant message_end event.
54
- module_function def assistant_message_from_line(line)
55
- message_from_line(line, %w[assistant])
56
- end
57
-
58
- # The message with one of the given roles from a single pi JSONL line,
59
- # or nil if the line is not a message_end event for one.
60
- module_function def message_from_line(line, roles)
61
- event =
62
- begin
63
- JSON.parse(line)
64
- rescue JSON::ParserError
65
- nil
66
- end
67
-
68
- return nil unless event.is_a?(Hash)
69
- return nil unless event['type'] == 'message_end'
70
-
71
- message = event['message']
72
- return nil unless message.is_a?(Hash) && roles.include?(message['role'])
73
-
74
- message
55
+ # The messages of a pi JSONL stream's message_end events with one of
56
+ # the given roles, in order.
57
+ def self.messages_with_role(jsonl, *roles)
58
+ events(jsonl).filter_map do |event|
59
+ message = event['message'] if event['type'] == 'message_end'
60
+ message if message.is_a?(Hash) && roles.include?(message['role'])
61
+ end
75
62
  end
63
+ private_class_method :messages_with_role
76
64
 
77
65
  # Assistant messages from all message_end events in a pi JSONL stream,
78
- # in order. Unparseable lines are skipped.
79
- module_function def assistant_messages(jsonl)
80
- jsonl.each_line.filter_map { |line| assistant_message_from_line(line) }
66
+ # in order.
67
+ def self.assistant_messages(jsonl)
68
+ messages_with_role(jsonl, 'assistant')
81
69
  end
82
70
 
83
- module_function def response_text(message)
71
+ def self.response_text(message)
84
72
  Array(message['content'])
85
73
  .select { |block| block['type'] == 'text' }
86
74
  .map { |block| block['text'] }
87
75
  .join("\n")
88
76
  end
77
+ private_class_method :response_text
89
78
 
90
79
  # The final assistant response: per pi's docs, message_end holds the
91
80
  # authoritative final message of each turn; the last assistant message_end
92
81
  # with actual text is the report (earlier ones belong to tool-use turns).
93
- module_function def final_response(jsonl)
82
+ def self.final_response(jsonl)
94
83
  message = saved_message(assistant_messages(jsonl))
95
84
  message && response_text(message)
96
85
  end
97
86
 
98
87
  # The message final_response saves: the last one with text.
99
- module_function def saved_message(messages)
88
+ def self.saved_message(messages)
100
89
  messages.reverse_each.detect { |m| !response_text(m).empty? }
101
90
  end
91
+ private_class_method :saved_message
102
92
 
103
93
  # Our usage keys, each mapped to pi's name for it. pi normalizes usage
104
94
  # across providers; its input excludes cache reads and writes.
@@ -111,18 +101,10 @@ module AgentCouncil
111
101
  # dollars when pi priced the usage. A tool result has usage when the
112
102
  # tool called a model itself, e.g. a codemode script's models.classify
113
103
  # call. nil when the stream reports no usage, as some providers don't.
114
- module_function def usage(jsonl)
115
- messages = jsonl.each_line.filter_map { |line| message_from_line(line, %w[assistant toolResult]) }
116
- usages = messages.map { |m| m['usage'] }.grep(Hash)
104
+ def self.usage(jsonl)
105
+ usages = messages_with_role(jsonl, 'assistant', 'toolResult').map { |m| m['usage'] }.grep(Hash)
117
106
  totals = USAGE_KEYS.transform_values { |key| usages.sum { |u| count(u[key]) } }
118
- return nil if totals.values.all?(&:zero?)
119
-
120
- cost = usages.sum { |u| u['cost'].is_a?(Hash) ? count(u['cost']['total']) : 0 }
121
- cost.positive? ? totals.merge('cost' => cost.round(6)) : totals
122
- end
123
-
124
- module_function def count(value)
125
- value.is_a?(Numeric) && value.positive? ? value : 0
107
+ usage_result(totals, usages.sum { |u| u['cost'].is_a?(Hash) ? count(u['cost']['total']) : 0 })
126
108
  end
127
109
 
128
110
  # Stop reasons meaning a message was cut off, cancelled, or failed, not
@@ -139,27 +121,15 @@ module AgentCouncil
139
121
  # message must not be saved just because a text-less message followed it).
140
122
  # A non-blank string errorMessage on either wins over a cut-off stopReason on
141
123
  # the other, since it says more about what went wrong.
142
- module_function def error_message(jsonl)
124
+ def self.error_message(jsonl)
143
125
  messages = assistant_messages(jsonl)
144
126
  candidates = [messages.last, saved_message(messages)].compact.uniq
145
- message = candidates.detect { |m| m['errorMessage'].is_a?(String) && !m['errorMessage'].strip.empty? }
127
+ message = candidates.detect { |m| nonblank_text(m['errorMessage']) }
146
128
  return message['errorMessage'] if message
147
129
 
148
130
  message = candidates.detect { |m| UNUSABLE_STOP_REASONS.include?(m['stopReason']) }
149
131
  message && "stopped early (stopReason: #{message['stopReason']})"
150
132
  end
151
-
152
- # Why an agent that exited nonzero failed: pi explains it on stderr.
153
- module_function def exit_detail(_stdout, stderr)
154
- stderr.lines.map(&:strip).reject(&:empty?).first || 'no error output'
155
- end
156
-
157
- # Warnings about an agent that succeeded: none. A failed tool call,
158
- # MCP calls included, is an ordinary tool error the agent sees, not a
159
- # refusal (DESIGN.md §11).
160
- module_function def warnings(_jsonl)
161
- []
162
- end
163
133
  end
164
134
  end
165
135
  end
@@ -1,9 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  # AgentCouncil::Harnesses.scaffold_text — the read-only scaffolding every
4
- # harness appends to its agents' system prompt. In its own file so each
5
- # harness module can require it without the harness registry
6
- # (lib/agent_council/harnesses.rb), which requires the harness modules.
4
+ # harness appends to its agents' system prompt. Required by Harness
5
+ # (harnesses/harness.rb), so each harness has it without the harness
6
+ # registry (lib/agent_council/harnesses.rb), which requires the harnesses.
7
7
 
8
8
  module AgentCouncil
9
9
  module Harnesses
@@ -1,38 +1,23 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  # AgentCouncil::Harnesses — the harnesses agents can run under, by the name
4
- # a config entry gives in its 'harness' key. What they share, the read-only
4
+ # a config entry gives in its 'harness' key. Each is a subclass of
5
+ # Harness (harnesses/harness.rb), which documents what AgentCouncil calls
6
+ # on one and gives defaults; AgentCouncil looks one up per agent with
7
+ # class_for. What every harness's agents are told, the read-only
5
8
  # scaffolding, is in harnesses/scaffold.rb.
6
- #
7
- # Each harness is a plain module shaped like PiHarness (NAME, argv, usage,
8
- # error_message, exit_detail, warnings, final_response,
9
- # assistant_messages), not an adapter framework; AgentCouncil looks one up
10
- # per agent with module_for. NAME is both the config value and the
11
- # executable argv runs, which the startup check looks for on PATH. The
12
- # scaffolding sends agents to $TMPDIR, which run_agent sets to the
13
- # scratch dir, so a harness must pass TMPDIR through to its tools. It also
14
- # goes into report filenames unsanitized, so it must be one
15
- # AgentCouncil.sanitize leaves unchanged (the specs check this).
16
- #
17
- # exit_detail (stdout, stderr) says why an agent that exited nonzero failed;
18
- # the caller puts it, and error_message's reason, on one line cut to 300
19
- # characters (AgentCouncil.failure_reason), so a harness returns the
20
- # reason whole. warnings returns an Array of messages (empty for none)
21
- # about an agent, failed or not; the caller prints and records them all, so a
22
- # harness keeps them few and short.
23
- #
24
- # usage returns the agent's token usage as AgentCouncil records it, summed
25
- # over all its requests: integer 'input' (excluding cached input), 'output',
26
- # 'cache_read', and 'cache_write', plus 'cost' in US dollars when the
27
- # harness priced the usage; or nil when the harness reports no usage.
28
9
 
10
+ require_relative 'harnesses/harness'
29
11
  require_relative 'harnesses/pi_harness'
30
12
  require_relative 'harnesses/claude_code_harness'
31
13
  require_relative 'harnesses/codex_harness'
14
+ require_relative 'harnesses/opencode_harness'
32
15
 
33
16
  module AgentCouncil
34
17
  module Harnesses
35
- BY_NAME = [PiHarness, ClaudeCodeHarness, CodexHarness].to_h { |harness| [harness::NAME, harness] }.freeze
18
+ BY_NAME = [PiHarness, ClaudeCodeHarness, CodexHarness, OpenCodeHarness].to_h do |harness|
19
+ [harness::NAME, harness]
20
+ end.freeze
36
21
 
37
22
  # The harness of a report or run.json entry without a 'harness' key:
38
23
  # agent-council writes one in each, so these are hand-edited or older
@@ -50,9 +35,9 @@ module AgentCouncil
50
35
  harness.is_a?(String) ? harness : DEFAULT_NAME
51
36
  end
52
37
 
53
- # The harness module for an entry; KeyError for an unknown name, which
38
+ # The harness class for an entry; KeyError for an unknown name, which
54
39
  # config validation rules out before any agent runs.
55
- module_function def module_for(entry)
40
+ module_function def class_for(entry)
56
41
  BY_NAME.fetch(name_of(entry))
57
42
  end
58
43
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'json'
4
4
  require 'open3'
5
+ require_relative 'platform'
5
6
 
6
7
  module AgentCouncil
7
8
  # Reads and formats the models available to pi.
@@ -181,5 +182,44 @@ module AgentCouncil
181
182
  module_function def format_as_ids(models)
182
183
  models.map { |model| "#{model.provider}/#{model.id}\n" }.join
183
184
  end
185
+
186
+ # The pi-models command (exe/pi-models). Prints its help, or the models in
187
+ # the format asked for, and exits 0; exits 1 on an unknown option, on a
188
+ # failure talking to pi, or on native Windows.
189
+ module_function def main(argv)
190
+ AgentCouncil.abort_if_native_windows('pi-models')
191
+ argv = argv.dup
192
+ help_output = argv.delete('-h') || argv.delete('--help')
193
+ json_output = argv.delete('--json') || argv.delete('-j')
194
+ ids_output = argv.delete('--ids') || argv.delete('-i')
195
+ argv.delete('--table') || argv.delete('-t') # table is the default format; accepted for explicitness
196
+
197
+ if help_output
198
+ puts help_text
199
+ exit
200
+ end
201
+
202
+ unless argv.empty?
203
+ warn "pi-models: unknown option(s): #{argv.join(' ')}"
204
+ warn "Try 'pi-models --help' for usage."
205
+ exit 1
206
+ end
207
+
208
+ begin
209
+ models = fetch_models
210
+ rescue Error => e
211
+ warn "pi-models: #{e.message}"
212
+ exit 1
213
+ end
214
+
215
+ if json_output
216
+ puts format_as_json(models)
217
+ elsif ids_output
218
+ print format_as_ids(models)
219
+ else
220
+ puts format_as_table(models)
221
+ end
222
+ exit
223
+ end
184
224
  end
185
225
  end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ # AgentCouncil.plain_line, in a file of its own so agent-council-ps, which
4
+ # doesn't load lib/agent_council.rb, can use it too.
5
+
6
+ module AgentCouncil
7
+ # Text on one line with no control characters: every run of whitespace
8
+ # or control characters (newlines, carriage returns, the ESC that starts
9
+ # a terminal escape sequence) becomes one space; the rest of an escape
10
+ # sequence, such as "[2J", stays as harmless text. Warnings can quote a
11
+ # model's refused command, so this keeps one from moving the cursor or
12
+ # clearing the screen when printed, or from breaking the line it appears
13
+ # on in a report. Text in any encoding is read as UTF-8 (a SystemCallError's
14
+ # message can be binary). Invisible format characters (Unicode category Cf, such
15
+ # as bidirectional overrides and zero-width spaces) are removed, so text
16
+ # can't display reordered or hide characters. Invalid bytes become U+FFFD,
17
+ # since this also runs in rescue clauses and must not raise.
18
+ module_function def plain_line(text)
19
+ # Alternation, not one bracket class: the two overlap, which ruby -w
20
+ # warns of.
21
+ String.new(text.to_s, encoding: Encoding::UTF_8).scrub.gsub(/\p{Cf}/, '')
22
+ .gsub(/(?:[[:space:]]|[[:cntrl:]])+/, ' ').strip
23
+ end
24
+ end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Kept free of other project requires so both executables can load it:
4
- # pi-models doesn't load lib/agent_council.rb.
3
+ # Kept free of other project requires so that pi_models.rb and ps.rb can
4
+ # load it without lib/agent_council.rb, which they don't need.
5
5
 
6
6
  require 'rbconfig'
7
7
 
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ # AgentCouncil::ProgressPrinter — prints a run's Started Agents and
4
+ # Finished Agents sections as WorkerPool#collect reports its analysts'
5
+ # spawns and finishes.
6
+
7
+ module AgentCouncil
8
+ class ProgressPrinter
9
+ # The line printed as an agent starts, giving its pid, which is also its
10
+ # process group's id (see WorkerPool), so a running agent can be found
11
+ # or stopped (e.g. kill -TERM -PID).
12
+ def self.spawned_line(label, pid) = " - pid #{pid} #{label}"
13
+
14
+ # Prints lines while agents run, flushed so they show at once when out
15
+ # is a file or a pipe. (main's $stdout, a SafeStdout, doesn't raise if
16
+ # it can't be written.)
17
+ def self.puts_live(lines, out: $stdout)
18
+ out.puts(lines)
19
+ out.flush
20
+ end
21
+
22
+ # agent_count: how many agents will report. Their labels must be
23
+ # unique, as analysts' are, carrying their agent numbers.
24
+ def initialize(agent_count, out: $stdout)
25
+ @agent_count = agent_count
26
+ @out = out
27
+ @accounted = {} # labels of the agents that have started or finished
28
+ @held = [] # finish lines not yet printed
29
+ @heading = "\nFinished Agents:"
30
+ end
31
+
32
+ def started(label, pid)
33
+ self.class.puts_live([self.class.spawned_line(label, pid)], out: @out)
34
+ @accounted[label] = true
35
+ print_held
36
+ end
37
+
38
+ # lines: the agent's finish line and any under it. They wait until
39
+ # every agent has started (or finished without starting, failing to
40
+ # spawn), so that none prints among the Started Agents lines.
41
+ def finished(label, lines)
42
+ @held.concat(lines)
43
+ @accounted[label] = true
44
+ print_held
45
+ end
46
+
47
+ # Prints whatever is held, as when collecting ended before every agent
48
+ # reported.
49
+ def flush_held = print_held(force: true)
50
+
51
+ private def print_held(force: false)
52
+ return if @held.empty? || (!force && @accounted.size < @agent_count)
53
+
54
+ self.class.puts_live([*@heading, *@held], out: @out)
55
+ @heading = nil
56
+ @held.clear
57
+ end
58
+ end
59
+ end