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.
@@ -5,17 +5,16 @@
5
5
  # with its tool allowlist and the shared read-only scaffolding, and how to
6
6
  # read its stream-json output 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
  # Authentication and billing are left to Claude Code: an agent bills however
11
11
  # claude would at the user's terminal.
12
12
 
13
- require 'json'
14
- require_relative 'scaffold'
13
+ require_relative 'harness'
15
14
 
16
15
  module AgentCouncil
17
16
  module Harnesses
18
- module ClaudeCodeHarness
17
+ class ClaudeCodeHarness < Harness
19
18
  NAME = 'claude'
20
19
 
21
20
  # Analysis toolset (Claude Code's built-in tool names): Edit, Write, and
@@ -27,7 +26,7 @@ module AgentCouncil
27
26
  # argv; it is piped to stdin. provider is not passed: Claude Code
28
27
  # takes none, so an entry's provider only labels the agent (e.g.
29
28
  # bedrock, for a claude set up to use it).
30
- module_function def argv(_provider, model)
29
+ def self.argv(_provider, model)
31
30
  [
32
31
  NAME,
33
32
  '-p', # non-interactive: process prompt and exit
@@ -42,31 +41,27 @@ module AgentCouncil
42
41
  ]
43
42
  end
44
43
 
45
- # --- event stream reading ---
46
-
47
- # The events of a stream-json stream, in order. Unparseable lines and
48
- # non-objects are skipped.
49
- module_function def events(jsonl)
50
- jsonl.each_line.filter_map do |line|
51
- event =
52
- begin
53
- JSON.parse(line)
54
- rescue JSON::ParserError
55
- nil
56
- end
57
- event if event.is_a?(Hash)
58
- end
44
+ # Variables for the agent's process beyond TMPDIR: the scratch dir as
45
+ # CLAUDE_CODE_TMPDIR, the base under which Claude Code's sandbox makes
46
+ # the writable TMPDIR it gives commands. Without it, a user's own
47
+ # CLAUDE_CODE_TMPDIR would put that dir outside the scratch dir,
48
+ # shared and never cleaned up.
49
+ def self.env(scratch_dir)
50
+ { 'CLAUDE_CODE_TMPDIR' => scratch_dir }
59
51
  end
60
52
 
53
+ # --- event stream reading ---
54
+
61
55
  # The agent's result event: the last one, which ends the stream. nil if
62
56
  # there is none, e.g. for an agent that was killed.
63
- module_function def result_event(jsonl)
64
- events(jsonl).reverse_each.detect { |event| event['type'] == 'result' }
57
+ def self.result_event(jsonl)
58
+ last_event(jsonl, 'result')
65
59
  end
60
+ private_class_method :result_event
66
61
 
67
62
  # The messages of the stream's assistant events, in order (several per
68
63
  # model request, one per content block).
69
- module_function def assistant_messages(jsonl)
64
+ def self.assistant_messages(jsonl)
70
65
  events(jsonl).filter_map do |event|
71
66
  message = event['message'] if event['type'] == 'assistant'
72
67
  message if message.is_a?(Hash)
@@ -75,7 +70,7 @@ module AgentCouncil
75
70
 
76
71
  # The final response: the result event's text, for an agent that didn't
77
72
  # fail.
78
- module_function def final_response(jsonl)
73
+ def self.final_response(jsonl)
79
74
  result = result_event(jsonl)
80
75
  return nil unless result && result['is_error'] != true
81
76
 
@@ -89,26 +84,18 @@ module AgentCouncil
89
84
  'cache_read' => 'cache_read_input_tokens',
90
85
  'cache_write' => 'cache_creation_input_tokens' }.freeze
91
86
 
92
- # Token usage as AgentCouncil expects it (see Harnesses), from the
87
+ # Token usage as AgentCouncil expects it (see Harness), from the
93
88
  # result event alone: it totals all the agent's requests, while the assistant
94
89
  # events' usage is per-message snapshots that undercount output. nil
95
90
  # when the stream has no result event (as for an agent whose claude was
96
91
  # killed: no usage beats an undercount) or reports no usage (as when
97
92
  # the agent never reached a model).
98
- module_function def usage(jsonl)
93
+ def self.usage(jsonl)
99
94
  result = result_event(jsonl)
