nemo-relay-cli 0.7.1

Coding-agent gateway CLI for NeMo Relay observability.
Documentation
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Interactive editor state and controls for dynamic plugin host configuration.

use std::collections::HashSet;

use dialoguer::theme::ColorfulTheme;
use nemo_relay::plugin::dynamic::DynamicPluginManifest;
use serde_json::{Map, Value};

use crate::error::CliError;

use super::config_io::{DynamicPluginConfigEntry, PluginConfigDocument};
use super::schema::{
    DynamicConfigField, DynamicConfigFieldKind, PluginConfigSchema, SecretEditValues,
};
use super::{
    MenuItem, MenuResponse, MenuShortcut, configured_label, editor_error, menu_response_index,
    prompt_menu, shortcut_label,
};

const REDACTED: &str = "<redacted>";

mod prompt;

#[derive(Debug)]
pub(super) struct DynamicPluginEditorState {
    document_index: usize,
    plugin_id: String,
    label: String,
    editor_title: Option<String>,
    description: Option<String>,
    original_config: Option<Map<String, Value>>,
    config: Option<Map<String, Value>>,
    schema: Option<PluginConfigSchema>,
    touched: bool,
}

impl DynamicPluginEditorState {
    pub(super) fn label(&self) -> &str {
        &self.label
    }

    pub(super) fn menu_summary(&self) -> String {
        let config = match &self.config {
            None => "config absent",
            Some(config) if config.is_empty() => "explicit empty config",
            Some(_) => "configured",
        };
        let editor = match &self.schema {
            Some(schema) if schema.fields().is_empty() => "schema-validated JSON",
            Some(_) => "schema fields",
            None => "raw JSON object",
        };
        format!("dynamic; {config}; {editor}")
    }

    pub(super) fn validate(&self) -> Result<(), CliError> {
        if let Some(schema) = &self.schema {
            schema.validate(&Value::Object(self.config.clone().unwrap_or_default()))?;
        }
        Ok(())
    }

    pub(super) fn has_persisted_secrets(&self) -> bool {
        self.config.as_ref().is_some_and(|config| {
            self.schema
                .as_ref()
                .is_some_and(|schema| schema.has_persisted_secrets(&Value::Object(config.clone())))
        })
    }

    pub(super) fn apply_to_document(
        &self,
        document: &mut PluginConfigDocument,
        redact_secrets: bool,
    ) -> Result<(), CliError> {
        let needs_preview_redaction = redact_secrets
            && self
                .schema
                .as_ref()
                .is_some_and(PluginConfigSchema::has_secrets);
        if !self.touched && !needs_preview_redaction {
            return Ok(());
        }
        match &self.config {
            None => document.patch_dynamic_config(
                self.document_index,
                self.original_config.as_ref(),
                None,
            ),
            Some(config) => {
                let config = if redact_secrets {
                    self.schema
                        .as_ref()
                        .map(|schema| schema.redact(&Value::Object(config.clone())))
                        .unwrap_or_else(|| Value::Object(config.clone()))
                } else {
                    Value::Object(config.clone())
                };
                let config = config.as_object().cloned().ok_or_else(|| {
                    CliError::Config(format!(
                        "dynamic plugin '{}' configuration must be a JSON object",
                        self.plugin_id
                    ))
                })?;
                document.patch_dynamic_config(
                    self.document_index,
                    self.original_config.as_ref(),
                    Some(config),
                )
            }
        }
    }

    fn redacted_config(&self) -> Option<Map<String, Value>> {
        self.config.as_ref().map(|config| {
            self.schema
                .as_ref()
                .map(|schema| schema.redact(&Value::Object(config.clone())))
                .unwrap_or_else(|| Value::Object(config.clone()))
                .as_object()
                .cloned()
                .unwrap_or_default()
        })
    }

    pub(super) fn reset(&mut self) {
        self.config = None;
        self.touched = true;
    }

    #[cfg(test)]
    pub(super) fn config(&self) -> Option<&Map<String, Value>> {
        self.config.as_ref()
    }

    #[cfg(test)]
    pub(super) fn top_level_field_labels(&self) -> Vec<String> {
        self.schema
            .as_ref()
            .map(|schema| {
                dynamic_field_menu_items(self, schema.fields(), &[])
                    .0
                    .into_iter()
                    .map(|item| console::strip_ansi_codes(&item.label).into_owned())
                    .collect()
            })
            .unwrap_or_default()
    }

