Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 49 additions & 9 deletions crates/cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::path::{Path, PathBuf};

use axum::http::HeaderMap;
use clap::{ArgGroup, Args, Parser, Subcommand, ValueEnum};
use nemo_relay::plugin::layer_plugin_config;
use serde::Deserialize;
use serde_json::Value;

Expand Down Expand Up @@ -222,6 +223,7 @@ pub(crate) struct GatewayConfig {
pub(crate) anthropic_base_url: String,
pub(crate) metadata: Option<Value>,
pub(crate) plugin_config: Option<Value>,
pub(crate) plugin_config_source: Option<String>,
}

#[derive(Debug, Clone, Args)]
Expand Down Expand Up @@ -312,8 +314,14 @@ impl GatewayConfig {
pub(crate) fn session_config_from_headers(&self, headers: &HeaderMap) -> SessionConfig {
let metadata =
header_json(headers, "x-nemo-relay-session-metadata").or_else(|| self.metadata.clone());
let plugin_config = header_json(headers, "x-nemo-relay-plugin-config")
.or_else(|| self.plugin_config.clone());
let plugin_config = match (
self.plugin_config.clone(),
header_json(headers, "x-nemo-relay-plugin-config"),
) {
(Some(base), Some(overlay)) => Some(layer_plugin_config(base, overlay)),
(None, Some(overlay)) => Some(overlay),
(base, None) => base,
};
let profile = header_string(headers, "x-nemo-relay-config-profile");
let gateway_mode = header_string(headers, "x-nemo-relay-gateway-mode");
SessionConfig {
Expand Down Expand Up @@ -423,6 +431,7 @@ impl Default for GatewayConfig {
anthropic_base_url: "https://api.anthropic.com".into(),
metadata: None,
plugin_config: None,
plugin_config_source: None,
}
}
}
Expand Down Expand Up @@ -568,6 +577,9 @@ fn load_shared_config(explicit: Option<&PathBuf>) -> Result<ResolvedConfig, CliE
..ResolvedConfig::default()
};
apply_file_config(&mut resolved, merged)?;
if let Some(source) = config_toml_plugin_sources.first() {
resolved.gateway.plugin_config_source = Some(config_toml_plugin_source(source));
}
apply_plugin_toml_config(
&mut resolved.gateway,
config_toml_plugin_sources.first(),
Expand Down Expand Up @@ -781,25 +793,42 @@ fn apply_plugin_toml_config(
};
if let Some(config_source) = config_toml_plugin_source {
return Err(CliError::Config(format!(
"plugin config is defined in both {} and {}; choose one source",
"plugin config is defined in both {} and {}; choose one file source before applying code-driven layers",
config_source.display(),
format_paths(&plugin_toml.sources)
)));
}
gateway.plugin_config_source = Some(plugin_toml_source(&plugin_toml.sources));
gateway.plugin_config = Some(plugin_toml.value);
Ok(())
}

fn apply_cli_plugin_config(config: &mut GatewayConfig, value: &str) -> Result<(), CliError> {
if config.plugin_config.is_some() {
return Err(CliError::Config(
"plugin config is defined by both --plugin-config and file configuration; choose one source".into(),
));
}
config.plugin_config = Some(parse_json_option("plugin config", value)?);
apply_code_plugin_config_layer(
config,
parse_json_option("plugin config", value)?,
"--plugin-config",
);
Ok(())
}

fn apply_code_plugin_config_layer(config: &mut GatewayConfig, value: Value, source: &str) {
match config.plugin_config.take() {
Some(base) => {
config.plugin_config = Some(layer_plugin_config(base, value));
let base_source = config
.plugin_config_source
.take()
.unwrap_or_else(|| "existing plugin config".into());
config.plugin_config_source = Some(format!("{base_source} overlaid by {source}"));
}
None => {
config.plugin_config = Some(value);
config.plugin_config_source = Some(source.into());
}
}
}

// Applies configured agent commands and Cursor's temporary-hook behavior. Cursor's
// `patch_restore_hooks` flag is intentionally tri-state in file config so omitted values preserve
// the safe default while explicit `false` disables temporary hook mutation.
Expand Down Expand Up @@ -879,6 +908,9 @@ fn merge_plugin_toml(left: &mut toml::Value, right: toml::Value) {
}
}

