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.
@@ -5,33 +5,44 @@
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
20
23
  # Windows-only powershell) are withheld. bash, a full shell, stays for
21
24
  # investigation (git log/status, dependency inspection, ...); only the
22
- # scaffolding text asks the model to use it read-only.
23
- TOOLS = 'read,grep,find,ls,bash'
25
+ # scaffolding text asks the model to use it read-only. The rest give
26
+ # agents the MCP tools pi gives an interactive session, however a
27
+ # server exposes them: codemode for the default exposure (a server's
28
+ # tools are called from a codemode script, which reaches only the
29
+ # tools listed here), mcp__* for servers with direct exposure,
30
+ # tool_search for servers with deferred exposure (it loads only MCP
31
+ # tools, not withheld built-in ones), and pi's MCP resource tools,
32
+ # which --tools would drop once it names an mcp__ entry.
33
+ TOOLS = %w[read grep find ls bash
34
+ codemode mcp__* tool_search
35
+ list_mcp_resources list_mcp_resource_templates read_mcp_resource].join(',')
24
36
 
25
37
  # Invocation for one agent. The substantive prompt is not part of argv;
26
38
  # it is piped to stdin (byte-identical for every analyst; the
27
39
  # consolidator gets its own).
28
- module_function def argv(provider, model)
40
+ def self.argv(provider, model)
29
41
  [
30
42
  NAME,
31
43
  '-p', # non-interactive: process prompt and exit
32
44
  '--mode', 'json', # JSONL event stream on stdout
33
45
  '--no-session', # ephemeral: no session state between agents
34
- '--no-mcp', # built-in MCP off: configured servers don't start
35
46
  '--tools', TOOLS,
36
47
  '--provider', provider,
37
48
  '--model', model,
@@ -41,50 +52,43 @@ module AgentCouncil
41
52
 
42
53
  # --- event stream reading ---
43
54
 
44
- # The assistant message from a single pi JSONL line, or nil if the line
45
- # is not an assistant message_end event.
46
- module_function def assistant_message_from_line(line)
47
- event =
48
- begin
49
- JSON.parse(line)
50
- rescue JSON::ParserError
51
- nil
52
- end
53
-
54
- return nil unless event.is_a?(Hash)
55
- return nil unless event['type'] == 'message_end'
56
-
57
- message = event['message']
58
- return nil unless message && message['role'] == 'assistant'
59
-
60
- 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
61
62
  end
63
+ private_class_method :messages_with_role
62
64
 
63
65
  # Assistant messages from all message_end events in a pi JSONL stream,
64
- # in order. Unparseable lines are skipped.
65
- module_function def assistant_messages(jsonl)
66
- 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')
67
69
  end
68
70
 
69
- module_function def response_text(message)
71
+ def self.response_text(message)
70
72
  Array(message['content'])
71
73
  .select { |block| block['type'] == 'text' }
72
74
  .map { |block| block['text'] }
73
75
  .join("\n")
74
76
  end
77
+ private_class_method :response_text
75
78
 
76
79
  # The final assistant response: per pi's docs, message_end holds the
77
80
  # authoritative final message of each turn; the last assistant message_end
78
81
  # with actual text is the report (earlier ones belong to tool-use turns).
79
- module_function def final_response(jsonl)
82
+ def self.final_response(jsonl)
80
83
  message = saved_message(assistant_messages(jsonl))
81
84
  message && response_text(message)
82
85
  end
83
86
 
84
87
  # The message final_response saves: the last one with text.
85
- module_function def saved_message(messages)
88
+ def self.saved_message(messages)
86
89
  messages.reverse_each.detect { |m| !response_text(m).empty? }
87
90
  end
91
+ private_class_method :saved_message
88
92
 
89
93
  # Our usage keys, each mapped to pi's name for it. pi normalizes usage
90
94
  # across providers; its input excludes cache reads and writes.
@@ -92,21 +96,15 @@ module AgentCouncil
92
96
  'cache_read' => 'cacheRead', 'cache_write' => 'cacheWrite' }.freeze
93
97
 
94
98
  # Token usage summed over all assistant messages (each is a separate
