agent-cli-runtime 0.2.0 → 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.
@@ -66,12 +66,26 @@ module AgentCliRuntime
66
66
  preparation.credential_environment_keys
67
67
  )
68
68
  plugins = selected_plugins(source_config, preparation.plugins)
69
- permission = permission_rules(preparation, roots, plugins: plugins)
70
69
 
71
70
  root = create_root!(preparation.invocation_root)
72
71
  cleanup = Cleanup.new(root)
73
72
  begin
74
73
  paths = create_directories(root)
74
+ permission = Permissions.compile(
75
+ permission_mode: preparation.request.permission_mode,
76
+ permission_policy: preparation.permission_policy,
77
+ working_directory: roots.fetch(:working),
78
+ additional_read_roots: roots.fetch(:read),
79
+ additional_write_roots: roots.fetch(:write),
80
+ edit_patterns: preparation.edit_patterns,
81
+ bash_patterns: preparation.bash_patterns,
82
+ plugins: plugins,
83
+ runtime_write_roots: [ paths.fetch(:temporary) ]
84
+ )
85
+ unless permission
86
+ raise ConfigurationError,
87
+ "OpenCode requires an explicit OpenCode permission policy when permission_mode is nil"
88
+ end
75
89
  pure = preparation.pure && plugins.empty?
76
90
  config = generated_configuration(
77
91
  source_config, plugins, requested_route, permission
@@ -91,9 +105,6 @@ module AgentCliRuntime
91
105
  )
92
106
  executable =
93
107
  preparation.request.executable || profile.bin(env: env)
94
- probe_env = env.to_h.merge(
95
- "AGENT_CLI_RUNTIME_OPENCODE_BIN" => executable
96
- )
97
108
  probe_request = ProbeRequest.new(
98
109
  profile: profile,
99
110
  route: requested_route,
@@ -103,9 +114,12 @@ module AgentCliRuntime
103
114
  credential_file_staged:
104
115
  staged_credential && credential_file_supports_provider?(
105
116
  staged_credential.last, requested_route.provider
106
- )
117
+ ),
118
+ configured_variants:
119
+ configured_variants(source_config, requested_route),
120
+ executable: executable
107
121
  )
