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
use anyhow::Result;
use clap::{Parser, Subcommand};
use navi_core::{LoadedConfig, LoggingRuntimeConfig, init_logging, log_path};
use navi_sdk::{NaviConfigSaveTarget, NaviEngineBuilder, NaviSessionRequest, NaviTurnRequest};
use navi_tui::TuiApp;
use std::path::PathBuf;
mod bench_cmd;
mod eval_cmd;
mod mcp_cmd;
mod memory_cmd;
mod plugin_cmd;
mod registry_cmd;
#[derive(Debug, Parser)]
#[command(name = "navi")]
#[command(about = "An opinionated, customizable TUI code agent")]
struct Cli {
#[command(subcommand)]
command: Option<Commands>,
#[arg(long)]
print_config: bool,
#[arg(long)]
print_providers: bool,
#[arg(long)]
sync_models: bool,
#[arg(long)]
print_log_path: bool,
#[arg(long, value_name = "LEVEL")]
log_level: Option<String>,
#[arg(long)]
no_log_file: bool,
#[arg(long)]
debug_payloads: bool,
#[arg(long)]
no_tui: bool,
#[arg(value_name = "TASK")]
task: Vec<String>,
}
#[derive(Debug, Subcommand)]
enum Commands {
/// Manage WASM plugins
Plugin {
#[command(subcommand)]
action: PluginAction,
},
/// Manage MCP servers
Mcp {
#[command(subcommand)]
action: McpAction,
},
/// Manage state-continuity memory
Memory {
#[command(subcommand)]
action: MemoryAction,
},
/// Run local harness eval suites
Eval {
#[command(subcommand)]
action: EvalAction,
},
/// Run agentic benchmark suites
Bench {
#[command(subcommand)]
action: BenchAction,
},
/// Run interactive setup wizard (provider login, agent-configured interview)
Setup,
/// Sync and list providers from the registry database
Registry {
#[command(subcommand)]
action: RegistryAction,
},
}
#[derive(Debug, Subcommand)]
pub enum BenchAction {
/// Run an agentic benchmark suite or single benchmark case
Run {
/// Path to a benchmark case file or directory of .toml/.json cases
path: PathBuf,
/// Project root used to resolve relative fixtures
#[arg(long)]
project: Option<PathBuf>,
/// Write the full BenchRun JSON to this path
#[arg(long)]
output: Option<PathBuf>,
/// Print the full BenchRun JSON
#[arg(long)]
json: bool,
/// Provider override for every benchmark case unless the case sets its own provider
#[arg(long)]
provider: Option<String>,
/// Model override for every benchmark case unless the case sets its own model
#[arg(long)]
model: Option<String>,
/// Automatically approve tool approval requests during the benchmark run
#[arg(long)]
auto_approve: bool,
/// Keep temporary workspaces after each case for inspection
#[arg(long)]
keep_workspaces: bool,
},
/// Compare a candidate benchmark run against an optional baseline
Compare {
/// Candidate BenchRun JSON path
candidate: PathBuf,
/// Baseline BenchRun JSON path
#[arg(long)]
baseline: Option<PathBuf>,
/// Minimum verified success rate for the candidate
#[arg(long, default_value_t = 1.0)]
min_success_rate: f64,
/// Maximum allowed success-rate drop from baseline
#[arg(long, default_value_t = 0.0)]
max_success_drop: f64,
/// Require candidate tokens_per_success to be no worse than baseline
#[arg(long)]
require_token_improvement: bool,
/// Require candidate tool_calls_per_success to be no worse than baseline
#[arg(long)]
require_tool_call_improvement: bool,
/// Print JSON report
#[arg(long)]
json: bool,
},
}
#[derive(Debug, Subcommand)]
pub enum EvalAction {
/// Run a verifier-replay eval suite or single eval case
Run {
/// Path to an eval case file or directory of .toml/.json cases
path: PathBuf,
/// Project root where verifier commands should run
#[arg(long)]
project: Option<PathBuf>,
/// Print the full EvalRun JSON
#[arg(long)]
json: bool,
},
/// Generate eval candidates and dataset JSONL from stored traces
GenerateFromTraces {
/// NAVI data directory containing traces/
data_dir: PathBuf,
/// Directory where generated EvalCase TOML files should be written
#[arg(long)]
output_dir: PathBuf,
/// Optional JSONL dataset output path
#[arg(long)]
dataset_jsonl: Option<PathBuf>,
},
/// Evaluate replay/superiority gates from EvalRun JSON files
Gate {
/// Candidate EvalRun JSON path
candidate: PathBuf,
/// Baseline EvalRun JSON path
#[arg(long)]
baseline: Option<PathBuf>,
/// Minimum verified success rate for replay gate
#[arg(long, default_value_t = 1.0)]
min_success_rate: f64,
/// Maximum allowed success-rate drop from baseline
#[arg(long, default_value_t = 0.0)]
max_success_drop: f64,
/// Unsafe guarded effects auto-approved count
#[arg(long, default_value_t = 0)]
unsafe_guarded_auto_approvals: u64,
/// Optional NAVI data directory; unsafe guarded auto-approvals are derived from traces/
#[arg(long)]
trace_data_dir: Option<PathBuf>,
/// Also require verified_success_per_1k_tokens improvement over baseline
#[arg(long)]
superiority: bool,
/// Print JSON report
#[arg(long)]
json: bool,
},
}
#[derive(Debug, Subcommand)]
pub enum MemoryAction {
/// Show current memory system status
Status,
/// Manually run checkpoint writer
Checkpoint,
/// Print the context that would be injected on rebuild
RebuildPreview,
/// Search raw history
History {
/// Search query
query: String,
/// Optional limit
#[arg(long)]
limit: Option<i64>,
/// Filter by session ID
#[arg(long)]
session_id: Option<String>,
},
/// Run dream maintenance
Dream {
/// Apply the dream output to active memory after writing the review copy
#[arg(long)]
apply: bool,
/// Number of recent sessions to mine, capped at 100
#[arg(long, default_value_t = 10)]
sessions: usize,
/// High-level synthesis guidance for the dream
#[arg(long)]
instructions: Option<String>,
},
/// Run distill maintenance
Distill,
/// Validate files, paths, permissions, SQLite schema, and config
Doctor,
}
#[derive(Debug, Subcommand)]
enum McpAction {
/// List configured MCP servers, connection status, and tools
List,
}
#[derive(Debug, Subcommand)]
enum RegistryAction {
/// Force-sync the provider registry from the remote database
Sync,
/// List all providers and model counts from the local cache
List,
}
#[derive(Debug, Subcommand)]
enum PluginAction {
/// Install a plugin from a local directory (developer workflow)
Install {
/// Path to the plugin directory (containing plugin.toml and .wasm)
path: PathBuf,
/// Skip the approval prompt and install non-interactively
#[arg(long)]
yes: bool,
},
/// Install a plugin from the marketplace registry by id
InstallMarketplace {
/// Plugin id from catalog.json
plugin_id: String,
/// Skip the approval prompt and install non-interactively
#[arg(long)]
yes: bool,
},
/// Update an installed plugin from a local directory (developer workflow)
Update {
/// Path to the new plugin directory (containing plugin.toml and .wasm)
path: PathBuf,
/// Force the update even when the publisher changed
#[arg(long)]
force: bool,
},
/// Update an installed plugin from the marketplace registry
UpdateMarketplace {
/// Plugin id from catalog.json
plugin_id: String,
/// Force the update even when the publisher changed
#[arg(long)]
force: bool,
},
/// Search the marketplace catalog
Search {
/// Optional search query (id, name, description)
query: Option<String>,
},
/// List installed plugins
List,
/// Remove an installed plugin
Remove {
/// Plugin ID to remove
plugin_id: String,
},
/// Show details of a plugin
Info {
/// Plugin ID or path
plugin_id: String,
},
}
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
let cwd = std::env::current_dir()?;
let mut loaded_config = navi_core::NaviConfig::load(&cwd)?;
if cli.debug_payloads {
loaded_config.config.logging.include_payloads = true;
}
// Handle plugin subcommand early
if let Some(Commands::Plugin { action }) = cli.command {
return plugin_cmd::handle_plugin_command(action, &loaded_config, &cwd);
}
// Handle mcp subcommand early
if let Some(Commands::Mcp { action }) = cli.command {
return mcp_cmd::handle_mcp_command(action, &loaded_config).await;
}
// Handle memory subcommand early
if let Some(Commands::Memory { action }) = cli.command {
return memory_cmd::handle_memory_command(action, &loaded_config, &cwd).await;
}
// Handle eval subcommand early
if let Some(Commands::Eval { action }) = cli.command {
return eval_cmd::handle_eval_command(action, cwd).await;
}
// Handle benchmark subcommand early
if let Some(Commands::Bench { action }) = cli.command {
return bench_cmd::handle_bench_command(action, loaded_config, cwd).await;
}
// Handle setup subcommand early — launch TUI in setup mode
if let Some(Commands::Setup) = cli.command {
let _logging_guard = init_logging(
&loaded_config.config.logging,
&loaded_config.data_dir,
LoggingRuntimeConfig {
stdout_enabled: cli.no_tui,
file_enabled: !cli.no_log_file,
level: cli.log_level.clone(),
include_payloads: cli.debug_payloads,
},
)?;
tracing::info!("starting interactive setup wizard");
navi_tui::run(TuiApp::setup_mode(loaded_config, cwd)?)?;
return Ok(());
}
// Handle registry subcommand early
if let Some(Commands::Registry { action }) = cli.command {
return registry_cmd::handle_registry_command(action, &loaded_config, &cwd).await;
}
if cli.print_log_path {
println!("{}", log_path(&loaded_config.data_dir).display());
return Ok(());
}
if cli.print_config {
println!("{}", serde_json::to_string_pretty(&loaded_config.config)?);
return Ok(());
}
if cli.print_providers {
println!(
"{}",
serde_json::to_string_pretty(&navi_core::provider_catalog(&loaded_config.config))?
);
return Ok(());
}
if cli.sync_models {
tracing::info!("starting model sync");
sync_models(loaded_config, &cwd).await?;
return Ok(());
}
let _logging_guard = init_logging(
&loaded_config.config.logging,
&loaded_config.data_dir,
LoggingRuntimeConfig {
stdout_enabled: cli.no_tui,
file_enabled: !cli.no_log_file,
level: cli.log_level.clone(),
include_payloads: cli.debug_payloads,
},
)?;
let task = normalize_task(cli.task);
if cli.no_tui {
tracing::info!(project = %cwd.display(), "starting headless run");
run_headless(loaded_config, cwd, task).await?;
return Ok(());
}
// Onboarding wizard removed — config v2 doesn't track onboarding_completed
// The TUI will now start normally and prompt for setup if needed.
tracing::info!(project = %cwd.display(), "starting TUI");
navi_tui::run(TuiApp::new(loaded_config, cwd.clone(), task)?)?;
Ok(())
}
async fn sync_models(loaded_config: LoadedConfig, cwd: &std::path::Path) -> Result<()> {
let engine = NaviEngineBuilder::from_project(cwd)
.loaded_config(loaded_config)
.build()?;
let report = engine.sync_models(NaviConfigSaveTarget::Auto).await?;
for provider in &report.updated {
println!(
"Synced {} models for provider \"{}\".",
provider.model_count, provider.provider_id
);
tracing::info!(
provider = %provider.provider_id,
models = provider.model_count,
"synced provider models"
);
}
for skipped in &report.skipped {
println!(
"Skipped provider \"{}\": {}",
skipped.provider_id, skipped.reason
);
}
for failure in &report.failed {
eprintln!(
"Failed to sync provider \"{}\": {}",
failure.provider_id, failure.message
);
tracing::warn!(
provider = %failure.provider_id,
error = %failure.message,
"failed to sync provider models"
);
}
if let Some(saved_path) = &report.saved_to {
println!(
"Saved updated models configuration to: {}",
saved_path.display()
);
} else if report.updated.is_empty() {
println!("No models were updated.");
}
Ok(())
}
async fn run_headless(
loaded_config: LoadedConfig,
cwd: PathBuf,
task: Option<String>,
) -> Result<()> {
let Some(task) = task else {
anyhow::bail!("headless mode requires a task");
};
let engine = NaviEngineBuilder::from_project(cwd.clone())
.loaded_config(loaded_config.clone())
.build()?;
tracing::info!(
provider = %loaded_config.config.model.provider,
model = %loaded_config.config.model.name,
"submitting headless task"
);
let session = engine
.start_session(NaviSessionRequest {
project_dir: Some(cwd),
session_id: None,
context_packets: Vec::new(),
active_skills: Vec::new(),
initial_messages: Vec::new(),
..NaviSessionRequest::default()
})
.await?;
let response = engine
.send_turn(NaviTurnRequest {
session_id: session.id.clone(),
message: task,
content_parts: Vec::new(),
context_packets: Vec::new(),
thinking: None,
})
.await?;
println!("{}", response.text);
engine.snapshot_session(&session.id).await?;
Ok(())
}
fn normalize_task(parts: Vec<String>) -> Option<String> {
let task = parts.join(" ");
let task = task.trim();
(!task.is_empty()).then(|| task.to_string())
}