agent-cli-runtime 0.2.4 → 0.2.5

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e0202bb311856ad96fcd486517d11cfc7175db0102a188920c4d851bf338b7d6
4
- data.tar.gz: 2e72a23b5e7a021fc439a9ce8ef34bf166c0af0141de491a27686d6f3ba3f139
3
+ metadata.gz: cdc9f14fbb7d9e17922d9689d51f101a7f0416c57b178112f3cae8dd38782e2e
4
+ data.tar.gz: 7620b45bfb0f64cad4be03131c0075a2721e2c7c2bf8dd609b7e36d4884d2dcb
5
5
  SHA512:
6
- metadata.gz: b3736f38aa29d809028b1e99c9df1dd17ddb4a210382e89f752def380e84cf22e3f144da2d10ee6c86c2dab8496865a35347196277367a0734b9c39991c33f0e
7
- data.tar.gz: 5adacccc362958a8cc9a2eeab22b9100041101de4795d7f31ddaa563406ec031f6b3662e84eca058b144ab86ee41d1505c42baa267c1eae436cda4566680b100
6
+ metadata.gz: e3217709874457c652fcb20b994d134ea7056f58112e07525c4162597bb6d932b87896988ab0eb64a133d548433ab0a48b9d043dd39e2e1aee944fafa247cc73
7
+ data.tar.gz: f92516a4af7caeb5909fe3ed66b55b50a0d273e982ee371e8a32620c9e599573d2ee86958bd9db78f5f8a0e6e4b105d944b9467a85ea0b5e7b62c4b5630e03e0
data/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.2.5 - 2026-11-26
6
+
7
+ Adds built-in **Antigravity CLI (`agy`)** and **Muse Code (`muse`)** providers alongside OpenCode 2.x compatibility and sharper provider error and environment handling. All changes are additive and backwards-compatible with `~> 0.2.0` consumers.
8
+
9
+ ### New providers
10
+
11
+ - **Antigravity CLI (`:agy`)**: Seventh built-in provider, appended after `:muse` without changing existing provider ordering. Compiles headless print mode (`agy --input-format=text --dangerously-skip-permissions --output-format stream-json`) over piped stdin so large prompts stay out of `argv`, with repeatable `--add-dir`, `--model`, and `--effort` flags. Includes binary-safe OAuth token probing (`~/.gemini/antigravity-cli/antigravity-oauth-token`), `step_update`/`result` usage extraction (`input_tokens`, `output_tokens`, `thinking_tokens` as `reasoning`, `cache_read_tokens` as `cache_read`, `output_includes_reasoning: true`), and non-`SUCCESS` `result` error extraction. Scoped `read-only` / `workspace-write` flags fail closed.
12
+ - **Muse Code (`:muse`)**: Sixth built-in provider, appended after `:opencode`. Compiles `muse exec --prompt-file=/dev/stdin --json` with tempfile-backed stdin, model and reasoning-effort pinning, sandboxed `workspace-write` and `read-only` modes, `run.usage` per-model token aggregation, `run.terminal` error extraction, and XDG config/data resolution. Adds three reusable profile hooks: dual-form version parsing (when one numeric core appears twice, e.g. `1.4.14 (1.4.14-R7309.1)`), `configuration_directory_probe`, and `prompt_argument`.
13
+
14
+ ### Provider compatibility & error handling
15
+
16
+ - **OpenCode 2.x private servers (`--standalone`)**: The route probe detects `--standalone` from `run --help`, records `:private_server` capability evidence, and threads the flag through `auth list`, `models`, prepared `run`, and sanitized `export` so isolated runs do not collide with OpenCode 2.x's shared background server. OpenCode 1.x is unchanged.
17
+ - **OpenCode 2.x flattened error payloads**: Parses both OpenCode 1.x nested (`error.name` + `error.data.message`) and 2.x flattened (`error.type` + `error.message` + `error.status`) error events, including pre-session errors without a `sessionID`, so upstream rate limits surface as typed `rate_limited` errors instead of `MalformedOutput`.
18
+ - **Claude quota window events**: Extracts Claude's message-free rejected `rate_limit_event` for `five_hour` and `seven_day` account windows as a typed `provider_limit` with bounded quota text.
19
+ - **Codex transport retry filtering**: Skips `Reconnecting... n/m` progress notices in provider error extraction so transient reconnect lines do not mask the terminal error (such as a `401` from a revoked login), and parses `unexpected status NNN` HTTP status codes.
20
+
21
+ ### Isolation & security
22
+
23
+ - **OpenCode probe & overlay environment hardening**: `ProbeRequest` restricts environment overrides to `OPENCODE_OVERLAY_ENVIRONMENT_KEYS` and scrubs Ruby/Bundler injection variables (`RUBYOPT`, `RUBYLIB`, `GEM_HOME`, `GEM_PATH`, `BUNDLE_BIN_PATH`, `BUNDLE_GEMFILE`) last; both `ProbeRequest` and `OpenCodePreparationRequest` reject credential keys overlapping `SCRUBBED_RUNTIME_ENVIRONMENT_KEYS`.
24
+
5
25
  ## 0.2.4 - 2026-08-25
6
26
 
7
27
  - Expose the OpenCode permission compiler independently from the prepared
data/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Agent CLI Runtime
2
2
 
3
3
  Agent CLI Runtime gives Ruby applications one stable integration layer for
4
- Claude Code, Codex CLI, Pi, Grok CLI, and OpenCode. It builds provider-specific
4
+ Claude Code, Codex CLI, Pi, Grok CLI, OpenCode, Muse Code, and Antigravity CLI. It builds provider-specific
5
5
  commands from a shared request model, checks local versions and named