    #[cfg(test)]
    pub(super) fn editor_fields(&self) -> &[DynamicConfigField] {
        self.schema.as_ref().map_or(&[], |schema| schema.fields())
    }

    #[cfg(test)]
    pub(super) fn reset_top_level_field(&mut self, key: &str) -> Result<(), CliError> {
        let field = self
            .schema
            .as_ref()
            .and_then(|schema| schema.fields().iter().find(|field| field.key == key))
            .cloned()
            .ok_or_else(|| CliError::Config(format!("unknown dynamic config field '{key}'")))?;
        self.reset_field(&[key.to_owned()], &field);
        Ok(())
    }

    #[cfg(test)]
    pub(super) fn clear_top_level_field(&mut self, key: &str) {
        self.remove_field(&[key.to_owned()]);
    }

    #[cfg(test)]
    pub(super) fn top_level_field_uses_hidden_json(&self, key: &str) -> bool {
        self.field_has_secrets(&[key.to_owned()])
    }

    fn set_raw_config(&mut self, config: Map<String, Value>) {
        self.config = Some(config);
        self.touched = true;
    }

    fn field_value(&self, path: &[String]) -> Option<&Value> {
        value_at_path(self.config.as_ref(), path)
    }

    fn display_field_value(&self, path: &[String]) -> Option<Value> {
        let redacted = self.redacted_config();
        value_at_path(redacted.as_ref(), path).cloned()
    }

    fn field_has_secrets(&self, path: &[String]) -> bool {
        self.schema
            .as_ref()
            .is_some_and(|schema| schema.has_secrets_at(path))
    }

    fn field_value_for_raw_edit(
        &self,
        path: &[String],
    ) -> (
        Option<Value>,
        Option<Map<String, Value>>,
        SecretEditValues,
        bool,
    ) {
        let original = Value::Object(self.config.clone().unwrap_or_default());
        let Some(schema) = &self.schema else {
            return (
                self.field_value(path).cloned(),
                None,
                SecretEditValues::new(),
                false,
            );
        };
        let (redacted, secrets) = schema.redact_for_edit(&original);
        let value = value_at_path(redacted.as_object(), path).cloned();
        (
            value,
            redacted.as_object().cloned(),
            secrets,
            schema.has_secrets_at(path),
        )
    }

    fn restore_raw_field_edit(
        &self,
        path: &[String],
        value: Value,
        redacted_config: Option<Map<String, Value>>,
        secrets: &SecretEditValues,
    ) -> Result<Value, CliError> {
        let Some(schema) = &self.schema else {
            return Ok(value);
        };
        let mut config = redacted_config;
        set_value_at_path(&mut config, path, value);
        let restored =
            schema.restore_edit_secrets(&Value::Object(config.unwrap_or_default()), secrets)?;
        value_at_path(restored.as_object(), path)
            .cloned()
            .ok_or_else(|| {
                CliError::Config(format!(
                    "dynamic plugin '{}' raw field '{}' could not be restored",
                    self.plugin_id,
                    path.join(".")
                ))
            })
    }

    #[cfg(test)]
    pub(super) fn restore_raw_field_for_test(&self, path: &[String]) -> Result<Value, CliError> {
        let (value, redacted_config, secrets, _) = self.field_value_for_raw_edit(path);
        self.restore_raw_field_edit(
            path,
            value.unwrap_or(Value::Null),
            redacted_config,
            &secrets,
        )
    }

    fn set_field(&mut self, path: &[String], value: Value) {
        set_value_at_path(&mut self.config, path, value);
        self.touched = true;
    }

    fn remove_field(&mut self, path: &[String]) {
        if let Some(config) = &mut self.config {
            remove_value_at_path(config, path);
            self.touched = true;
        }
    }

    fn reset_field(&mut self, path: &[String], field: &DynamicConfigField) {
        match &field.default {
            Some(default) => self.set_field(path, default.clone()),
            None => self.remove_field(path),
        }
    }
}

