agent-council 0.3.0 → 0.5.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.
@@ -0,0 +1,234 @@
1
+ # frozen_string_literal: true
2
+
3
+ # AgentCouncil::Harnesses::OpenCodeHarness — all knowledge specific to the
4
+ # OpenCode harness: how to invoke `opencode run` for one agent, with the
5
+ # shared scaffolding, and how to read its --format json event stream
6
+ # afterward.
7
+ #
8
+ # AgentCouncil is harness-agnostic and finds this class through
9
+ # AgentCouncil::Harnesses (lib/agent_council/harnesses.rb), by its NAME.
10
+ # Authentication and billing are left to OpenCode: an agent uses the
11
+ # credentials `opencode auth login` saved, as it would at the user's terminal.
12
+
13
+ require 'json'
14
+ require_relative 'harness'
15
+
16
+ module AgentCouncil
17
+ module Harnesses
18
+ class OpenCodeHarness < Harness
19
+ NAME = 'opencode'
20
+
21
+ # The scaffolding file env writes into the scratch dir: OpenCode reads
22
+ # extra system-prompt text only from files its config's instructions
23
+ # name.
24
+ SCAFFOLD_FILE = 'agent-council-scaffold.md'
25
+
26
+ # Invocation for one agent. The substantive prompt is not part of
27
+ # argv; opencode run reads it from stdin. Unlike Claude Code's and
28
+ # Codex's, the provider is passed: OpenCode takes provider/model.
29
+ # --agent pins the agent whose edit permission env denies, whatever
30
+ # default_agent a config names. No --auto: a tool call the user's
31
+ # permissions set to "ask" is refused, since opencode run never asks.
32
+ def self.argv(provider, model)
33
+ [NAME, 'run', '--format', 'json', '--agent', AGENT, '--model', "#{provider}/#{model}"]
34
+ end
35
+
36
+ # The agent every OpenCode agent runs as.
37
+ AGENT = 'build'
38
+
39
+ # "provider / model" from an agent's command line: its --model gives
40
+ # both, as provider/model (see argv). The model may itself contain a
41
+ # "/", so only the first one separates them.
42
+ def self.model_label(words)
43
+ model = flag_value(words, '--model')
44
+ model&.include?('/') ? model.split('/', 2).join(' / ') : super
45
+ end
46
+
47
+ # Variables for the agent's process, beside TMPDIR:
48
+ # - OPENCODE_DB, a database in the scratch dir, so the session is
49
+ # deleted with it when the agent finishes (pi, Claude Code, and Codex
50
+ # save none either), and concurrent agents don't share one database.
51
+ # - OPENCODE_CONFIG_CONTENT, which OpenCode merges over the user's and
52
+ # the project's config (replacing a user's own value):
53
+ # - the scaffolding, as an instructions file;
54
+ # - edit permission denied, globally and for AGENT, withholding the
55
+ # file-editing tools by default, as the other harnesses withhold
56
+ # theirs (a config can still allow them; bash stays either way);
57
+ # - the scratch dir allowed as an external directory for AGENT, so
58
+ # its own tools can read what it puts in $TMPDIR (per agent, since
59
+ # a global map would replace a user's scalar value);
60
+ # - experimental.continue_loop_on_deny, so a refused tool call
61
+ # doesn't end the session;
62
+ # - the title agent disabled, since its request isn't in the stream
63
+ # (so not in usage);
64
+ # - snapshots off, so the project's files aren't copied into
65
+ # OpenCode's data dir.
66
+ # Writes the scaffolding file into scratch_dir.
67
+ def self.env(scratch_dir)
68
+ scaffold = File.join(scratch_dir, SCAFFOLD_FILE)
69
+ File.write(scaffold, Harnesses.scaffold_text)
70
+ deny = { 'edit' => 'deny' }
71
+ scratch = { 'external_directory' => { File.join(scratch_dir, '*') => 'allow' } }
72
+ config = { 'instructions' => [scaffold], 'permission' => deny,
73
+ 'agent' => { AGENT => { 'permission' => deny.merge(scratch) },
74
+ 'title' => { 'disable' => true } },
75
+ 'snapshot' => false, 'experimental' => { 'continue_loop_on_deny' => true } }
76
+ { 'OPENCODE_DB' => File.join(scratch_dir, 'opencode.db'),
77
+ 'OPENCODE_CONFIG_CONTENT' => JSON.generate(config) }
78
+ end
79
+
80
+ # --- event stream reading ---
81
+
82
+ # The parts of the events of the given type, in order.
83
+ def self.parts(jsonl, type)
84
+ events(jsonl).filter_map do |event|
85
+ part = event['part'] if event['type'] == type
86
+ part if part.is_a?(Hash)
87
+ end
88
+ end
89
+ private_class_method :parts
90
+
91
+ # The agent's model requests: one step_finish part each, carrying its
92
+ # tokens and cost.
93
+ def self.assistant_messages(jsonl)
94
+ parts(jsonl, 'step_finish')
95
+ end
96
+
97
+ # The final response: the text of the last assistant message with any,
98
+ # its text parts joined, for an agent that hit no error. Earlier
99
+ # messages narrate its tool use. Synthetic parts, which OpenCode
100
+ # writes itself (e.g. after compacting the session), are skipped.
101
+ def self.final_response(jsonl)
102
+ return nil if failure_reason(jsonl)
103
+
104
+ texts = report_texts(jsonl)
105
+ return nil if texts.empty?
106
+
107
+ last_id = texts.last['messageID']
108
+ texts.select { |part| part['messageID'] == last_id }.map { |part| part['text'] }.join("\n")
109
+ end
110
+
111
+ # The nonblank text parts, less those OpenCode wrote itself
112
+ # (synthetic) or marked ignored.
113
+ def self.report_texts(jsonl)
114
+ parts(jsonl, 'text').select do |part|
115
+ nonblank_text(part['text']) && !part['synthetic'] && !part['ignored']
116
+ end
117
+ end
118
+ private_class_method :report_texts
119
+
120
+ # The ID of the message final_response takes its text from, or nil.
121
+ def self.final_response_message_id(jsonl)
122
+ report_texts(jsonl).last&.fetch('messageID', nil)
123
+ end
124
+ private_class_method :final_response_message_id
125
+
126
+ # Token usage as AgentCouncil expects it (see Harness), summed over
127
+ # the step_finish parts. OpenCode's input excludes cached input;
128
+ # reasoning tokens, counted apart, are added to output. 'cost' is
129
+ # OpenCode's own estimate, from its model catalog.
130
+ # nil when the stream reports no usage.
131
+ def self.usage(jsonl)
132
+ steps = assistant_messages(jsonl)
133
+ tokens = steps.map { |part| part['tokens'] }.grep(Hash)
134
+ caches = tokens.map { |t| t['cache'] }.grep(Hash)
135
+ totals = { 'input' => tokens.sum { |t| count(t['input']) },
136
+ 'output' => tokens.sum { |t| count(t['output']) + count(t['reasoning']) },
137
+ 'cache_read' => caches.sum { |c| count(c['read']) },
138
+ 'cache_write' => caches.sum { |c| count(c['write']) } }
139
+ usage_result(totals, steps.sum { |part| count(part['cost']) })
140
+ end
141
+
142
+ # Finish reasons meaning a model request was cut off or failed, not
143
+ # completed (the AI SDK's, which OpenCode reports).
144
+ UNUSABLE_FINISH_REASONS = %w[length content-filter error].freeze
145
+
146
+ # Why the agent produced no usable report, or nil. Older OpenCode
147
+ # versions exit 0 after an error (e.g. an unavailable model), so an
148
+ # error event fails the agent whatever the exit status; and a request
149
+ # that finished for an UNUSABLE_FINISH_REASONS reason leaves a
150
+ # partial report if it was the last one or the report's message,
151
+ # even if a later request (with no text) completed. A stream with no
152
+ # text is left to run_agent, which says what it has.
153
+ def self.error_message(jsonl)
154
+ failure = failure_reason(jsonl)
155
+ return failure if failure
156
+
157
+ steps = assistant_messages(jsonl)
158
+ report_id = final_response_message_id(jsonl)
159
+ reason = [steps.last, steps.reverse_each.detect { |s| report_id && s['messageID'] == report_id }]
160
+ .compact.map { |s| s['reason'] }.find { |r| UNUSABLE_FINISH_REASONS.include?(r) }
161
+ return "stopped early (reason: #{reason})" if reason
162
+
163
+ stopped_at_tool_calls(steps, jsonl)
164
+ end
165
+
166
+ # A session whose last request ended in tool calls, with nothing
167
+ # after, was stopped (exit 0, no error event), its last text being
168
+ # the model's lead-in to the call: as a rejected "ask" call would
169
+ # stop it without the continue_loop_on_deny env sets. nil otherwise.
170
+ # Only the last request's rejected calls are named: an earlier one
171
+ # the agent went on from didn't stop it.
172
+ def self.stopped_at_tool_calls(steps, jsonl)
173
+ return nil unless steps.last&.fetch('reason', nil) == 'tool-calls'
174
+
175
+ last_id = steps.last['messageID']
176
+ tools = last_id ? rejected_tools(jsonl, last_id) : []
177
+ return 'stopped early (reason: tool-calls)' if tools.empty?
178
+
179
+ "stopped when OpenCode refused a tool call its permissions set to ask (#{tools.uniq.join(', ')})"
180
+ end
181
+ private_class_method :stopped_at_tool_calls
182
+
183
+ # The error text OpenCode gives a tool call whose permission it rejected.
184
+ REJECTION_PREFIX = 'The user rejected permission'
185
+
186
+ # The tools of the tool calls OpenCode rejected for want of permission,
187
+ # in order, only those of the message with the given ID if one is
188
+ # given.
189
+ def self.rejected_tools(jsonl, message_id = nil)
190
+ parts(jsonl, 'tool_use').filter_map do |part|
191
+ state = part['state'].is_a?(Hash) ? part['state'] : {}
192
+ next unless state['status'] == 'error' && state['error'].to_s.start_with?(REJECTION_PREFIX)
193
+ next if message_id && part['messageID'] != message_id
194
+
195
+ part['tool'].is_a?(String) ? part['tool'] : 'unknown tool'
196
+ end
197
+ end
198
+ private_class_method :rejected_tools
199
+
200
+ # The last error event's message, else its error's name. nil if the
201
+ # stream has no error event.
202
+ def self.failure_reason(jsonl)
203
+ event = last_event(jsonl, 'error')
204
+ return nil unless event
205
+
206
+ error = event['error'].is_a?(Hash) ? event['error'] : {}
207
+ data = error['data'].is_a?(Hash) ? error['data'] : {}
208
+ nonblank_strings([data['message'], error['name']]).first ||
209
+ 'an error event gave no reason'
210
+ end
211
+ private_class_method :failure_reason
212
+
213
+ # Why an agent that exited nonzero failed: the stream's error event
214
+ # if there is one, else stderr (e.g. for a bad flag).
215
+ def self.exit_detail(stdout, stderr)
216
+ failure_reason(stdout) || super
217
+ end
218
+
219
+ # Warnings about an agent: one for the tool calls OpenCode rejected
220
+ # for want of permission (set to "ask", which opencode run can't
221
+ # ask), as the other harnesses report refusals, with their count and
222
+ # tools. A call a deny rule blocks has another error text, and like
223
+ # other failed tool calls is an ordinary tool error the agent sees
224
+ # and goes on from.
225
+ def self.warnings(jsonl)
226
+ tools = rejected_tools(jsonl)
227
+ return [] if tools.empty?
228
+
229
+ calls = tools.size == 1 ? 'a tool call' : "#{tools.size} tool calls"
230
+ ["OpenCode refused #{calls} for want of permission (#{tools.uniq.join(', ')})"]
231
+ end
232
+ end
233
+ end
234
+ end
@@ -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,13 +1,15 @@
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 gives its agents (appended to the system prompt, or prepended to
5
+ # the user message for Antigravity). Required by Harness
6
+ # (harnesses/harness.rb), so each harness has it without the harness
7
+ # registry (lib/agent_council/harnesses.rb), which requires the harnesses.
7
8
 
8
9
  module AgentCouncil
9
10
  module Harnesses
10
- # Scaffolding appended to every harness's system prompt, identical for
11
+ # Scaffolding given to every harness's agents (appended to the system
12
+ # prompt, or prepended to the user message for Antigravity), identical for
11
13
  # every agent. It names the scratch dir as $TMPDIR, not by path: Claude
12
14
  # Code's sandbox makes the dir itself read-only and points TMPDIR at a
13
15
  # writable dir inside it.
@@ -1,38 +1,26 @@
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'
15
+ require_relative 'harnesses/antigravity_harness'
32
16
 
33
17
  module AgentCouncil
34
18
  module Harnesses
35
- BY_NAME = [PiHarness, ClaudeCodeHarness, CodexHarness].to_h { |harness| [harness::NAME, harness] }.freeze
19
+ BY_NAME = [
20
+ PiHarness, ClaudeCodeHarness, CodexHarness, OpenCodeHarness, AntigravityHarness
21
+ ].to_h do |harness|
22
+ [harness::NAME, harness]
23
+ end.freeze
36
24
 
37
25
  # The harness of a report or run.json entry without a 'harness' key:
38
26
  # agent-council writes one in each, so these are hand-edited or older
@@ -50,9 +38,9 @@ module AgentCouncil
50
38
  harness.is_a?(String) ? harness : DEFAULT_NAME
51
39
  end
52
40
 
53
- # The harness module for an entry; KeyError for an unknown name, which
41
+ # The harness class for an entry; KeyError for an unknown name, which
54
42
  # config validation rules out before any agent runs.
55
- module_function def module_for(entry)
43
+ module_function def class_for(entry)
56
44
  BY_NAME.fetch(name_of(entry))
57
45
  end
58
46
  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