6
6
  capabilities, and normalizes usage and results afterward. Centralized profiles,
7
7
  environment rules, and parsers make agent providers easier to add, switch, and
@@ -6,7 +6,7 @@ Gem::Specification.new do |spec|
6
6
  spec.authors = [ "Ivan Kuznetsov" ]
7
7
  spec.email = [ "ivan@ikuznetsov.com" ]
8
8
  spec.summary =
9
- "One Ruby API for Claude Code, Codex CLI, Pi, Grok CLI, and OpenCode"
9
+ "One Ruby API for Claude Code, Codex CLI, Pi, Grok CLI, OpenCode, Muse Code, and Antigravity CLI"
10
10
  spec.description = <<~DESC
11
11
  Agent CLI Runtime gives Ruby applications one stable integration layer for
12
12
  local coding-agent CLIs. It builds provider-specific commands from a shared
@@ -43,7 +43,7 @@ Gem::Specification.new do |spec|
43
43
  spec.executables = [ "agent-runtime" ]
44
44
  spec.require_paths = [ "lib" ]
45
45
 
46
- spec.add_dependency "json", ">= 2.7", "< 3.0"
46
+ spec.add_dependency "json", ">= 2.7", "< 4.0"
47
47
  spec.add_dependency "open3", "~> 0.2"
48
48
  spec.add_dependency "timeout", ">= 0.4", "< 1.0"
49
49
  end
@@ -47,6 +47,19 @@ module AgentCliRuntime
47
47
  DEFAULT.call(event)
48
48
  end
49
49
 
50
+ # Codex reports each transport retry as its own "error" event
51
+ # ("Reconnecting... 2/5 (stream disconnected ...)") before the terminal
52
+ # error and turn.failed. Callers keep the first provider error, so a
53
+ # retry notice used to mask the real failure (for example a 401 from a
54
+ # revoked login). Retry notices are progress, not the failure.
55
+ CODEX_RETRY_NOTICE = /\AReconnecting\.\.\.\s*\d+\s*\/\s*\d+\b/
56
+ CODEX = lambda do |event|
57
+ text = DEFAULT.call(event)
58
+ next nil if text.is_a?(String) && text.match?(CODEX_RETRY_NOTICE)
59
+
60
+ text
61
+ end
62
+
50
63
  # pi keeps the envelope type ("message_start"/"message_end") and moves the
51
64
  # terminal state into stopReason. Provider refusals use
52
65
  # stopReason=error/errorMessage. A model that consumes its entire output
@@ -67,15 +80,61 @@ module AgentCliRuntime
67
80
  end
68
81
  end
69
82
 
70
- # OpenCode keeps provider failures under error.data.message rather than
71
- # the top-level/message and error.message shapes used by the default
72
- # extractor. Read only the dedicated error event so ordinary model text
73
- # cannot forge a provider-limit signal.
83
+ # OpenCode 1.x keeps provider failures under error.data.message; 2.x
84
+ # flattens them to error.message (with error.type and error.status).
85
+ # Read only the dedicated error event so ordinary model text cannot forge
86
+ # a provider-limit signal.
74
87
  OPENCODE = lambda do |event|
75
88
  next nil unless event.is_a?(Hash) && event["type"] == "error"
76
89
 
77
- data = event.dig("error", "data")
78
- message = data["message"] if data.is_a?(Hash)
90
+ ErrorExtractors.opencode_error_message(event["error"])
91
+ end
92
+
93
+ # Muse terminates every headless run with one `run.terminal.*` event.
94
+ # Only that run-level terminal is authoritative: `task.lifecycle.failed`
95
+ # also fires for internal reminder children on otherwise successful
96
+ # runs, so task-level failures must never become provider errors.
97
+ MUSE = lambda do |event|
98
+ next nil unless event.is_a?(Hash)
99
+ next nil unless event["payload_type"].to_s.start_with?("run.terminal.")
100
+
101
+ payload = event["payload"]
102
+ next nil unless payload.is_a?(Hash)
103
+
104
+ terminal = payload["terminal"].to_s
105
+ next nil if terminal.empty? || terminal == "completed"
106
+
107
+ reason = payload["reason"].to_s.strip
108
+ reason.empty? ? "muse run #{terminal}" : reason
109
+ end
110
+
111
+ # Antigravity CLI (`agy`) terminates every stream-json run with an
112
+ # `{"event":"result","result":{...}}` envelope. Non-SUCCESS statuses
113
+ # (`ERROR`, `CANCELED`, etc.) carry the provider/CLI diagnostic in
114
+ # `result.error`.
115
+ AGY = lambda do |event|
116
+ next nil unless event.is_a?(Hash)
117
+
118
+ case event["event"]
119
+ when "result"
120
+ result = event["result"]
121
+ next nil unless result.is_a?(Hash)
122
+
123
+ status = result["status"].to_s.upcase
124
+ next nil if status.empty? || status == "SUCCESS"
125
+
126
+ message = result["error"].to_s.strip
127
+ message.empty? ? "agy run #{status.downcase}" : message
128
+ when "error"
129
+ ErrorExtractors.message_from(event)
130
+ end
131
+ end
132
+
133
+ def opencode_error_message(error)
134
+ return nil unless error.is_a?(Hash)
135
+
136
+ data = error["data"]
137
+ message = data.is_a?(Hash) ? data["message"] : error["message"]
79
138
  message if message.is_a?(String) && !message.strip.empty?
80
139
  end
81
140
 
@@ -16,9 +16,15 @@ module AgentCliRuntime
16
16
  "sanitized export inspection requires an OpenCode invocation"
17
17
  end
