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
use tracing_subscriber::EnvFilter;
use clap::Parser;
use infinity_agent_cli::daemon_client;
use infinity_agent_cli::install;
mod acp_server;
type BoxError = Box<dyn std::error::Error + Send + Sync>;
/// Infinity Agent CLI
#[derive(Parser, Debug)]
#[command(name = "infinity-agent-cli", version, about)]
struct Cli {
#[command(subcommand)]
command: Option<Commands>,
/// Send an initial message to the agent on startup.
#[arg(short = 'i', long = "initial-message")]
initial_message: Option<String>,
/// Send the task to the daemon and exit without opening the TUI.
#[arg(short = 'H', long, conflicts_with = "local")]
headless: Option<String>,
/// Connect directly to an existing session by ID.
#[arg(short = 's', long)]
session: Option<String>,
#[arg(short, long)]
local: bool,
}
#[derive(clap::Subcommand, Debug)]
enum Commands {
/// RAP tool management
Rap {
#[command(subcommand)]
action: RapCommands,
},
/// Model provider management
Provider {
#[command(subcommand)]
action: ProviderCommands,
},
/// Update the CLI itself
Update {
/// Comma-separated list of features to pass to cargo install (overrides auto-detected features)
#[arg(long)]
features: Option<String>,
},
/// Daemon management
Daemon {
#[command(subcommand)]
action: Option<DaemonCommands>,
},
/// Remote daemon management
Remote {
#[command(subcommand)]
action: RemoteCommands,
},
/// Run as an ACP (Agent Client Protocol) stdio server
Acp,
}
#[derive(clap::Subcommand, Debug)]
enum DaemonCommands {
/// Stop the running daemon
Stop,
/// Restart the daemon (stop it if running, then start a fresh instance)
Restart,
}
#[derive(clap::Subcommand, Debug)]
enum RemoteCommands {
/// Add a new remote: infinity remote add <name> -- ssh <ssh_args...>
Add {
/// Name for this remote
name: String,
/// Transport and arguments (passed after --), e.g. "ssh my-host"
#[arg(last = true, required = true)]
args: Vec<String>,
},
}
#[derive(clap::Subcommand, Debug)]
enum RapCommands {
/// Install a RAP crate and register it in rap.json
Install {
/// Install to user-level ~/.infinity/rap.json (required)
#[arg(long)]
user: bool,
/// Crate name to install
#[arg(long = "crate")]
crate_name: String,
/// Git repository URL (passed to cargo install --git)
#[arg(long)]
git: Option<String>,
/// Local path (passed to cargo install --path)
#[arg(long)]
path: Option<String>,
},
/// Re-install all RAP tools that have a recorded source
Update {
/// Update user-level ~/.infinity/rap.json tools (required)
#[arg(long)]
user: bool,
},
}
#[derive(clap::Subcommand, Debug)]
enum ProviderCommands {
/// Install a model provider crate and register it in ~/.infinity/providers.json
Install {
/// Provider id to register under (e.g. "bedrock")
id: String,
/// Crate name to install (its binary becomes the provider command)
#[arg(long = "crate")]
crate_name: String,
/// Git repository URL (passed to cargo install --git)
#[arg(long)]
git: Option<String>,
/// Local path (passed to cargo install --path)
#[arg(long)]
path: Option<String>,
},
/// Re-install all model providers that have a recorded source
Update,
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> std::process::ExitCode {
// Parse CLI arguments via clap.
let cli = Cli::parse();
std::fs::create_dir_all(".infinity").ok();
if !matches!(cli.command, Some(Commands::Daemon { .. })) {
let log_name = if matches!(cli.command, Some(Commands::Acp)) {
"acp.log"
} else {
"cli.log"
};
let log_file = std::fs::File::create(format!(".infinity/{log_name}")).ok();
if let Some(file) = log_file {
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.with_writer(std::sync::Mutex::new(file))
.with_ansi(false)
.init();
}
}
let local = tokio::task::LocalSet::new();
match local.run_until(async_main(cli)).await {
Ok(()) => std::process::ExitCode::SUCCESS,
// Print errors with Display formatting: the default `main` error
// handling uses Debug, which escapes newlines in string-based
// errors and mangles multi-line reports (e.g. captured daemon
// startup output).
Err(e) => {
eprintln!("Error: {e}");
std::process::ExitCode::FAILURE
}
}
}
async fn async_main(cli: Cli) -> Result<(), BoxError> {
// Handle subcommands
if let Some(command) = cli.command {
return match command {
Commands::Acp => acp_server::run().await,
Commands::Update { features } => install::run_self_update(features.as_deref()).await,
Commands::Daemon { action } => match action {
Some(DaemonCommands::Stop) => {
let pid = daemon_client::stop_daemon()
.await?
.ok_or("daemon is not running")?;
println!("daemon stopped (pid {pid})");
Ok(())
}
Some(DaemonCommands::Restart) => daemon_client::restart_daemon().await,
None => infinity_daemon::run_daemon(true).await,
},
Commands::Rap { action } => match action {
RapCommands::Install {
user,
crate_name,
git,
path,
} => {
if !user {
return Err("--user is currently required for rap install".into());
}
install::run_install(install::InstallArgs {
crate_name,
git,
path,
})
.await
}
RapCommands::Update { user } => {
if !user {
return Err("--user is currently required for rap update".into());
}
install::run_update().await
}
},
Commands::Provider { action } => match action {
ProviderCommands::Install {
id,
crate_name,
git,
path,
} => {
install::run_provider_install(install::ProviderInstallArgs {
id,
crate_name,
git,
path,
})
.await
}
ProviderCommands::Update => install::run_provider_update().await,
},
Commands::Remote { action } => match action {
RemoteCommands::Add { name, args } => {
if args.first().map(|s| s.as_str()) != Some("ssh") {
return Err("expected 'ssh' as first argument after --".into());
}
let ssh_args = &args[1..];
if ssh_args.is_empty() {
return Err("no ssh arguments provided after 'ssh'".into());
}
let path = infinity_protocol::remotes_config_path();
let mut remotes: Vec<infinity_daemon::remote::RemoteConfig> =
match std::fs::read_to_string(&path) {
Ok(s) => serde_json::from_str(&s)
.map_err(|e| format!("failed to parse {}: {e}", path.display()))?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
Err(e) => {
return Err(
format!("failed to read {}: {e}", path.display()).into()
);
}
};
if remotes.iter().any(|r| r.name.as_str() == name) {
return Err(format!("remote '{name}' already exists").into());
}
remotes.push(infinity_daemon::remote::RemoteConfig {
name: name.clone().into(),
ssh_args: ssh_args.to_vec(),
});
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).ok();
}
std::fs::write(&path, serde_json::to_string_pretty(&remotes)?)?;
println!("added remote '{name}' (ssh {})", ssh_args.join(" "));
Ok(())
}
},
};
}
// Headless mode: send task to daemon and exit without TUI.
if let Some(message) = cli.headless {
return daemon_client::run_headless(message).await;
}
// Try daemon mode first — auto-launches daemon if not running.
let daemon_err = if cli.local {
None
} else {
match daemon_client::run_with_daemon(cli.initial_message.clone(), cli.session.clone()).await
{
Ok(()) => return Ok(()),
Err(e) => {
tracing::debug!("daemon mode failed, falling back to direct mode: {e}");
Some(format!("{e}"))
}
}
};
// Direct mode: run daemon session manager in-process
run_direct(cli.initial_message, cli.session, daemon_err).await
}
#[tracing::instrument]
async fn run_direct(
initial_message: Option<String>,
session: Option<String>,
daemon_err: Option<String>,
) -> Result<(), BoxError> {
let state_dir = std::env::current_dir()?.join(".infinity");
let mgr = infinity_daemon::launch_session_manager(state_dir)
.await
.map_err(|e| format!("Failed to start callback server: {e}"))?;
tracing::info!("Shared callback server started");
// In-memory channels — no serialization
let (to_daemon_tx, to_daemon_rx) = tokio::sync::mpsc::unbounded_channel();
let (from_daemon_tx, from_daemon_rx) = tokio::sync::mpsc::unbounded_channel();
// Run the daemon's client handler on channels directly
let (_, res) = tokio::join!(
infinity_daemon::client_handler::handle_client_channels(
to_daemon_rx,
from_daemon_tx,
mgr.clone(),
),
daemon_client::run_in_memory(
from_daemon_rx,
to_daemon_tx,
initial_message,
session,
daemon_err
)
);
// Stop every booted RAP server; sessions themselves need no teardown
// (their state is already durable).
let mgr = mgr.lock().await;
mgr.rap_manager.shutdown_all().await;
res
}