100
95
  usage = result && result['usage']
101
96
  return nil unless usage.is_a?(Hash)
102
97
 
103
- totals = USAGE_KEYS.transform_values { |key| count(usage[key]) }
104
- return nil if totals.values.all?(&:zero?)
105
-
106
- cost = count(result['total_cost_usd'])
107
- cost.positive? ? totals.merge('cost' => cost.round(6)) : totals
108
- end
109
-
110
- module_function def count(value)
111
- value.is_a?(Numeric) && value.positive? ? value : 0
98
+ usage_result(USAGE_KEYS.transform_values { |key| count(usage[key]) }, count(result['total_cost_usd']))
112
99
  end
113
100
 
114
101
  # Why the agent produced no usable report, or nil. A failed agent has a
@@ -118,23 +105,20 @@ module AgentCouncil
118
105
  # is its errors, if any (e.g. the turn limit, with no result text),
119
106
  # otherwise its result text (e.g. "Not logged in · Please run
120
107
  # /login").
121
- module_function def error_message(jsonl)
108
+ def self.error_message(jsonl)
122
109
  result = result_event(jsonl)
123
110
  return 'the stream has no result event' unless result
124
111
  return error_reason(result) || 'the agent failed and gave no reason' if result['is_error'] == true
125
112
 
126
- text = result['result']
127
- 'the result event has no text' unless text.is_a?(String) && !text.strip.empty?
113
+ 'the result event has no text' unless nonblank_text(result['result'])
128
114
  end
129
115
 
130
116
  # The reason a failed agent's result event gives, or nil if it gives none.
131
- module_function def error_reason(result)
132
- errors = Array(result['errors']).grep(String).map(&:strip).reject(&:empty?)
133
- return errors.join('; ') unless errors.empty?
134
-
135
- text = result['result']
136
- text if text.is_a?(String) && !text.strip.empty?
117
+ def self.error_reason(result)
118
+ errors = nonblank_strings(Array(result['errors']))
119
+ errors.empty? ? nonblank_text(result['result']) : errors.join('; ')
137
120
  end
121
+ private_class_method :error_reason
138
122
 
139
123
  # Why an agent that exited nonzero failed. Claude Code explains a failure
140
124
  # in a result event with is_error true, and its stderr is then
@@ -142,16 +126,13 @@ module AgentCouncil
142
126
  # Otherwise stderr is likelier to say why (e.g. for a crash) than
143
127
  # whatever else the stream shows (e.g. a result with no text), which
144
128
  # is the last resort. Returned whole: the caller puts it on one line
145
- # and shortens it (see Harnesses).
146
- module_function def exit_detail(stdout, stderr)
129
+ # and shortens it (see Harness).
130
+ def self.exit_detail(stdout, stderr)
147
131
  result = result_event(stdout)
148
132
  reason = error_reason(result) if result && result['is_error'] == true
149
133
  return reason if reason
150
134
 
151
- stderr_line = stderr.lines.map(&:strip).reject(&:empty?).first
152
- return stderr_line if stderr_line
153
-
154
- (error_message(stdout) if result) || 'no error output'
135
+ first_line(stderr) || (error_message(stdout) if result) || NO_ERROR_OUTPUT
155
136
  end
156
137
 
157
138
  # Warnings about an agent, succeeded or not: the tool calls Claude Code
@@ -160,23 +141,25 @@ module AgentCouncil
160
141
  # call), but its report may be missing what the call would have
161
142
  # found; an agent that fails (say, out of turns) may have failed
162
143
  # because of them.
163
- module_function def warnings(jsonl)
144
+ def self.warnings(jsonl)
164
145
  result = result_event(jsonl)
165
146
  denials = result && result['permission_denials']
166
147
  return [] unless denials.is_a?(Array) && !denials.empty?
167
148
 
168
- calls = denials.map { |denial| denied_call(denial) }.uniq
169
- listed = calls.first(MAX_LISTED_CALLS).map do |tool, target|
170
- target ? "#{tool} (#{shorten(target)})" : tool
149
+ calls = denials.map { |denial| denied_call(denial) }.uniq.map do |tool, target|
150
+ target ? "#{tool} (#{shorten(target, MAX_TARGET_LENGTH)})" : tool
171
151
  end