pub(super) fn load_dynamic_plugin_states(
    document: &PluginConfigDocument,
) -> Result<Vec<DynamicPluginEditorState>, CliError> {
    let entries = document.dynamic_entries()?;
    let mut plugin_ids = HashSet::new();
    entries
        .into_iter()
        .map(|entry| load_dynamic_plugin_state(entry, &mut plugin_ids))
        .collect()
}

fn load_dynamic_plugin_state(
    entry: DynamicPluginConfigEntry,
    plugin_ids: &mut HashSet<String>,
) -> Result<DynamicPluginEditorState, CliError> {
    let (manifest, manifest_ref) = crate::configuration::load_bounded_dynamic_plugin_manifest(
        &entry.manifest_path,
    )
    .map_err(|error| {
        CliError::Config(format!(
            "could not load dynamic plugin manifest '{}' for editing: {error}",
            entry.manifest
        ))
    })?;
    let plugin_id = manifest.plugin.id.trim().to_owned();
    if !plugin_ids.insert(plugin_id.clone()) {
        return Err(CliError::Config(format!(
            "dynamic plugin '{}' is declared more than once in {}",
            plugin_id,
            entry.manifest_path.display()
        )));
    }
    let schema = load_config_schema(&manifest, &manifest_ref)?;
    let label = manifest
        .plugin
        .name
        .as_deref()
        .filter(|name| *name != plugin_id)
        .map(|name| format!("{name} ({plugin_id})"))
        .unwrap_or_else(|| plugin_id.clone());
    let description = schema
        .as_ref()
        .and_then(|schema| schema.editor().description.clone())
        .or(manifest.description);
    let editor_title = schema
        .as_ref()
        .and_then(|schema| schema.editor().title.clone());

    let original_config = entry.config.clone();
    Ok(DynamicPluginEditorState {
        document_index: entry.index,
        plugin_id,
        label,
        editor_title,
        description,
        original_config,
        config: entry.config,
        schema,
        touched: false,
    })
}

fn load_config_schema(
    manifest: &DynamicPluginManifest,
    manifest_ref: &str,
) -> Result<Option<PluginConfigSchema>, CliError> {
    manifest
        .resolve_config_schema_path(manifest_ref)
        .map_err(|error| {
            CliError::Config(format!(
                "dynamic plugin '{}' config schema path could not be resolved from '{}': {error}",
                manifest.plugin.id, manifest_ref
            ))
        })?
        .map(|path| PluginConfigSchema::load(manifest.plugin.id.trim(), path))
        .transpose()
}

#[derive(Debug, Clone, Copy)]
pub(super) enum DynamicMenuAction {
    EditField(usize),
    EditRawConfig,
    ResetPlugin,
    Back,
}

pub(super) fn edit_dynamic_plugin(
    theme: &ColorfulTheme,
    state: &mut DynamicPluginEditorState,
) -> Result<(), CliError> {
    prompt::edit_dynamic_plugin(theme, state)
}

pub(super) fn dynamic_root_menu_items(
    state: &DynamicPluginEditorState,
    fields: &[DynamicConfigField],
) -> (Vec<MenuItem>, Vec<DynamicMenuAction>) {
    let mut items = Vec::new();
    let mut actions = Vec::new();
    if fields.is_empty() {
        items.push(MenuItem::new(configured_label(
            state.config.is_some(),
            "Edit configuration as JSON object",
        )));
        actions.push(DynamicMenuAction::EditRawConfig);
    }
    items.push(MenuItem::new(shortcut_label(
        "Reset plugin configuration",
        "r",
    )));
    actions.push(DynamicMenuAction::ResetPlugin);
    items.push(MenuItem::new(shortcut_label("Back", "q")));
    actions.push(DynamicMenuAction::Back);
    (items, actions)
}