18
18
 
19
+ # Export through a private server exactly when the run used one: both
20
+ # read the same overlay data home, and neither may attach to (or
21
+ # start) the shared background service.
22
+ server_arguments =
23
+ OpenCode::Probe.supported_arguments(prepared.invocation, :private_server)
19
24
  InspectionCommand.new(
20
25
  argv: [
21
- prepared.executable, "export", parsed_run.session_id, "--sanitize"
26
+ prepared.executable, "export", parsed_run.session_id, "--sanitize",
27
+ *server_arguments
22
28
  ],
23
29
  stdin_data: nil,
24
30
  environment: prepared.environment,
@@ -443,6 +443,12 @@ module AgentCliRuntime
443
443
  trusted = source.trusted_cli_arguments.dup
444
444
  trusted.concat([ "--dir", roots.fetch(:working) ])
445
445
  trusted << "--pure" if pure
446
+ # Run on a private server when the probe saw `--standalone`, so this
447
+ # invocation's overlay environment is the one the server loads.
448
+ trusted.concat(
449
+ OpenCode::Probe.supported_arguments(probe_result, :private_server) -
450
+ trusted
451
+ )
446
452
  request = Request.new(
447
453
  profile: profile,
448
454
  prompt: source.prompt,
@@ -7,6 +7,16 @@ module AgentCliRuntime
7
7
  --model --variant --format --dir --pure --auto
8
8
  ].freeze
9
9
  MODEL_INVENTORY_TIMEOUT_SECONDS = 30
10
+ # OpenCode 2.x serves CLI commands from one shared per-user background
11
+ # server on a fixed loopback port, starting it when absent. That server
12
+ # was started with some other command's environment, so a
13
+ # per-invocation overlay (XDG homes, OPENCODE_CONFIG, pure mode, staged
14
+ # credentials) is not guaranteed to reach an attached command, and a
15
+ # command whose overlay differs from the server's identity fails
16
+ # because the port is taken.
17
+ # `--standalone` gives each command a private server that ends with it.
18
+ # OpenCode 1.x has no such flag, so it is used only when advertised.
19
+ PRIVATE_SERVER_FLAG = "--standalone"
10
20
  SAFE_ENVIRONMENT_KEYS = %w[
11
21
  HOME LANG LC_ALL LOGNAME PATH SHELL SSL_CERT_DIR SSL_CERT_FILE
12
22
  TMPDIR USER
@@ -82,6 +92,9 @@ module AgentCliRuntime
82
92
  evidence.concat(REQUIRED_RUN_FLAGS.map do |flag|
83
93
  evidence(profile, capability_for(flag), [ flag ])
84
94
  end)
95
+ server_arguments = private_server_arguments(run_help)
96
+ evidence << evidence(profile, :private_server, server_arguments) unless
97
+ server_arguments.empty?
85
98
 
86
99
  export_help = capture!(
87
100
  profile, child_env, "export", "--help", executable: request.executable
@@ -93,7 +106,8 @@ module AgentCliRuntime
93
106
  evidence << evidence(profile, :sanitized_export, [ "--sanitize" ])
94
107
 
95
108
  auth_output = capture!(
96
- profile, child_env, "auth", "list", executable: request.executable
109
+ profile, child_env, "auth", "list", *server_arguments,
110
+ executable: request.executable
97
111
  )
98
112
  configured_key = request.credential_environment_keys.find do |key|
99
113
  !env[key].to_s.empty?
@@ -120,6 +134,7 @@ module AgentCliRuntime
120
134
  inventory_variants = if configured_variants.nil?
121
135
  models_output = capture!(
122
136
  profile, child_env, "models", request.route.provider, "--verbose",
137
+ *server_arguments,
123
138
  executable: request.executable,
124
139
  timeout_sec: MODEL_INVENTORY_TIMEOUT_SECONDS
125
140
  )
@@ -165,6 +180,23 @@ module AgentCliRuntime
165
180
  raise ProbeError, Redactor.diagnostic(e)
166
181
  end
167
182
 
183
+ # The private-server arguments a CLI whose help text is +help+ accepts:
184
+ # `["--standalone"]` when advertised, otherwise empty.
185
+ def private_server_arguments(help)
186
+ advertised?(help.to_s, PRIVATE_SERVER_FLAG) ?
187
+ [ PRIVATE_SERVER_FLAG ].freeze : [].freeze
188
+ end
189
+
190
+ # The arguments recorded by supported +capability+ evidence on +subject+
191
+ # (a RouteProbeResult or CompiledInvocation), or empty when +subject+
192
+ # carries no such evidence.
193
+ def supported_arguments(subject, capability)
194
+ evidence = Array(subject&.capability_evidence).find do |item|
195
+ item.capability == capability && item.supported
196
+ end
197
+ evidence ? evidence.arguments : [].freeze
198
+ end
199
+
168
200
  def child_environment(profile, request, env:)
169
201
  selected = (ENV.keys | env.keys).to_h { |key| [ key, nil ] }
170
202
  env.each do |key, value|
@@ -173,16 +205,26 @@ module AgentCliRuntime
173
205
  selected[key] = value.to_s
174
206
  end
175
207
  end
176
- %w[
177
- BUNDLE_BIN_PATH BUNDLE_GEMFILE GEM_HOME GEM_PATH RUBYLIB RUBYOPT
178
- ].each { |key| selected[key] = nil }
179
208
  profile.env_bin_override_keys.each do |key|
180
209
  selected[key] = env[key].to_s unless env[key].to_s.empty?
181
210
  end
182
211
  request.credential_environment_keys.each do |key|
183
212
  selected[key] = env[key].to_s unless env[key].to_s.empty?
184
213
  end
185
- selected.merge(request.environment).freeze
214
+ # The overlay is the only caller-supplied channel into the child
215
+ # environment. Filtering here keeps the denylist cleanup final even if
216
+ # a request is built with keys outside the validated overlay contract.
217
+ request.environment.each do |key, value|
218
+ next unless OPENCODE_OVERLAY_ENVIRONMENT_KEYS.include?(key)
219
+
220
+ selected[key] = value.to_s
221
+ end
222
+ # The denylist scrub must stay last: every caller-controlled channel
223
+ # above (credential keys, executable overrides, the overlay) copies
224
+ # selected values into the child environment, so no selection may
225
+ # reintroduce a scrubbed runtime injection key.
226
+ SCRUBBED_RUNTIME_ENVIRONMENT_KEYS.each { |key| selected[key] = nil }
227
+ selected.freeze
186
228
  end
187
229
  private_class_method :child_environment
188
230
 
@@ -60,17 +60,22 @@ module AgentCliRuntime
60
60
  next
61
61
  end
62
62
 
63
- event_session = required_string(event, "sessionID", "event sessionID")
64
- session_id ||= event_session
65
- malformed!("OpenCode run sessionID changed within one capture") unless
66
- session_id == event_session
67
-
68
63
  if type == "error"
64
+ # OpenCode 2.x reports failures raised before a session exists
65
+ # (for example an empty prompt) with an empty sessionID.
66
+ error_session = validate_additive_session!(event, session_id) unless
67
+ event["sessionID"] == ""
68
+ session_id ||= error_session
69
69
  validate_error!(event)
70
70
  error_seen = true
71
71
  next
72
72
  end
73
73
 
74
+ event_session = required_string(event, "sessionID", "event sessionID")
75
+ session_id ||= event_session
76
+ malformed!("OpenCode run sessionID changed within one capture") unless
77
+ session_id == event_session
78
+
74
79
  part = required_hash(event, "part", "event part")
75
80
  validate_part!(part, type, session_id)
76
81
  message_id = required_string(part, "messageID", "part messageID")
@@ -260,11 +265,18 @@ module AgentCliRuntime
260
265
  end
261
266
  private_class_method :validate_part!
262
267
 
268
+ # OpenCode 1.x: {"name": ..., "data": {"message": ...}}.
269
+ # OpenCode 2.x: {"type": ..., "message": ..., "status"?: ...}.
263
270
  def validate_error!(event)
264
271
  error = required_hash(event, "error", "error event payload")
265
- required_string(error, "name", "error name")
266
- data = required_hash(error, "data", "error data")
267
- required_string(data, "message", "error message")
272
+ if error.key?("name") || error.key?("data")
273
+ required_string(error, "name", "error name")
274
+ data = required_hash(error, "data", "error data")
275
+ required_string(data, "message", "error message")
276
+ else
277
+ required_string(error, "type", "error type")
278
+ required_string(error, "message", "error message")
279
+ end
268
280
  end
269
281
  private_class_method :validate_error!
270
282
 
@@ -310,9 +322,8 @@ module AgentCliRuntime
310
322
  error = event["error"]
311
323
  next unless error.is_a?(Hash)
312
324
 
313
- name = error["name"].to_s
314
- data = error["data"]
315
- message = data.is_a?(Hash) ? data["message"].to_s : ""
325
+ name = (error["name"] || error["type"]).to_s
326
+ message = ErrorExtractors.opencode_error_message(error).to_s
316
327
  [ name, message ].reject(&:empty?).join(": ")
317
328
  rescue JSON::ParserError
318
329
  nil
@@ -23,7 +23,8 @@ module AgentCliRuntime
23
23
  :permission_skip_flag, :workspace_write_flags,
24
24
  :read_only_flags, :add_dir_flag, :tool_scope_flags,
25
25
  :budget_flag, :output_format_flags, :version_flag,
26
- :min_version, :prompt_style, :model_argument_builder,
26
+ :min_version, :prompt_style, :prompt_argument,
27
+ :model_argument_builder,
27
28
  :effort_argument_builder, :launcher_identity,
28
29
  :cli_capabilities, :declared_capability_support,
29
30
  :credential_environment_keys, :configuration_environment_key,
@@ -36,13 +37,15 @@ module AgentCliRuntime
36
37
  workspace_write_flags: [], read_only_flags: [],
37
38
  add_dir_flag: nil, tool_scope_flags: {}, budget_flag: nil,
38
39
  output_format_flags: [], min_version: nil,
39
- prompt_style: :positional, model_argument_builder: nil,
40
+ prompt_style: :positional, prompt_argument: nil,
41
+ model_argument_builder: nil,
40
42
  effort_argument_builder: nil, launcher_identity: nil,
41
43
  usage_extractor: nil, error_extractor: nil,
42
44
  auth_configuration_probe: nil,
43
45
  cli_capabilities: {}, raw_cli_arguments_supported: false,
44
46
  credential_environment_keys: [], configuration_environment_key: nil,
45
47
  default_configuration_directory: nil,
48
+ configuration_directory_probe: nil,
46
49
  permission_policy_required: false, result_parser: nil,
47
50
  version_check_timeout_sec: CAPTURE_TIMEOUT_SECONDS)
48
51
  normalized_prompt_style = prompt_style.to_sym
@@ -66,6 +69,8 @@ module AgentCliRuntime
66
69
  @version_flag = immutable_string(version_flag)
67
70
  @min_version = min_version.nil? ? nil : immutable_string(min_version)
68
71
  @prompt_style = normalized_prompt_style
72
+ @prompt_argument =
73
+ prompt_argument.nil? ? nil : immutable_string(prompt_argument)
69
74
  @model_argument_builder = model_argument_builder
70
75
  @effort_argument_builder = effort_argument_builder
71
76
  @launcher_identity =
@@ -84,6 +89,7 @@ module AgentCliRuntime
84
89
  @default_configuration_directory = optional_relative_directory(
85
90
  default_configuration_directory
86
91
  )
92
+ @configuration_directory_probe = configuration_directory_probe
87
93
  @permission_policy_required = permission_policy_required == true
88
94
  @result_parser = result_parser
89
95
  @version_check_timeout_sec = Float(version_check_timeout_sec)
@@ -188,12 +194,16 @@ module AgentCliRuntime
188
194
  raise VersionError,
189
195
  "could not parse #{@name} #{@version_flag} output"
190
196
  end
191
- if versions.length > 1
197
+ # A CLI may print one version twice in different forms (Muse prints
198
+ # "1.4.14 (1.4.14-R7309.1)"). That is one version, not ambiguity: only
199
+ # distinct numeric cores disagree about what is installed.
200
+ cores = versions.map { |value| value[/\A\d+\.\d+\.\d+/] }.uniq
201
+ if cores.length > 1
192
202
  raise VersionError,
193
203
  "ambiguous #{@name} #{@version_flag} output: " \
194
204
  "#{versions.join(', ')}"
195
205
  end
196
- version = versions.fetch(0)
206
+ version = versions.length == 1 ? versions.fetch(0) : cores.fetch(0)
197
207
  if @min_version &&
198
208
  Gem::Version.new(version) < Gem::Version.new(@min_version)
199
209
  raise VersionError,
@@ -256,6 +266,10 @@ module AgentCliRuntime
256
266
  end
257
267
 
258
268
  def configuration_directory(home: nil, env: ENV)
269
+ if @configuration_directory_probe
270
+ resolved = @configuration_directory_probe.call(home: home, env: env)
271
+ return File.expand_path(resolved) if resolved
272
+ end
259
273
  if @configuration_environment_key
260
274
  configured = env[@configuration_environment_key].to_s
261
275
  unless configured.empty?
@@ -66,7 +66,7 @@ module AgentCliRuntime
66
66
 
67
67
  def auth_from_file(path, source:)
68
68
  configured = File.file?(path) &&
69
- !File.read(path).strip.match?(/\A(?:|\{\s*\})\z/m)
69
+ !File.binread(path).strip.match?(/\A(?:|\{\s*\})\z/m)
70
70
  AuthConfiguration.new(
71
71
  status: configured ? :configured : :missing,
72
72
  source: source
@@ -103,6 +103,61 @@ module AgentCliRuntime
103
103
  home_path(home, ".grok", "auth.json")
104
104
  end
105
105
 
106
+ # Muse keeps credentials and settings under the XDG config root
107
+ # ($XDG_CONFIG_HOME/muse, default ~/.config/muse). It has no config-dir
108
+ # environment override of its own, so XDG_CONFIG_HOME is the only
109
+ # relocation lever and it names the base, not the muse directory.
110
+ def muse_configuration_directory(home:, env:)
111
+ xdg = env["XDG_CONFIG_HOME"]
112
+ unless xdg.to_s.empty?
113
+ unless File.absolute_path?(xdg)
114
+ raise ArgumentError, "XDG_CONFIG_HOME must be absolute"
115
+ end
116
+
117
+ return File.join(File.expand_path(xdg), "muse")
118
+ end
119
+
120
+ base = home || env["HOME"]
121
+ base = nil if base.to_s.empty?
122
+ home_path(base, ".config", "muse")
123
+ end
124
+
125
+ def muse_auth_path(home:, env:)
126
+ File.join(muse_configuration_directory(home:, env:), "auth.json")
127
+ end
128
+
129
+ # Plugin state (installed.json, package cache) lives under the XDG data
130
+ # root ($XDG_DATA_HOME/muse, default ~/.local/share/muse), not beside
131
+ # the settings in the config root.
132
+ def muse_data_directory(home:, env:)
133
+ xdg = env["XDG_DATA_HOME"]
134
+ unless xdg.to_s.empty?
135
+ unless File.absolute_path?(xdg)
136
+ raise ArgumentError, "XDG_DATA_HOME must be absolute"
137
+ end
138
+
139
+ return File.join(File.expand_path(xdg), "muse")
140
+ end
141
+
142
+ base = home || env["HOME"]
143
+ base = nil if base.to_s.empty?
144
+ home_path(base, ".local", "share", "muse")
145
+ end
146
+
147
+ # Antigravity CLI (`agy`) stores settings and its fallback OAuth token
148
+ # under `~/.gemini/antigravity-cli`, while skills and plugins live under
149
+ # `~/.gemini/config`. Neither path has a CLI-specific environment override;
150
+ # both follow `HOME`.
151
+ def agy_state_directory(home:, env:)
152
+ base = home || env["HOME"]
153
+ base = nil if base.to_s.empty?
154
+ home_path(base, ".gemini", "antigravity-cli")
155
+ end
156
+
157
+ def agy_auth_path(home:, env:)
158
+ File.join(agy_state_directory(home:, env:), "antigravity-oauth-token")
159
+ end
160
+
106
161
  def opencode_auth_path(home:, env:)
107
162
  data_home = env["XDG_DATA_HOME"]
108
163
  if !data_home.to_s.empty?
@@ -203,6 +258,7 @@ module AgentCliRuntime
203
258
  ->(effort) { [ "-c", "model_reasoning_effort=#{effort}" ] },
204
259
  launcher_identity: "codex-cli/v1",
205
260
  usage_extractor: UsageExtractors::CODEX,
261
+ error_extractor: ErrorExtractors::CODEX,
206
262
  credential_environment_keys: %w[OPENAI_API_KEY],
207
263
  configuration_environment_key: "CODEX_HOME",
208
264
  default_configuration_directory: ".codex",
@@ -323,7 +379,10 @@ module AgentCliRuntime
323
379
  working_directory: [ "run", "--dir" ],
324
380
  model_variant: [ "run", "--variant" ],
325
381
  pure: [ "run", "--pure" ],
326
- sanitized_export: [ "export", "--sanitize" ]
382
+ sanitized_export: [ "export", "--sanitize" ],
383
+ # OpenCode 2.x only: a private server instead of the shared
384
+ # background service. The route probe records it when advertised.
385
+ private_server: [ "run", "--standalone" ]
327
386
  },
328
387
  auth_configuration_probe: lambda do |home:, env:|
329
388
  if env_configured?(env, *PI_CREDENTIAL_ENVIRONMENT_KEYS)
@@ -337,7 +396,111 @@ module AgentCliRuntime
337
396
  end
338
397
  )
339
398
 
340
- PROFILES = [ CLAUDE, CODEX, PI, GROK, OPENCODE ].to_h do |profile|
399
+ MUSE = Profile.new(
400
+ name: :muse,
401
+ bin_default: "muse",
402
+ env_bin_override_keys: %w[AGENT_CLI_RUNTIME_MUSE_BIN HIVE_MUSE_BIN],
403
+ headless_flag: "exec",
404
+ # Muse does not read a prompt from stdin, but --prompt-file accepts
405
+ # /dev/stdin when the host materializes stdin as a regular file (Hive
406
+ # spawns agents with stdin redirected from a tempfile). That keeps
407
+ # arbitrarily large prompts out of argv.
408
+ prompt_style: :piped_stdin,
409
+ prompt_argument: "--prompt-file=/dev/stdin",
410
+ # The unscoped path mirrors the other CLIs' skip flags: no approval
411
+ # prompts and no sandbox. The scoped modes below keep Muse's shell
412
+ # sandbox on (its default) and bound the run with approval policy
413
+ # instead of a prompt a headless caller can never answer.
414
+ permission_skip_flag: "--yolo",
415
+ workspace_write_flags: [
416
+ "--approval-mode", "never",
417
+ "--trust-workspace", "--disable-request-user-input"
418
+ ],
419
+ # Muse has no read-only filesystem sandbox mode. Disabling the write
420
+ # tools and the shell is the strongest native read-only boundary it
421
+ # offers; read/search tools stay available.
422
+ read_only_flags: [
423
+ "--approval-mode", "never",
424
+ "--trust-workspace", "--disable-request-user-input",
425
+ "--disable-write", "--disable-shell"
426
+ ],
427
+ # --json emits the MSP event stream (final text on
428
+ # run.terminal.completed, usage on run.usage). Reminder agents add
429
+ # extra model calls and injected prompts to a one-shot run, and
430
+ # request_user_input can never be answered headlessly.
431
+ output_format_flags: [
432
+ "--json", "--disable-reminders", "--disable-request-user-input",
433
+ "--no-session-log"
434
+ ],
435
+ version_flag: "--version",
436
+ min_version: "1.4.14",
437
+ model_argument_builder: ->(model) { [ "--model", model ] },
438
+ effort_argument_builder:
439
+ ->(effort) { [ "--reasoning-effort", effort ] },
440
+ launcher_identity: "muse-code/v1",
441
+ usage_extractor: UsageExtractors::MUSE,
442
+ error_extractor: ErrorExtractors::MUSE,
443
+ credential_environment_keys: %w[META_API_KEY],
444
+ # No configuration_environment_key: Muse has no private config-dir
445
+ # variable, and XDG_CONFIG_HOME names a base shared by every XDG
446
+ # tool (gh, git, Hive), so a launch binding must not export it. The
447
+ # probe below resolves the directory; non-default bindings are
448
+ # unsupported until Muse grows its own override.
449
+ default_configuration_directory: ".config/muse",
450
+ configuration_directory_probe: lambda do |home:, env:|
451
+ muse_configuration_directory(home: home, env: env)
452
+ end,
453
+ auth_configuration_probe: lambda do |home:, env:|
454
+ if env_configured?(env, "META_API_KEY")
455
+ AuthConfiguration.new(status: :configured, source: "environment")
456
+ else
457
+ auth_from_file(
458
+ muse_auth_path(home: home, env: env),
459
+ source: "muse auth.json"
460
+ )
461
+ end
462
+ end
463
+ )
464
+
465
+ AGY = Profile.new(
466
+ name: :agy,
467
+ bin_default: "agy",
468
+ env_bin_override_keys: %w[AGENT_CLI_RUNTIME_AGY_BIN HIVE_AGY_BIN],
469
+ # `agy` runs non-interactively and reads the prompt from piped or
470
+ # file-redirected stdin when `--input-format=text` is passed without `-p`,
471
+ # keeping arbitrarily large prompts out of argv.
472
+ headless_flag: "--input-format=text",
473
+ prompt_style: :piped_stdin,
474
+ permission_skip_flag: "--dangerously-skip-permissions",
475
+ add_dir_flag: "--add-dir",
476
+ output_format_flags: [ "--output-format", "stream-json" ],
477
+ version_flag: "--version",
478
+ min_version: "1.5.17",
479
+ model_argument_builder: ->(model) { [ "--model", model ] },
480
+ effort_argument_builder: ->(effort) { [ "--effort", effort ] },
481
+ launcher_identity: "antigravity-cli/v1",
482
+ usage_extractor: UsageExtractors::AGY,
483
+ error_extractor: ErrorExtractors::AGY,
484
+ credential_environment_keys: %w[
485
+ GEMINI_API_KEY GOOGLE_API_KEY GOOGLE_APPLICATION_CREDENTIALS
486
+ ],
487
+ configuration_environment_key: nil,
488
+ default_configuration_directory: ".gemini/config",
489
+ auth_configuration_probe: lambda do |home:, env:|
490
+ if env_configured?(
491
+ env, "GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS"
492
+ )
493
+ AuthConfiguration.new(status: :configured, source: "environment")
494
+ else
495
+ auth_from_file(
496
+ agy_auth_path(home: home, env: env),
497
+ source: "~/.gemini/antigravity-cli/antigravity-oauth-token"
498
+ )
499
+ end
500
+ end
501
+ )
502
+
503
+ PROFILES = [ CLAUDE, CODEX, PI, GROK, OPENCODE, MUSE, AGY ].to_h do |profile|
341
504
  [ profile.name, profile ]
342
505
  end.freeze
343
506
  PROVIDER_ORDER = PROFILES.keys.freeze
@@ -13,6 +13,7 @@ module AgentCliRuntime
13
13
  argv = [ request.executable || profile.bin ]
14
14
  prompt_style = profile.prompt_style
15
15
  argv << profile.headless_flag
16
+ argv << profile.prompt_argument if profile.prompt_argument
16
17
  argv << request.prompt if prompt_style == :headless_flag_value
17
18
 
18
19
  argv.concat(
@@ -328,7 +329,8 @@ module AgentCliRuntime
328
329
  # human-readable wording, which differs per provider and changes freely.
329
330
  def status_code_from(text)
330
331
  value = text[/\A\s*(\d{3})\s*:/, 1] ||
331
- text[/"(?:code|http_status)"\s*:\s*(\d{3})\b/, 1]
332
+ text[/"(?:code|http_status)"\s*:\s*(\d{3})\b/, 1] ||
333
+ text[/\Aunexpected status (\d{3})\b/, 1]
332
334
  code = value.to_i
333
335
  code.between?(100, 599) ? code : nil
334
336
  end
@@ -34,6 +34,97 @@ module AgentCliRuntime
34
34
  usage_result(event, usage, model_from(event), provider: :grok) if usage
35
35
  end
36
36
 
37
+ # Muse reports one terminal `run.usage` event whose payload carries a
38
+ # per-model breakdown (`models: [{model:, input_tokens:, ...}]`) instead
39
+ # of a single usage hash. Sum the breakdown; cache and reasoning
40
+ # inclusion in the headline counts is not documented, so both stay
41
+ # unknown rather than inferred.
42
+ MUSE = lambda do |event|
43
+ next nil unless event.is_a?(Hash) && event["payload_type"] == "run.usage"
44
+
45
+ payload = event["payload"]
46
+ next nil unless payload.is_a?(Hash)
47
+
48
+ models = payload["models"]
49
+ next nil unless models.is_a?(Array)
50
+
51
+ entries = models.select { |entry| entry.is_a?(Hash) }
52
+ next nil if entries.empty?
53
+
54
+ names = entries.map { |entry| entry["model"].to_s }.reject(&:empty?).uniq
55
+ {
56
+ input: UsageExtractors.muse_total(entries, "input_tokens"),
57
+ output: UsageExtractors.muse_total(entries, "output_tokens"),
58
+ cached: UsageExtractors.muse_total(entries, "cached_tokens"),
59
+ cache_read: nil,
60
+ cache_write: nil,
61
+ reasoning: UsageExtractors.muse_total(entries, "reasoning_tokens"),
62
+ input_includes_cache_read: nil,
63
+ input_includes_cache_write: nil,
64
+ output_includes_reasoning: nil,
65
+ model: names.length == 1 ? names.first : nil,
66
+ provider_reported_cost: nil
67
+ }
68
+ end
69
+
70
+ # Antigravity CLI (`agy`) emits per-step usage on `step_update` events and
71
+ # cumulative run usage on the terminal `result` event under `result.usage`.
72
+ # Captured streams show `input_tokens + output_tokens == total_tokens` with
73
+ # `thinking_tokens <= output_tokens`, so `output_includes_reasoning` is true
74
+ # when thinking tokens are reported; cache-read inclusion in `input_tokens`
75
+ # stays unknown (`nil`). Zero-turn error results (such as an empty prompt)
76
+ # emit zero counters without a model call and return nil.
77
+ AGY = lambda do |event|
78
+ next nil unless event.is_a?(Hash)
79
+
80
+ kind = event["event"]
81
+ envelope = case kind
82
+ when "result"
83
+ event["result"]
84
+ when "step_update"
85
+ event["step_update"]
86
+ end
87
+ next nil unless envelope.is_a?(Hash)
88
+
89
+ usage = envelope["usage"]
90
+ next nil unless usage.is_a?(Hash) && !usage.empty?
91
+
92
+ if kind == "result" &&
93
+ envelope["status"].to_s.upcase != "SUCCESS" &&
94
+ envelope["num_turns"].to_i.zero? &&
95
+ usage["total_tokens"].to_i.zero?
96
+ next nil
97
+ end
98
+
99
+ input = UsageExtractors.optional_token_count(usage, "input_tokens")
100
+ output = UsageExtractors.optional_token_count(usage, "output_tokens")
101
+ cache_read = UsageExtractors.optional_token_count(usage, "cache_read_tokens")
102
+ reasoning = UsageExtractors.optional_token_count(usage, "thinking_tokens")
103
+ next nil if input.nil? && output.nil? && cache_read.nil? && reasoning.nil?
104
+
105
+ model = envelope["model"].to_s
106
+ {
107
+ input: input,
108
+ output: output,
109
+ cached: nil,
110
+ cache_read: cache_read,
111
+ cache_write: nil,
112
+ reasoning: reasoning,
113
+ input_includes_cache_read: nil,
114
+ input_includes_cache_write: nil,
115
+ output_includes_reasoning: reasoning.nil? ? nil : true,
116
+ model: model.empty? ? nil : model,
117
+ provider_reported_cost: nil
118
+ }
119
+ end
120
+
121
+ def muse_total(entries, key)
122
+ present = entries.select { |entry| entry.key?(key) }
123
+ return nil if present.empty?
124
+
125
+ present.sum { |entry| entry[key].to_i }
126
+ end
127
+
37
128
  def usage_hash(event)
38
129
  candidates = [
39
130
  event["usage"],
@@ -6,6 +6,14 @@ module AgentCliRuntime
6
6
  OPENCODE_DISABLE_AUTOUPDATE OPENCODE_PURE
7
7
  ].freeze
8
8
 
9
+ # Environment keys that Ruby, Bundler, and RubyGems honor at startup to
10
+ # inject load paths. The OpenCode probe scrubs them from every child
11
+ # environment, so request constructors must refuse to select them back as
12
+ # credential keys.
13
+ SCRUBBED_RUNTIME_ENVIRONMENT_KEYS = %w[
14
+ BUNDLE_BIN_PATH BUNDLE_GEMFILE GEM_HOME GEM_PATH RUBYLIB RUBYOPT
15
+ ].freeze
16
+
9
17
  module Immutable
10
18
  module_function
11
19
 
@@ -301,6 +309,11 @@ module AgentCliRuntime
301
309
  raise ArgumentError,
302
310
  "credential environment keys cannot override the OpenCode overlay: #{reserved.join(', ')}"
303
311
  end
312
+ scrubbed = keys & SCRUBBED_RUNTIME_ENVIRONMENT_KEYS
313
+ unless scrubbed.empty?
314
+ raise ArgumentError,
315
+ "credential environment keys cannot restore scrubbed runtime injection keys: #{scrubbed.join(', ')}"
316
+ end
304
317
  normalized_bash_patterns = Immutable.strings(bash_patterns)
305
318
  if normalized_bash_patterns.any?(&:empty?)
306
319
  raise ArgumentError, "OpenCode bash patterns must be non-empty"
@@ -339,13 +352,24 @@ module AgentCliRuntime
339
352
  configured_variants: nil,
340
353
  executable: nil)
341
354
  parsed_route = route.is_a?(Route) ? route : Route.parse(route)
355
+ normalized_environment = Immutable.hash(environment)
356
+ unallowed = normalized_environment.keys - OPENCODE_OVERLAY_ENVIRONMENT_KEYS
357
+ unless unallowed.empty?
358
+ raise ArgumentError,
359
+ "ProbeRequest environment keys must be OpenCode overlay keys: #{unallowed.join(', ')}"
360
+ end
361
+ normalized_credential_keys = Immutable.strings(credential_environment_keys)
362
+ scrubbed = normalized_credential_keys & SCRUBBED_RUNTIME_ENVIRONMENT_KEYS
363
+ unless scrubbed.empty?
364
+ raise ArgumentError,
365
+ "ProbeRequest credential environment keys cannot restore scrubbed runtime injection keys: #{scrubbed.join(', ')}"
366
+ end
342
367
  super(
343
368
  profile: profile,
344
369
  route: parsed_route,
345
370
  variant: variant.nil? ? nil : Immutable.string(variant),
346
- environment: Immutable.hash(environment),
347
- credential_environment_keys:
348
- Immutable.strings(credential_environment_keys),
371
+ environment: normalized_environment,
372
+ credential_environment_keys: normalized_credential_keys,
349
373
  credential_file_staged: credential_file_staged == true,
350
374
  configured_variants:
351
375
  configured_variants.nil? ? nil : Immutable.strings(configured_variants),
@@ -1,3 +1,3 @@
1
1
  module AgentCliRuntime
2
- VERSION = "0.2.4".freeze
2
+ VERSION = "0.2.5".freeze
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: agent-cli-runtime
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.4
4
+ version: 0.2.5
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ivan Kuznetsov
@@ -18,7 +18,7 @@ dependencies:
18
18
  version: '2.7'
19
19
  - - "<"
20
20
  - !ruby/object:Gem::Version
21
- version: '3.0'
21
+ version: '4.0'
22
22
  type: :runtime
23
23
  prerelease: false
24
24
  version_requirements: !ruby/object:Gem::Requirement
@@ -28,7 +28,7 @@ dependencies:
28
28
  version: '2.7'
29
29
  - - "<"
30
30
  - !ruby/object:Gem::Version
31
- version: '3.0'
31
+ version: '4.0'
32
32
  - !ruby/object:Gem::Dependency
33
33
  name: open3
34
34
  requirement: !ruby/object:Gem::Requirement
@@ -124,5 +124,6 @@ required_rubygems_version: !ruby/object:Gem::Requirement
124
124
  requirements: []
125
125
  rubygems_version: 3.6.9
126
126
  specification_version: 4
127
- summary: One Ruby API for Claude Code, Codex CLI, Pi, Grok CLI, and OpenCode
127
+ summary: One Ruby API for Claude Code, Codex CLI, Pi, Grok CLI, OpenCode, Muse Code,
128
+ and Antigravity CLI
128
129
  test_files: []