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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! Bamboo binary entry point
//!
//! Standalone HTTP server for Bamboo
use bamboo_llm::Config;
use clap::{Parser, Subcommand};
use std::path::PathBuf;
#[derive(Parser)]
#[command(name = "bamboo")]
#[command(version)]
#[command(about = "A fully self-contained AI agent backend framework", long_about = None)]
#[command(
after_help = "QUICK RUN (headless server):\n bamboo -p \"your task\" full agent run (incl. sub-agents), print result, exit\n bamboo -p \"next step\" -s <session> continue an existing session's loop\n bamboo -p \"...\" -m provider:model pin the model\n bamboo -p \"ping\" --echo no-key smoke of the actor chain (no server)"
)]
struct Cli {
#[command(subcommand)]
command: Option<Commands>,
/// Run a full headless agent on this prompt and print the result. Boots
/// the complete server runtime (root tool surface incl. SubAgent, so it
/// CAN spawn actor children), finishes when the whole tree finishes.
#[arg(short = 'p', long = "prompt", global = false)]
prompt: Option<String>,
/// With -p: continue this existing session instead of creating a new one.
#[arg(short = 's', long)]
session: Option<String>,
/// With -p: model as 'provider:model'. Defaults to the session/config default.
#[arg(short = 'm', long)]
model: Option<String>,
/// With -p: working directory for a NEW session (defaults to the current dir).
#[arg(long)]
workspace: Option<PathBuf>,
/// With -p: data directory holding config.json (defaults to ~/.bamboo).
#[arg(long)]
data_dir: Option<PathBuf>,
/// With -p: skip the server and run the bare actor chain with the echo
/// executor (no LLM, no key) — transport smoke test only.
#[arg(long)]
echo: bool,
/// With -p: NDJSON streaming on stdout — one JSON object per line:
/// {"type":"session_started",...}, every agent event verbatim, then a
/// final {"type":"result",...} envelope. Pipe-safe (logs go to stderr).
#[arg(long = "stream-json", alias = "raw")]
stream_json: bool,
/// With -p: permission mode for the headless run, which has no interactive
/// approver. One of: default | plan | accept-edits | dont-ask | bypass.
/// Use `bypass` to let a tool-using agent run unattended (otherwise the run
/// stalls at the first permission-gated tool such as Bash).
#[arg(long = "permission-mode")]
permission_mode: Option<String>,
}
/// Spawn the sidecar orphan guard: a dedicated OS thread that exits the process
/// when the shell that spawned us goes away.
///
/// The primary signal is `getppid()`: when our parent terminates — even via
/// SIGKILL / force-quit, even while it lingers as an unreaped zombie — the
/// kernel reparents us to init/launchd *at the moment of termination*, so
/// `getppid()` changes. That is reap-independent, unlike `kill(pid, 0)` (which
/// still reports a zombie as alive). The recorded shell PID fully disappearing
/// is kept as a secondary trigger.
#[cfg(unix)]
fn spawn_orphan_guard(shell_pid: u32) {
std::thread::spawn(move || {
let initial_parent = unsafe { libc::getppid() };
loop {
let current_parent = unsafe { libc::getppid() };
// Reparented away from our original parent (it terminated → the kernel
// handed us to init/launchd). This is immediate at the parent's exit and
// independent of when its zombie is reaped — unlike `kill(pid, 0)`, which
// still reports a not-yet-reaped zombie as alive. The shell PID fully
// disappearing is kept as a secondary trigger.
let reparented = current_parent != initial_parent || current_parent <= 1;
let shell_gone = {
let r = unsafe { libc::kill(shell_pid as libc::pid_t, 0) };
r != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
};
if reparented || shell_gone {
std::process::exit(0);
}
std::thread::sleep(std::time::Duration::from_millis(300));
}
});
}
#[cfg(windows)]
fn spawn_orphan_guard(shell_pid: u32) {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Threading::{
OpenProcess, WaitForSingleObject, PROCESS_SYNCHRONIZE,
};
// Open a synchronizable handle to the shell and block until it exits, then take
// the sidecar down with it. Covers normal quit AND hard kills (the shell runs no
// cleanup). If the shell is already gone, OpenProcess fails and we exit at once.
std::thread::spawn(move || unsafe {
let handle = OpenProcess(PROCESS_SYNCHRONIZE, 0, shell_pid);
if handle.is_null() {
std::process::exit(0);
}
// INFINITE (0xFFFF_FFFF): wait until the shell process terminates.
WaitForSingleObject(handle, u32::MAX);
let _ = CloseHandle(handle);
std::process::exit(0);
});
}
#[derive(Subcommand)]
enum Commands {
/// Start the Bamboo HTTP server
Serve {
/// Port to listen on (overrides config file)
#[arg(short, long)]
port: Option<u16>,
/// Bind address (overrides config file)
#[arg(short, long)]
bind: Option<String>,
/// Data directory (overrides config file)
#[arg(short, long)]
data_dir: Option<PathBuf>,
/// Static files directory (for Docker mode)
#[arg(short, long)]
static_dir: Option<PathBuf>,
/// Number of worker threads (overrides config file)
#[arg(short, long)]
workers: Option<usize>,
/// Exit when this parent process id no longer exists. The Bodhi desktop
/// shell spawns `bamboo serve` as a sidecar and passes its own PID here, so
/// the backend shuts down if the shell dies — including via SIGKILL /
/// force-quit, which run no cleanup. Polled on a dedicated thread, so it is
/// independent of the async runtime and of how the parent wired our stdio.
#[arg(long)]
parent_pid: Option<u32>,
},
/// Show Bamboo configuration
Config {
/// Show config file path
#[arg(short, long)]
path: bool,
/// Show sensitive values (API keys, etc.)
#[arg(long)]
show_secrets: bool,
},
/// Run as a sub-agent worker process (spawned by a parent bamboo server).
///
/// Reads a ProvisionSpec JSON document from stdin (the parent writes it and
/// closes the pipe), self-registers into the discovery fabric, and serves
/// one run over a loopback WebSocket. Not intended for interactive use.
#[command(name = "subagent-worker", hide = true)]
SubagentWorker,
/// Run a sub-agent actor from the terminal (spawns the real worker
/// process + WebSocket chain against your configured providers).
Actor {
#[command(subcommand)]
command: ActorCommands,
},
/// Run the standalone sub-agent message broker: a WebSocket bus over durable
/// per-session mailboxes. The orchestrator and its workers (local subprocess,
/// Docker, or SSH/remote) connect here to exchange ask/reply traffic.
Broker {
#[command(subcommand)]
command: BrokerCommands,
},
/// Run a broker-connected agent: connect to a central broker and answer
/// Ask/Task (query/steer) for this agent's mailbox. Deploy locally, in
/// Docker, or on a remote host — it only needs `--broker` + `--token`.
#[command(name = "broker-agent")]
BrokerAgent {
#[command(subcommand)]
command: BrokerAgentCommands,
},
/// Probe a running server's health endpoint. Exits non-zero if it is
/// unreachable or reports unhealthy — usable as a readiness check.
Health {
#[command(flatten)]
conn: ConnArgs,
},
/// One-screen overview of a running server: address, health, session counts.
Status {
#[command(flatten)]
conn: ConnArgs,
},
/// List sessions on a running server (stop one with `bamboo stop <id>`).
Sessions {
#[command(flatten)]
conn: ConnArgs,
},
/// Stop a running agent session's loop by id (POST /api/v1/stop/{id}).
Stop {
/// Session id to stop.
session_id: String,
#[command(flatten)]
conn: ConnArgs,
},
}
/// Connection options shared by the admin subcommands (`health` / `status` /
/// `sessions` / `stop`). Resolves which running server to talk to.
#[derive(clap::Args, Clone)]
struct ConnArgs {
/// Full base URL of the server, e.g. `http://127.0.0.1:9562`.
/// Overrides `--port` / `--data-dir`.
#[arg(long)]
server_url: Option<String>,
/// Server port (defaults to the configured port, normally 9562).
#[arg(long)]
port: Option<u16>,
/// Data dir holding config.json, to resolve the port/bind (defaults to ~/.bamboo).
#[arg(long)]
data_dir: Option<PathBuf>,
}
impl From<ConnArgs> for bamboo_agent::admin_cli::ConnArgs {
fn from(c: ConnArgs) -> Self {
bamboo_agent::admin_cli::ConnArgs {
server_url: c.server_url,
port: c.port,
data_dir: c.data_dir,
}
}
}
#[derive(Subcommand)]
enum BrokerCommands {
/// Serve the broker on a WebSocket endpoint until terminated.
Serve {
/// Bind address. Use `0.0.0.0:9600` to accept connections from remote /
/// containerized workers; `127.0.0.1:9600` for local-only.
#[arg(long, default_value = "127.0.0.1:9600")]
bind: String,
/// Bearer token every client must present in its `Hello` frame. Falls
/// back to the `BAMBOO_BROKER_TOKEN` env var; required (no default, so a
/// broker is never accidentally unauthenticated).
#[arg(long)]
token: Option<String>,
/// Durable mailbox storage root. Defaults to `<bamboo_dir>/broker`.
#[arg(long)]
root: Option<PathBuf>,
},
}
#[derive(Subcommand)]
enum BrokerAgentCommands {
/// Connect to a broker and serve this agent's mailbox until terminated.
Serve {
/// Broker WebSocket endpoint, e.g. `ws://broker-host:9600`.
#[arg(long)]
broker: String,
/// Bearer token (falls back to the `BAMBOO_BROKER_TOKEN` env var).
#[arg(long)]
token: Option<String>,
/// This agent's mailbox key / session id — how it is addressed.
#[arg(long)]
id: String,
/// Optional role/profile label.
#[arg(long)]
role: Option<String>,
/// Optional model `provider:model` (real mode).
#[arg(long)]
model: Option<String>,
/// Optional workspace directory for file tools (real mode).
#[arg(long)]
workspace: Option<String>,
/// Use the dependency-free echo executor (no LLM) — for smoke tests.
#[arg(long)]
echo: bool,
/// Proxy all MCP tool calls to this orchestrator id over the broker
/// (host-bound MCP servers run only there).
#[arg(long = "mcp-proxy")]
mcp_proxy: Option<String>,
},
}
#[derive(Subcommand)]
enum ActorCommands {
/// Spawn an actor, give it a task, and stream its events live.
Run {
/// The task / prompt for the actor.
prompt: String,
/// Model as 'provider:model' (or a bare model id on the default
/// provider). Defaults to defaults.sub_agent, then defaults.chat.
#[arg(short, long)]
model: Option<String>,
/// Role label published in the discovery record.
#[arg(long, default_value = "cli")]
role: String,
/// Working directory for the actor (defaults to the current dir).
#[arg(short, long)]
workspace: Option<PathBuf>,
/// Data directory holding config.json (defaults to ~/.bamboo).
#[arg(short, long)]
data_dir: Option<PathBuf>,
/// Use the dependency-free echo executor (no LLM, no key needed) to
/// smoke-test the whole actor chain.
#[arg(long)]
echo: bool,
/// Print raw event JSON instead of pretty streaming.
#[arg(long)]
raw: bool,
},
/// Become a long-running service agent: announce into the local discovery
/// fabric and serve calls until Ctrl-C (one isolated session per call).
Serve {
/// Role to announce (how others find you), e.g. "summarizer".
#[arg(long, default_value = "service")]
role: String,
/// Stable agent id; defaults to '<role>-<short-uuid>'.
#[arg(long)]
id: Option<String>,
/// Model as 'provider:model'; defaults to defaults.sub_agent/chat.
#[arg(short, long)]
model: Option<String>,
/// Working directory for the agent (defaults to the current dir).
#[arg(short, long)]
workspace: Option<PathBuf>,
/// Data directory holding config.json (defaults to ~/.bamboo).
#[arg(short, long)]
data_dir: Option<PathBuf>,
/// Serve the echo executor (no LLM) — for smoke tests.
#[arg(long)]
echo: bool,
},
/// List actors currently discoverable in the local fabric.
List,
/// Discover a service agent (by id, or first match by role) and send it a task.
Call {
/// Agent id (exact) or role (first live match).
agent: String,
/// The task / prompt to send.
prompt: String,
/// Print raw event JSON instead of pretty streaming.
#[arg(long)]
raw: bool,
},
}
#[tokio::main]
async fn main() {
let cli = Cli::parse();
// Initialize logging (file + stdout, with rotation).
// Use debug level in debug builds, info in release.
let debug = cfg!(debug_assertions);
match &cli.command {
Some(Commands::Serve { data_dir, .. }) => {
let home = data_dir
.clone()
.unwrap_or_else(bamboo_config::paths::resolve_bamboo_dir);
bamboo_agent::server::logging::init_logging_with_home(&home, debug);
}
Some(Commands::Config { .. }) => {
// No file logging for config subcommand; stdout only.
tracing_subscriber::fmt()
.with_target(true)
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.init();
}
Some(Commands::SubagentWorker)
| Some(Commands::Actor { .. })
| Some(Commands::Broker { .. })
| Some(Commands::BrokerAgent { .. })
| Some(Commands::Health { .. })
| Some(Commands::Status { .. })
| Some(Commands::Sessions { .. })
| Some(Commands::Stop { .. })
| None => {
// Worker/CLI logs go to stderr only: stdin/stdout are part of the
// bootstrap & streaming protocol and must stay clean. (`None` is
// the top-level `-p` quick run, or bare `bamboo` -> help.)
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_target(true)
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")),
)
.init();
}
}
// Top-level quick run: `bamboo -p "<prompt>"` — a complete headless server.
let command = match cli.command {
Some(command) => command,
None => {
let Some(prompt) = cli.prompt else {
use clap::CommandFactory;
let _ = Cli::command().print_help();
std::process::exit(2);
};
// --echo stays a bare actor-chain smoke (no server, no key).
if cli.echo {
let args = bamboo_agent::actor_cli::ActorRunArgs {
prompt,
model: cli.model,
role: "cli".to_string(),
workspace: cli.workspace,
data_dir: cli.data_dir,
echo: true,
raw: cli.stream_json,
};
if let Err(e) = bamboo_agent::actor_cli::run(args).await {
eprintln!("run failed: {e}");
std::process::exit(1);
}
return;
}
// Full headless server: same data-dir conventions as `serve`.
let bamboo_home_dir = cli
.data_dir
.clone()
.unwrap_or_else(bamboo_config::paths::resolve_bamboo_dir);
bamboo_config::paths::init_bamboo_dir(bamboo_home_dir.clone());
// SAFETY: main thread, before any async runtime work reads the env.
unsafe {
std::env::set_var("BAMBOO_DATA_DIR", bamboo_home_dir.as_os_str());
}
let args = bamboo_agent::headless::HeadlessArgs {
prompt,
session: cli.session,
model: cli.model,
workspace: cli.workspace,
data_dir: bamboo_home_dir,
stream_json: cli.stream_json,
permission_mode: cli.permission_mode,
};
if let Err(e) = bamboo_agent::headless::run(args).await {
eprintln!("run failed: {e}");
std::process::exit(1);
}
return;
}
};
match command {
Commands::Serve {
port,
bind,
data_dir,
static_dir,
workers,
parent_pid,
} => {
let bamboo_home_dir = data_dir
.clone()
.unwrap_or_else(bamboo_config::paths::resolve_bamboo_dir);
// Stabilize the data dir for the lifetime of this process.
bamboo_config::paths::init_bamboo_dir(bamboo_home_dir.clone());
// Keep runtime path resolution consistent: most helpers derive their base dir from
// BAMBOO_DATA_DIR / `${HOME}/.bamboo` via `core::paths::bamboo_dir()`.
// SAFETY: Called on the main thread before any async runtime work begins,
// so no concurrent reads of the env are possible.
unsafe {
std::env::set_var("BAMBOO_DATA_DIR", bamboo_home_dir.as_os_str());
}
// Load config (with env var overrides already applied)
// If --data-dir is specified, load from that directory.
let mut config = bamboo_llm::Config::from_data_dir(Some(bamboo_home_dir.clone()));
// Apply CLI argument overrides (highest priority)
if let Some(p) = port {
config.server.port = p;
}
if let Some(b) = bind {
config.server.bind = b;
}
if let Some(s) = static_dir {
config.server.static_dir = Some(s);
}
if let Some(w) = workers {
config.server.workers = w;
}
// Map config-level worker count into an env var that the server entrypoints can
// consume without requiring breaking signature changes.
// SAFETY: Still on the main thread before async work begins.
if workers.is_some() || std::env::var("BAMBOO_WORKERS").is_err() {
unsafe {
std::env::set_var("BAMBOO_WORKERS", config.server.workers.to_string());
}
}
// Orphan guard: when spawned as a sidecar, watch the parent process and
// exit if it goes away — normal exit OR SIGKILL/force-quit, which run no
// cleanup. Polled on a dedicated OS thread so it is independent of the
// async runtime (once actix-web is serving it owns the runtime) and of
// how the parent wired our stdio — a Tauri sidecar does not hand us a
// pipe whose EOF we could watch, so a PID poll is the portable signal.
if let Some(ppid) = parent_pid {
spawn_orphan_guard(ppid);
}
// Start server using the unified config
println!("Starting Bamboo server at {}", config.server_addr());
let result = if config.server.static_dir.is_some() {
bamboo_agent::server::run_with_bind_and_static(
bamboo_home_dir,
config.server.port,
&config.server.bind,
config.server.static_dir.clone(),
)
.await
} else {
bamboo_agent::server::run_with_bind(
bamboo_home_dir,
config.server.port,
&config.server.bind,
)
.await
};
if let Err(e) = result {
eprintln!("Failed to start server: {}", e);
std::process::exit(1);
}
}
Commands::SubagentWorker => {
if let Err(e) = bamboo_agent::subagent_worker::run().await {
eprintln!("subagent-worker failed: {e}");
std::process::exit(1);
}
}
Commands::Actor { command } => {
let result = match command {
ActorCommands::Run {
prompt,
model,
role,
workspace,
data_dir,
echo,
raw,
} => {
bamboo_agent::actor_cli::run(bamboo_agent::actor_cli::ActorRunArgs {
prompt,
model,
role,
workspace,
data_dir,
echo,
raw,
})
.await
}
ActorCommands::Serve {
role,
id,
model,
workspace,
data_dir,
echo,
} => {
bamboo_agent::actor_cli::serve(bamboo_agent::actor_cli::ActorServeArgs {
role,
id,
model,
workspace,
data_dir,
echo,
})
.await
}
ActorCommands::List => bamboo_agent::actor_cli::list().await,
ActorCommands::Call { agent, prompt, raw } => {
bamboo_agent::actor_cli::call(bamboo_agent::actor_cli::ActorCallArgs {
agent,
prompt,
raw,
})
.await
}
};
if let Err(e) = result {
eprintln!("actor command failed: {e}");
std::process::exit(1);
}
}
Commands::Broker { command } => {
let BrokerCommands::Serve { bind, token, root } = command;
let token = match token
.or_else(|| std::env::var("BAMBOO_BROKER_TOKEN").ok())
.filter(|t| !t.is_empty())
{
Some(t) => t,
None => {
eprintln!(
"broker: a Bearer token is required (pass --token or set BAMBOO_BROKER_TOKEN)"
);
std::process::exit(1);
}
};
let root =
root.unwrap_or_else(|| bamboo_config::paths::resolve_bamboo_dir().join("broker"));
let listener = match tokio::net::TcpListener::bind(&bind).await {
Ok(l) => l,
Err(e) => {
eprintln!("broker: failed to bind {bind}: {e}");
std::process::exit(1);
}
};
let addr = listener
.local_addr()
.map(|a| a.to_string())
.unwrap_or_else(|_| bind.clone());
tracing::info!(%addr, root = %root.display(), "bamboo broker serving");
let core = std::sync::Arc::new(bamboo_broker::BrokerCore::new(root));
let server = std::sync::Arc::new(bamboo_broker::BrokerServer::new(core, token));
if let Err(e) = server.serve(listener).await {
eprintln!("broker server failed: {e}");
std::process::exit(1);
}
}
Commands::BrokerAgent { command } => {
let BrokerAgentCommands::Serve {
broker,
token,
id,
role,
model,
workspace,
echo,
mcp_proxy,
} = command;
let token = match token
.or_else(|| std::env::var("BAMBOO_BROKER_TOKEN").ok())
.filter(|t| !t.is_empty())
{
Some(t) => t,
None => {
eprintln!(
"broker-agent: a Bearer token is required (pass --token or set BAMBOO_BROKER_TOKEN)"
);
std::process::exit(1);
}
};
let result =
bamboo_agent::broker_agent::run(bamboo_agent::broker_agent::BrokerAgentArgs {
broker,
token,
id,
role,
model,
workspace,
echo,
mcp_proxy,
})
.await;
if let Err(e) = result {
eprintln!("broker-agent failed: {e}");
std::process::exit(1);
}
}
Commands::Config { path, show_secrets } => {
if path {
println!("{}", bamboo_config::paths::config_json_path().display());
} else {
let mut config = Config::new();
config.normalize_tool_settings();
let config_value = match serialize_config_for_cli(config, show_secrets) {
Ok(value) => value,
Err(e) => {
eprintln!("Failed to serialize config: {}", e);
std::process::exit(1);
}
};
match serde_json::to_string_pretty(&config_value) {
Ok(json) => println!("{}", json),
Err(e) => {
eprintln!("Failed to render config as JSON: {}", e);
std::process::exit(1);
}
}
}
}
Commands::Health { conn } => {
if let Err(e) = bamboo_agent::admin_cli::health(conn.into()).await {
eprintln!("{e}");
std::process::exit(1);
}
}
Commands::Status { conn } => {
if let Err(e) = bamboo_agent::admin_cli::status(conn.into()).await {
eprintln!("{e}");
std::process::exit(1);
}
}
Commands::Sessions { conn } => {
if let Err(e) = bamboo_agent::admin_cli::sessions_list(conn.into()).await {
eprintln!("{e}");
std::process::exit(1);
}
}
Commands::Stop { session_id, conn } => {
if let Err(e) = bamboo_agent::admin_cli::stop(conn.into(), &session_id).await {
eprintln!("{e}");
std::process::exit(1);
}
}
}
}
fn serialize_config_for_cli(
mut config: Config,
show_secrets: bool,
) -> bamboo_agent::Result<serde_json::Value> {
config.refresh_proxy_auth_encrypted()?;
config.refresh_provider_api_keys_encrypted()?;
config.refresh_mcp_secrets_encrypted()?;
config.normalize_tool_settings();
let mut value = serde_json::to_value(&config)?;
if !show_secrets {
value = bamboo_agent::server::handlers::settings::redact_config_for_api(value, &config);
}
Ok(value)
}
#[cfg(test)]
mod tests {
use super::serialize_config_for_cli;
use bamboo_config::{Config, OpenAIConfig, ProviderConfigs, ProxyAuth};
use bamboo_mcp::{McpServerConfig, StdioConfig, TransportConfig};
use serde_json::json;
use std::collections::{BTreeMap, HashMap};
// fields set conditionally below
#[allow(clippy::field_reassign_with_default)]
fn configured_config() -> Config {
let mut config = Config::default();
config.proxy_auth = Some(ProxyAuth {
username: "alice".to_string(),
password: "secret".to_string(),
});
config.providers = ProviderConfigs {
openai: Some(OpenAIConfig {
api_key: "sk-cli-secret".to_string(),
api_key_encrypted: None,
base_url: Some("https://api.openai.com/v1".to_string()),
model: Some("gpt-4o".to_string()),
fast_model: None,
vision_model: None,
reasoning_effort: None,
responses_only_models: vec![],
request_overrides: None,
extra: BTreeMap::new(),
}),
..ProviderConfigs::default()
};
config.tools.disabled = vec![" bash ".to_string(), "read_file".to_string()];
config.mcp.servers.push(McpServerConfig {
id: "stdio-server".to_string(),
name: None,
enabled: true,
transport: TransportConfig::Stdio(StdioConfig {
command: "node".to_string(),
args: vec!["server.js".to_string()],
cwd: None,
env: HashMap::from([("TOKEN".to_string(), "super-secret".to_string())]),
env_encrypted: HashMap::new(),
startup_timeout_ms: 5_000,
}),
request_timeout_ms: 5_000,
healthcheck_interval_ms: 1_000,
reconnect: Default::default(),
allowed_tools: vec![],
denied_tools: vec![],
});
config
}
#[test]
fn serialize_config_for_cli_redacts_sensitive_fields_by_default() {
let value = serialize_config_for_cli(configured_config(), false)
.expect("CLI config should serialize");
assert_eq!(value["providers"]["openai"]["api_key"], "****...****");
assert!(value["providers"]["openai"]
.as_object()
.is_some_and(|obj| !obj.contains_key("api_key_encrypted")));
assert!(value.get("proxy_auth_encrypted").is_none());
assert_eq!(
value["mcpServers"]["stdio-server"]["env"]["TOKEN"],
"****...****"
);
assert_eq!(value["tools"]["disabled"], json!(["Bash", "Read"]));
}
#[test]
fn serialize_config_for_cli_can_include_secrets_when_requested() {
let value = serialize_config_for_cli(configured_config(), true)
.expect("CLI config should serialize");
assert!(value["providers"]["openai"]["api_key_encrypted"]
.as_str()
.is_some());
assert!(value.get("proxy_auth_encrypted").is_some());
assert_eq!(
value["mcpServers"]["stdio-server"]["env"]["TOKEN"],
"super-secret"
);
assert_eq!(value["tools"]["disabled"], json!(["Bash", "Read"]));
}
}