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,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,185 @@
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 agent's token usage as AgentCouncil records it, summed over all
45
+ # its requests: integer 'input' (excluding cached input), 'output',
46
+ # 'cache_read', and 'cache_write', plus 'cost' in US dollars when the
47
+ # harness priced the usage; or nil when the harness reports no usage.
48
+ def self.usage(_stdout)
49
+ raise_undefined(:usage)
50
+ end
51
+
52
+ # The agent's report, the text of its final response, or nil if
53
+ # there's none.
54
+ def self.final_response(_stdout)
55
+ raise_undefined(:final_response)
56
+ end
57
+
58
+ # The agent's assistant messages, in order (empty for none), which
59
+ # says whether the stream had any when final_response finds no report.
60
+ def self.assistant_messages(_stdout)
61
+ raise_undefined(:assistant_messages)
62
+ end
63
+
64
+ # Why an agent that exited 0 produced no usable report, or nil.
65
+ def self.error_message(_stdout)
66
+ raise_undefined(:error_message)
67
+ end
68
+
69
+ # Why an agent that exited nonzero failed; by default, the first
70
+ # nonblank line of its stderr, or NO_ERROR_OUTPUT. The caller puts it,
71
+ # and error_message's reason, on one line cut to 300 characters
72
+ # (AgentCouncil.failure_reason), so a harness returns the reason whole.
73
+ def self.exit_detail(_stdout, stderr)
74
+ first_line(stderr) || NO_ERROR_OUTPUT
75
+ end
76
+
77
+ # Messages (empty for none, the default) about an agent, failed or
78
+ # not; the caller prints and records them all, so a harness keeps them
79
+ # few and short.
80
+ def self.warnings(_stdout)
81
+ []
82
+ end
83
+
84
+ # "provider / model" from an agent's command line (its words, as
85
+ # agent-council-ps reads them), as far as it shows them: by default,
86
+ # its --provider and --model values, either of which may be missing
87
+ # ("" if both are). The specs check that it reads back what argv
88
+ # gives.
89
+ def self.model_label(words)
90
+ [flag_value(words, '--provider'), flag_value(words, '--model')].compact.join(' / ')
91
+ end
92
+
93
+ # Raised by the methods above that a subclass must define. A
94
+ # NoMethodError, as calling a missing method would raise, so
95
+ # run_agent's rescue fails only that agent (NotImplementedError, a
96
+ # ScriptError, would escape it and stop the run).
97
+ def self.raise_undefined(name)
98
+ raise NoMethodError.new("#{self} must define #{name}", name)
99
+ end
100
+ private_class_method :raise_undefined
101
+
102
+ # --- helpers for subclasses ---
103
+
104
+ # The word after the first flag in words, or nil.
105
+ def self.flag_value(words, flag)
106
+ index = words.index(flag)
107
+ words[index + 1] if index
108
+ end
109
+ private_class_method :flag_value
110
+
111
+ # The events of a JSONL stream, in order. Unparseable lines and
112
+ # non-objects are skipped.
113
+ def self.events(jsonl)
114
+ jsonl.each_line.filter_map do |line|
115
+ event =
116
+ begin
117
+ JSON.parse(line)
118
+ rescue JSON::ParserError
119
+ nil
120
+ end
121
+ event if event.is_a?(Hash)
122
+ end
123
+ end
124
+ private_class_method :events
125
+
126
+ # The last event of a JSONL stream whose type is one of types, or nil.
127
+ def self.last_event(jsonl, *types)
128
+ events(jsonl).reverse_each.detect { |event| types.include?(event['type']) }
129
+ end
130
+ private_class_method :last_event
131
+
132
+ # A token count or cost from a stream: value if it's a positive
133
+ # number, else 0.
134
+ def self.count(value)
135
+ value.is_a?(Numeric) && value.positive? ? value : 0
136
+ end
137
+ private_class_method :count
138
+
139
+ # What usage returns for totals (our four keys, each a count) and the
140
+ # cost the harness gave them: nil if every total is zero, else the
141
+ # totals, with the cost, rounded, if it's positive.
142
+ def self.usage_result(totals, cost = 0)
143
+ return nil if totals.values.all?(&:zero?)
144
+
145
+ cost.positive? ? totals.merge('cost' => cost.round(6)) : totals
146
+ end
147
+ private_class_method :usage_result
148
+
149
+ # One value: itself, as is (not stripped), if it's a string with
150
+ # something besides whitespace in it, else nil.
151
+ def self.nonblank_text(value)
152
+ value if value.is_a?(String) && !value.strip.empty?
153
+ end
154
+ private_class_method :nonblank_text
155
+
156
+ # An array of values: those that are strings with something besides
157
+ # whitespace in them, stripped, in order.
158
+ def self.nonblank_strings(values)
159
+ values.grep(String).map(&:strip).reject(&:empty?)
160
+ end
161
+ private_class_method :nonblank_strings
162
+
163
+ # text, cut to max characters with "..." if longer.
164
+ def self.shorten(text, max)
165
+ text.length > max ? "#{text[0, max]}..." : text
166
+ end
167
+ private_class_method :shorten
168
+
169
+ # A warning: label, then the first max entries, then how many more
170
+ # there are, if any.
171
+ def self.listing(label, entries, max)
172
+ listed = entries.first(max)
173
+ listed += ["and #{entries.size - max} more"] if entries.size > max
174
+ "#{label}: #{listed.join('; ')}"
175
+ end
176
+ private_class_method :listing
177
+
178
+ # The first nonblank line of text, stripped, or nil.
179
+ def self.first_line(text)
180
+ text.lines.map(&:strip).reject(&:empty?).first
181
+ end
182
+ private_class_method :first_line
183
+ end
184
+ end
185
+ end
@@ -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 (the other harnesses
50
+ # save none), 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