pub(super) fn dynamic_field_menu_items(
    state: &DynamicPluginEditorState,
    fields: &[DynamicConfigField],
    parent_path: &[String],
) -> (Vec<MenuItem>, Vec<DynamicMenuAction>) {
    let mut items = Vec::with_capacity(fields.len() + 2);
    let mut actions = Vec::with_capacity(fields.len() + 2);
    for (index, field) in fields.iter().enumerate() {
        let path = field_path(parent_path, field);
        let configured = state.field_value(&path).is_some();
        let value = state
            .display_field_value(&path)
            .map(|value| display_dynamic_value(&value, &field.kind))
            .or_else(|| {
                field.default.as_ref().map(|default| {
                    if field_is_secret(field) || state.field_has_secrets(&path) {
                        format!("{REDACTED} (default)")
                    } else {
                        format!("{} (default)", display_dynamic_value(default, &field.kind))
                    }
                })
            })
            .unwrap_or_else(|| "(unset)".to_owned());
        let required = if field.required { " [required]" } else { "" };
        items.push(MenuItem::new(format!(
            "{}{} = {value}",
            configured_label(configured, &field.title),
            required
        )));
        actions.push(DynamicMenuAction::EditField(index));
    }
    if parent_path.is_empty() {
        items.push(MenuItem::new(shortcut_label(
            "Reset plugin configuration",
            "r",
        )));
        actions.push(DynamicMenuAction::ResetPlugin);
    }
    items.push(MenuItem::new(shortcut_label("Back", "q")));
    actions.push(DynamicMenuAction::Back);
    (items, actions)
}

pub(super) fn reset_dynamic_selection(
    state: &mut DynamicPluginEditorState,
    fields: &[DynamicConfigField],
    parent_path: &[String],
    actions: &[DynamicMenuAction],
    selected: usize,
) {
    match actions.get(selected).copied() {
        Some(DynamicMenuAction::EditField(index)) => {
            let field = &fields[index];
            state.reset_field(&field_path(parent_path, field), field);
        }
        Some(DynamicMenuAction::ResetPlugin) => state.reset(),
        _ => println!("  Select a setting to reset."),
    }
}

pub(super) fn clear_dynamic_selection(
    state: &mut DynamicPluginEditorState,
    fields: &[DynamicConfigField],
    parent_path: &[String],
    actions: &[DynamicMenuAction],
    selected: usize,
) {
    match actions.get(selected).copied() {
        Some(DynamicMenuAction::EditField(index)) => {
            state.remove_field(&field_path(parent_path, &fields[index]));
        }
        _ => println!("  Select a field to clear."),
    }
}

pub(super) fn field_path(parent_path: &[String], field: &DynamicConfigField) -> Vec<String> {
    let mut path = parent_path.to_vec();
    path.push(field.key.clone());
    path
}

fn field_is_secret(field: &DynamicConfigField) -> bool {
    matches!(
        field.kind,
        DynamicConfigFieldKind::String { secret: true }
            | DynamicConfigFieldKind::StringEnum { secret: true, .. }
    )
}

pub(super) fn value_at_path<'a>(
    config: Option<&'a Map<String, Value>>,
    path: &[String],
) -> Option<&'a Value> {
    let (first, rest) = path.split_first()?;
    let mut value = config?.get(first)?;
    for segment in rest {
        value = value.as_object()?.get(segment)?;
    }
    Some(value)
}

pub(super) fn set_value_at_path(
    config: &mut Option<Map<String, Value>>,
    path: &[String],
    value: Value,
) {
    let Some((last, parents)) = path.split_last() else {
        return;
    };
    let mut object = config.get_or_insert_with(Map::new);
    for segment in parents {
        let entry = object
            .entry(segment.clone())
            .or_insert_with(|| Value::Object(Map::new()));
        if !entry.is_object() {
            *entry = Value::Object(Map::new());
        }
        object = entry
            .as_object_mut()
            .expect("newly inserted path segment is an object");
    }
    object.insert(last.clone(), value);
}

pub(super) fn remove_value_at_path(config: &mut Map<String, Value>, path: &[String]) -> bool {
    let Some((first, rest)) = path.split_first() else {
        return config.is_empty();
    };
    if rest.is_empty() {
        config.remove(first);
        return config.is_empty();
    }
    let remove_parent = config
        .get_mut(first)
        .and_then(Value::as_object_mut)
        .is_some_and(|object| remove_value_at_path(object, rest));
    if remove_parent {
        config.remove(first);
    }
    config.is_empty()
}

fn display_dynamic_value(value: &Value, kind: &DynamicConfigFieldKind) -> String {
    if matches!(kind, DynamicConfigFieldKind::Object { .. }) {
        return "{…}".to_owned();
    }
    json_text(value)
}

fn json_text(value: &Value) -> String {
    serde_json::to_string(value).unwrap_or_else(|_| "<invalid JSON>".to_owned())
}