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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use ratatui::prelude::*;
use ratatui::{TerminalOptions, Viewport};
use std::io::stdout;
use std::sync::Arc;
use std::time::{Duration, Instant};
mod app;
mod commands;
mod completion;
mod deploy;
mod orchestrator;
mod orchestrator_executor;
mod remote;
mod secrets_store;
mod session;
mod ui;
mod validation;
use app::App;
const TICK_RATE: Duration = Duration::from_millis(100);
/// Parsed CLI flags — kept minimal so we don't drag in clap for the
/// handful of flags the shell exposes.
struct ShellArgs {
/// `--resume <id-or-name>` — restore a saved session before the
/// first render. Accepts a UUID (from a prior auto-save) or a
/// named snapshot (`/snapshot foo`).
resume: Option<String>,
/// `--list-sessions` — print the saved sessions and exit.
list_sessions: bool,
/// `--cleanup-sessions` — delete stale session files and exit.
/// Requires `--older-than` to specify the cutoff.
cleanup_sessions: bool,
/// Cutoff for `--list-sessions` (filter) and `--cleanup-sessions`
/// (delete). Format: `30d` / `12h` / `5m` / `90s`.
older_than: Option<std::time::Duration>,
/// `--dry-run` with `--cleanup-sessions` — report what would be
/// deleted without touching disk.
dry_run: bool,
/// `--profile <name>` — isolate session/state dir under
/// `$HOME/.symbi-<name>/` instead of `$HOME/.symbi/`.
profile: Option<String>,
/// `--yes` — pre-approve orchestrator save/create actions so the
/// shell can be scripted without interactive "looks good" replies.
auto_approve: bool,
/// `--theme <name>` — select a built-in theme. User TOML at
/// `$HOME/.symbi[-<profile>]/theme.toml` still wins if present.
theme: Option<String>,
}
fn parse_args() -> Result<ShellArgs> {
let mut resume: Option<String> = None;
let mut list_sessions = false;
let mut cleanup_sessions = false;
let mut older_than: Option<std::time::Duration> = None;
let mut dry_run = false;
let mut profile: Option<String> = None;
let mut auto_approve = false;
let mut theme: Option<String> = None;
let mut iter = std::env::args().skip(1);
while let Some(arg) = iter.next() {
match arg.as_str() {
"-h" | "--help" => {
print_help();
std::process::exit(0);
}
"--version" => {
println!("symbi-shell {}", env!("CARGO_PKG_VERSION"));
std::process::exit(0);
}
"--list-sessions" => list_sessions = true,
"--cleanup-sessions" => cleanup_sessions = true,
"--dry-run" => dry_run = true,
"-y" | "--yes" => auto_approve = true,
"--resume" => {
resume =
Some(iter.next().ok_or_else(|| {
anyhow::anyhow!("--resume requires a session id or name")
})?);
}
flag if flag.starts_with("--resume=") => {
resume = Some(flag.trim_start_matches("--resume=").to_string());
}
"--older-than" => {
let v = iter.next().ok_or_else(|| {
anyhow::anyhow!("--older-than requires a duration (e.g. 30d)")
})?;
older_than = Some(session::parse_duration(&v)?);
}
flag if flag.starts_with("--older-than=") => {
older_than = Some(session::parse_duration(
flag.trim_start_matches("--older-than="),
)?);
}
"--profile" => {
profile = Some(
iter.next()
.ok_or_else(|| anyhow::anyhow!("--profile requires a name"))?,
);
}
flag if flag.starts_with("--profile=") => {
profile = Some(flag.trim_start_matches("--profile=").to_string());
}
"--theme" => {
theme = Some(
iter.next()
.ok_or_else(|| anyhow::anyhow!("--theme requires a name"))?,
);
}
flag if flag.starts_with("--theme=") => {
theme = Some(flag.trim_start_matches("--theme=").to_string());
}
other => {
return Err(anyhow::anyhow!("unknown argument: {}", other));
}
}
}
Ok(ShellArgs {
resume,
list_sessions,
cleanup_sessions,
older_than,
dry_run,
profile,
auto_approve,
theme,
})
}
fn print_help() {
println!(
"symbi-shell — interactive agent orchestration shell\n\
\n\
USAGE:\n symbi-shell [FLAGS]\n\
\n\
FLAGS:\n\
--resume <id|name> Resume a saved session (UUID from a prior exit,\n\
or a name set via /snapshot).\n\
--list-sessions List saved sessions and exit. Combine with\n\
--older-than to filter to stale sessions.\n\
--cleanup-sessions Delete sessions older than --older-than and exit.\n\
Add --dry-run to preview without deleting.\n\
--older-than <dur> Age cutoff for --list-sessions / --cleanup-sessions.\n\
Accepts 30d / 12h / 90m / 45s.\n\
--dry-run With --cleanup-sessions, print names but do not\n\
delete anything.\n\
--profile <name> Isolate session/state dir under\n\
$HOME/.symbi-<name>/ for parallel workspaces.\n\
-y, --yes Pre-approve orchestrator save/create actions\n\
so scripted flows don't block on confirmation.\n\
--theme <name> Select a built-in theme (default-dark,\n\
solarized-dark, high-contrast). A user file at\n\
$HOME/.symbi[-<profile>]/theme.toml overrides this.\n\
--version Print version and exit.\n\
-h, --help Show this help and exit.\n\
\n\
Sessions are stored under $HOME/.symbi/sessions/ (or $HOME/.symbi-<profile>/\n\
when --profile is set). The SYMBIONT_SESSION_DIR env var overrides both.\n\
On clean exit the shell auto-saves to <uuid>.json and prints the resume command.\n"
);
}
/// Detect whether we're running inside the Zellij terminal multiplexer.
///
/// Zellij sets `$ZELLIJ` in every child pane. It does not implement
/// DECSTBM scroll regions, which ratatui's inline `insert_before`
/// relies on to flush settled entries into the host terminal's
/// scrollback. Detection today is used only to warn the user that
/// above-viewport scrollback may be missing; a full Zellij-safe
/// render path is task #103.
fn running_inside_zellij() -> bool {
std::env::var("ZELLIJ").is_ok()
}
/// When `--profile <name>` is given, point the sessions dir at
/// `$HOME/.symbi-<name>/sessions` by setting `SYMBIONT_SESSION_DIR`
/// unless the env var is already explicitly set (which wins). This is
/// the least-invasive way to thread the profile through every session
/// read/write without changing every helper signature.
fn apply_profile(profile: &str) {
if std::env::var(session::SESSION_DIR_ENV).is_ok() {
return;
}
if let Some(mut home) = dirs::home_dir() {
home.push(format!(".symbi-{}", profile));
home.push("sessions");
std::env::set_var(session::SESSION_DIR_ENV, home);
}
}
#[tokio::main]
async fn main() -> Result<()> {
let args = match parse_args() {
Ok(a) => a,
Err(e) => {
eprintln!("error: {e}");
eprintln!("run `symbi-shell --help` for usage");
std::process::exit(2);
}
};
if let Some(profile) = args.profile.as_deref() {
apply_profile(profile);
}
// Install the theme before any UI module touches a color.
// Resolution order: user TOML → --theme → $SYMBI_THEME → default.
let theme_spec = match ui::theme::resolve(args.theme.as_deref()) {
Ok(t) => t,
Err(e) => {
eprintln!("error: {}", e);
std::process::exit(2);
}
};
ui::theme::init(theme_spec);
let in_zellij = running_inside_zellij();
if args.list_sessions {
return handle_list_sessions(args.older_than);
}
if args.cleanup_sessions {
return handle_cleanup_sessions(args.older_than, args.dry_run);
}
// Inline viewport: ratatui draws a bounded region at the bottom
// of the terminal (input + popup + throbber) while the rest of the
// terminal stays "native". New transcript entries (user input,
// agent replies, tool cards, notices, meta lines) are pushed above
// the viewport via `Terminal::insert_before` so they flow into the
// terminal's real scrollback. Closing the shell leaves the full
// transcript behind in scrollback.
//
// Height budget: 12 popup rows + 1 border + 1 input + 1 footer = 15.
const INLINE_VIEWPORT_ROWS: u16 = 15;
enable_raw_mode()?;
let mut terminal = Terminal::with_options(
CrosstermBackend::new(stdout()),
TerminalOptions {
viewport: Viewport::Inline(INLINE_VIEWPORT_ROWS),
},
)?;
// symbi shell is a local interactive dev tool; opt into permissive bus
// semantics explicitly so deploying a multi-agent DSL composition works
// out of the box. Production deployments must use the server crate with
// an explicit policy instead of this shell.
let runtime_bridge = Arc::new(repl_core::RuntimeBridge::new_permissive_for_dev());
// Load project constraints for artifact validation
let constraints = Arc::new(
validation::constraints::ProjectConstraints::load(std::path::Path::new(
".symbi/constraints.toml",
))
.unwrap_or_default(),
);
// Auto-detect inference provider and create ORGA-governed orchestrator
let orch = if let Some(provider) =
symbi_runtime::reasoning::providers::cloud::CloudInferenceProvider::from_env()
{
let provider = Arc::new(provider);
runtime_bridge.set_inference_provider(Arc::clone(&provider)
as Arc<dyn symbi_runtime::reasoning::inference::InferenceProvider>);
// Create the orchestrator's action executor with validation tools
let engine = Arc::new(repl_core::ReplEngine::new(Arc::clone(&runtime_bridge)));
let executor = Arc::new(orchestrator_executor::OrchestratorExecutor::new(
Arc::clone(&constraints),
engine,
));
Some(orchestrator::Orchestrator::new(
provider,
executor,
args.auto_approve,
))
} else {
None
};
let mut app = App::new(runtime_bridge, orch);
// Make the flags we're running under visible in the transcript so
// the user can confirm they took effect without digging in docs.
if args.auto_approve {
app.output.push(app::OutputEntry {
source: app::EntrySource::System,
content: "Auto-approve (--yes) enabled — orchestrator saves without asking."
.to_string(),
});
}
if let Some(ref profile) = args.profile {
app.output.push(app::OutputEntry {
source: app::EntrySource::System,
content: format!(
"Profile '{}' — sessions under {}",
profile,
session::session_dir().display()
),
});
}
if in_zellij {
// Zellij doesn't implement DECSTBM scroll regions, which ratatui's
// `Terminal::insert_before` relies on to flush settled entries into
// real scrollback. The TUI still functions but the transcript will
// not persist above the live viewport the way it does in
// iTerm2/Kitty/Alacritty/tmux. A Zellij-safe render path using
// raw-newline scrolling is filed as task #103.
app.push_notice(
app::NoticeKind::Warning,
"zellij".to_string(),
"Detected Zellij — scrollback above the inline viewport may not render. Use a native terminal or tmux for full fidelity until the Zellij-safe render path lands.".to_string(),
);
}
// Best-effort resume: if the caller asked for a specific session and
// it loads, restore it; otherwise show a visible system note and
// continue with a fresh session rather than hard-failing.
let mut resume_status: Option<String> = None;
if let Some(ref requested) = args.resume {
match session::load_session(requested) {
Ok(saved) => {
let entries = saved.output.len();
let had_memory = saved.conversation.is_some();
match app.restore_from_session(saved) {
Ok(()) => {
resume_status = Some(format!(
"Resumed '{}' — {} entries{}",
requested,
entries,
if had_memory {
", memory restored"
} else {
", no memory in saved file"
}
));
}
Err(e) => {
resume_status = Some(format!("Could not restore '{}': {}", requested, e));
}
}
}
Err(e) => {
resume_status = Some(format!("Could not resume '{}': {}", requested, e));
}
}
}
if let Some(msg) = resume_status {
app.output.push(app::OutputEntry {
source: app::EntrySource::System,
content: msg,
});
}
let session_id = app.session_id.clone();
let result = run_loop(&mut terminal, &mut app).await;
// Auto-save before restoring the terminal so a crashed save doesn't
// leave the terminal in a weird state either way.
let snapshot = app.build_session_snapshot(&session_id);
let save_result = session::save_session(&session_id, &snapshot);
// Before dropping raw mode, push a final blank line below the
// inline viewport so the shell's prompt lands on a fresh row —
// otherwise the viewport rectangle remains in place visually
// until the terminal redraws. `clear()` scrolls the viewport
// region off; then we disable raw mode so the parent shell takes
// back input handling.
let _ = terminal.clear();
drop(terminal);
disable_raw_mode()?;
// Resume hint is printed to stdout AFTER dropping the terminal
// so the user actually sees it in their terminal scrollback.
match save_result {
Ok(path) => {
println!();
// OSC-8: in a supporting terminal the path is clickable and
// opens the session file in the user's default handler; in
// a plain terminal the link text reads identically.
let display = path.display().to_string();
let link = if ui::osc8::stdout_is_tty() {
ui::osc8::file_link(&path, &display)
} else {
display
};
println!("Session saved to {}", link);
println!();
println!("Resume this session with:");
println!(" symbi-shell --resume {}", session_id);
}
Err(e) => {
eprintln!("\nsymbi-shell: failed to auto-save session: {}", e);
eprintln!("Your transcript was not persisted. Run `/snapshot <name>` next time to save manually.");
}
}
result
}
async fn run_loop(
terminal: &mut Terminal<CrosstermBackend<std::io::Stdout>>,
app: &mut App,
) -> Result<()> {
let mut last_tick = Instant::now();
loop {
// Flush any entries that have settled since the last frame
// into terminal scrollback. This is what makes the shell feel
// "inline" — tool cards, agent replies, notices flow upward
// into the real terminal buffer rather than being redrawn in
// an alternate-screen rectangle on every frame.
let pending = app.drain_unflushed();
if !pending.is_empty() {
let lines = ui::content::render_entries_to_lines(&pending);
// Height passed to insert_before is the number of rows we
// need above the viewport. Line wrapping isn't accounted
// for here; long lines will truncate to their first row in
// scrollback. This matches how inline TUIs typically flush.
let height = lines.len() as u16;
if height > 0 {
use ratatui::layout::Rect;
use ratatui::widgets::{Paragraph, Wrap};
terminal.insert_before(height, |buf| {
let area = Rect::new(0, 0, buf.area.width, height);
Paragraph::new(lines)
.wrap(Wrap { trim: false })
.render(area, buf);
})?;
}
}
terminal.draw(|frame| ui::draw(frame, app))?;
let timeout = TICK_RATE.saturating_sub(last_tick.elapsed());
if event::poll(timeout)? {
match event::read()? {
Event::Key(key) => handle_key(app, key).await,
// Resize: ratatui's inline viewport needs an explicit
// clear+redraw to re-anchor below the new screen
// height, otherwise a shrink leaves the viewport
// offscreen and a grow leaves stale content above it.
Event::Resize(_, _) => {
let _ = terminal.clear();
}
_ => {} // Mouse, focus, paste — ignored today.
}
}
// Tick: advance throbber animation and check for pending results
if last_tick.elapsed() >= TICK_RATE {
app.on_tick().await;
last_tick = Instant::now();
}
if app.should_quit {
break;
}
}
Ok(())
}
async fn handle_key(app: &mut App, key: KeyEvent) {
// Ignore most keys while a request is pending (except Ctrl+C to cancel)
if app.is_busy() {
if let (KeyCode::Char('c'), KeyModifiers::CONTROL) = (key.code, key.modifiers) {
app.cancel_pending();
}
return;
}
match (key.code, key.modifiers) {
// Quit
(KeyCode::Char('d'), KeyModifiers::CONTROL) => app.should_quit = true,
(KeyCode::Char('c'), KeyModifiers::CONTROL) => {
if app.input.is_empty() {
app.should_quit = true;
} else {
app.input.clear();
app.cursor = 0;
}
}
// Submit input / accept completion.
//
// If the popup is visible but the highlighted candidate is
// already fully typed (e.g. the user typed "/exit" — the popup
// still shows "/exit" as the sole suggestion), accepting would
// be a no-op. Treat that press as a submit so the user doesn't
// have to hit Enter twice.
(KeyCode::Enter, _) => {
if app.completion_visible && !app.completion_accept_is_noop() {
app.accept_completion();
} else {
if app.completion_visible {
app.dismiss_completion();
}
let text = app.submit_input();
if !text.is_empty() {
app.handle_input(&text).await;
}
}
}
// Up/Down — navigate completion popup, or history when popup hidden
(KeyCode::Up, _) => {
if app.completion_visible {
app.completion_up();
} else {
app.history_up();
}
}
(KeyCode::Down, _) => {
if app.completion_visible {
app.completion_down();
} else {
app.history_down();
}
}
// Editing
(KeyCode::Backspace, _) if app.cursor > 0 => {
app.cursor -= 1;
app.input.remove(app.cursor);
app.trigger_completion();
}
(KeyCode::Delete, _) if app.cursor < app.input.len() => {
app.input.remove(app.cursor);
app.trigger_completion();
}
(KeyCode::Left, _) if app.cursor > 0 => {
app.cursor -= 1;
app.dismiss_completion();
}
(KeyCode::Right, _) if app.cursor < app.input.len() => {
app.cursor += 1;
app.dismiss_completion();
}
(KeyCode::Home, _) => {
app.cursor = 0;
app.dismiss_completion();
}
(KeyCode::End, _) => {
app.cursor = app.input.len();
app.dismiss_completion();
}
// Toggle sidebar
(KeyCode::Char('s'), KeyModifiers::CONTROL) => {
app.sidebar_visible = !app.sidebar_visible;
}
// Toggle memory in sidebar
(KeyCode::Char('m'), KeyModifiers::CONTROL) => {
app.toggle_sidebar_memory();
}
// Expand / collapse the most recent tool-call card. Mirrors the
// "… +N more (ctrl+o)" hint rendered in collapsed card bodies.
(KeyCode::Char('o'), KeyModifiers::CONTROL) => {
app.toggle_last_tool_card();
}
// Tab — also accepts completion (alternative to Enter)
(KeyCode::Tab, _) => {
if app.completion_visible {
app.accept_completion();
} else {
app.trigger_completion();
}
}
// Escape — dismiss completion
(KeyCode::Esc, _) => {
app.dismiss_completion();
}
// Scroll content
(KeyCode::PageUp, _) => app.scroll_up(10),
(KeyCode::PageDown, _) => app.scroll_down(10),
// Regular character input — auto-trigger completion on / and @
(KeyCode::Char(c), KeyModifiers::NONE | KeyModifiers::SHIFT) => {
app.input.insert(app.cursor, c);
app.cursor += 1;
if c == '/' || c == '@' || app.completion_visible {
app.trigger_completion();
}
}
_ => {}
}
}
/// Implement the `--list-sessions [--older-than <dur>]` early-exit path.
fn handle_list_sessions(older_than: Option<std::time::Duration>) -> Result<()> {
let sessions = session::list_sessions_with_metadata()
.map_err(|e| anyhow::anyhow!("Failed to list sessions: {}", e))?;
if sessions.is_empty() {
println!("No saved sessions.");
return Ok(());
}
let now = std::time::SystemTime::now();
let filtered: Vec<&session::SessionInfo> = match older_than {
Some(age) => {
let cutoff = now
.checked_sub(age)
.ok_or_else(|| anyhow::anyhow!("cutoff underflow — duration too large"))?;
sessions.iter().filter(|s| s.modified <= cutoff).collect()
}
None => sessions.iter().collect(),
};
if filtered.is_empty() {
println!("No sessions match the filter.");
return Ok(());
}
println!("Saved sessions ({}):", filtered.len());
for info in filtered {
let age = now
.duration_since(info.modified)
.unwrap_or_default()
.as_secs();
println!(" {} ({})", info.name, format_age(age));
}
Ok(())
}
/// Implement the `--cleanup-sessions --older-than <dur> [--dry-run]`
/// early-exit path.
fn handle_cleanup_sessions(older_than: Option<std::time::Duration>, dry_run: bool) -> Result<()> {
let cutoff = older_than.ok_or_else(|| {
anyhow::anyhow!("--cleanup-sessions requires --older-than <duration> (e.g. 30d)")
})?;
let report = session::cleanup_sessions(cutoff, dry_run)
.map_err(|e| anyhow::anyhow!("Cleanup failed: {}", e))?;
let verb = if report.dry_run {
"Would remove"
} else {
"Removed"
};
if report.removed.is_empty() {
println!("No sessions older than cutoff. {} kept.", report.kept);
} else {
println!("{} {} session(s):", verb, report.removed.len());
for name in &report.removed {
println!(" {}", name);
}
println!("{} kept.", report.kept);
}
Ok(())
}
fn format_age(secs: u64) -> String {
if secs < 60 {
format!("{}s ago", secs)
} else if secs < 3600 {
format!("{}m ago", secs / 60)
} else if secs < 86_400 {
format!("{}h ago", secs / 3600)
} else {
format!("{}d ago", secs / 86_400)
}
}