172
- listed << "and #{calls.size - listed.size} more" if calls.size > listed.size
173
- ["Claude Code refused #{denials.size} tool call#{'s' unless denials.size == 1}: #{listed.join('; ')}"]
152
+ [listing("Claude Code refused #{denials.size} tool call#{'s' unless denials.size == 1}", calls,
153
+ MAX_LISTED_CALLS)]
174
154
  end
175
155
 
176
156
  # Distinct refused calls named in a warning, so an agent refused many
177
157
  # times still gets a warning of a readable length.
178
158
  MAX_LISTED_CALLS = 5
179
159
 
160
+ # Characters of a refused call's target a warning shows.
161
+ MAX_TARGET_LENGTH = 80
162
+
180
163
  # The tool_input keys that say what a refused call was for, in order
181
164
  # of preference: Bash's command, Read's file_path, then Grep's and
182
165
  # Glob's pattern and path.
@@ -186,7 +169,7 @@ module AgentCouncil
186
169
  # such as a Bash command or the file a Read asked for, on one line,
187
170
  # or nil if the call gives none. Compared whole, so calls that differ
188
171
  # only past where a warning shortens them still count as different.
189
- module_function def denied_call(denial)
172
+ def self.denied_call(denial)
190
173
  return ['unknown tool', nil] unless denial.is_a?(Hash)
191
174
 
192
175
  tool = denial['tool_name'].is_a?(String) ? denial['tool_name'] : 'unknown tool'
@@ -195,10 +178,7 @@ module AgentCouncil
195
178
  target = target&.gsub(/\s+/, ' ')&.strip
196
179
  [tool, (target unless target.nil? || target.empty?)]
197
180
  end
198
-
199
- module_function def shorten(target)
200
- target.length > 80 ? "#{target[0, 80]}..." : target
201
- end
181
+ private_class_method :denied_call
202
182
  end
203
183
  end
204
184
  end
@@ -5,17 +5,17 @@
5
5
  # with the shared scaffolding, and how to read
6
6
  # its --json 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
  # Authentication and billing are left to Codex: an agent bills however
11
11
  # codex would at the user's terminal (ChatGPT plan or API key).
12
12
 
13
13
  require 'json'
14
- require_relative 'scaffold'
14
+ require_relative 'harness'
15
15
 
16
16
  module AgentCouncil
17
17
  module Harnesses
18
- module CodexHarness
18
+ class CodexHarness < Harness
19
19
  NAME = 'codex'
20
20
 
21
21
  # Invocation for one agent. The substantive prompt is not part of
@@ -33,7 +33,7 @@ module AgentCouncil
33
33
  #
34
34
  # developer_instructions replaces any the user's config sets; Codex
35
35
  # has no way to append to it.