// Mirrors the runtime layering merge in `nemo_relay::plugin`
// (`merge_plugin_components` over `serde_json::Value`). Keep the two in sync if
// the by-`kind` component merge rule changes.
fn merge_plugin_components(left: &mut toml::Value, right: toml::Value) {
let toml::Value::Array(left_components) = left else {
*left = right;
Expand Down Expand Up @@ -964,6 +996,14 @@ fn legacy_observability_sections(value: &toml::Value) -> Vec<&'static str> {
sections
}

fn config_toml_plugin_source(path: &Path) -> String {
format!("[plugins].config in {}", path.display())
}

fn plugin_toml_source(paths: &[PathBuf]) -> String {
format!("plugins.toml {}", format_paths(paths))
}

fn format_paths(paths: &[PathBuf]) -> String {
paths
.iter()
Expand Down
12 changes: 8 additions & 4 deletions crates/cli/src/doctor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -577,18 +577,22 @@ async fn collect_observability(gateway: &GatewayConfig) -> Vec<Check> {
checks.push(Check {
name: "Plugins",
status: Status::Info,
details: "plugins.toml not configured".into(),
details: "plugin config not configured".into(),
});
return checks;
};
let source = gateway
.plugin_config_source
.as_deref()
.unwrap_or("plugin config");

let plugin_config = match serde_json::from_value::<PluginConfig>(plugin_value.clone()) {
Ok(config) => config,
Err(err) => {
checks.push(Check {
name: "Plugins",
status: Status::Fail,
details: format!("invalid plugin config: {err}"),
details: format!("invalid plugin config from {source}: {err}"),
});
return checks;
}
Expand All @@ -606,7 +610,7 @@ async fn collect_observability(gateway: &GatewayConfig) -> Vec<Check> {
checks.push(Check {
name: "Plugins",
status: Status::Pass,
details: "validation passed".into(),
details: format!("validation passed from {source}"),
});
} else {
for diagnostic in report.diagnostics {
Expand All @@ -617,7 +621,7 @@ async fn collect_observability(gateway: &GatewayConfig) -> Vec<Check> {
} else {
Status::Warn
},
details: format!("{}: {}", diagnostic.code, diagnostic.message),
details: format!("{source}: {}: {}", diagnostic.code, diagnostic.message),
});
}
}
Expand Down
6 changes: 6 additions & 0 deletions crates/cli/src/launcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,9 @@ impl PreparedRun {
));
}
}
if let Some(source) = &resolved.gateway.plugin_config_source {
lines.push(format!(" Plugins {source}"));
}
if !self.notes.is_empty() {
lines.push(String::new());
for note in &self.notes {
Expand Down Expand Up @@ -592,6 +595,9 @@ impl PreparedRun {
if let Some(cursor) = &self.cursor_restore {
println!("cursor_hooks = {}", cursor.path.display());
}
if let Some(source) = &resolved.gateway.plugin_config_source {
println!("plugin_config_source = {source}");
}
for note in &self.notes {
println!("note = {note}");
}
Expand Down
20 changes: 13 additions & 7 deletions crates/cli/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,11 @@ pub(crate) async fn serve_listener(
config: GatewayConfig,
shutdown: Option<oneshot::Receiver<()>>,
) -> Result<(), CliError> {
let plugin_activation = PluginActivation::initialize(config.plugin_config.clone()).await?;
let plugin_activation = PluginActivation::initialize(
config.plugin_config.clone(),
config.plugin_config_source.as_deref(),
)
.await?;
let state = AppState::new(config);
let sessions = state.sessions.clone();
let app = router_with_state(state);
Expand Down Expand Up @@ -150,18 +154,20 @@ struct PluginActivation {
}

impl PluginActivation {
async fn initialize(config: Option<Value>) -> Result<Self, CliError> {
async fn initialize(config: Option<Value>, source: Option<&str>) -> Result<Self, CliError> {
let Some(config) = config else {
return Ok(Self { active: false });
};
let source = source.unwrap_or("plugin config");
register_adaptive_component().map_err(|error| {
CliError::Config(format!("adaptive plugin registration failed: {error}"))
})?;
let plugin_config: PluginConfig = serde_json::from_value(config)
.map_err(|error| CliError::Config(format!("invalid plugin config: {error}")))?;
initialize_plugins(plugin_config)
.await
.map_err(|error| CliError::Config(format!("plugin activation failed: {error}")))?;
let plugin_config: PluginConfig = serde_json::from_value(config).map_err(|error| {
CliError::Config(format!("invalid plugin config from {source}: {error}"))
})?;
initialize_plugins(plugin_config).await.map_err(|error| {
CliError::Config(format!("plugin activation failed for {source}: {error}"))
})?;
Ok(Self { active: true })
}

Expand Down
70 changes: 70 additions & 0 deletions crates/cli/tests/cli_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,76 @@ command = "codex --full-auto"
assert!(stdout.contains("argv = codex"));
}

#[test]
fn cli_run_dry_run_layers_plugin_config_over_plugins_toml() {
let temp = tempfile::tempdir().unwrap();
let config = temp.path().join("config.toml");
std::fs::write(
&config,
r#"
[agents.codex]
command = "codex"
"#,
)
.unwrap();
std::fs::write(
temp.path().join("plugins.toml"),
r#"
version = 1

[[components]]
kind = "observability"
enabled = true

[components.config]
version = 1

[components.config.atof]
enabled = false
output_directory = "logs"
filename = "events.jsonl"
"#,
)
.unwrap();

let output = Command::new(gateway_bin())
.args([
"--config",
config.to_str().unwrap(),
"run",
"--agent",
"codex",
"--plugin-config",
r#"{"components":[{"kind":"observability","config":{"atof":{"enabled":true}}}]}"#,
"--dry-run",
])
.output()
.unwrap();

assert!(
output.status.success(),
"dry run should resolve layered plugin config: stderr={}",
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8_lossy(&output.stdout);
let expected_exporter = format!(
"exporter = ATOF {}",
std::path::Path::new("logs").join("events.jsonl").display()
);
assert!(
stdout.contains(&expected_exporter),
"expected dry-run output to contain `{expected_exporter}`, got:\n{stdout}"
);
assert!(
stdout.contains("plugin_config_source = plugins.toml"),
"expected dry-run output to include plugin config source, got:\n{stdout}"
);
assert!(
stdout.contains("overlaid by --plugin-config"),
"expected dry-run output to include overlay source, got:\n{stdout}"
);
}

#[test]
fn cli_hook_forward_fails_open_without_gateway_url() {
let mut child = Command::new(gateway_bin())
Expand Down
Loading