95
- # model request), as AgentCouncil expects it: integer 'input', 'output',
96
- # 'cache_read', and 'cache_write', plus 'cost' in US dollars when pi
97
- # priced the usage. nil when the stream reports no usage, as some
98
- # providers don't.
99
- module_function def usage(jsonl)
100
- usages = assistant_messages(jsonl).map { |m| m['usage'] }.grep(Hash)
99
+ # model request) and tool results, as AgentCouncil expects it: integer
100
+ # 'input', 'output', 'cache_read', and 'cache_write', plus 'cost' in US
101
+ # dollars when pi priced the usage. A tool result has usage when the
102
+ # tool called a model itself, e.g. a codemode script's models.classify
103
+ # call. nil when the stream reports no usage, as some providers don't.
104
+ def self.usage(jsonl)
105
+ usages = messages_with_role(jsonl, 'assistant', 'toolResult').map { |m| m['usage'] }.grep(Hash)
101
106
  totals = USAGE_KEYS.transform_values { |key| usages.sum { |u| count(u[key]) } }
102
- return nil if totals.values.all?(&:zero?)
103
-
104
- cost = usages.sum { |u| u['cost'].is_a?(Hash) ? count(u['cost']['total']) : 0 }
105
- cost.positive? ? totals.merge('cost' => cost.round(6)) : totals
106
- end
107
-
108
- module_function def count(value)
109
- 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 })
110
108
  end
111
109
 
112
110
  # Stop reasons meaning a message was cut off, cancelled, or failed, not
@@ -123,25 +121,15 @@ module AgentCouncil
123
121
  # message must not be saved just because a text-less message followed it).
124
122
  # A non-blank string errorMessage on either wins over a cut-off stopReason on
125
123
  # the other, since it says more about what went wrong.
126
- module_function def error_message(jsonl)
124
+ def self.error_message(jsonl)
127
125
  messages = assistant_messages(jsonl)
128
126
  candidates = [messages.last, saved_message(messages)].compact.uniq
129
- message = candidates.detect { |m| m['errorMessage'].is_a?(String) && !m['errorMessage'].strip.empty? }
127
+ message = candidates.detect { |m| nonblank_text(m['errorMessage']) }
130
128
  return message['errorMessage'] if message
131
129
 
132
130
  message = candidates.detect { |m| UNUSABLE_STOP_REASONS.include?(m['stopReason']) }
133
131
  message && "stopped early (stopReason: #{message['stopReason']})"
134
132
  end
135
-
136
- # Why an agent that exited nonzero failed: pi explains it on stderr.
137
- module_function def exit_detail(_stdout, stderr)
138
- stderr.lines.map(&:strip).reject(&:empty?).first || 'no error output'
139
- end
140
-
141
- # Warnings about an agent that succeeded; pi's stream has none to give.
142
- module_function def warnings(_jsonl)
143
- []
144
- end
145
133
  end
146
134
  end
147
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
@@ -21,6 +21,10 @@ module AgentCouncil
21
21
  configuration file. Do not change git state, install or remove
22
22
  software, modify user or system configuration, or start persistent
23
23
  services.
24
+ - Do not act outside this machine, with any tool (MCP tools
25
+ included): do not post, comment, send messages, or create or
26
+ change issues, tickets, records, or other remote data. Reading
27
+ remote information is fine.
24
28
  - Do not run test suites, builds, coverage tools, application servers,
25
29
  or database tasks unless the user's prompt explicitly permits it:
26
30
  other agents may be running concurrently and such commands can collide
@@ -1,37 +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'
13
+ require_relative 'harnesses/codex_harness'
14
+ require_relative 'harnesses/opencode_harness'
31
15
 
32
16
  module AgentCouncil
33
17
  module Harnesses
34
- BY_NAME = [PiHarness, ClaudeCodeHarness].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
35
21
 
36
22
  # The harness of a report or run.json entry without a 'harness' key:
37
23
  # agent-council writes one in each, so these are hand-edited or older
@@ -49,9 +35,9 @@ module AgentCouncil
49
35
  harness.is_a?(String) ? harness : DEFAULT_NAME
50
36
  end
51
37
 
52
- # 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
53
39
  # config validation rules out before any agent runs.
54
- module_function def module_for(entry)
40
+ module_function def class_for(entry)
55
41
  BY_NAME.fetch(name_of(entry))
56
42
  end
57
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