36
- module_function def argv(_provider, model)
36
+ def self.argv(_provider, model)
37
37
  [
38
38
  NAME, 'exec',
39
39
  '--json', # JSONL event stream on stdout
@@ -48,88 +48,65 @@ module AgentCouncil
48
48
 
49
49
  # A TOML basic string (JSON's string escapes are valid TOML ones), so
50
50
  # -c reads the value as the string itself, not as TOML to parse.
51
- module_function def toml_string(text)
51
+ def self.toml_string(text)
52
52
  JSON.generate(text)
53
53
  end
54
+ private_class_method :toml_string
54
55
 
55
56
  # --- event stream reading ---
56
57
 
57
- # The events of a --json stream, in order. Unparseable lines and
58
- # non-objects are skipped.
59
- module_function def events(jsonl)
60
- jsonl.each_line.filter_map do |line|
61
- event =
62
- begin
63
- JSON.parse(line)
64
- rescue JSON::ParserError
65
- nil
66
- end
67
- event if event.is_a?(Hash)
68
- end
69
- end
70
-
71
58
  # The completed items of the given type, in order.
72
- module_function def completed_items(jsonl, type)
59
+ def self.completed_items(jsonl, type)
73
60
  events(jsonl).filter_map do |event|
74
61
  item = event['item'] if event['type'] == 'item.completed'
75
62
  item if item.is_a?(Hash) && item['type'] == type
76
63
  end
77
64
  end
65
+ private_class_method :completed_items
78
66
 
79
67
  # The agent's messages (its text between and after tool calls), in order.
80
- module_function def assistant_messages(jsonl)
68
+ def self.assistant_messages(jsonl)
81
69
  completed_items(jsonl, 'agent_message')
82
70
  end
83
71
 
84
72
  # The event that ended the agent's turn: turn.completed or
85
73
  # turn.failed. nil if there is none, e.g. for an agent that was killed.
86
- module_function def turn_end(jsonl)
87
- events(jsonl).reverse_each.detect { |event| %w[turn.completed turn.failed].include?(event['type']) }
74
+ def self.turn_end(jsonl)
75
+ last_event(jsonl, 'turn.completed', 'turn.failed')
88
76
  end
77
+ private_class_method :turn_end
89
78
 
90
79
  # The final response: the last agent message with text, for an agent
91
80
  # whose turn completed. Earlier messages narrate its tool use.
92
- module_function def final_response(jsonl)
81
+ def self.final_response(jsonl)
93
82
  return nil unless turn_end(jsonl)&.fetch('type') == 'turn.completed'
94
83
 
95
- message = assistant_messages(jsonl).reverse_each.detect { |m| text_of(m) }
96
- message && text_of(message)
97
- end
98
-
99
- # A message's text, or nil if it has none.
100
- module_function def text_of(item)
101
- text = item['text']
102
- text if text.is_a?(String) && !text.strip.empty?
84
+ assistant_messages(jsonl).filter_map { |message| nonblank_text(message['text']) }.last
103
85
  end
104
86
 
105
- # Token usage as AgentCouncil expects it (see Harnesses), from the
87
+ # Token usage as AgentCouncil expects it (see Harness), from the
106
88
  # turn.completed event, which totals the turn's requests. Codex's
107
89
  # input_tokens is all input, OpenAI's convention, so the cached reads
108
90
  # and writes it reports are subtracted from it; reasoning tokens are
109
91
  # part of output_tokens. Codex prices nothing, so there is no 'cost'.
110
92
  # nil when the turn didn't complete or reports no usage.
111
- module_function def usage(jsonl)
93
+ def self.usage(jsonl)
112
94
  turn = turn_end(jsonl)
113
95
  usage = turn['usage'] if turn && turn['type'] == 'turn.completed'
114
96
  return nil unless usage.is_a?(Hash)
115
97
 
116
98
  cache_read = count(usage['cached_input_tokens'])
117
99
  cache_write = count(usage['cache_write_input_tokens'])
118
- totals = { 'input' => [count(usage['input_tokens']) - cache_read - cache_write, 0].max,
119
- 'output' => count(usage['output_tokens']),
120
- 'cache_read' => cache_read,
121
- 'cache_write' => cache_write }
122
- totals.values.all?(&:zero?) ? nil : totals
123
- end
124
-
125
- module_function def count(value)
126
- value.is_a?(Numeric) && value.positive? ? value : 0
100
+ usage_result({ 'input' => [count(usage['input_tokens']) - cache_read - cache_write, 0].max,
101
+ 'output' => count(usage['output_tokens']),
102
+ 'cache_read' => cache_read,
103
+ 'cache_write' => cache_write })
127
104
  end
128
105
 
129
106
  # Why the agent produced no usable report, or nil. A failed turn ends
130
107
  # with turn.failed, whose error says why (e.g. a model the account
131
108
  # can't use); a completed one with no text is reported as such.
132
- module_function def error_message(jsonl)
109
+ def self.error_message(jsonl)
133
110
  turn = turn_end(jsonl)
134
111
  return 'the stream has no turn.completed or turn.failed event' unless turn
135
112
  return failure_reason(jsonl) || 'the turn failed and gave no reason' if turn['type'] == 'turn.failed'
@@ -139,24 +116,21 @@ module AgentCouncil
139
116
 
140
117
  # The reason a failed turn gives: its turn.failed error message, else
141
118
  # the last top-level error event's. nil if neither gives one.
142
- module_function def failure_reason(jsonl)
143
- all = events(jsonl)
144
- failed = all.reverse_each.detect { |event| event['type'] == 'turn.failed' }
145
- error = failed['error'] if failed
146
- reason = error['message'] if error.is_a?(Hash)
147
- return reason.strip if reason.is_a?(String) && !reason.strip.empty?
148
-
149
- nonblank(all.filter_map { |event| event['message'] if event['type'] == 'error' }).last
119
+ def self.failure_reason(jsonl)
120
+ error = last_event(jsonl, 'turn.failed')&.fetch('error', nil)
121
+ reason = nonblank_text(error['message'])&.strip if error.is_a?(Hash)
122
+ return reason if reason
123
+
124
+ messages = events(jsonl).filter_map { |event| event['message'] if event['type'] == 'error' }
125
+ nonblank_strings(messages).last
150
126
  end
127
+ private_class_method :failure_reason
151
128
 
152
129
  # Why an agent that exited nonzero failed. Codex explains a failed
153
130
  # turn in the stream, with stderr usually empty, so that comes first;
154
131
  # then stderr (e.g. for a bad flag or a crash).
155
- module_function def exit_detail(stdout, stderr)
156
- reason = failure_reason(stdout)
157
- return reason if reason
158
-
159
- stderr.lines.map(&:strip).reject(&:empty?).first || 'no error output'
132
+ def self.exit_detail(stdout, stderr)
133
+ failure_reason(stdout) || super
160
134
  end
161
135
 
162
136
  # Warnings about an agent, failed or not, each listing at most
@@ -169,53 +143,32 @@ module AgentCouncil
169
143
  # codex exec never asks for approval ("MCP tool call requires
170
144
  # approval, but approval policy is never"), whose results the
171
145
  # report may lack.
172
- module_function def warnings(jsonl)
173
- errors = nonblank(completed_items(jsonl, 'error').map { |item| item['message'] }).uniq
146
+ def self.warnings(jsonl)
147
+ errors = nonblank_strings(completed_items(jsonl, 'error').map { |item| item['message'] }).uniq
174
148
  calls = failed_calls(completed_items(jsonl, 'mcp_tool_call').select do |item|
175
149
  item['status'] == 'failed'
176
150
  end)
177
- warnings = []
178
- unless errors.empty?
179
- warnings << listing("Codex reported #{errors.size == 1 ? 'an error' : 'errors'}",
180
- errors)
181
- end
182
- unless calls.empty?
183
- warnings << listing("Codex MCP tool call#{'s' unless calls.size == 1} failed",
184
- calls)
151
+ found = { "Codex reported #{errors.size == 1 ? 'an error' : 'errors'}" => errors,
152
+ "Codex MCP tool call#{'s' unless calls.size == 1} failed" => calls }
153
+ found.reject { |_label, entries| entries.empty? }.map do |label, entries|
154
+ listing(label, entries.map { |entry| shorten(entry, MAX_ERROR_LENGTH) }, MAX_LISTED_ERRORS)
185
155
  end
186
- warnings
187
- end
188
-
189
- # A warning: label, then entries, at most MAX_LISTED_ERRORS of them.
190
- module_function def listing(label, entries)
191
- listed = entries.first(MAX_LISTED_ERRORS).map { |entry| shorten(entry, MAX_ERROR_LENGTH) }
192
- listed << "and #{entries.size - listed.size} more" if entries.size > listed.size
193
- "#{label}: #{listed.join('; ')}"
194
156
  end
195
157
 
196
158
  # Failed MCP tool calls as distinct "server.tool (reason)" entries.
197
- module_function def failed_calls(calls)
159
+ def self.failed_calls(calls)
198
160
  calls.map do |call|
199
- server, name = nonblank([call['server']]).first, nonblank([call['tool']]).first
161
+ server, name = [call['server'], call['tool']].map { |value| nonblank_text(value)&.strip }
200
162
  tool = name ? [server, name].compact.join('.') : 'unknown tool'
201
163
  error = call['error']
202
- reason = error['message'] if error.is_a?(Hash)
203
- reason.is_a?(String) && !reason.strip.empty? ? "#{tool} (#{reason.strip})" : tool
164
+ reason = nonblank_text(error['message'])&.strip if error.is_a?(Hash)
165
+ reason ? "#{tool} (#{reason})" : tool
204
166
  end.uniq
205
167
  end
168
+ private_class_method :failed_calls
206
169
 
207
170
  MAX_LISTED_ERRORS = 5
208
171
  MAX_ERROR_LENGTH = 200
209
-
210
- # text, cut to max characters with "..." if longer.
211
- module_function def shorten(text, max)
212
- text.length > max ? "#{text[0, max]}..." : text
213
- end
214
-
215
- # The values that are nonblank strings, stripped.
216
- module_function def nonblank(values)
217
- values.grep(String).map(&:strip).reject(&:empty?)
218
- end
219
172
  end
220
173
  end
221
174
  end
@@ -0,0 +1,193 @@
1
+ # frozen_string_literal: true
2
+
3
+ # AgentCouncil::Harnesses::Harness — the base class of every harness: the
4
+ # interface agent-council and agent-council-ps call, with defaults a
5
+ # harness inherits unless it overrides them. A harness is a subclass used
6
+ # as is, through class methods; it's never instantiated. AgentCouncil
7
+ # looks one up per agent through AgentCouncil::Harnesses
8
+ # (lib/agent_council/harnesses.rb).
9
+ #
10
+ # Each subclass defines NAME, both the config value and the executable
11
+ # argv runs, which the startup check looks for on PATH. It also goes into
12
+ # report filenames unsanitized, so it must be one AgentCouncil.sanitize
13
+ # leaves unchanged (the specs check this). The scaffolding sends agents to
14
+ # $TMPDIR, which run_agent sets to the scratch dir, so a harness must pass
15
+ # TMPDIR through to its tools.
16
+ #
17
+ # A subclass defines argv, usage, final_response, assistant_messages, and
18
+ # error_message (here they raise NoMethodError); the rest have defaults
19
+ # here. Helpers are private class methods.
20
+
21
+ require 'json'
22
+ require_relative 'scaffold'
23
+
24
+ module AgentCouncil
25
+ module Harnesses
26
+ class Harness
27
+ # exit_detail's reason when the agent left none.
28
+ NO_ERROR_OUTPUT = 'no error output'
29
+
30
+ # The command line for one agent, starting with NAME. The prompt
31
+ # isn't in it; run_agent pipes it to stdin.
32
+ def self.argv(_provider, _model)
33
+ raise_undefined(:argv)
34
+ end
35
+
36
+ # The variables the agent's process needs beyond TMPDIR, which
37
+ # run_agent sets: String names, each with a String value; by default
38
+ # none. It may write files into scratch_dir, which is removed after the
39
+ # agent finishes.
40
+ def self.env(_scratch_dir)
41
+ {}
42
+ end
43
+
44
+ # The bytes run_agent pipes to the harness's stdin for prompt; by
45
+ # default the prompt itself. A harness whose CLI takes structured input
46
+ # on stdin (or has no system-prompt flag for the scaffolding) overrides
47
+ # this.
48
+ def self.stdin_data(prompt)
49
+ prompt
50
+ end
51
+
52
+ # The agent's token usage as AgentCouncil records it, summed over all
53
+ # its requests: integer 'input' (excluding cached input), 'output',
54
+ # 'cache_read', and 'cache_write', plus 'cost' in US dollars when the
55
+ # harness priced the usage; or nil when the harness reports no usage.
56
+ def self.usage(_stdout)
57
+ raise_undefined(:usage)
58
+ end
59
+
60
+ # The agent's report, the text of its final response, or nil if
61
+ # there's none.
62
+ def self.final_response(_stdout)
63
+ raise_undefined(:final_response)
64
+ end
65
+
66
+ # The agent's assistant messages, in order (empty for none), which
67
+ # says whether the stream had any when final_response finds no report.
68
+ def self.assistant_messages(_stdout)
69
+ raise_undefined(:assistant_messages)
70
+ end
71
+
72
+ # Why an agent that exited 0 produced no usable report, or nil.
73
+ def self.error_message(_stdout)
74
+ raise_undefined(:error_message)
75
+ end
76
+
77
+ # Why an agent that exited nonzero failed; by default, the first
78
+ # nonblank line of its stderr, or NO_ERROR_OUTPUT. The caller puts it,
79
+ # and error_message's reason, on one line cut to 300 characters
80
+ # (AgentCouncil.failure_reason), so a harness returns the reason whole.
81
+ def self.exit_detail(_stdout, stderr)
82
+ first_line(stderr) || NO_ERROR_OUTPUT
83
+ end
84
+
85
+ # Messages (empty for none, the default) about an agent, failed or
86
+ # not; the caller prints and records them all, so a harness keeps them
87
+ # few and short.
88
+ def self.warnings(_stdout)
89
+ []
90
+ end
91
+
92
+ # "provider / model" from an agent's command line (its words, as
93
+ # agent-council-ps reads them), as far as it shows them: by default,
94
+ # its --provider and --model values, either of which may be missing
95
+ # ("" if both are). The specs check that it reads back what argv
96
+ # gives.
97
+ def self.model_label(words)
98
+ [flag_value(words, '--provider'), flag_value(words, '--model')].compact.join(' / ')
99
+ end
100
+
101
+ # Raised by the methods above that a subclass must define. A
102
+ # NoMethodError, as calling a missing method would raise, so
103
+ # run_agent's rescue fails only that agent (NotImplementedError, a
104
+ # ScriptError, would escape it and stop the run).
105
+ def self.raise_undefined(name)
106
+ raise NoMethodError.new("#{self} must define #{name}", name)
107
+ end
108
+ private_class_method :raise_undefined
109
+
110
+ # --- helpers for subclasses ---
111
+
112
+ # The word after the first flag in words, or nil.
113
+ def self.flag_value(words, flag)
114
+ index = words.index(flag)
115
+ words[index + 1] if index
116
+ end
117
+ private_class_method :flag_value
118
+
119
+ # The events of a JSONL stream, in order. Unparseable lines and
120
+ # non-objects are skipped.
121
+ def self.events(jsonl)
122
+ jsonl.each_line.filter_map do |line|
123
+ event =
124
+ begin
125
+ JSON.parse(line)
126
+ rescue JSON::ParserError
127
+ nil
128
+ end
129
+ event if event.is_a?(Hash)
130
+ end
131
+ end
132
+ private_class_method :events
133
+
134
+ # The last event of a JSONL stream whose type is one of types, or nil.
135
+ def self.last_event(jsonl, *types)
136
+ events(jsonl).reverse_each.detect { |event| types.include?(event['type']) }
137
+ end
138
+ private_class_method :last_event
139
+
140
+ # A token count or cost from a stream: value if it's a positive
141
+ # number, else 0.
142
+ def self.count(value)
143
+ value.is_a?(Numeric) && value.positive? ? value : 0
144
+ end
145
+ private_class_method :count
146
+
147
+ # What usage returns for totals (our four keys, each a count) and the
148
+ # cost the harness gave them: nil if every total is zero, else the
149
+ # totals, with the cost, rounded, if it's positive.
150
+ def self.usage_result(totals, cost = 0)
151
+ return nil if totals.values.all?(&:zero?)
152
+
153
+ cost.positive? ? totals.merge('cost' => cost.round(6)) : totals
154
+ end
155
+ private_class_method :usage_result
156
+
157
+ # One value: itself, as is (not stripped), if it's a string with
158
+ # something besides whitespace in it, else nil.
159
+ def self.nonblank_text(value)
160
+ value if value.is_a?(String) && !value.strip.empty?
161
+ end
162
+ private_class_method :nonblank_text
163
+
164
+ # An array of values: those that are strings with something besides
165
+ # whitespace in them, stripped, in order.
166
+ def self.nonblank_strings(values)
167
+ values.grep(String).map(&:strip).reject(&:empty?)
168
+ end
169
+ private_class_method :nonblank_strings
170
+
171
+ # text, cut to max characters with "..." if longer.
172
+ def self.shorten(text, max)
173
+ text.length > max ? "#{text[0, max]}..." : text
174
+ end
175
+ private_class_method :shorten
176
+
177
+ # A warning: label, then the first max entries, then how many more
178
+ # there are, if any.
179
+ def self.listing(label, entries, max)
180
+ listed = entries.first(max)
181
+ listed += ["and #{entries.size - max} more"] if entries.size > max
182
+ "#{label}: #{listed.join('; ')}"
183
+ end
184
+ private_class_method :listing
185
+
186
+ # The first nonblank line of text, stripped, or nil.
187
+ def self.first_line(text)
188
+ text.lines.map(&:strip).reject(&:empty?).first
189
+ end
190
+ private_class_method :first_line
191
+ end
192
+ end
193
+ end