-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathruntime_support.rs
More file actions
501 lines (440 loc) · 18.9 KB
/
Copy pathruntime_support.rs
File metadata and controls
501 lines (440 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
use serde::Deserialize;
use serde_json::Value;
#[derive(Debug, Clone, Deserialize, Default)]
pub struct WorkflowPhaseRuntimeSettings {
#[serde(default)]
pub tool: Option<String>,
#[serde(default)]
pub tool_profile: Option<String>,
#[serde(default)]
pub model: Option<String>,
#[serde(default)]
pub fallback_models: Vec<String>,
/// Optional explicit tool overrides for each fallback model.
/// When non-empty, `fallback_tools[i]` is used for `fallback_models[i]`.
/// If shorter than `fallback_models`, missing entries are auto-derived.
#[serde(default)]
pub fallback_tools: Vec<String>,
#[serde(default)]
pub reasoning_effort: Option<String>,
/// Provider permission/approval mode forwarded verbatim to the spawned
/// CLI (claude `--permission-mode`, codex `-c approval_policy`, gemini
/// approval mode). Mirrors `AgentRuntimeOverrides::permission_mode` in
/// the compiled agent runtime config; the workflow_runner plugin maps it
/// onto the session request.
#[serde(default)]
pub permission_mode: Option<String>,
#[serde(default)]
pub web_search: Option<bool>,
#[serde(default)]
pub network_access: Option<bool>,
#[serde(default)]
pub timeout_secs: Option<u64>,
#[serde(default)]
pub max_attempts: Option<usize>,
#[serde(default)]
pub extra_args: Vec<String>,
#[serde(default)]
pub codex_config_overrides: Vec<String>,
#[serde(default)]
pub max_continuations: Option<usize>,
}
fn parse_env_usize(key: &str) -> Option<usize> {
std::env::var(key).ok().and_then(|value| value.trim().parse::<usize>().ok())
}
const DEFAULT_PHASE_RUN_ATTEMPTS: usize = 3;
const DEFAULT_PHASE_MAX_CONTINUATIONS: usize = 3;
pub fn phase_runner_attempts() -> usize {
parse_env_usize("ANIMUS_PHASE_RUN_ATTEMPTS").unwrap_or(DEFAULT_PHASE_RUN_ATTEMPTS).clamp(1, 10)
}
pub fn phase_max_continuations() -> usize {
parse_env_usize("ANIMUS_PHASE_MAX_CONTINUATIONS").unwrap_or(DEFAULT_PHASE_MAX_CONTINUATIONS).clamp(0, 10)
}
fn codex_web_search_enabled(web_search_override: Option<bool>) -> bool {
web_search_override.or_else(|| protocol::parse_env_bool_opt("ANIMUS_CODEX_WEB_SEARCH")).unwrap_or(true)
}
fn claude_bypass_permissions_enabled() -> bool {
protocol::parse_env_bool("ANIMUS_CLAUDE_BYPASS_PERMISSIONS")
}
fn codex_reasoning_effort(reasoning_override: Option<&str>) -> Option<String> {
reasoning_override.map(str::trim).filter(|value| !value.is_empty()).map(|value| value.to_ascii_lowercase())
}
fn codex_exec_insert_index(args: &[Value]) -> usize {
args.iter().position(|item| item.as_str().is_some_and(|v| v == "exec")).unwrap_or(0)
}
fn launch_prompt_insert_index(args: &[Value]) -> usize {
args.len().saturating_sub(1)
}
fn ensure_flag_value_if_missing(args: &mut Vec<Value>, flag: &str, value: &str, insert_at: usize) {
if args.iter().any(|item| item.as_str().is_some_and(|v| v == flag)) {
return;
}
let insert_at = insert_at.min(args.len());
args.insert(insert_at, Value::String(flag.to_string()));
args.insert((insert_at + 1).min(args.len()), Value::String(value.to_string()));
}
fn ensure_codex_config_override(args: &mut Vec<Value>, key: &str, value_expr: &str) {
let key_prefix = format!("{key}=");
let target = format!("{key}={value_expr}");
let mut index = 0usize;
while index + 1 < args.len() {
let flag = args[index].as_str().unwrap_or_default();
let value = args.get(index + 1).and_then(Value::as_str).unwrap_or_default();
if (flag == "-c" || flag == "--config") && value.starts_with(&key_prefix) {
args[index + 1] = Value::String(target);
return;
}
index += 1;
}
let insert_at = codex_exec_insert_index(args);
args.insert(insert_at, Value::String("-c".to_string()));
args.insert(insert_at + 1, Value::String(target));
}
fn codex_network_access_enabled(network_access_override: Option<bool>) -> bool {
network_access_override.or_else(|| protocol::parse_env_bool_opt("ANIMUS_CODEX_NETWORK_ACCESS")).unwrap_or(true)
}
fn parse_env_string_list_json(key: &str, fallback_key: Option<&str>, split_by_semicolon: bool) -> Vec<String> {
let parse_json = |raw: &str| serde_json::from_str::<Vec<String>>(raw).ok().unwrap_or_default();
let normalize = |items: Vec<String>| {
items.into_iter().map(|item| item.trim().to_string()).filter(|item| !item.is_empty()).collect::<Vec<_>>()
};
if let Ok(raw) = std::env::var(key) {
let trimmed = raw.trim();
if !trimmed.is_empty() {
return normalize(parse_json(trimmed));
}
}
let Some(fallback_key) = fallback_key else {
return Vec::new();
};
let Ok(raw) = std::env::var(fallback_key) else {
return Vec::new();
};
let trimmed = raw.trim();
if trimmed.is_empty() {
return Vec::new();
}
if split_by_semicolon {
return normalize(trimmed.split(';').map(ToOwned::to_owned).collect());
}
normalize(trimmed.split_whitespace().map(ToOwned::to_owned).collect())
}
fn cli_tool_extra_args_env_keys(tool_id: &str) -> Option<(&'static str, &'static str)> {
match tool_id.trim().to_ascii_lowercase().as_str() {
"codex" => Some(("ANIMUS_CODEX_EXTRA_ARGS_JSON", "ANIMUS_CODEX_EXTRA_ARGS")),
"claude" => Some(("ANIMUS_CLAUDE_EXTRA_ARGS_JSON", "ANIMUS_CLAUDE_EXTRA_ARGS")),
"gemini" => Some(("ANIMUS_GEMINI_EXTRA_ARGS_JSON", "ANIMUS_GEMINI_EXTRA_ARGS")),
"opencode" | "open-code" => Some(("ANIMUS_OPENCODE_EXTRA_ARGS_JSON", "ANIMUS_OPENCODE_EXTRA_ARGS")),
_ => None,
}
}
fn resolved_phase_extra_args(
tool_id: &str,
phase_runtime_settings: Option<&WorkflowPhaseRuntimeSettings>,
) -> Vec<String> {
if let Some(settings) = phase_runtime_settings {
let explicit = settings
.extra_args
.iter()
.map(String::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
.collect::<Vec<_>>();
if !explicit.is_empty() {
return explicit;
}
}
let mut resolved =
parse_env_string_list_json("ANIMUS_AI_CLI_EXTRA_ARGS_JSON", Some("ANIMUS_AI_CLI_EXTRA_ARGS"), false);
if let Some((json_key, plain_key)) = cli_tool_extra_args_env_keys(tool_id) {
resolved.extend(parse_env_string_list_json(json_key, Some(plain_key), false));
}
resolved
}
fn parse_codex_override_entry(entry: &str) -> Option<(String, String)> {
let trimmed = entry.trim();
let (key, value_expr) = trimmed.split_once('=')?;
let key = key.trim();
let value_expr = value_expr.trim();
if key.is_empty() || value_expr.is_empty() {
return None;
}
Some((key.to_string(), value_expr.to_string()))
}
fn resolved_codex_config_overrides(
phase_runtime_settings: Option<&WorkflowPhaseRuntimeSettings>,
) -> Vec<(String, String)> {
let from_settings =
phase_runtime_settings.map(|settings| settings.codex_config_overrides.as_slice()).unwrap_or_default();
let overrides: Vec<(String, String)> =
from_settings.iter().filter_map(|entry| parse_codex_override_entry(entry)).collect();
if !overrides.is_empty() {
return overrides;
}
parse_env_string_list_json(
"ANIMUS_CODEX_EXTRA_CONFIG_OVERRIDES_JSON",
Some("ANIMUS_CODEX_EXTRA_CONFIG_OVERRIDES"),
true,
)
.iter()
.filter_map(|entry| parse_codex_override_entry(entry))
.collect()
}
fn inject_cli_extra_args(
runtime_contract: &mut Value,
tool_id: &str,
phase_runtime_settings: Option<&WorkflowPhaseRuntimeSettings>,
) {
let extra_args = resolved_phase_extra_args(tool_id, phase_runtime_settings);
inject_cli_extra_args_list(runtime_contract, &extra_args);
}
/// Insert a literal list of extra CLI args into `/cli/launch/args`, just
/// before the trailing prompt argument — the same placement the workflow
/// phase path uses. Shared core for the workflow `extra_args` setting and
/// the ad-hoc skill `extra_args` wiring. Empty/whitespace entries are
/// skipped; a contract without a launch block is left untouched.
pub fn inject_cli_extra_args_list(runtime_contract: &mut Value, extra_args: &[String]) {
let cleaned: Vec<&str> = extra_args.iter().map(|arg| arg.trim()).filter(|arg| !arg.is_empty()).collect();
if cleaned.is_empty() {
return;
}
let Some(args) = runtime_contract.pointer_mut("/cli/launch/args").and_then(Value::as_array_mut) else {
return;
};
let insert_at = launch_prompt_insert_index(args);
for (offset, extra_arg) in cleaned.into_iter().enumerate() {
args.insert(insert_at + offset, Value::String(extra_arg.to_string()));
}
}
pub fn inject_cli_launch_env(runtime_contract: &mut Value, launch_env: &std::collections::BTreeMap<String, String>) {
if launch_env.is_empty() {
return;
}
if runtime_contract.pointer("/cli/launch/env").is_none() {
if let Some(launch) = runtime_contract.pointer_mut("/cli/launch").and_then(Value::as_object_mut) {
launch.insert("env".to_string(), Value::Object(serde_json::Map::new()));
}
}
if let Some(env) = runtime_contract.pointer_mut("/cli/launch/env").and_then(Value::as_object_mut) {
for (key, value) in launch_env {
env.entry(key.clone()).or_insert(Value::String(value.clone()));
}
}
}
fn inject_codex_extra_config_overrides(
runtime_contract: &mut Value,
tool_id: &str,
phase_runtime_settings: Option<&WorkflowPhaseRuntimeSettings>,
) {
if !tool_id.eq_ignore_ascii_case("codex") {
return;
}
let overrides = resolved_codex_config_overrides(phase_runtime_settings);
if overrides.is_empty() {
return;
}
if let Some(args) = runtime_contract.pointer_mut("/cli/launch/args").and_then(Value::as_array_mut) {
for (key, value_expr) in overrides {
ensure_codex_config_override(args, &key, &value_expr);
}
}
}
/// Apply raw `key=value` codex `-c` config-override entries to
/// `/cli/launch/args`, replacing an existing `-c key=...` pair when present
/// (same upsert semantics as the workflow phase path). No-op for non-codex
/// tools, unparseable entries, or a contract without a launch block. Shared
/// core for the workflow `codex_config_overrides` setting and the ad-hoc
/// skill `codex_config_overrides` wiring.
pub fn inject_codex_config_overrides_list(runtime_contract: &mut Value, tool_id: &str, overrides: &[String]) {
if !tool_id.eq_ignore_ascii_case("codex") {
return;
}
let parsed: Vec<(String, String)> =
overrides.iter().filter_map(|entry| parse_codex_override_entry(entry)).collect();
if parsed.is_empty() {
return;
}
if let Some(args) = runtime_contract.pointer_mut("/cli/launch/args").and_then(Value::as_array_mut) {
for (key, value_expr) in parsed {
ensure_codex_config_override(args, &key, &value_expr);
}
}
}
pub fn inject_codex_search_launch_flag(runtime_contract: &mut Value, tool_id: &str, web_search_override: Option<bool>) {
if !tool_id.eq_ignore_ascii_case("codex") || !codex_web_search_enabled(web_search_override) {
return;
}
if let Some(args) = runtime_contract.pointer_mut("/cli/launch/args").and_then(Value::as_array_mut) {
let has_search_flag = args.iter().any(|item| item.as_str().is_some_and(|value| value == "--search"));
if !has_search_flag {
let insert_at = codex_exec_insert_index(args);
args.insert(insert_at, Value::String("--search".to_string()));
}
}
if let Some(capabilities) = runtime_contract.pointer_mut("/cli/capabilities").and_then(Value::as_object_mut) {
capabilities.insert("supports_web_search".to_string(), Value::Bool(true));
}
}
pub fn inject_codex_reasoning_effort(runtime_contract: &mut Value, tool_id: &str, reasoning_override: Option<&str>) {
if !tool_id.eq_ignore_ascii_case("codex") {
return;
}
let Some(effort) = codex_reasoning_effort(reasoning_override) else {
return;
};
if let Some(args) = runtime_contract.pointer_mut("/cli/launch/args").and_then(Value::as_array_mut) {
let mut has_override = false;
for window in args.windows(2) {
let Some(flag) = window[0].as_str() else {
continue;
};
let Some(value) = window[1].as_str() else {
continue;
};
if flag == "-c" && value.starts_with("model_reasoning_effort=") {
has_override = true;
break;
}
}
if !has_override {
let insert_at = codex_exec_insert_index(args);
args.insert(insert_at, Value::String("-c".to_string()));
args.insert(insert_at + 1, Value::String(format!("model_reasoning_effort={effort}")));
}
}
}
pub fn inject_codex_network_access(runtime_contract: &mut Value, tool_id: &str, network_access_override: Option<bool>) {
if !tool_id.eq_ignore_ascii_case("codex") {
return;
}
let value_expr = if codex_network_access_enabled(network_access_override) { "true" } else { "false" };
if let Some(args) = runtime_contract.pointer_mut("/cli/launch/args").and_then(Value::as_array_mut) {
ensure_codex_config_override(args, "sandbox_workspace_write.network_access", value_expr);
}
}
pub fn inject_claude_permission_mode(runtime_contract: &mut Value, tool_id: &str) {
if !tool_id.eq_ignore_ascii_case("claude") || !claude_bypass_permissions_enabled() {
return;
}
if let Some(args) = runtime_contract.pointer_mut("/cli/launch/args").and_then(Value::as_array_mut) {
ensure_flag_value_if_missing(args, "--permission-mode", "bypassPermissions", 0);
}
}
pub fn inject_cli_launch_overrides(
runtime_contract: &mut Value,
tool_id: &str,
phase_runtime_settings: Option<&WorkflowPhaseRuntimeSettings>,
) {
inject_codex_search_launch_flag(
runtime_contract,
tool_id,
phase_runtime_settings.and_then(|settings| settings.web_search),
);
inject_codex_reasoning_effort(
runtime_contract,
tool_id,
phase_runtime_settings.and_then(|settings| settings.reasoning_effort.as_deref()),
);
inject_codex_network_access(
runtime_contract,
tool_id,
phase_runtime_settings.and_then(|settings| settings.network_access),
);
inject_claude_permission_mode(runtime_contract, tool_id);
inject_codex_extra_config_overrides(runtime_contract, tool_id, phase_runtime_settings);
inject_cli_extra_args(runtime_contract, tool_id, phase_runtime_settings);
}
#[cfg(test)]
mod phase_runtime_settings_tests {
use super::*;
// The workflow_runner plugin deserializes `WorkflowPhaseRuntimeSettings`
// straight from the compiled agent runtime config's `phases.<id>.runtime`
// block, which the kernel serializes from
// `orchestrator_config::agent_runtime_config::AgentRuntimeOverrides`.
// This round-trip pins the additive `permission_mode` field so the
// kernel-populated value survives into the runner-side settings struct.
#[test]
fn permission_mode_round_trips_from_compiled_agent_runtime_overrides() {
let overrides = orchestrator_config::agent_runtime_config::AgentRuntimeOverrides {
permission_mode: Some("acceptEdits".to_string()),
reasoning_effort: Some("high".to_string()),
..Default::default()
};
let compiled = serde_json::to_value(&overrides).expect("overrides serialize");
let settings: WorkflowPhaseRuntimeSettings =
serde_json::from_value(compiled).expect("settings deserialize from compiled runtime block");
assert_eq!(settings.permission_mode.as_deref(), Some("acceptEdits"));
assert_eq!(settings.reasoning_effort.as_deref(), Some("high"));
}
#[test]
fn permission_mode_defaults_to_none_for_legacy_runtime_blocks() {
let settings: WorkflowPhaseRuntimeSettings =
serde_json::from_value(serde_json::json!({ "model": "claude-sonnet-4-6" }))
.expect("legacy block deserializes");
assert!(settings.permission_mode.is_none());
}
}
#[cfg(test)]
mod skill_launch_injection_tests {
use super::*;
use serde_json::json;
fn contract_with_launch(args: &[&str]) -> Value {
json!({
"cli": {
"name": "codex",
"launch": {
"command": "codex",
"args": args.iter().map(|a| Value::String((*a).to_string())).collect::<Vec<_>>(),
}
}
})
}
#[test]
fn extra_args_list_inserts_before_the_trailing_prompt() {
let mut contract = contract_with_launch(&["exec", "--json", "the prompt"]);
inject_cli_extra_args_list(&mut contract, &["--alpha".to_string(), "--beta".to_string()]);
let args: Vec<&str> = contract
.pointer("/cli/launch/args")
.and_then(Value::as_array)
.unwrap()
.iter()
.filter_map(Value::as_str)
.collect();
assert_eq!(args, vec!["exec", "--json", "--alpha", "--beta", "the prompt"]);
}
#[test]
fn extra_args_list_skips_blank_entries_and_missing_launch() {
let mut contract = contract_with_launch(&["exec", "p"]);
inject_cli_extra_args_list(&mut contract, &[" ".to_string()]);
assert_eq!(contract.pointer("/cli/launch/args").and_then(Value::as_array).unwrap().len(), 2);
// No launch block — must not panic or insert anything.
let mut bare = json!({ "cli": { "name": "codex" } });
inject_cli_extra_args_list(&mut bare, &["--alpha".to_string()]);
assert!(bare.pointer("/cli/launch").is_none());
}
#[test]
fn codex_overrides_list_upserts_config_pairs_for_codex_only() {
let mut contract = contract_with_launch(&["exec", "-c", "approval_policy=\"never\"", "p"]);
inject_codex_config_overrides_list(
&mut contract,
"codex",
&["approval_policy=\"on-request\"".to_string(), "model_reasoning_effort=\"high\"".to_string()],
);
let args: Vec<&str> = contract
.pointer("/cli/launch/args")
.and_then(Value::as_array)
.unwrap()
.iter()
.filter_map(Value::as_str)
.collect();
// Existing approval_policy pair is REPLACED, new override prepended at exec index.
assert!(args.contains(&"approval_policy=\"on-request\""), "{args:?}");
assert!(!args.contains(&"approval_policy=\"never\""), "{args:?}");
assert!(args.contains(&"model_reasoning_effort=\"high\""), "{args:?}");
// Non-codex tool: untouched.
let mut claude = contract_with_launch(&["--print", "p"]);
inject_codex_config_overrides_list(&mut claude, "claude", &["approval_policy=\"never\"".to_string()]);
assert_eq!(claude.pointer("/cli/launch/args").and_then(Value::as_array).unwrap().len(), 2);
}
}