Repository navigation
Expand file tree
/
Copy pathmain.rs
More file actions
390 lines (382 loc) · 13.9 KB
/
Copy pathmain.rs
File metadata and controls
390 lines (382 loc) · 13.9 KB
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
//! Runner process entry: argument parsing, startup and exit only.
mod webcodex_runner;
use std::path::PathBuf;
use tracing_subscriber::EnvFilter;
use webcodex_build_info as build_info;
use webcodex_runner::config::{
client_profile_runner_config, default_config_path, load_config, load_config_with_server_url,
validate_client_profile,
};
use webcodex_runner::transport::{registration::process_started_at, run_runner};
#[derive(Debug, Clone, PartialEq, Eq)]
enum RunnerCliAction {
Run {
config_path: PathBuf,
server_url: Option<String>,
once: bool,
stop_on_stdin_eof: bool,
computer_session_dir: Option<PathBuf>,
},
CheckConfig {
config_path: PathBuf,
},
ComputerSessionHelper {
session_state_dir: PathBuf,
},
Exit {
code: i32,
stdout: String,
stderr: String,
},
}
fn usage() -> &'static str {
"Usage: webcodex-runner [--config PATH] [--server-url URL] [--once] [--stop-on-stdin-eof] [--computer-session-dir PATH]\n\n\
Options:\n\
-h, --help Print help and exit\n\
-V, --version Print version and exit\n\
-c, --config PATH Runner config path for normal runtime\n\
--server-url URL Server origin; overrides runner.toml server_url for this process\n\
--check-config Validate configuration without starting a Runner\n\
--profile NAME Client config profile for default config path\n\
--once Complete one successful poll, then exit (polling transport)\n\
--stop-on-stdin-eof Stop when the invoking parent closes stdin\n\n\
--computer-session-dir PATH Route Computer calls to login-session helper\n\
--computer-session-helper --session-state-dir PATH Run login-session helper\n\n\
With --profile, the default config path is derived under\n\
/etc/webcodex/clients/<profile> for root or\n\
~/.config/webcodex/clients/<profile> for non-root users. Explicit\n\
--config overrides the profile-derived default.\n\n\
Environment:\n\
WEBCODEX_RUNNER_CONFIG default config path override\n\
Example runner.toml:\n\
server_url = \"https://v4.yyjeqhc.cn\"\n\
token = \"...\"\n\
client_id = \"xrh\"\n\
display_name = \"XRH\"\n\
owner = \"yyjeqhc\"\n\
project_registry_dir = \"/root/.config/webcodex/project-registry\"\n\
poll_interval_ms = 1000\n\
\n\
[policy]\n\
allow_raw_shell = true\n\
allow_cwd_anywhere = true\n\
max_timeout_secs = 3600\n\
max_output_bytes = 262144\n"
}
fn parse_args() -> Result<RunnerCliAction, String> {
parse_runner_args(std::env::args().skip(1))
}
#[cfg(windows)]
fn parse_service_runner_args(args: &[String]) -> Result<(PathBuf, PathBuf), String> {
if args.len() != 4
|| args[0] != "--config"
|| args[2] != "--computer-session-dir"
|| args[1].is_empty()
|| args[3].is_empty()
{
return Err("Runner service requires --config PATH --computer-session-dir PATH".into());
}
Ok((PathBuf::from(&args[1]), PathBuf::from(&args[3])))
}
fn parse_runner_args<I, S>(args: I) -> Result<RunnerCliAction, String>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let args: Vec<String> = args
.into_iter()
.map(|arg| arg.as_ref().to_string())
.collect();
if args
.first()
.is_some_and(|arg| arg == "--computer-session-helper")
{
if args.len() != 3 || args[1] != "--session-state-dir" || args[2].is_empty() {
return Err(
"computer session helper requires only --session-state-dir PATH".to_string(),
);
}
return Ok(RunnerCliAction::ComputerSessionHelper {
session_state_dir: PathBuf::from(&args[2]),
});
}
if args.len() == 1 {
match args[0].as_str() {
"--build-info-json" => {
return Ok(RunnerCliAction::Exit {
code: 0,
stdout: build_info::build_info_json("webcodex-runner"),
stderr: String::new(),
});
}
"--help" | "-h" => {
return Ok(RunnerCliAction::Exit {
code: 0,
stdout: usage().to_string(),
stderr: String::new(),
});
}
"--version" | "-V" => {
return Ok(RunnerCliAction::Exit {
code: 0,
stdout: build_info::version_output("webcodex-runner"),
stderr: String::new(),
});
}
_ => {}
}
}
let runner_config_env = std::env::var("WEBCODEX_RUNNER_CONFIG").ok();
let mut config_path: Option<PathBuf> = None;
let mut profile: Option<String> = None;
let mut server_url = None;
let mut check_config = false;
let mut once = false;
let mut stop_on_stdin_eof = false;
let mut computer_session_dir = None;
let mut args = args.into_iter();
while let Some(arg) = args.next() {
match arg.as_str() {
"--help" | "-h" => {
return Ok(RunnerCliAction::Exit {
code: 0,
stdout: usage().to_string(),
stderr: String::new(),
});
}
"--version" | "-V" => {
return Ok(RunnerCliAction::Exit {
code: 0,
stdout: build_info::version_output("webcodex-runner"),
stderr: String::new(),
});
}
"--server-url" => {
if server_url.is_some() {
return Err("--server-url must be specified only once".into());
}
server_url = Some(args.next().ok_or("--server-url requires a URL")?);
}
"--check-config" => check_config = true,
"--once" => once = true,
"--stop-on-stdin-eof" => stop_on_stdin_eof = true,
"--computer-session-dir" => {
let Some(path) = args.next() else {
return Err("--computer-session-dir requires a path".to_string());
};
computer_session_dir = Some(PathBuf::from(path));
}
"--config" | "-c" => {
let Some(path) = args.next() else {
return Err("--config requires a path".to_string());
};
config_path = Some(PathBuf::from(path));
}
"--profile" => {
let Some(value) = args.next() else {
return Err("--profile requires a value".to_string());
};
profile = Some(value);
}
_ => return Err(format!("unknown argument: {}\n{}", arg, usage())),
}
}
let profile = profile
.as_deref()
.map(validate_client_profile)
.transpose()?;
let config_path = if let Some(config_path) = config_path {
config_path
} else if let Some(profile) = profile {
client_profile_runner_config(&profile)?
} else {
runner_config_env
.map(PathBuf::from)
.map(Ok)
.unwrap_or_else(default_config_path)?
};
if check_config {
if once || stop_on_stdin_eof || computer_session_dir.is_some() || server_url.is_some() {
return Err("--check-config cannot be combined with runtime-only options".into());
}
return Ok(RunnerCliAction::CheckConfig { config_path });
}
Ok(RunnerCliAction::Run {
config_path,
server_url,
once,
stop_on_stdin_eof,
computer_session_dir,
})
}
fn main() {
let raw_args: Vec<String> = std::env::args().skip(1).collect();
let service = match webcodex_environment::runtime_entry::split_windows_service_args(&raw_args) {
Ok(service) => service,
Err(error) => {
eprintln!("{error}");
std::process::exit(2);
}
};
if let Some((name, args)) = service {
#[cfg(windows)]
{
let (config_path, computer_session_dir) = match parse_service_runner_args(&args) {
Ok(paths) => paths,
Err(error) => {
eprintln!("{error}");
std::process::exit(2);
}
};
let result =
webcodex_environment::service::runtime::run_windows_service(&name, move |stop| {
let log_dir = config_path
.parent()
.ok_or("Runner config has no parent directory")?;
let mut service_log = webcodex_environment::service::ServiceLogGuard::open(
log_dir,
webcodex_environment::service::Component::Runner,
)?;
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
let _ = tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("info")),
)
.try_init();
let cfg = load_config(&config_path)?;
let result = run_runner(
cfg,
config_path,
false,
false,
Some(computer_session_dir),
Some(stop),
);
if result.is_ok() {
service_log.stopped()?;
}
result
});
if let Err(error) = result {
eprintln!("webcodex-runner service failed: {error}");
std::process::exit(1);
}
return;
}
#[cfg(not(windows))]
{
let _ = (name, args);
unreachable!("service prefix rejected on non-Windows");
}
}
if let Some(code) = webcodex_runner::detached_job::maybe_run_internal_mode(raw_args.iter()) {
std::process::exit(code);
}
// Pin the process start timestamp before any transport work so register
// payloads report real process identity even after reconnect loops.
let _ = process_started_at();
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
let _ = tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
)
.try_init();
let action = match parse_args() {
Ok(v) => v,
Err(e) => {
eprintln!("{}", e);
std::process::exit(2);
}
};
let (config_path, server_url, once, stop_on_stdin_eof, computer_session_dir) = match action {
RunnerCliAction::Run {
config_path,
server_url,
once,
stop_on_stdin_eof,
computer_session_dir,
} => (
config_path,
server_url,
once,
stop_on_stdin_eof,
computer_session_dir,
),
RunnerCliAction::CheckConfig { config_path } => {
// Use exactly the native loader, before logs, providers or network
// startup. Parse errors can quote secret TOML values: do not echo them.
if load_config(&config_path).is_err() {
eprintln!("Runner configuration invalid or unreadable. Check the current configuration contract; use project_registry_dir, not projects_dir. No Runner was started.");
std::process::exit(2);
}
println!("WebCodex Runner configuration valid");
return;
}
RunnerCliAction::ComputerSessionHelper { session_state_dir } => {
if let Err(error) = webcodex_runner::computer_session::run_helper(&session_state_dir) {
eprintln!("{error}");
std::process::exit(2);
}
return;
}
RunnerCliAction::Exit {
code,
stdout,
stderr,
} => {
if !stdout.is_empty() {
print!("{}", stdout);
}
if !stderr.is_empty() {
eprint!("{}", stderr);
}
std::process::exit(code);
}
};
#[cfg(any(target_os = "macos", windows))]
let mut service_log = match webcodex_environment::service::ServiceLogGuard::from_managed_env(
webcodex_environment::service::Component::Runner,
) {
Ok(log) => log,
Err(error) => {
eprintln!("Runner service lifecycle log unavailable: {error}");
std::process::exit(2);
}
};
let cfg = match load_config_with_server_url(&config_path, server_url.as_deref()) {
Ok(cfg) => cfg,
Err(e) => {
#[cfg(any(target_os = "macos", windows))]
drop(service_log);
eprintln!("{}", e);
std::process::exit(2);
}
};
if cfg.token.trim().is_empty() {
eprintln!(
"webcodex-runner warning: agent token is empty; connecting without Authorization; the server must be started with --open"
);
}
if let Err(e) = run_runner(
cfg,
config_path,
once,
stop_on_stdin_eof,
computer_session_dir,
#[cfg(windows)]
None,
) {
#[cfg(any(target_os = "macos", windows))]
drop(service_log);
eprintln!("webcodex-runner failed: {}", e);
std::process::exit(webcodex_runner::transport::failure_exit_code(&e));
}
#[cfg(any(target_os = "macos", windows))]
if let Some(log) = service_log.as_mut() {
let _ = log.stopped();
}
}
#[cfg(test)]
#[path = "main_tests.rs"]
mod tests;