108
- probe_result = OpenCode::Probe.call!(probe_request, env: probe_env)
122
+ probe_result = OpenCode::Probe.call!(probe_request, env: env)
109
123
  invocation = compile_invocation(
110
124
  preparation, profile, requested_route, roots,
111
125
  executable:, pure: pure,
@@ -175,6 +189,21 @@ module AgentCliRuntime
175
189
  end
176
190
  private_class_method :validate_provider!
177
191
 
192
+ # A selected OpenCode configuration may declare a custom model that is
193
+ # newer than the CLI's bundled provider catalog. With model fetching
194
+ # disabled for hermetic launches, that declaration is durable route
195
+ # evidence; the large `models --verbose` inventory is complementary,
196
+ # not its replacement.
197
+ def configured_variants(config, route)
198
+ models = config.dig("provider", route.provider, "models")
199
+ return nil unless models.is_a?(Hash) && models.key?(route.model)
200
+
201
+ definition = models.fetch(route.model)
202
+ variants = definition.is_a?(Hash) ? definition["variants"] : nil
203
+ variants.is_a?(Hash) ? variants.keys.sort.freeze : [].freeze
204
+ end
205
+ private_class_method :configured_variants
206
+
178
207
  def validate_nonsecret!(value, key = nil)
179
208
  case value
180
209
  when Hash
@@ -244,120 +273,6 @@ module AgentCliRuntime
244
273
  end
245
274
  private_class_method :resolve_roots
246
275
 
247
- def permission_rules(preparation, roots, plugins: preparation.plugins)
248
- mode = preparation.request.permission_mode
249
- if mode.nil?
250
- policy = preparation.permission_policy
251
- unless policy
252
- raise ConfigurationError,
253
- "OpenCode requires an explicit OpenCode permission policy when permission_mode is nil"
254
- end
255
- return deep_copy(policy.rules)
256
- end
257
-
258
- unless %w[read-only workspace-write].include?(mode)
259
- raise ConfigurationError,
260
- "unsupported OpenCode permission mode"
261
- end
262
-
263
- external = { "*" => "deny" }
264
- (roots.fetch(:read) + roots.fetch(:write)).uniq.each do |root|
265
- external[root] = "allow"
266
- external["#{root}/**"] = "allow"
267
- end
268
- common = {
269
- "*" => "deny",
270
- "read" => {
271
- "*" => "allow",
272
- "*.env" => "deny",
273
- "*.env.*" => "deny",
274
- "*.env.example" => "allow"
275
- },
276
- "glob" => "allow",
277
- "grep" => "allow",
278
- "list" => "allow",
279
- "lsp" => "allow",
280
- "skill" => plugins.empty? ? "deny" : "allow",
281
- "external_directory" => external
282
- }
283
- if mode == "read-only"
284
- return common.merge(
285
- "edit" => "deny", "bash" => "deny", "task" => "deny",
286
- "webfetch" => "deny", "websearch" => "deny",
287
- "question" => "deny"
288
- )
289
- end
290
-
291
- # OpenCode applies the last matching permission rule. Start from a
292
- # denial and append only the invocation's declared write roots. The
293
- # working directory is an implicit write root for workspace-write;
294
- # additional read roots remain explicitly denied unless the caller
295
- # also declared them writable.
296
- writable_roots = [ roots.fetch(:working), *roots.fetch(:write) ].uniq
297
- edit = { "*" => "deny" }
298
- allows = if preparation.edit_patterns.empty?
299
- writable_roots.flat_map do |root|
300
- edit_patterns(root, working: roots.fetch(:working))
301
- end
302
- else
303
- normalize_declared_edit_patterns(
304
- preparation.edit_patterns, writable_roots,
305
- working: roots.fetch(:working)
306
- )
307
- end
308
- allows.each do |pattern|
309
- edit[pattern] = "allow"
310
- end
311
- (roots.fetch(:read) - roots.fetch(:write)).each do |root|
312
- edit_patterns(root, working: roots.fetch(:working)).each do |pattern|
313
- edit[pattern] = "deny"
314
- end
315
- end
316
- common.merge(
317
- "edit" => edit, "bash" => "deny", "task" => "deny",
318
- "webfetch" => "deny", "websearch" => "deny",
319
- "question" => "deny"
320
- )
321
- end
322
- private_class_method :permission_rules
323
-
324
- def edit_patterns(root, working:)
325
- if root == working
326
- [ "**" ]
327
- elsif root.start_with?(working + File::SEPARATOR)
328
- relative = root.delete_prefix(working + File::SEPARATOR)
329
- [ relative, "#{relative}/**" ]
330
- else
331
- [ root, "#{root}/**" ]
332
- end
333
- end
334
- private_class_method :edit_patterns
335
-
336
- def normalize_declared_edit_patterns(patterns, writable_roots, working:)
337
- patterns.map do |value|
338
- pattern = value.sub(%r{\A//}, "/")
339
- unless File.absolute_path?(pattern) && !pattern.include?("\0")
340
- raise ConfigurationError,
341
- "OpenCode edit patterns must be absolute path patterns"
342
- end
343
- literal_prefix = pattern.split(/[*?]/, 2).first.sub(%r{/+\z}, "")
344
- unless writable_roots.any? do |root|
345
- literal_prefix == root || literal_prefix.start_with?(root + File::SEPARATOR)
346
- end
347
- raise ConfigurationError,
348
- "OpenCode edit pattern is outside the declared write roots"
349
- end
350
- if pattern == working
351
- "**"
352
- elsif pattern.start_with?(working + File::SEPARATOR)
353
- pattern.delete_prefix(working + File::SEPARATOR)
354
- else
355
- pattern
356
- end
357
- end.uniq.freeze
358
- end
359
- private_class_method :normalize_declared_edit_patterns
360
-
361
276
  def create_root!(value)
362
277
  path = File.expand_path(value)
363
278
  unless File.absolute_path?(value.to_s)
@@ -528,6 +443,12 @@ module AgentCliRuntime
528
443
  trusted = source.trusted_cli_arguments.dup
529
444
  trusted.concat([ "--dir", roots.fetch(:working) ])
530
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
+ )
531
452
  request = Request.new(
532
453
  profile: profile,
533
454
  prompt: source.prompt,
@@ -0,0 +1,144 @@
1
+ require "json"
2
+
3
+ module AgentCliRuntime
4
+ module OpenCode
5
+ # Compiles provider-neutral permission modes into OpenCode's
6
+ # per-run permission document. The document can be written into an
7
+ # isolated overlay or supplied through OPENCODE_PERMISSION while the CLI
8
+ # continues to use its native configuration and login.
9
+ module Permissions
10
+ module_function
11
+
12
+ def compile(permission_mode:, permission_policy: nil,
13
+ working_directory:, additional_read_roots: [],
14
+ additional_write_roots: [], edit_patterns: [],
15
+ bash_patterns: [], plugins: [], runtime_write_roots: [])
16
+ mode = permission_mode
17
+ if mode.nil?
18
+ return nil unless permission_policy
19
+ unless permission_policy.is_a?(OpenCodePermissionPolicy)
20
+ raise ArgumentError,
21
+ "permission_policy must be an OpenCodePermissionPolicy"
22
+ end
23
+
24
+ return deep_copy(permission_policy.rules)
25
+ end
26
+
27
+ unless %w[read-only workspace-write].include?(mode)
28
+ raise ConfigurationError, "unsupported OpenCode permission mode"
29
+ end
30
+
31
+ roots = {
32
+ working: File.expand_path(working_directory),
33
+ read: expanded_roots(additional_read_roots),
34
+ write: expanded_roots(additional_write_roots)
35
+ }
36
+ runtime_roots = expanded_roots(runtime_write_roots)
37
+ external = { "*" => "deny" }
38
+ [ *roots.fetch(:read), *roots.fetch(:write), *runtime_roots ].uniq.each do |root|
39
+ external[root] = "allow"
40
+ external["#{root}/**"] = "allow"
41
+ end
42
+ common = {
43
+ "*" => "deny",
44
+ "read" => {
45
+ "*" => "allow",
46
+ "*.env" => "deny",
47
+ "*.env.*" => "deny",
48
+ "*.env.example" => "allow"
49
+ },
50
+ "glob" => "allow",
51
+ "grep" => "allow",
52
+ "list" => "allow",
53
+ "lsp" => "allow",
54
+ "skill" => Array(plugins).empty? ? "deny" : "allow",
55
+ "external_directory" => external
56
+ }
57
+ if mode == "read-only"
58
+ return common.merge(
59
+ "edit" => "deny", "bash" => "deny", "task" => "deny",
60
+ "webfetch" => "deny", "websearch" => "deny",
61
+ "question" => "deny"
62
+ )
63
+ end
64
+
65
+ writable_roots = [
66
+ roots.fetch(:working), *roots.fetch(:write), *runtime_roots
67
+ ].uniq
68
+ edit = { "*" => "deny" }
69
+ allows = if Array(edit_patterns).empty?
70
+ writable_roots.flat_map do |root|
71
+ root_edit_patterns(root, working: roots.fetch(:working))
72
+ end
73
+ else
74
+ normalize_declared_edit_patterns(
75
+ edit_patterns, writable_roots, working: roots.fetch(:working)
76
+ )
77
+ end
78
+ allows.each { |pattern| edit[pattern] = "allow" }
79
+ (roots.fetch(:read) - roots.fetch(:write)).each do |root|
80
+ root_edit_patterns(root, working: roots.fetch(:working)).each do |pattern|
81
+ edit[pattern] = "deny"
82
+ end
83
+ end
84
+ bash = { "*" => "deny" }
85
+ Array(bash_patterns).each { |pattern| bash[pattern.to_s] = "allow" }
86
+ common.merge(
87
+ "edit" => edit,
88
+ "bash" => Array(bash_patterns).empty? ? "deny" : bash,
89
+ "task" => "deny",
90
+ "webfetch" => "deny", "websearch" => "deny",
91
+ "question" => "deny"
92
+ )
93
+ end
94
+
95
+ def expanded_roots(values)
96
+ Array(values).map { |value| File.expand_path(value) }.uniq.freeze
97
+ end
98
+ private_class_method :expanded_roots
99
+
100
+ def root_edit_patterns(root, working:)
101
+ if root == working
102
+ [ "**" ]
103
+ elsif root.start_with?(working + File::SEPARATOR)
104
+ relative = root.delete_prefix(working + File::SEPARATOR)
105
+ [ relative, "#{relative}/**" ]
106
+ else
107
+ [ root, "#{root}/**" ]
108
+ end
109
+ end
110
+ private_class_method :root_edit_patterns
111
+
112
+ def normalize_declared_edit_patterns(patterns, writable_roots, working:)
113
+ Array(patterns).map do |value|
114
+ pattern = value.to_s.sub(%r{\A//}, "/")
115
+ unless File.absolute_path?(pattern) && !pattern.include?("\0")
116
+ raise ConfigurationError,
117
+ "OpenCode edit patterns must be absolute path patterns"
118
+ end
119
+ literal_prefix = pattern.split(/[*?]/, 2).first.sub(%r{/+\z}, "")
120
+ unless writable_roots.any? do |root|
121
+ literal_prefix == root ||
122
+ literal_prefix.start_with?(root + File::SEPARATOR)
123
+ end
124
+ raise ConfigurationError,
125
+ "OpenCode edit pattern is outside the declared write roots"
126
+ end
127
+ if pattern == working
128
+ "**"
129
+ elsif pattern.start_with?(working + File::SEPARATOR)
130
+ pattern.delete_prefix(working + File::SEPARATOR)
131
+ else
132
+ pattern
133
+ end
134
+ end.uniq.freeze
135
+ end
136
+ private_class_method :normalize_declared_edit_patterns
137
+
138
+ def deep_copy(value)
139
+ JSON.parse(JSON.generate(value))
140
+ end
141
+ private_class_method :deep_copy
142
+ end
143
+ end
144
+ end
@@ -6,6 +6,17 @@ module AgentCliRuntime
6
6
  REQUIRED_RUN_FLAGS = %w[
7
7
  --model --variant --format --dir --pure --auto
8
8
  ].freeze
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"
9
20
  SAFE_ENVIRONMENT_KEYS = %w[
10
21
  HOME LANG LC_ALL LOGNAME PATH SHELL SSL_CERT_DIR SSL_CERT_FILE
11
22
  TMPDIR USER
@@ -19,11 +30,11 @@ module AgentCliRuntime
19
30
  call!(request, env:)
20
31
  rescue Error => e
21
32
  profile = Profiles.resolve(request.profile)
22
- executable = profile.bin(env:)
33
+ executable = request.executable || profile.bin(env:)
23
34
  RouteProbeResult.new(
24
35
  provider: profile.name,
25
36
  ready: false,
26
- installed: profile.binary_installed?(env:),
37
+ installed: profile.binary_installed?(env:, executable:),
27
38
  executable: executable,
28
39
  version: nil,
29
40
  minimum_version: profile.min_version,
@@ -54,20 +65,25 @@ module AgentCliRuntime
54
65
  raise ArgumentError,
55
66
  "route-aware ProbeRequest currently requires profile :opencode"
56
67
  end
57
- installed = profile.binary_installed?(env:)
68
+ installed = profile.binary_installed?(env:, executable: request.executable)
58
69
  unless installed
59
70
  raise BinaryUnavailable,
60
- "opencode binary not runnable: #{profile.bin(env:)}"
71
+ "opencode binary not runnable: " \
72
+ "#{request.executable || profile.bin(env:)}"
61
73
  end
62
74
 
63
75
  child_env = child_environment(profile, request, env:)
64
- version = profile.check_version!(env: child_env)
76
+ version = profile.check_version!(
77
+ env: child_env, executable: request.executable
78
+ )
65
79
  evidence = [
66
80
  evidence(profile, :installation),
67
81
  evidence(profile, :version, [ version ])
68
82
  ]
69
83
 
70
- run_help = capture!(profile, child_env, "run", "--help")
84
+ run_help = capture!(
85
+ profile, child_env, "run", "--help", executable: request.executable
86
+ )
71
87
  missing = REQUIRED_RUN_FLAGS.reject { |flag| advertised?(run_help, flag) }
72
88
  unless missing.empty?
73
89
  raise UnsupportedCapability,
@@ -76,15 +92,23 @@ module AgentCliRuntime
76
92
  evidence.concat(REQUIRED_RUN_FLAGS.map do |flag|
77
93
  evidence(profile, capability_for(flag), [ flag ])
78
94
  end)
95
+ server_arguments = private_server_arguments(run_help)
96
+ evidence << evidence(profile, :private_server, server_arguments) unless
97
+ server_arguments.empty?
79
98
 
80
- export_help = capture!(profile, child_env, "export", "--help")
99
+ export_help = capture!(
100
+ profile, child_env, "export", "--help", executable: request.executable
101
+ )
81
102
  unless advertised?(export_help, "--sanitize")
82
103
  raise UnsupportedCapability,
83
104
  "OpenCode export is missing required --sanitize capability"
84
105
  end
85
106
  evidence << evidence(profile, :sanitized_export, [ "--sanitize" ])
86
107
 
87
- auth_output = capture!(profile, child_env, "auth", "list")
108
+ auth_output = capture!(
109
+ profile, child_env, "auth", "list", *server_arguments,
110
+ executable: request.executable
111
+ )
88
112
  configured_key = request.credential_environment_keys.find do |key|
89
113
  !env[key].to_s.empty?
90
114
  end
@@ -106,19 +130,31 @@ module AgentCliRuntime
106
130
  )
107
131
  evidence << evidence(profile, :auth_configuration)
108
132
 
109
- models_output = capture!(
110
- profile, child_env, "models", request.route.provider, "--verbose"
111
- )
112
- variants = variants_for(models_output, request.route.to_s)
113
- if variants.nil?
133
+ configured_variants = request.configured_variants
134
+ inventory_variants = if configured_variants.nil?
135
+ models_output = capture!(
136
+ profile, child_env, "models", request.route.provider, "--verbose",
137
+ *server_arguments,
138
+ executable: request.executable,
139
+ timeout_sec: MODEL_INVENTORY_TIMEOUT_SECONDS
140
+ )
141
+ variants_for(models_output, request.route.to_s)
142
+ end
143
+ if configured_variants.nil? && inventory_variants.nil?
114
144
  raise RouteUnavailable,
115
145
  "requested OpenCode route is unavailable in the local model inventory"
116
146
  end
147
+ variants = [ *inventory_variants, *configured_variants ].uniq.sort.freeze
117
148
  if request.variant && !variants.include?(request.variant)
118
149
  raise RouteUnavailable,
119
150
  "requested OpenCode variant is unavailable for the exact route"
120
151
  end
121
152
  evidence << evidence(profile, :model_route, [ request.route.to_s ])
153
+ if inventory_variants.nil?
154
+ evidence << evidence(
155
+ profile, :configured_model_route, [ request.route.to_s ]
156
+ )
157
+ end
122
158
  evidence << evidence(profile, :model_variant, [ request.variant ]) if
123
159
  request.variant
124
160
 
@@ -126,7 +162,7 @@ module AgentCliRuntime
126
162
  provider: profile.name,
127
163
  ready: true,
128
164
  installed: true,
129
- executable: profile.bin(env: child_env),
165
+ executable: request.executable || profile.bin(env: child_env),
130
166
  version: version,
131
167
  minimum_version: profile.min_version,
132
168
  auth_configuration: auth,
@@ -144,6 +180,23 @@ module AgentCliRuntime
144
180
  raise ProbeError, Redactor.diagnostic(e)
145
181
  end
146
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
+
147
200
  def child_environment(profile, request, env:)
148
201
  selected = (ENV.keys | env.keys).to_h { |key| [ key, nil ] }
149
202
  env.each do |key, value|
@@ -152,21 +205,34 @@ module AgentCliRuntime
152
205
  selected[key] = value.to_s
153
206
  end
154
207
  end
155
- %w[
156
- BUNDLE_BIN_PATH BUNDLE_GEMFILE GEM_HOME GEM_PATH RUBYLIB RUBYOPT
157
- ].each { |key| selected[key] = nil }
158
208
  profile.env_bin_override_keys.each do |key|
159
209
  selected[key] = env[key].to_s unless env[key].to_s.empty?
160
210
  end
161
211
  request.credential_environment_keys.each do |key|
162
212
  selected[key] = env[key].to_s unless env[key].to_s.empty?
163
213
  end
164
- 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
165
228
  end
166
229
  private_class_method :child_environment
167
230
 
168
- def capture!(profile, environment, *arguments)
169
- out, err, status = profile.capture_local(*arguments, env: environment)
231
+ def capture!(profile, environment, *arguments, executable: nil,
232
+ timeout_sec: nil)
233
+ options = { env: environment, executable: executable }
234
+ options[:timeout_sec] = timeout_sec if timeout_sec
235
+ out, err, status = profile.capture_local(*arguments, **options)
170
236
  unless status.success?
171
237
  diagnostic = normalized_output("#{err}\n#{out}")
172
238
  raise ConfigurationError,