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.
data/USE_CASES.md CHANGED
@@ -32,8 +32,8 @@ Where a sample prompt exists, it's linked; the samples are in
32
32
  or periodically to track health over time
33
33
  ([`state-of-the-code-base-prompt.md`](examples/prompts/state-of-the-code-base-prompt.md)).
34
34
  - Due diligence on a library, fork, or acquisition before adopting it
35
- (in a sandbox; see the README's [Safety and
36
- privacy](README.md#safety-and-privacy)).
35
+ (in a sandbox; see [`CAUTIONS.md`](CAUTIONS.md) and the README's
36
+ [Safety and privacy](README.md#safety-and-privacy)).
37
37
  - Specific questions about how something works ("what happens when the
38
38
  cache is unavailable?"), where agreement builds confidence and
39
39
  disagreement shows where to look.
@@ -110,7 +110,7 @@ saved.
110
110
  - Comparing providers serving the same model, on latency, price, and
111
111
  reliability.
112
112
  - Comparing harnesses running the same model (say, pi and Claude Code,
113
- or pi and Codex), on
113
+ pi and Codex, pi and OpenCode, or pi and Antigravity), on
114
114
  speed, cost, and what they find.
115
115
  - Finding out which listed models your plan actually covers.
116
116
 
@@ -0,0 +1,20 @@
1
+ # Sample Google Antigravity ensemble: runs under your own `agy` setup
2
+ # (Google AI subscription, Gemini API key, or Vertex AI — see "Choosing a
3
+ # harness" in the README). Run `agy models` to list available model slugs.
4
+ # `provider` is a label only; use `google` (or `anthropic` / `openai` when
5
+ # selecting non-Gemini models served through Antigravity).
6
+ agents:
7
+ - harness: agy
8
+ provider: google
9
+ model: gemini-4-neon-high
10
+ - harness: agy
11
+ provider: google
12
+ model: gemini-4-carbon-high
13
+ - harness: agy
14
+ provider: anthropic
15
+ model: claude-sonnet-5-5-high
16
+
17
+ consolidator:
18
+ harness: agy
19
+ provider: google
20
+ model: gemini-4-neon-medium
@@ -1,9 +1,10 @@
1
- # Sample mixed-harness ensemble: Claude Code and Codex analysts alongside pi
2
- # analysts, with a Claude Code consolidator. Claude Code and Codex entries run
3
- # under your own `claude` and `codex` setups and bill however they do (see
4
- # "Choosing a harness" in the README); pi entries need credentials for their
5
- # providers (see `pi --list-models`). Replace any provider or model you don't
6
- # have.
1
+ # Sample mixed-harness ensemble: Claude Code, Codex, OpenCode, and Antigravity
2
+ # analysts alongside pi analysts, with a Claude Code consolidator. Claude Code,
3
+ # Codex, and Antigravity entries run under your own `claude`, `codex`, and `agy`
4
+ # setups and bill however they do (see "Choosing a harness" in the README); pi
5
+ # and OpenCode entries need credentials for their providers. Replace any
6
+ # provider or model you don't have; "Discovering and configuring models" in the
7
+ # README says how to find each harness's models.
7
8
  agents:
8
9
  - harness: claude
9
10
  provider: anthropic
@@ -11,16 +12,25 @@ agents:
11
12
  - harness: codex
12
13
  provider: openai
13
14
  model: gpt-5.6-terra
15
+ - harness: agy
16
+ provider: google
17
+ model: gemini-4-neon-high
14
18
  - harness: pi
15
19
  provider: deepseek
16
20
  model: deepseek-flash
17
21
  - harness: pi
18
22
  provider: openrouter
19
23
  model: z-ai/glm-5.3-flash
20
- # The same model under the other harness, to compare harnesses:
24
+ - harness: opencode
25
+ provider: opencode-go
26
+ model: glm-5.3
27
+ # The same models under another harness, to compare harnesses:
21
28
  - harness: pi
22
29
  provider: anthropic
23
30
  model: claude-opus-5-5
31
+ - harness: pi
32
+ provider: opencode-go
33
+ model: glm-5.3
24
34
 
25
35
  consolidator:
26
36
  harness: claude
@@ -27,6 +27,9 @@ solution would be appropriate.
27
27
  context, but they are local to this checkout, so judge the changes
28
28
  against tracked files.
29
29
  - Do not report preexisting issues unless the changes introduce or worsen them.
30
+ - If the repository has a `REVIEW_NOTES.md`, don't report issues it
31
+ records as accepted risks or non-issues, unless the changes make one
32
+ worse or its reasoning no longer holds.
30
33
  - You may suggest improvements to the commit message, particularly if the
31
34
  commit has not been pushed.
32
35
 
@@ -37,6 +40,12 @@ Investigate thoroughly before reaching conclusions.
37
40
  You are permitted and encouraged to inspect files, run Git commands, execute
38
41
  relevant tests and linters, and reproduce suspected defects.
39
42
 
43
+ Several agents run this review at the same time on the same machine, so
44
+ keep your test runs light: where you can, run the tests relevant to the
45
+ change rather than the whole suite, and run them under one language
46
+ version or interpreter, not several. If you suspect a defect specific
47
+ to one version or interpreter, run only the relevant tests under it.
48
+
40
49
  **DO NOT EDIT ANY CODE OR TRACKED FILES.**
41
50
 
42
51
  Tests and linters that generate temporary files or coverage data are
@@ -71,6 +71,12 @@ Investigate thoroughly before reaching conclusions.
71
71
  You are permitted and encouraged to inspect files, run Git commands, execute
72
72
  relevant tests and linters, and reproduce suspected defects.
73
73
 
74
+ Several agents run this review at the same time on the same machine, so
75
+ keep your test runs light: where you can, run the tests relevant to the
76
+ change rather than the whole suite, and run them under one language
77
+ version or interpreter, not several. If you suspect a defect specific
78
+ to one version or interpreter, run only the relevant tests under it.
79
+
74
80
  **DO NOT EDIT ANY CODE OR TRACKED FILES.**
75
81
 
76
82
  Tests and linters that generate temporary files or coverage data are
@@ -8,8 +8,8 @@ gaps by risk. It never asks for input, so it also works headless (e.g.
8
8
 
9
9
  **Requirement:** run your full test suite (every suite that feeds SimpleCov)
10
10
  first, make sure it passes, and don't change source or test files until the
11
- analysis finishes. The prompt does not run tests; it reads the existing
12
- `coverage.json` and refuses to start if that file looks out of date. This lets
11
+ analysis finishes. The prompt does not run tests; it reads the coverage file
12
+ that run left and refuses to start if that file looks out of date. This lets
13
13
  several agents run it concurrently against the same coverage data.
14
14
 
15
15
  ---
@@ -33,7 +33,7 @@ Before you begin the analysis:
33
33
  3. If `git status` shows uncommitted changes, include them in the analysis:
34
34
  analyze the working tree as it is, and list the `git status` details
35
35
  immediately after the commit citation.
36
- 4. Analyze the files git would consider part of the project: tracked files
36
+ 4. Analyze the files git would consider part of the project: git-tracked files
37
37
  plus new files not yet added, excluding anything git ignores
38
38
  (`git ls-files --cached --others --exclude-standard`). Mark the untracked
39
39
  files in the `git status` details.
@@ -44,12 +44,20 @@ Before you begin the analysis:
44
44
  - Your task is to produce a report of line coverage **organized by the logical
45
45
  parts of the system**, not just a per-file list, and to judge where the gaps
46
46
  actually matter.
47
- - Get every coverage number from cov-loupe. Do not read `coverage.json`
47
+ - Get every coverage number from cov-loupe. Do not read the coverage file
48
48
  directly, and do not estimate coverage by reading tests. Aggregating
49
49
  cov-loupe's per-line output into area totals is expected (see Step 4).
50
- - Use the cov-loupe CLI (`cov-loupe`, or `bundle exec cov-loupe` if it is in
51
- the Gemfile; run `cov-loupe --help` for usage), adding `-m cli -fJ` for JSON
52
- output.
50
+ - Prefer the cov-loupe MCP server. If it is unavailable, or its calls are
51
+ refused, use the CLI (`cov-loupe`, or `bundle exec cov-loupe` if it is in
52
+ the Gemfile). Every command needs a subcommand, such as `list`; ask for
53
+ JSON output (`-f J`). If the CLI rejects the subcommand because it is in
54
+ MCP mode (COV_LOUPE_OPTS can select it), put `-m cli` before the
55
+ subcommand. Say in the report which interface you used, and which
56
+ cov-loupe version.
57
+ - cov-loupe's options, tool parameters, and field names differ between
58
+ versions. The names below, such as `not_in_coverage_files`, are examples
59
+ from one version; take the real ones from the MCP tool schemas or from
60
+ `cov-loupe --help`, and from the output itself.
53
61
  - Use source and test files only to define the logical areas and to judge the
54
62
  importance of uncovered code.
55
63
  - Do not run the test suite, and do not modify source files, test files, or
@@ -71,20 +79,22 @@ error, not a report.
71
79
 
72
80
  1. Find the SimpleCov configuration (`.simplecov`, `spec/spec_helper.rb`,
73
81
  `test/test_helper.rb`, or wherever the project starts SimpleCov) and the
74
- coverage file (`coverage/coverage.json` unless the configuration or the
75
- invocation says otherwise). The file must exist and be written by
76
- SimpleCov 1.x. Record its path, size in bytes, and modification time (in
82
+ coverage file: the file cov-loupe reads (`cov-loupe --help` gives its
83
+ default location), unless the configuration or the invocation names
84
+ another. The file must exist. Record its path, size in bytes, and modification time (in
77
85
  UTC) from the file system (e.g. `ls -l` or `stat`); this metadata is not
78
86
  coverage data, so reading it is allowed.
79
- 2. Run the project totals with the tracked globs from Step 2
80
- (`cov-loupe -m cli -fJ -g '<globs>' totals`) and the file list with the
81
- same globs (`cov-loupe -m cli -fJ -g '<globs>' list`). `timestamp_status`
82
- must be `ok`, and `newer_files`, `deleted_files`, `length_mismatch_files`,
83
- `unreadable_files`, and `skipped_files` must all be empty. These show
84
- whether source files changed after the run.
87
+ 2. Run the project totals (`project_coverage_totals` /
88
+ `cov-loupe totals`) and the file list (`project_coverage` /
89
+ `cov-loupe list`), each limited to the file globs from Step 2. The
90
+ output's staleness fields must report no problem: the timestamp status
91
+ must be ok, and the lists of files that are newer than the coverage
92
+ data, deleted, of mismatched length, unreadable, or skipped (e.g.
93
+ `newer_files`, `deleted_files`) must all be empty. These show whether
94
+ source files changed after the run.
85
95
  3. No test, fixture, or configuration file may be newer than the coverage
86
96
  file, since cov-loupe checks only source files. For example:
87
- `find spec test features Gemfile.lock .rspec .simplecov -newer coverage/coverage.json`
97
+ `find spec test features Gemfile.lock .rspec .simplecov -newer <coverage file>`
88
98
  (adjusted to the paths that exist). Include directories in the search,
89
99
  not just files, so that deleted test files show up too.
90
100
  4. If the project records test results, they must show no failures: for
@@ -94,18 +104,19 @@ error, not a report.
94
104
  These checks cannot prove that the last run was the complete suite. Say in
95
105
  the report that the analysis relies on the user's assurance that it was.
96
106
 
97
- `missing_tracked_files` (tracked files the suite never loaded) is not a
98
- staleness failure; it is a finding for Step 2.
107
+ Files that match the file globs but that the suite never loaded are not a
108
+ staleness failure; they are a finding for Step 2.
99
109
 
100
110
  ## Step 2: Establish the project baseline
101
111
 
102
- 1. Get overall totals with no globs, then with tracked globs matching the
103
- code SimpleCov is meant to measure (from its `track_files` and filter
104
- settings; typically `lib/**/*.rb`, or `app/**/*.rb,lib/**/*.rb` for Rails).
105
- Passing tracked globs (`-g`) makes cov-loupe report tracked files that have
106
- **no** coverage data at all (`missing_tracked_files`, `without_coverage`);
107
- these are files never loaded by the suite and are often the biggest real
108
- gap.
112
+ 1. Get overall totals with no globs, then with file globs matching the
113
+ code SimpleCov is meant to measure, taken from its `cover` setting
114
+ (formerly `track_files`) and its filters; typically `lib/**/*.rb`, or
115
+ `app/**/*.rb,lib/**/*.rb` for Rails.
116
+ Passing file globs makes cov-loupe report matching files that have
117
+ **no** coverage data at all (e.g. `not_in_coverage_files` in the list,
118
+ and a count of them in totals); these are files never loaded by the
119
+ suite and are often the biggest real gap.
109
120
  2. Get the full file list as JSON, sorted ascending (worst first).
110
121
  3. Note what the numbers cover: cov-loupe reports **line** coverage only.
111
122
  If SimpleCov also collects branch coverage, say that branch coverage is out
@@ -161,16 +172,17 @@ and more tokens than a file-level rollup; that is the point.
161
172
  ## Step 4: Compute coverage per area
162
173
 
163
174
  1. For each file touched by an area, get per-line data with
164
- `cov-loupe -m cli -fJ detailed <path>`. Each row gives a line number, its
165
- hit count, and whether it is covered; lines that are not coverable
166
- (comments, blank lines, `end`) do not appear.
175
+ `file_coverage_detailed` / `cov-loupe detailed <path>`. Each row
176
+ gives a line number, its hit count, and whether it is covered; lines that
177
+ are not coverable (comments, blank lines, `end`) do not appear.
167
178
  2. For each area, sum the covered and coverable lines that fall in its line
168
179
  ranges, and compute the percentage. Also record the number of code units
169
180
  in the area and its weakest units (e.g. the least-covered methods).
170
181
  3. Get a broader area's numbers by summing its children's line counts, never
171
182
  by averaging child percentages.
172
183
  4. For an area made of whole files, cross-check your sums against
173
- `cov-loupe -m cli -fJ -g '<globs>' totals`; they must match exactly.
184
+ `project_coverage_totals` / `cov-loupe totals`, limited to that area's
185
+ globs; they must match exactly.
174
186
  5. Confirm that the line totals for the partition level from Step 3 add up to
175
187
  the project's covered and total lines for the same overall globs. If they
176
188
  don't, find the overlap or orphaned lines and fix the map; state any
@@ -185,16 +197,17 @@ and more tokens than a file-level rollup; that is the point.
185
197
  Decide for yourself which files and areas deserve a close look. Do not apply a
186
198
  fixed percentage cutoff: weigh each area's coverage against its criticality,
187
199
  so a critical area at a high percentage can still warrant scrutiny while a
188
- low-stakes area at a lower percentage may not. Always include every tracked
189
- file with no coverage data. State the reasoning behind your selection in the
190
- report.
200
+ low-stakes area at a lower percentage may not. Always include every file
201
+ matching the file globs that has no coverage data. State the reasoning behind
202
+ your selection in the report.
191
203
 
192
204
  For each selected file or area:
193
205
 
194
- 1. Get the uncovered lines (`cov-loupe -m cli -fJ uncovered <path>`); use
195
- `cov-loupe -m cli -fJ detailed <path>` or
196
- `cov-loupe -m cli -s uncovered -n 2 uncovered <path>` to see the source in
197
- context.
206
+ 1. Get the uncovered lines (`file_uncovered_lines` /
207
+ `cov-loupe uncovered <path>`). To see them in context, run
208
+ `cov-loupe uncovered <path>` with its source display set to uncovered
209
+ lines, or read the source file around them; the MCP tools give line
210
+ numbers and hit counts, not source.
198
211
  2. Characterize each cluster of uncovered lines: error/rescue path, edge-case
199
212
  branch, defensive guard, platform-specific code, dead code, debug/logging
200
213
  code, or core logic.
@@ -246,11 +259,12 @@ The report should have the following structure:
246
259
  ---
247
260
 
248
261
  ### Executive Summary
249
- - Commit cited and the results of the Step 1 checks.
262
+ - Commit cited, cov-loupe interface used (MCP or CLI), and the results of the
263
+ Step 1 checks.
250
264
  - The coverage file's path (relative to the project root), size, and
251
265
  modification time (UTC), so readers can tell which test run the report
252
266
  describes.
253
- - Overall line coverage (with and without tracked globs).
267
+ - Overall line coverage (with and without file globs).
254
268
  - The best- and worst-covered areas, and the top risk areas.
255
269
  - A **one-line verdict** (e.g. *"Strong domain coverage; payment error
256
270
  handling is the main gap"*).
@@ -269,7 +283,7 @@ percentage:
269
283
  | Area | Criticality | Code units | Covered | Total | % | Weakest unit (%) |
270
284
  |------|-------------|------------|---------|-------|---|------------------|
271
285
 
272
- List tracked files with no coverage data separately, with the areas they
286
+ List matching files with no coverage data separately, with the areas they
273
287
  belong to.
274
288
 
275
289
  Follow with a short interpretation of each area that stands out, positively or
@@ -297,7 +311,7 @@ citations.
297
311
 
298
312
  ### Data Caveats
299
313
  Reliance on the user's assurance that the last run was the complete, passing
300
- suite; tracked files missing from the coverage data; branch coverage being out
314
+ suite; matching files not in the coverage data; branch coverage being out
301
315
  of scope; ambiguous line assignments at area boundaries; anything else that
302
316
  limits confidence in the numbers.
303
317
 
@@ -322,7 +336,7 @@ table, give each task a ready-to-use prompt the user can give an AI assistant
322
336
  to implement it, keyed by its number.
323
337
 
324
338
  ### Appendix: Commands Run
325
- Every cov-loupe command and
339
+ Every cov-loupe call (MCP tool name and arguments, or CLI command) and
326
340
  freshness check used to produce the numbers, plus any aggregation script, so the
327
341
  report can be reproduced.
328
342
 
data/exe/agent-council CHANGED
@@ -4,12 +4,17 @@
4
4
  # agent-council — executable entry point. All code lives in lib/:
5
5
  # lib/agent_council.rb orchestration (AgentCouncil)
6
6
  # lib/agent_council/harnesses.rb harnesses by name (AgentCouncil::Harnesses)
7
- # lib/agent_council/harnesses/scaffold.rb read-only scaffolding every harness appends
7
+ # lib/agent_council/harnesses/harness.rb the base class every harness subclasses (Harness)
8
+ # lib/agent_council/harnesses/scaffold.rb read-only scaffolding every harness gives agents
8
9
  # lib/agent_council/harnesses/pi_harness.rb pi-specific behavior (AgentCouncil::Harnesses::PiHarness)
9
10
  # lib/agent_council/harnesses/claude_code_harness.rb
10
11
  # Claude Code-specific behavior (ClaudeCodeHarness)
11
12
  # lib/agent_council/harnesses/codex_harness.rb
12
13
  # Codex-specific behavior (CodexHarness)
14
+ # lib/agent_council/harnesses/opencode_harness.rb
15
+ # OpenCode-specific behavior (OpenCodeHarness)
16
+ # lib/agent_council/harnesses/antigravity_harness.rb
17
+ # Antigravity-specific behavior (AntigravityHarness)
13
18
  #
14
19
  # Usage, options, and AGENT_COUNCIL_OPTS: agent-council -h, and the README.
15
20
 
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # agent-council-ps — executable entry point; the command is
5
+ # AgentCouncil::Ps.main (lib/agent_council/ps.rb).
6
+
7
+ require_relative '../lib/agent_council/ps'
8
+
9
+ AgentCouncil::Ps.main(ARGV)
data/exe/pi-models CHANGED
@@ -1,39 +1,9 @@
1
1
  #!/usr/bin/env ruby
2
2
  # frozen_string_literal: true
3
3
 
4
- require_relative '../lib/agent_council/platform'
5
-
6
- AgentCouncil.abort_if_native_windows('pi-models')
4
+ # pi-models — executable entry point; the command is AgentCouncil::PiModels.main
5
+ # (lib/agent_council/pi_models.rb).
7
6
 
8
7
  require_relative '../lib/agent_council/pi_models'
9
8
 
10
- help_output = ARGV.delete('-h') || ARGV.delete('--help')
11
- json_output = ARGV.delete('--json') || ARGV.delete('-j')
12
- ids_output = ARGV.delete('--ids') || ARGV.delete('-i')
13
- ARGV.delete('--table') || ARGV.delete('-t') # table is the default format; accepted for explicitness
14
-
15
- if help_output
16
- puts AgentCouncil::PiModels.help_text
17
- exit
18
- end
19
-
20
- unless ARGV.empty?
21
- warn "pi-models: unknown option(s): #{ARGV.join(' ')}"
22
- warn "Try 'pi-models --help' for usage."
23
- exit 1
24
- end
25
-
26
- begin
27
- models = AgentCouncil::PiModels.fetch_models
28
- rescue AgentCouncil::PiModels::Error => e
29
- warn "pi-models: #{e.message}"
30
- exit 1
31
- end
32
-
33
- if json_output
34
- puts AgentCouncil::PiModels.format_as_json(models)
35
- elsif ids_output
36
- print AgentCouncil::PiModels.format_as_ids(models)
37
- else
38
- puts AgentCouncil::PiModels.format_as_table(models)
39
- end
9
+ AgentCouncil::PiModels.main(ARGV)
@@ -0,0 +1,249 @@
1
+ # frozen_string_literal: true
2
+
3
+ # AgentCouncil::Harnesses::AntigravityHarness — all knowledge specific to
4
+ # the Google Antigravity CLI harness: how to invoke `agy` for one agent,
5
+ # with its session permission denials and the shared read-only scaffolding,
6
+ # and how to read its stream-json output 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 Antigravity: an agent uses
11
+ # whatever account or provider `agy` would at the user's terminal (Google AI
12
+ # subscription, Gemini API key, or Vertex AI).
13
+
14
+ require 'json'
15
+ require_relative 'harness'
16
+
17
+ module AgentCouncil
18
+ module Harnesses
19
+ class AntigravityHarness < Harness
20
+ NAME = 'agy'
21
+
22
+ # Session-only permission overrides merged over the user's settings.json
23
+ # (never saved):
24
+ # - write_file(*) withholds the file-editing tools (write_file, edit_file)
25
+ # while preserving the user's allow rules (e.g. MCP servers);
26
+ # - execute_url(*) withholds browser actions that act outside the machine;
27
+ # - download_url(*) withholds direct URL downloads to disk.
28
+ # Shell commands stay governed by the user's agy settings and terminal
29
+ # sandbox (where commands can still write $TMPDIR).
30
+ SETTINGS = JSON.generate(
31
+ 'permissions' => { 'deny' => %w[write_file(*) execute_url(*) download_url(*)] }
32
+ ).freeze
33
+
34
+ # Invocation for one agent. The prompt is not part of argv: agy's -p
35
+ # flag takes a string argument rather than reading stdin, so we use
36
+ # --input-format stream-json instead (see stdin_data), which reads one
37
+ # NDJSON user message per line and finishes cleanly on EOF. provider is
38
+ # not passed: agy takes none, so an entry's provider only labels the
39
+ # agent. --model comes before --settings so the model slug stays near
40
+ # the start of the command line.
41
+ def self.argv(_provider, model)
42
+ [
43
+ NAME,
44
+ '--input-format', 'stream-json', # NDJSON user message on stdin
45
+ '--output-format', 'stream-json', # JSONL event stream on stdout
46
+ '--disable-slash-commands', # keep prompts starting with '/' literal
47
+ '--model', model,
48
+ '--settings', SETTINGS
49
+ ]
50
+ end
51
+
52
+ # One NDJSON user-message line for --input-format stream-json. agy has
53
+ # no system-prompt flag or settings key, so the shared read-only
54
+ # scaffolding is prepended to the user message.
55
+ def self.stdin_data(prompt)
56
+ str = prompt.to_s
57
+ clean_prompt =
58
+ if str.encoding == Encoding::UTF_8
59
+ str.scrub
60
+ else
61
+ str.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
62
+ end
63
+ text = "#{Harnesses.scaffold_text}\n\n#{clean_prompt}"
64
+ "#{JSON.generate('event' => 'user', 'message' => { 'content' => text })}\n"
65
+ end
66
+
67
+ # --- event stream reading ---
68
+
69
+ # The payload hashes for events whose 'event' key equals name, in order.
70
+ # Antigravity keys its stream by 'event' (with the payload under a key
71
+ # of the same name), not by 'type', so Harness.last_event does not apply.
72
+ def self.payloads(jsonl, name)
73
+ events(jsonl).filter_map do |event|
74
+ payload = event[name] if event['event'] == name
75
+ payload if payload.is_a?(Hash)
76
+ end
77
+ end
78
+ private_class_method :payloads
79
+
80
+ # The agent's terminal result payload, or nil if the stream has none
81
+ # (e.g. for an agent killed with SIGKILL).
82
+ def self.result_event(jsonl)
83
+ payloads(jsonl, 'result').last
84
+ end
85
+ private_class_method :result_event
86
+
87
+ # The agent's response steps, grouped by step_index in order, with each
88
+ # step's streamed text_delta fragments joined.
89
+ def self.assistant_messages(jsonl)
90
+ steps = payloads(jsonl, 'step_update').select { |step| step['step_type'] == 'agent_response' }
91
+ steps.group_by { |step| step['step_index'] }.map do |index, group|
92
+ text = group.filter_map { |step| step['text_delta'] if step['text_delta'].is_a?(String) }.join
93
+ { 'step_index' => index, 'text' => text }
94
+ end
95
+ end
96
+
97
+ # Finish reasons indicating a run was cut off or failed even if status
98
+ # is reported as "SUCCESS".
99
+ UNUSABLE_FINISH_REASONS = %w[
100
+ print_timeout interrupted error length content-filter max_tokens
101
+ ].freeze
102
+
103
+ # The final response: the result payload's text, for an agent that
104
+ # succeeded without an unusable finished_reason.
105
+ def self.final_response(jsonl)
106
+ result = result_event(jsonl)
107
+ return nil unless result && result['status'] == 'SUCCESS'
108
+ return nil if UNUSABLE_FINISH_REASONS.include?(result['finished_reason'])
109
+
110
+ nonblank_text(result['response'])
111
+ end
112
+
113
+ # Our usage keys, each mapped to Antigravity's name for it. Antigravity's
114
+ # input_tokens excludes cache_read_tokens, and its output_tokens includes
115
+ # thinking_tokens; it reports neither cache writes nor cost.
116
+ USAGE_KEYS = { 'input' => 'input_tokens',
117
+ 'output' => 'output_tokens',
118
+ 'cache_read' => 'cache_read_tokens' }.freeze
119
+
120
+ # Token usage as AgentCouncil expects it (see Harness), from the
121
+ # terminal result event alone: it totals all steps in the run, whereas
122
+ # step_update usage is per-step. Antigravity prices nothing, so there is
123
+ # no 'cost'. nil when the stream has no result event or reports no usage.
124
+ def self.usage(jsonl)
125
+ result = result_event(jsonl)
126
+ usage = result && result['usage']
127
+ return nil unless usage.is_a?(Hash)
128
+
129
+ totals = USAGE_KEYS.transform_values { |key| count(usage[key]) }.merge('cache_write' => 0)
130
+ usage_result(totals)
131
+ end
132
+
133
+ # Why the agent produced no usable report, or nil. A failed or
134
+ # interrupted run has a result event with status other than "SUCCESS"
135
+ # (e.g. "ERROR") or an unusable finished_reason; one that succeeded
136
+ # with no text is reported as such (noting any refused actions).
137
+ def self.error_message(jsonl)
138
+ result = result_event(jsonl)
139
+ return agy_error_line(jsonl) || 'the stream has no result event' unless result
140
+
141
+ unless result['status'] == 'SUCCESS'
142
+ return error_reason(result) || missing_reason(result)
143
+ end
144
+
145
+ reason = result['finished_reason']
146
+ return "stopped early (reason: #{reason})" if UNUSABLE_FINISH_REASONS.include?(reason)
147
+ return nil if nonblank_text(result['response'])
148
+
149
+ actions = denied_action_names(result)
150
+ return "the result event has no text (refused: #{actions.join(', ')})" unless actions.empty?
151
+
152
+ 'the result event has no text'
153
+ end
154
+
155
+ # An AGY_ERROR line emitted when agy fails without a result event (e.g.
156
+ # on stderr for print-timeout or startup errors). Extracts short_error
157
+ # (or message/error/status/code) from a JSON payload after "AGY_ERROR:"
158
+ # when present, else returns the stripped line.
159
+ def self.agy_error_line(text)
160
+ line = text.each_line.map(&:strip).find { |l| l.start_with?('AGY_ERROR') }
161
+ return nil unless line
162
+
163
+ payload = line.sub(/\AAGY_ERROR:?\s*/, '')
164
+ parsed = begin
165
+ JSON.parse(payload)
166
+ rescue JSON::ParserError
167
+ nil
168
+ end
169
+ if parsed.is_a?(Hash)
170
+ keys = %w[short_error message error status code]
171
+ return nonblank_strings(keys.map { |k| parsed[k] }).first || line
172
+ end
173
+
174
+ line
175
+ end
176
+ private_class_method :agy_error_line
177
+
178
+ # The reason a failed result payload gives, or nil if it gives none.
179
+ # Falls back to finished_reason when error is blank.
180
+ def self.error_reason(result)
181
+ error = nonblank_text(result['error'])&.strip
182
+ return error if error
183
+
184
+ reason = nonblank_text(result['finished_reason'])&.strip
185
+ "stopped early (reason: #{reason})" if reason
186
+ end
187
+ private_class_method :error_reason
188
+
189
+ def self.missing_reason(result)
190
+ return 'the result event has no status' unless nonblank_text(result['status'])
191
+
192
+ 'the agent failed and gave no reason'
193
+ end
194
+ private_class_method :missing_reason
195
+
196
+ # Why an agent that exited nonzero failed. Antigravity explains failures
197
+ # (unknown model, interruption, auth/quota errors) in a result event with
198
+ # status != "SUCCESS", so that comes first; otherwise an AGY_ERROR line
199
+ # on stderr or stdout, then stderr's first line, then any stream-level
200
+ # error (e.g. a blank result), else NO_ERROR_OUTPUT.
201
+ def self.exit_detail(stdout, stderr)
202
+ result = result_event(stdout)
203
+ reason = error_reason(result) if result && result['status'] != 'SUCCESS'
204
+ return reason if reason
205
+
206
+ agy_error_line(stderr) ||
207
+ agy_error_line(stdout) ||
208
+ first_line(stderr) ||
209
+ (error_message(stdout) if result) ||
210
+ NO_ERROR_OUTPUT
211
+ end
212
+
213
+ # Warnings about an agent, succeeded or not: the tool calls Antigravity
214
+ # soft-denied because headless mode cannot prompt for approval, reported
215
+ # in the result event's denied_actions list.
216
+ def self.warnings(jsonl)
217
+ result = result_event(jsonl)
218
+ denials = result && result['denied_actions']
219
+ return [] unless denials.is_a?(Array) && !denials.empty?
220
+
221
+ actions = denied_action_names(result)
222
+ [listing("Antigravity refused #{denials.size} tool call#{'s' unless denials.size == 1}",
223
+ actions, MAX_LISTED_ACTIONS)]
224
+ end
225
+
226
+ # Distinct refused actions named in a warning, so an agent refused many
227
+ # times still gets a warning of a readable length.
228
+ MAX_LISTED_ACTIONS = 5
229
+
230
+ # Distinct labels for a result event's denied_actions list, in order.
231
+ def self.denied_action_names(result)
232
+ denials = result && result['denied_actions']
233
+ return [] unless denials.is_a?(Array)
234
+
235
+ denials.map { |denial| denied_action(denial) }.uniq
236
+ end
237
+ private_class_method :denied_action_names
238
+
239
+ # A refused action's label: its display_name (e.g. "Bash"), else its
240
+ # action key (e.g. "command"), else "unknown tool".
241
+ def self.denied_action(denial)
242
+ return 'unknown tool' unless denial.is_a?(Hash)
243
+
244
+ nonblank_strings([denial['display_name'], denial['action']]).first || 'unknown tool'
245
+ end
246
+ private_class_method :denied_action
247
+ end
248
+ end
249
+ end