aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
468
akode-rs/cli/src/bin/logs_client.rs
Normal file
468
akode-rs/cli/src/bin/logs_client.rs
Normal file
@@ -0,0 +1,468 @@
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use chrono::DateTime;
|
||||
use clap::Parser;
|
||||
use clap::ValueEnum;
|
||||
use akode_core::config::ConfigBuilder;
|
||||
use akode_state::LogQuery;
|
||||
use akode_state::LogRow;
|
||||
use akode_state::SqliteConfig;
|
||||
use akode_state::StateRuntime;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use owo_colors::OwoColorize;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(name = "codex-state-logs")]
|
||||
#[command(about = "Tail aKode logs from the dedicated logs SQLite DB with simple filters")]
|
||||
struct Args {
|
||||
/// Path to AKODE_HOME. Defaults to $AKODE_HOME or ~/.akode.
|
||||
#[arg(long, env = "AKODE_HOME")]
|
||||
codex_home: Option<PathBuf>,
|
||||
|
||||
/// Direct path to the logs SQLite database. Overrides --codex-home.
|
||||
#[arg(long)]
|
||||
db: Option<PathBuf>,
|
||||
|
||||
/// Minimum log level to include.
|
||||
#[arg(long, value_enum, ignore_case = true)]
|
||||
level: Option<LogLevelThreshold>,
|
||||
|
||||
/// Start timestamp (RFC3339 or unix seconds).
|
||||
#[arg(long, value_name = "RFC3339|UNIX")]
|
||||
from: Option<String>,
|
||||
|
||||
/// End timestamp (RFC3339 or unix seconds).
|
||||
#[arg(long, value_name = "RFC3339|UNIX")]
|
||||
to: Option<String>,
|
||||
|
||||
/// Substring match on module_path. Repeat to include multiple substrings.
|
||||
#[arg(long = "module")]
|
||||
module: Vec<String>,
|
||||
|
||||
/// Substring match on file path. Repeat to include multiple substrings.
|
||||
#[arg(long = "file")]
|
||||
file: Vec<String>,
|
||||
|
||||
/// Match one or more thread ids. Repeat to include multiple threads.
|
||||
#[arg(long = "thread-id")]
|
||||
thread_id: Vec<String>,
|
||||
|
||||
/// Substring match against the rendered log body.
|
||||
#[arg(long)]
|
||||
search: Option<String>,
|
||||
|
||||
/// Include logs that do not have a thread id.
|
||||
#[arg(long)]
|
||||
threadless: bool,
|
||||
|
||||
/// Number of matching rows to show before tailing.
|
||||
#[arg(long, default_value_t = 200)]
|
||||
backfill: usize,
|
||||
|
||||
/// Poll interval in milliseconds.
|
||||
#[arg(long, default_value_t = 500)]
|
||||
poll_ms: u64,
|
||||
|
||||
/// Show compact output with only time, level, and rendered log body.
|
||||
#[arg(long)]
|
||||
compact: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct LogFilter {
|
||||
levels_upper: Vec<String>,
|
||||
from_ts: Option<i64>,
|
||||
to_ts: Option<i64>,
|
||||
module_like: Vec<String>,
|
||||
file_like: Vec<String>,
|
||||
thread_ids: Vec<String>,
|
||||
search: Option<String>,
|
||||
include_threadless: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
enum LogLevelThreshold {
|
||||
Trace,
|
||||
Debug,
|
||||
Info,
|
||||
Warn,
|
||||
Error,
|
||||
}
|
||||
|
||||
impl LogLevelThreshold {
|
||||
fn levels_upper(self) -> Vec<String> {
|
||||
let levels = match self {
|
||||
LogLevelThreshold::Trace => &["TRACE", "DEBUG", "INFO", "WARN", "ERROR"][..],
|
||||
LogLevelThreshold::Debug => &["DEBUG", "INFO", "WARN", "ERROR"],
|
||||
LogLevelThreshold::Info => &["INFO", "WARN", "ERROR"],
|
||||
LogLevelThreshold::Warn => &["WARN", "ERROR"],
|
||||
LogLevelThreshold::Error => &["ERROR"],
|
||||
};
|
||||
levels.iter().map(ToString::to_string).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let args = Args::parse();
|
||||
let sqlite = resolve_sqlite_config(&args).await?;
|
||||
let filter = build_filter(&args)?;
|
||||
let runtime = StateRuntime::init(sqlite, "logs-client".to_string()).await?;
|
||||
|
||||
let mut last_id =
|
||||
print_backfill(runtime.as_ref(), &filter, args.backfill, args.compact).await?;
|
||||
if last_id == 0 {
|
||||
last_id = fetch_max_id(runtime.as_ref(), &filter).await?;
|
||||
}
|
||||
|
||||
let poll_interval = Duration::from_millis(args.poll_ms);
|
||||
loop {
|
||||
let rows = fetch_new_rows(runtime.as_ref(), &filter, last_id).await?;
|
||||
for row in rows {
|
||||
last_id = last_id.max(row.id);
|
||||
println!("{}", format_row(&row, args.compact));
|
||||
}
|
||||
tokio::time::sleep(poll_interval).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_sqlite_config(args: &Args) -> anyhow::Result<SqliteConfig> {
|
||||
if let Some(db_path) = args.db.as_ref() {
|
||||
let sqlite_home = db_path
|
||||
.parent()
|
||||
.map(ToOwned::to_owned)
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
return Ok(SqliteConfig::from_sqlite_home_with_nfs_enforcement(
|
||||
AbsolutePathBuf::relative_to_current_dir(sqlite_home)?,
|
||||
/*enforce_delete_on_nfs*/ false,
|
||||
));
|
||||
}
|
||||
|
||||
let mut config_builder = ConfigBuilder::default();
|
||||
if let Some(codex_home) = args.codex_home.as_ref() {
|
||||
config_builder = config_builder.codex_home(codex_home.clone());
|
||||
}
|
||||
let config = config_builder.build().await?;
|
||||
Ok(config.sqlite_config().clone())
|
||||
}
|
||||
|
||||
fn build_filter(args: &Args) -> anyhow::Result<LogFilter> {
|
||||
let from_ts = args
|
||||
.from
|
||||
.as_deref()
|
||||
.map(parse_timestamp)
|
||||
.transpose()
|
||||
.context("failed to parse --from")?;
|
||||
let to_ts = args
|
||||
.to
|
||||
.as_deref()
|
||||
.map(parse_timestamp)
|
||||
.transpose()
|
||||
.context("failed to parse --to")?;
|
||||
|
||||
let levels_upper = args
|
||||
.level
|
||||
.map_or_else(Vec::new, LogLevelThreshold::levels_upper);
|
||||
let module_like = args
|
||||
.module
|
||||
.iter()
|
||||
.filter(|module| !module.is_empty())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let file_like = args
|
||||
.file
|
||||
.iter()
|
||||
.filter(|file| !file.is_empty())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let thread_ids = args
|
||||
.thread_id
|
||||
.iter()
|
||||
.filter(|thread_id| !thread_id.is_empty())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(LogFilter {
|
||||
levels_upper,
|
||||
from_ts,
|
||||
to_ts,
|
||||
module_like,
|
||||
file_like,
|
||||
thread_ids,
|
||||
search: args.search.clone(),
|
||||
include_threadless: args.threadless,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_timestamp(value: &str) -> anyhow::Result<i64> {
|
||||
if let Ok(secs) = value.parse::<i64>() {
|
||||
return Ok(secs);
|
||||
}
|
||||
|
||||
let dt = DateTime::parse_from_rfc3339(value)
|
||||
.with_context(|| format!("expected RFC3339 or unix seconds, got {value}"))?;
|
||||
Ok(dt.timestamp())
|
||||
}
|
||||
|
||||
async fn print_backfill(
|
||||
runtime: &StateRuntime,
|
||||
filter: &LogFilter,
|
||||
backfill: usize,
|
||||
compact: bool,
|
||||
) -> anyhow::Result<i64> {
|
||||
if backfill == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let mut rows = fetch_backfill(runtime, filter, backfill).await?;
|
||||
rows.reverse();
|
||||
|
||||
let mut last_id = 0;
|
||||
for row in rows {
|
||||
last_id = last_id.max(row.id);
|
||||
println!("{}", format_row(&row, compact));
|
||||
}
|
||||
Ok(last_id)
|
||||
}
|
||||
|
||||
async fn fetch_backfill(
|
||||
runtime: &StateRuntime,
|
||||
filter: &LogFilter,
|
||||
backfill: usize,
|
||||
) -> anyhow::Result<Vec<LogRow>> {
|
||||
let query = to_log_query(
|
||||
filter,
|
||||
Some(backfill),
|
||||
/*after_id*/ None,
|
||||
/*descending*/ true,
|
||||
);
|
||||
runtime
|
||||
.query_logs(&query)
|
||||
.await
|
||||
.context("failed to fetch backfill logs")
|
||||
}
|
||||
|
||||
async fn fetch_new_rows(
|
||||
runtime: &StateRuntime,
|
||||
filter: &LogFilter,
|
||||
last_id: i64,
|
||||
) -> anyhow::Result<Vec<LogRow>> {
|
||||
let query = to_log_query(
|
||||
filter,
|
||||
/*limit*/ None,
|
||||
Some(last_id),
|
||||
/*descending*/ false,
|
||||
);
|
||||
runtime
|
||||
.query_logs(&query)
|
||||
.await
|
||||
.context("failed to fetch new logs")
|
||||
}
|
||||
|
||||
async fn fetch_max_id(runtime: &StateRuntime, filter: &LogFilter) -> anyhow::Result<i64> {
|
||||
let query = to_log_query(
|
||||
filter, /*limit*/ None, /*after_id*/ None, /*descending*/ false,
|
||||
);
|
||||
runtime
|
||||
.max_log_id(&query)
|
||||
.await
|
||||
.context("failed to fetch max log id")
|
||||
}
|
||||
|
||||
fn to_log_query(
|
||||
filter: &LogFilter,
|
||||
limit: Option<usize>,
|
||||
after_id: Option<i64>,
|
||||
descending: bool,
|
||||
) -> LogQuery {
|
||||
LogQuery {
|
||||
levels_upper: filter.levels_upper.clone(),
|
||||
from_ts: filter.from_ts,
|
||||
to_ts: filter.to_ts,
|
||||
module_like: filter.module_like.clone(),
|
||||
file_like: filter.file_like.clone(),
|
||||
thread_ids: filter.thread_ids.clone(),
|
||||
search: filter.search.clone(),
|
||||
include_threadless: filter.include_threadless,
|
||||
after_id,
|
||||
limit,
|
||||
descending,
|
||||
}
|
||||
}
|
||||
|
||||
fn format_row(row: &LogRow, compact: bool) -> String {
|
||||
let timestamp = formatter::ts(row.ts, row.ts_nanos, compact);
|
||||
let level = row.level.as_str();
|
||||
let target = row.target.as_str();
|
||||
let message = row.message.as_deref().unwrap_or("");
|
||||
let level_colored = formatter::level(level);
|
||||
let timestamp_colored = timestamp.dimmed().to_string();
|
||||
let thread_id = row.thread_id.as_deref().unwrap_or("-");
|
||||
let thread_id_colored = thread_id.blue().dimmed().to_string();
|
||||
let target_colored = target.dimmed().to_string();
|
||||
let message_colored = heuristic_formatting(message);
|
||||
if compact {
|
||||
format!("{timestamp_colored} {level_colored} {message_colored}")
|
||||
} else {
|
||||
format!(
|
||||
"{timestamp_colored} {level_colored} [{thread_id_colored}] {target_colored} - {message_colored}"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn heuristic_formatting(message: &str) -> String {
|
||||
if matcher::apply_patch(message) {
|
||||
formatter::apply_patch(message)
|
||||
} else {
|
||||
message.bold().to_string()
|
||||
}
|
||||
}
|
||||
|
||||
mod matcher {
|
||||
pub(super) fn apply_patch(message: &str) -> bool {
|
||||
message.contains("ToolCall: apply_patch")
|
||||
}
|
||||
}
|
||||
|
||||
mod formatter {
|
||||
use chrono::DateTime;
|
||||
use chrono::SecondsFormat;
|
||||
use chrono::Utc;
|
||||
use owo_colors::OwoColorize;
|
||||
|
||||
pub(super) fn apply_patch(message: &str) -> String {
|
||||
message
|
||||
.lines()
|
||||
.map(|line| {
|
||||
if line.starts_with('+') {
|
||||
line.green().bold().to_string()
|
||||
} else if line.starts_with('-') {
|
||||
line.red().bold().to_string()
|
||||
} else {
|
||||
line.bold().to_string()
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
pub(super) fn ts(ts: i64, ts_nanos: i64, compact: bool) -> String {
|
||||
let nanos = u32::try_from(ts_nanos).unwrap_or(0);
|
||||
match DateTime::<Utc>::from_timestamp(ts, nanos) {
|
||||
Some(dt) if compact => dt.format("%H:%M:%S").to_string(),
|
||||
Some(dt) => dt.to_rfc3339_opts(SecondsFormat::Millis, true),
|
||||
None => format!("{ts}.{ts_nanos:09}Z"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn level(level: &str) -> String {
|
||||
let padded = format!("{level:<5}");
|
||||
if level.eq_ignore_ascii_case("error") {
|
||||
return padded.red().bold().to_string();
|
||||
}
|
||||
if level.eq_ignore_ascii_case("warn") {
|
||||
return padded.yellow().bold().to_string();
|
||||
}
|
||||
if level.eq_ignore_ascii_case("info") {
|
||||
return padded.green().bold().to_string();
|
||||
}
|
||||
if level.eq_ignore_ascii_case("debug") {
|
||||
return padded.blue().bold().to_string();
|
||||
}
|
||||
if level.eq_ignore_ascii_case("trace") {
|
||||
return padded.magenta().bold().to_string();
|
||||
}
|
||||
padded.bold().to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[test]
|
||||
fn log_level_threshold_includes_more_severe_levels() {
|
||||
assert_eq!(
|
||||
LogLevelThreshold::Warn.levels_upper(),
|
||||
vec!["WARN".to_string(), "ERROR".to_string()]
|
||||
);
|
||||
assert_eq!(
|
||||
LogLevelThreshold::Trace.levels_upper(),
|
||||
vec![
|
||||
"TRACE".to_string(),
|
||||
"DEBUG".to_string(),
|
||||
"INFO".to_string(),
|
||||
"WARN".to_string(),
|
||||
"ERROR".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_level_rejects_aliases_and_unknown_values() {
|
||||
assert!(Args::try_parse_from(["codex-state-logs", "--level", "warning"]).is_err());
|
||||
assert!(Args::try_parse_from(["codex-state-logs", "--level", "err"]).is_err());
|
||||
assert!(Args::try_parse_from(["codex-state-logs", "--level", "warn,error"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_level_accepts_canonical_values_case_insensitively() {
|
||||
let args = Args::try_parse_from(["codex-state-logs", "--level", "WARN"])
|
||||
.expect("parse uppercase log level");
|
||||
|
||||
assert_eq!(args.level, Some(LogLevelThreshold::Warn));
|
||||
}
|
||||
|
||||
/// Explicit database selection must not parse an overridden Codex home.
|
||||
#[tokio::test]
|
||||
async fn direct_db_skips_codex_home_config() {
|
||||
let codex_home = tempfile::tempdir().expect("create Codex home");
|
||||
std::fs::write(codex_home.path().join("config.toml"), "model = [")
|
||||
.expect("write invalid config");
|
||||
let sqlite_home = tempfile::tempdir().expect("create SQLite home");
|
||||
let db_path = sqlite_home.path().join("logs_2.sqlite");
|
||||
let args = Args::try_parse_from([
|
||||
OsString::from("codex-state-logs"),
|
||||
OsString::from("--codex-home"),
|
||||
codex_home.path().as_os_str().to_owned(),
|
||||
OsString::from("--db"),
|
||||
db_path.as_os_str().to_owned(),
|
||||
])
|
||||
.expect("parse arguments");
|
||||
|
||||
let sqlite = resolve_sqlite_config(&args)
|
||||
.await
|
||||
.expect("resolve SQLite config");
|
||||
|
||||
assert_eq!(sqlite.logs_db_path(), db_path);
|
||||
}
|
||||
|
||||
/// Direct database selection must preserve native path bytes.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn direct_db_preserves_non_utf8_path() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let mut db_path = temp_dir.path().as_os_str().as_bytes().to_vec();
|
||||
db_path.extend_from_slice(b"/non-utf8-\xff/logs_2.sqlite");
|
||||
let db_path = PathBuf::from(OsString::from_vec(db_path));
|
||||
let args = Args::try_parse_from([
|
||||
OsString::from("codex-state-logs"),
|
||||
OsString::from("--db"),
|
||||
db_path.as_os_str().to_owned(),
|
||||
])
|
||||
.expect("parse arguments");
|
||||
|
||||
let sqlite = resolve_sqlite_config(&args)
|
||||
.await
|
||||
.expect("resolve SQLite config");
|
||||
|
||||
assert_eq!(sqlite.logs_db_path(), db_path);
|
||||
}
|
||||
}
|
||||
29
akode-rs/cli/src/config_override_args.rs
Normal file
29
akode-rs/cli/src/config_override_args.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
//! Preserve config overrides across command boundaries without changing typed child arguments.
|
||||
|
||||
use crate::MultitoolCli;
|
||||
use clap::CommandFactory;
|
||||
use clap::FromArgMatches;
|
||||
use akode_utils_cli::collect_config_overrides;
|
||||
use std::ffi::OsString;
|
||||
|
||||
pub(super) fn try_parse_from(
|
||||
args: impl IntoIterator<Item = impl Into<OsString>>,
|
||||
) -> Result<MultitoolCli, clap::Error> {
|
||||
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
|
||||
let mut command = MultitoolCli::command();
|
||||
let mut matches = command.try_get_matches_from_mut(&args)?;
|
||||
crate::queue_cmd::validate_options(&command, &matches)?;
|
||||
let mut cli = MultitoolCli::from_arg_matches_mut(&mut matches)
|
||||
.map_err(|error| error.format(&mut command))?;
|
||||
if cli.subcommand.is_none() || cli.config_overrides.raw_overrides.is_empty() {
|
||||
return Ok(cli);
|
||||
}
|
||||
|
||||
// Keep child copies unchanged: dispatch merges apply them after feature overrides.
|
||||
cli.config_overrides = collect_config_overrides(MultitoolCli::command(), args)?;
|
||||
Ok(cli)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "config_override_args_tests.rs"]
|
||||
mod tests;
|
||||
37
akode-rs/cli/src/config_override_args_tests.rs
Normal file
37
akode-rs/cli/src/config_override_args_tests.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
//! Regression coverage for overrides split across CLI command boundaries.
|
||||
|
||||
use super::try_parse_from;
|
||||
use crate::Subcommand;
|
||||
use crate::mcp_cmd::McpSubcommand;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn preserves_scoped_overrides_and_forwarded_arguments() {
|
||||
let cli = try_parse_from([
|
||||
"codex",
|
||||
"--config=a=1",
|
||||
"mcp",
|
||||
"-cb=2",
|
||||
"add",
|
||||
"example",
|
||||
"-c",
|
||||
"a=3",
|
||||
"--",
|
||||
"program",
|
||||
"-c",
|
||||
"payload",
|
||||
])
|
||||
.expect("parse");
|
||||
assert_eq!(cli.config_overrides.raw_overrides, ["a=1", "b=2", "a=3"]);
|
||||
let Some(Subcommand::Mcp(mcp)) = cli.subcommand else {
|
||||
panic!("expected mcp");
|
||||
};
|
||||
assert_eq!(mcp.config_overrides.raw_overrides, ["a=3"]);
|
||||
let McpSubcommand::Add(add) = mcp.subcommand else {
|
||||
panic!("expected add");
|
||||
};
|
||||
assert_eq!(
|
||||
add.transport_args.stdio.expect("stdio transport").command,
|
||||
["program", "-c", "payload"],
|
||||
);
|
||||
}
|
||||
42
akode-rs/cli/src/daemon_install.rs
Normal file
42
akode-rs/cli/src/daemon_install.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
//! Confirmation for copying the invoking CLI package into a daemon installation.
|
||||
|
||||
use std::io::IsTerminal;
|
||||
|
||||
use anyhow::Result;
|
||||
use akode_app_server_daemon::InstallRequest;
|
||||
|
||||
pub(crate) fn confirm_install(request: &InstallRequest, yes: bool) -> Result<bool> {
|
||||
eprintln!("{}", describe_install(request));
|
||||
if yes {
|
||||
return Ok(true);
|
||||
}
|
||||
anyhow::ensure!(
|
||||
std::io::stdin().is_terminal() && std::io::stderr().is_terminal(),
|
||||
"daemon installation requires confirmation; rerun with --yes to copy this CLI package"
|
||||
);
|
||||
let confirmed = crate::confirm("Copy this package? [y/N]: ")?;
|
||||
if !confirmed {
|
||||
eprintln!("Daemon installation cancelled.");
|
||||
}
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
fn describe_install(request: &InstallRequest) -> String {
|
||||
let mut message = format!(
|
||||
"Replace installed daemon version {} with CLI version {} from {}.\nThe daemon package will be installed in {}.\nThe selected package will be pinned. Run `akode app-server daemon update` to return to production updates.",
|
||||
request.installed_version.as_deref().unwrap_or("unknown"),
|
||||
request.version,
|
||||
request.source.display(),
|
||||
request.destination.display()
|
||||
);
|
||||
if request.restart_required {
|
||||
message.push_str(
|
||||
"\nThe running daemon will restart; active or queued work may be interrupted.",
|
||||
);
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "daemon_install_tests.rs"]
|
||||
mod tests;
|
||||
18
akode-rs/cli/src/daemon_install_tests.rs
Normal file
18
akode-rs/cli/src/daemon_install_tests.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn running_daemon_replacement_prompt() {
|
||||
let request = InstallRequest {
|
||||
source: "/cli/package".into(),
|
||||
version: "0.0.0".into(),
|
||||
destination: "/home/packages/app-server-daemon".into(),
|
||||
installed_version: Some("0.152.0".into()),
|
||||
restart_required: true,
|
||||
};
|
||||
insta::assert_snapshot!(describe_install(&request), @r"
|
||||
Replace installed daemon version 0.152.0 with CLI version 0.0.0 from /cli/package.
|
||||
The daemon package will be installed in /home/packages/app-server-daemon.
|
||||
The selected package will be pinned. Run `akode app-server daemon update` to return to production updates.
|
||||
The running daemon will restart; active or queued work may be interrupted.
|
||||
");
|
||||
}
|
||||
69
akode-rs/cli/src/daemon_update_tests.rs
Normal file
69
akode-rs/cli/src/daemon_update_tests.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use akode_tui::DaemonUpdateSource;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
#[test]
|
||||
fn package_update_runs_outside_the_project() -> anyhow::Result<()> {
|
||||
const CHILD: &str = "AKODE_TEST_PACKAGE_UPDATE_CHILD";
|
||||
if std::env::var_os(CHILD).is_some() {
|
||||
return run_update_action(UpdateAction::PnpmGlobalLatest, /*cli_executable*/ None);
|
||||
}
|
||||
|
||||
let project = tempfile::tempdir()?;
|
||||
let bin = tempfile::tempdir()?;
|
||||
akode_utils_cargo_bin::write_executable(
|
||||
&bin.path().join("pnpm"),
|
||||
"#!/bin/sh\npwd -P > \"$0.cwd\"\n",
|
||||
)?;
|
||||
assert_cmd::Command::new(std::env::current_exe()?)
|
||||
.args([
|
||||
"--exact",
|
||||
"daemon_update_tests::package_update_runs_outside_the_project",
|
||||
])
|
||||
.current_dir(project.path())
|
||||
.env("TMPDIR", project.path())
|
||||
.env("PATH", bin.path())
|
||||
.env(CHILD, "1")
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let cwd = std::fs::read_to_string(bin.path().join("pnpm.cwd"))?;
|
||||
assert!(!std::path::Path::new(cwd.trim_end()).starts_with(project.path().canonicalize()?));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daemon_handoff_uses_selected_executable_and_propagates_failure() -> anyhow::Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let executable = dir.path().join("launching CLI");
|
||||
let receipt = dir.path().join("launching CLI.args");
|
||||
akode_utils_cargo_bin::write_executable(
|
||||
&executable,
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$0.args\"\n",
|
||||
)?;
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(/*mode*/ 0o700))?;
|
||||
for (source, expected) in [
|
||||
(
|
||||
DaemonUpdateSource::PublicStable,
|
||||
"app-server\ndaemon\nupdate\n",
|
||||
),
|
||||
(
|
||||
DaemonUpdateSource::ThisCli,
|
||||
"app-server\ndaemon\nupdate\n--from-cli\n--yes\n",
|
||||
),
|
||||
] {
|
||||
run_update_action(UpdateAction::Daemon(source), Some(&executable))?;
|
||||
assert_eq!(std::fs::read_to_string(&receipt)?, expected);
|
||||
}
|
||||
akode_utils_cargo_bin::write_executable(&executable, "#!/bin/sh\nexit 7\n")?;
|
||||
let error = run_update_action(
|
||||
UpdateAction::Daemon(DaemonUpdateSource::ThisCli),
|
||||
Some(&executable),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("Daemon update failed"));
|
||||
Ok(())
|
||||
}
|
||||
1275
akode-rs/cli/src/debug_sandbox.rs
Normal file
1275
akode-rs/cli/src/debug_sandbox.rs
Normal file
File diff suppressed because it is too large
Load Diff
372
akode-rs/cli/src/debug_sandbox/pid_tracker.rs
Normal file
372
akode-rs/cli/src/debug_sandbox/pid_tracker.rs
Normal file
@@ -0,0 +1,372 @@
|
||||
use std::collections::HashSet;
|
||||
use tokio::task::JoinHandle;
|
||||
use tracing::warn;
|
||||
|
||||
/// Tracks the (recursive) descendants of a process by using `kqueue` to watch for fork events, and
|
||||
/// `proc_listchildpids` to list the children of a process.
|
||||
pub(crate) struct PidTracker {
|
||||
kq: libc::c_int,
|
||||
handle: JoinHandle<HashSet<i32>>,
|
||||
}
|
||||
|
||||
impl PidTracker {
|
||||
pub(crate) fn new(root_pid: i32) -> Option<Self> {
|
||||
if root_pid <= 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let kq = unsafe { libc::kqueue() };
|
||||
let handle = tokio::task::spawn_blocking(move || track_descendants(kq, root_pid));
|
||||
|
||||
Some(Self { kq, handle })
|
||||
}
|
||||
|
||||
pub(crate) async fn stop(self) -> HashSet<i32> {
|
||||
trigger_stop_event(self.kq);
|
||||
self.handle.await.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" {
|
||||
fn proc_listchildpids(
|
||||
ppid: libc::c_int,
|
||||
buffer: *mut libc::c_void,
|
||||
buffersize: libc::c_int,
|
||||
) -> libc::c_int;
|
||||
}
|
||||
|
||||
/// Wrap proc_listchildpids.
|
||||
fn list_child_pids(parent: i32) -> Vec<i32> {
|
||||
unsafe {
|
||||
let mut capacity: usize = 16;
|
||||
loop {
|
||||
let mut buf: Vec<i32> = vec![0; capacity];
|
||||
let count = proc_listchildpids(
|
||||
parent as libc::c_int,
|
||||
buf.as_mut_ptr() as *mut libc::c_void,
|
||||
(buf.len() * std::mem::size_of::<i32>()) as libc::c_int,
|
||||
);
|
||||
if count <= 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let returned = count as usize;
|
||||
if returned < capacity {
|
||||
buf.truncate(returned);
|
||||
return buf;
|
||||
}
|
||||
capacity = capacity.saturating_mul(2).max(returned + 16);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pid_is_alive(pid: i32) -> bool {
|
||||
if pid <= 0 {
|
||||
return false;
|
||||
}
|
||||
let res = unsafe { libc::kill(pid as libc::pid_t, 0) };
|
||||
if res == 0 {
|
||||
true
|
||||
} else {
|
||||
matches!(
|
||||
std::io::Error::last_os_error().raw_os_error(),
|
||||
Some(libc::EPERM)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
enum WatchPidError {
|
||||
ProcessGone,
|
||||
Other(std::io::Error),
|
||||
}
|
||||
|
||||
/// Add `pid` to the watch list in `kq`.
|
||||
fn watch_pid(kq: libc::c_int, pid: i32) -> Result<(), WatchPidError> {
|
||||
if pid <= 0 {
|
||||
return Err(WatchPidError::ProcessGone);
|
||||
}
|
||||
|
||||
let kev = libc::kevent {
|
||||
ident: pid as libc::uintptr_t,
|
||||
filter: libc::EVFILT_PROC,
|
||||
flags: libc::EV_ADD | libc::EV_CLEAR,
|
||||
fflags: libc::NOTE_FORK | libc::NOTE_EXEC | libc::NOTE_EXIT,
|
||||
data: 0,
|
||||
udata: std::ptr::null_mut(),
|
||||
};
|
||||
|
||||
let res = unsafe { libc::kevent(kq, &kev, 1, std::ptr::null_mut(), 0, std::ptr::null()) };
|
||||
if res < 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
if err.raw_os_error() == Some(libc::ESRCH) {
|
||||
Err(WatchPidError::ProcessGone)
|
||||
} else {
|
||||
Err(WatchPidError::Other(err))
|
||||
}
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn watch_children(
|
||||
kq: libc::c_int,
|
||||
parent: i32,
|
||||
seen: &mut HashSet<i32>,
|
||||
active: &mut HashSet<i32>,
|
||||
) {
|
||||
for child_pid in list_child_pids(parent) {
|
||||
add_pid_watch(kq, child_pid, seen, active);
|
||||
}
|
||||
}
|
||||
|
||||
/// Watch `pid` and its children, updating `seen` and `active` sets.
|
||||
fn add_pid_watch(kq: libc::c_int, pid: i32, seen: &mut HashSet<i32>, active: &mut HashSet<i32>) {
|
||||
if pid <= 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
let newly_seen = seen.insert(pid);
|
||||
let mut should_recurse = newly_seen;
|
||||
|
||||
if active.insert(pid) {
|
||||
match watch_pid(kq, pid) {
|
||||
Ok(()) => {
|
||||
should_recurse = true;
|
||||
}
|
||||
Err(WatchPidError::ProcessGone) => {
|
||||
active.remove(&pid);
|
||||
return;
|
||||
}
|
||||
Err(WatchPidError::Other(err)) => {
|
||||
warn!("failed to watch pid {pid}: {err}");
|
||||
active.remove(&pid);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if should_recurse {
|
||||
watch_children(kq, pid, seen, active);
|
||||
}
|
||||
}
|
||||
const STOP_IDENT: libc::uintptr_t = 1;
|
||||
|
||||
fn register_stop_event(kq: libc::c_int) -> bool {
|
||||
let kev = libc::kevent {
|
||||
ident: STOP_IDENT,
|
||||
filter: libc::EVFILT_USER,
|
||||
flags: libc::EV_ADD | libc::EV_CLEAR,
|
||||
fflags: 0,
|
||||
data: 0,
|
||||
udata: std::ptr::null_mut(),
|
||||
};
|
||||
|
||||
let res = unsafe { libc::kevent(kq, &kev, 1, std::ptr::null_mut(), 0, std::ptr::null()) };
|
||||
res >= 0
|
||||
}
|
||||
|
||||
fn trigger_stop_event(kq: libc::c_int) {
|
||||
if kq < 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
let kev = libc::kevent {
|
||||
ident: STOP_IDENT,
|
||||
filter: libc::EVFILT_USER,
|
||||
flags: 0,
|
||||
fflags: libc::NOTE_TRIGGER,
|
||||
data: 0,
|
||||
udata: std::ptr::null_mut(),
|
||||
};
|
||||
|
||||
let _ = unsafe { libc::kevent(kq, &kev, 1, std::ptr::null_mut(), 0, std::ptr::null()) };
|
||||
}
|
||||
|
||||
/// Put all of the above together to track all the descendants of `root_pid`.
|
||||
fn track_descendants(kq: libc::c_int, root_pid: i32) -> HashSet<i32> {
|
||||
if kq < 0 {
|
||||
let mut seen = HashSet::new();
|
||||
seen.insert(root_pid);
|
||||
return seen;
|
||||
}
|
||||
|
||||
if !register_stop_event(kq) {
|
||||
let mut seen = HashSet::new();
|
||||
seen.insert(root_pid);
|
||||
let _ = unsafe { libc::close(kq) };
|
||||
return seen;
|
||||
}
|
||||
|
||||
let mut seen: HashSet<i32> = HashSet::new();
|
||||
let mut active: HashSet<i32> = HashSet::new();
|
||||
|
||||
add_pid_watch(kq, root_pid, &mut seen, &mut active);
|
||||
|
||||
const EVENTS_CAP: usize = 32;
|
||||
let mut events: [libc::kevent; EVENTS_CAP] =
|
||||
unsafe { std::mem::MaybeUninit::zeroed().assume_init() };
|
||||
|
||||
let mut stop_requested = false;
|
||||
loop {
|
||||
if active.is_empty() {
|
||||
if !pid_is_alive(root_pid) {
|
||||
break;
|
||||
}
|
||||
add_pid_watch(kq, root_pid, &mut seen, &mut active);
|
||||
if active.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let nev = unsafe {
|
||||
libc::kevent(
|
||||
kq,
|
||||
std::ptr::null::<libc::kevent>(),
|
||||
0,
|
||||
events.as_mut_ptr(),
|
||||
EVENTS_CAP as libc::c_int,
|
||||
std::ptr::null(),
|
||||
)
|
||||
};
|
||||
|
||||
if nev < 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
if err.kind() == std::io::ErrorKind::Interrupted {
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if nev == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
for ev in events.iter().take(nev as usize) {
|
||||
let pid = ev.ident as i32;
|
||||
|
||||
if ev.filter == libc::EVFILT_USER && ev.ident == STOP_IDENT {
|
||||
stop_requested = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (ev.flags & libc::EV_ERROR) != 0 {
|
||||
if ev.data == libc::ESRCH as isize {
|
||||
active.remove(&pid);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ev.fflags & libc::NOTE_FORK) != 0 {
|
||||
watch_children(kq, pid, &mut seen, &mut active);
|
||||
}
|
||||
|
||||
if (ev.fflags & libc::NOTE_EXIT) != 0 {
|
||||
active.remove(&pid);
|
||||
}
|
||||
}
|
||||
|
||||
if stop_requested {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let _ = unsafe { libc::close(kq) };
|
||||
|
||||
seen
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn pid_is_alive_detects_current_process() {
|
||||
let pid = std::process::id() as i32;
|
||||
assert!(pid_is_alive(pid));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn list_child_pids_includes_spawned_child() {
|
||||
let mut child = Command::new("/bin/sleep")
|
||||
.arg("5")
|
||||
.stdin(Stdio::null())
|
||||
.spawn()
|
||||
.expect("failed to spawn child process");
|
||||
|
||||
let child_pid = child.id() as i32;
|
||||
let parent_pid = std::process::id() as i32;
|
||||
|
||||
let mut found = false;
|
||||
for _ in 0..100 {
|
||||
if list_child_pids(parent_pid).contains(&child_pid) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
|
||||
assert!(found, "expected to find child pid {child_pid} in list");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[tokio::test]
|
||||
async fn pid_tracker_collects_spawned_children() {
|
||||
let tracker = PidTracker::new(std::process::id() as i32).expect("failed to create tracker");
|
||||
|
||||
let mut child = Command::new("/bin/sleep")
|
||||
.arg("0.1")
|
||||
.stdin(Stdio::null())
|
||||
.spawn()
|
||||
.expect("failed to spawn child process");
|
||||
|
||||
let child_pid = child.id() as i32;
|
||||
let parent_pid = std::process::id() as i32;
|
||||
|
||||
let _ = child.wait();
|
||||
|
||||
let seen = tracker.stop().await;
|
||||
|
||||
assert!(
|
||||
seen.contains(&parent_pid),
|
||||
"expected tracker to include parent pid {parent_pid}"
|
||||
);
|
||||
assert!(
|
||||
seen.contains(&child_pid),
|
||||
"expected tracker to include child pid {child_pid}"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[tokio::test]
|
||||
async fn pid_tracker_collects_bash_subshell_descendants() {
|
||||
let tracker = PidTracker::new(std::process::id() as i32).expect("failed to create tracker");
|
||||
|
||||
let child = Command::new("/bin/bash")
|
||||
.arg("-c")
|
||||
.arg("(sleep 0.1 & echo $!; wait)")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("failed to spawn bash");
|
||||
|
||||
let output = child.wait_with_output().unwrap().stdout;
|
||||
let subshell_pid = String::from_utf8_lossy(&output)
|
||||
.trim()
|
||||
.parse::<i32>()
|
||||
.expect("failed to parse subshell pid");
|
||||
|
||||
let seen = tracker.stop().await;
|
||||
|
||||
assert!(
|
||||
seen.contains(&subshell_pid),
|
||||
"expected tracker to include subshell pid {subshell_pid}"
|
||||
);
|
||||
}
|
||||
}
|
||||
114
akode-rs/cli/src/debug_sandbox/seatbelt.rs
Normal file
114
akode-rs/cli/src/debug_sandbox/seatbelt.rs
Normal file
@@ -0,0 +1,114 @@
|
||||
use std::collections::HashSet;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::process::Child;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use super::pid_tracker::PidTracker;
|
||||
|
||||
pub struct SandboxDenial {
|
||||
pub name: String,
|
||||
pub capability: String,
|
||||
}
|
||||
|
||||
pub struct DenialLogger {
|
||||
log_stream: Child,
|
||||
pid_tracker: Option<PidTracker>,
|
||||
log_reader: Option<JoinHandle<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl DenialLogger {
|
||||
pub(crate) fn new() -> Option<Self> {
|
||||
let mut log_stream = start_log_stream()?;
|
||||
let stdout = log_stream.stdout.take()?;
|
||||
let log_reader = tokio::spawn(async move {
|
||||
let mut reader = tokio::io::BufReader::new(stdout);
|
||||
let mut logs = Vec::new();
|
||||
let mut chunk = Vec::new();
|
||||
loop {
|
||||
match reader.read_until(b'\n', &mut chunk).await {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(_) => {
|
||||
logs.extend_from_slice(&chunk);
|
||||
chunk.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
logs
|
||||
});
|
||||
|
||||
Some(Self {
|
||||
log_stream,
|
||||
pid_tracker: None,
|
||||
log_reader: Some(log_reader),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn on_child_spawn(&mut self, child: &Child) {
|
||||
if let Some(root_pid) = child.id() {
|
||||
self.pid_tracker = PidTracker::new(root_pid as i32);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn finish(mut self) -> Vec<SandboxDenial> {
|
||||
let pid_set = match self.pid_tracker {
|
||||
Some(tracker) => tracker.stop().await,
|
||||
None => Default::default(),
|
||||
};
|
||||
|
||||
if pid_set.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let _ = self.log_stream.kill().await;
|
||||
let _ = self.log_stream.wait().await;
|
||||
|
||||
let logs_bytes = match self.log_reader.take() {
|
||||
Some(handle) => handle.await.unwrap_or_default(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let logs = String::from_utf8_lossy(&logs_bytes);
|
||||
|
||||
let mut seen: HashSet<(String, String)> = HashSet::new();
|
||||
let mut denials: Vec<SandboxDenial> = Vec::new();
|
||||
for line in logs.lines() {
|
||||
if let Ok(json) = serde_json::from_str::<serde_json::Value>(line)
|
||||
&& let Some(msg) = json.get("eventMessage").and_then(|v| v.as_str())
|
||||
&& let Some((pid, name, capability)) = parse_message(msg)
|
||||
&& pid_set.contains(&pid)
|
||||
&& seen.insert((name.clone(), capability.clone()))
|
||||
{
|
||||
denials.push(SandboxDenial { name, capability });
|
||||
}
|
||||
}
|
||||
denials
|
||||
}
|
||||
}
|
||||
|
||||
fn start_log_stream() -> Option<Child> {
|
||||
use std::process::Stdio;
|
||||
|
||||
const PREDICATE: &str = r#"(((processID == 0) AND (senderImagePath CONTAINS "/Sandbox")) OR (subsystem == "com.apple.sandbox.reporting"))"#;
|
||||
|
||||
tokio::process::Command::new("log")
|
||||
.args(["stream", "--style", "ndjson", "--predicate", PREDICATE])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.ok()
|
||||
}
|
||||
|
||||
fn parse_message(msg: &str) -> Option<(i32, String, String)> {
|
||||
// Example message:
|
||||
// Sandbox: processname(1234) deny(1) capability-name args...
|
||||
static RE: std::sync::OnceLock<regex_lite::Regex> = std::sync::OnceLock::new();
|
||||
let re = RE.get_or_init(|| {
|
||||
#[expect(clippy::unwrap_used)]
|
||||
regex_lite::Regex::new(r"^Sandbox:\s*(.+?)\((\d+)\)\s+deny\(.*?\)\s*(.+)$").unwrap()
|
||||
});
|
||||
|
||||
let (_, [name, pid_str, capability]) = re.captures(msg)?.extract();
|
||||
let pid = pid_str.trim().parse::<i32>().ok()?;
|
||||
Some((pid, name.to_string(), capability.to_string()))
|
||||
}
|
||||
4539
akode-rs/cli/src/doctor.rs
Normal file
4539
akode-rs/cli/src/doctor.rs
Normal file
File diff suppressed because it is too large
Load Diff
365
akode-rs/cli/src/doctor/background.rs
Normal file
365
akode-rs/cli/src/doctor/background.rs
Normal file
@@ -0,0 +1,365 @@
|
||||
//! Reports app-server daemon state without starting or stopping the daemon.
|
||||
//!
|
||||
//! The background-server check is deliberately passive. It reads the daemon
|
||||
//! state directory, PID files, settings file, and control socket path, then
|
||||
//! attempts only a bounded initialize probe when a socket already exists. That
|
||||
//! keeps doctor safe to run while the user is debugging startup or update-loop
|
||||
//! issues.
|
||||
|
||||
use std::io::Read;
|
||||
use std::num::NonZeroU32;
|
||||
use std::path::Path;
|
||||
|
||||
use akode_core::config::Config;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
|
||||
const MAX_PROBE_ERROR_CHARS: usize = 120;
|
||||
const STATE_DIR_NAME: &str = "app-server-daemon";
|
||||
const SETTINGS_FILE_NAME: &str = "settings.json";
|
||||
const PID_FILE_NAME: &str = "app-server.pid";
|
||||
const UPDATE_PID_FILE_NAME: &str = "app-server-updater.pid";
|
||||
const MAX_SETTINGS_BYTES: u64 = 16 * 1024;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ConfiguredSettings {
|
||||
updater: Option<ConfiguredUpdater>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ConfiguredUpdater {
|
||||
auto_update_enabled: Option<bool>,
|
||||
update_interval_minutes: Option<NonZeroU32>,
|
||||
}
|
||||
|
||||
/// Builds the app-server status row from existing daemon state.
|
||||
///
|
||||
/// Missing files are expected for the ephemeral/not-running case and should not
|
||||
/// be treated as failures. A stale socket is a warning because it can explain
|
||||
/// client connection problems without proving the daemon itself is broken.
|
||||
pub(super) async fn background_server_check(config: &Config) -> DoctorCheck {
|
||||
let mut details = Vec::new();
|
||||
let state_dir = config.codex_home.join(STATE_DIR_NAME);
|
||||
details.push(format!("daemon state dir: {}", state_dir.display()));
|
||||
push_file_detail(
|
||||
&mut details,
|
||||
"settings",
|
||||
&state_dir.join(SETTINGS_FILE_NAME),
|
||||
);
|
||||
push_file_detail(&mut details, "pid file", &state_dir.join(PID_FILE_NAME));
|
||||
push_file_detail(
|
||||
&mut details,
|
||||
"update-loop pid file",
|
||||
&state_dir.join(UPDATE_PID_FILE_NAME),
|
||||
);
|
||||
push_file_detail(
|
||||
&mut details,
|
||||
"dedicated pid file",
|
||||
&state_dir.join("daemon.pid"),
|
||||
);
|
||||
push_file_detail(
|
||||
&mut details,
|
||||
"dedicated update-loop pid file",
|
||||
&state_dir.join("daemon-updater.pid"),
|
||||
);
|
||||
push_configured_updater(&mut details, &state_dir.join(SETTINGS_FILE_NAME));
|
||||
|
||||
let socket_path = match akode_app_server::app_server_control_socket_path(&config.codex_home) {
|
||||
Ok(socket_path) => socket_path,
|
||||
Err(err) => {
|
||||
return DoctorCheck::new(
|
||||
"app_server.status",
|
||||
"app-server",
|
||||
CheckStatus::Warning,
|
||||
"background server socket path could not be resolved",
|
||||
)
|
||||
.details(details)
|
||||
.detail(err.to_string());
|
||||
}
|
||||
};
|
||||
|
||||
details.push(format!("control socket: {}", socket_path.display()));
|
||||
let status = socket_status(socket_path.as_path()).await;
|
||||
details.push(format!("status: {}", status.detail_label()));
|
||||
if let Some(version_detail) = status.app_server_version_detail() {
|
||||
details.push(version_detail);
|
||||
}
|
||||
details.push(format!("mode: {}", server_mode(&state_dir)));
|
||||
|
||||
let mut check = DoctorCheck::new(
|
||||
"app_server.status",
|
||||
"app-server",
|
||||
status.check_status(),
|
||||
status.summary(),
|
||||
)
|
||||
.details(details);
|
||||
if status.check_status() == CheckStatus::Warning {
|
||||
check = check.remediation("Run akode app-server daemon version for more details.");
|
||||
}
|
||||
check
|
||||
}
|
||||
|
||||
fn push_file_detail(details: &mut Vec<String>, label: &str, path: &Path) {
|
||||
match std::fs::metadata(path) {
|
||||
Ok(metadata) if metadata.is_file() => {
|
||||
details.push(format!("{label}: {} (file)", path.display()));
|
||||
}
|
||||
Ok(_) => {
|
||||
details.push(format!("{label}: {} (not a file)", path.display()));
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
|
||||
details.push(format!("{label}: {} (missing)", path.display()));
|
||||
}
|
||||
Err(err) => details.push(format!("{label}: {} ({err})", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
fn push_configured_updater(details: &mut Vec<String>, path: &Path) {
|
||||
if !path.is_file() {
|
||||
return;
|
||||
}
|
||||
let mut contents = Vec::new();
|
||||
let read = std::fs::File::open(path)
|
||||
.and_then(|file| file.take(MAX_SETTINGS_BYTES + 1).read_to_end(&mut contents));
|
||||
let settings = read
|
||||
.ok()
|
||||
.filter(|_| contents.len() as u64 <= MAX_SETTINGS_BYTES)
|
||||
.and_then(|_| serde_json::from_slice::<ConfiguredSettings>(&contents).ok());
|
||||
let Some(settings) = settings else {
|
||||
details.push("configured updater settings: unreadable or invalid".into());
|
||||
return;
|
||||
};
|
||||
if let Some(updater) = settings.updater {
|
||||
if let Some(enabled) = updater.auto_update_enabled {
|
||||
details.push(format!(
|
||||
"automatic updates: {} (configured)",
|
||||
if enabled { "enabled" } else { "disabled" }
|
||||
));
|
||||
}
|
||||
if let Some(minutes) = updater.update_interval_minutes {
|
||||
details.push(format!("update interval: {minutes} minutes (configured)"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn server_mode(state_dir: &Path) -> &'static str {
|
||||
if state_dir.join(SETTINGS_FILE_NAME).is_file() {
|
||||
"persistent"
|
||||
} else {
|
||||
"ephemeral"
|
||||
}
|
||||
}
|
||||
|
||||
enum SocketStatus {
|
||||
NotRunning,
|
||||
Running(String),
|
||||
StaleOrUnreachable(String),
|
||||
}
|
||||
|
||||
impl SocketStatus {
|
||||
fn check_status(&self) -> CheckStatus {
|
||||
match self {
|
||||
Self::NotRunning | Self::Running(_) => CheckStatus::Ok,
|
||||
Self::StaleOrUnreachable(_) => CheckStatus::Warning,
|
||||
}
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
match self {
|
||||
Self::NotRunning => "background server is not running",
|
||||
Self::Running(_) => "background server is running",
|
||||
Self::StaleOrUnreachable(_) => "background server socket is stale or unreachable",
|
||||
}
|
||||
}
|
||||
|
||||
fn detail_label(&self) -> &'static str {
|
||||
match self {
|
||||
Self::NotRunning => "not running",
|
||||
Self::Running(_) => "running",
|
||||
Self::StaleOrUnreachable(_) => "stale or unreachable",
|
||||
}
|
||||
}
|
||||
|
||||
fn app_server_version_detail(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::NotRunning => None,
|
||||
Self::Running(app_server_version) => {
|
||||
Some(format!("app-server version: {app_server_version}"))
|
||||
}
|
||||
Self::StaleOrUnreachable(error) => {
|
||||
Some(format!("app-server version: unavailable ({error})"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn socket_status(socket_path: &Path) -> SocketStatus {
|
||||
if !socket_path.exists() {
|
||||
return SocketStatus::NotRunning;
|
||||
}
|
||||
|
||||
match akode_app_server_daemon::probe_app_server_version(socket_path).await {
|
||||
Ok(app_server_version) => SocketStatus::Running(app_server_version),
|
||||
Err(err) => SocketStatus::StaleOrUnreachable(concise_probe_error(&err, socket_path)),
|
||||
}
|
||||
}
|
||||
|
||||
fn concise_probe_error(err: &anyhow::Error, socket_path: &Path) -> String {
|
||||
let socket_path = socket_path.display().to_string();
|
||||
let message = err
|
||||
.to_string()
|
||||
.replace(&socket_path, "control socket")
|
||||
.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
if message.is_empty() {
|
||||
return "unknown error".to_string();
|
||||
}
|
||||
let mut chars = message.chars();
|
||||
let truncated = chars
|
||||
.by_ref()
|
||||
.take(MAX_PROBE_ERROR_CHARS)
|
||||
.collect::<String>();
|
||||
if chars.next().is_some() {
|
||||
format!("{truncated}...")
|
||||
} else {
|
||||
message
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use akode_core::config::ConfigBuilder;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
async fn test_config(codex_home: PathBuf) -> Config {
|
||||
ConfigBuilder::default()
|
||||
.codex_home(codex_home)
|
||||
.build()
|
||||
.await
|
||||
.expect("config")
|
||||
}
|
||||
|
||||
fn create_socket_placeholder(config: &Config) {
|
||||
let socket_path = akode_app_server::app_server_control_socket_path(&config.codex_home)
|
||||
.expect("socket path");
|
||||
std::fs::create_dir_all(socket_path.parent().expect("socket parent"))
|
||||
.expect("create socket dir");
|
||||
std::fs::write(socket_path, "").expect("create socket placeholder");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn not_running_background_server_stays_ok_without_version() {
|
||||
let temp = tempfile::tempdir().expect("tempdir");
|
||||
let config = test_config(temp.path().to_path_buf()).await;
|
||||
|
||||
let check = background_server_check(&config).await;
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Ok);
|
||||
assert_eq!(check.summary, "background server is not running");
|
||||
assert!(check.details.contains(&"status: not running".to_string()));
|
||||
assert!(
|
||||
!check
|
||||
.details
|
||||
.iter()
|
||||
.any(|detail| detail.starts_with("app-server version:"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn running_background_server_reports_app_server_version() {
|
||||
let status = SocketStatus::Running("1.2.3".to_string());
|
||||
|
||||
assert_eq!(status.check_status(), CheckStatus::Ok);
|
||||
assert_eq!(status.summary(), "background server is running");
|
||||
assert_eq!(status.detail_label(), "running");
|
||||
assert_eq!(
|
||||
status.app_server_version_detail(),
|
||||
Some("app-server version: 1.2.3".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_version_probe_reports_unavailable() {
|
||||
let temp = tempfile::tempdir().expect("tempdir");
|
||||
let config = test_config(temp.path().to_path_buf()).await;
|
||||
create_socket_placeholder(&config);
|
||||
|
||||
let check = background_server_check(&config).await;
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert_eq!(
|
||||
check.summary,
|
||||
"background server socket is stale or unreachable"
|
||||
);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"status: stale or unreachable".to_string())
|
||||
);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.iter()
|
||||
.any(|detail| detail.starts_with("app-server version: unavailable ("))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn configured_updates_and_missing_updater_record_are_visible() {
|
||||
let temp = tempfile::tempdir().expect("tempdir");
|
||||
let state_dir = temp.path().join(STATE_DIR_NAME);
|
||||
std::fs::create_dir(&state_dir).expect("state dir");
|
||||
std::fs::write(
|
||||
state_dir.join(SETTINGS_FILE_NAME),
|
||||
r#"{"updater":{"autoUpdateEnabled":false,"updateIntervalMinutes":90}}"#,
|
||||
)
|
||||
.expect("settings");
|
||||
let config = test_config(temp.path().to_path_buf()).await;
|
||||
|
||||
let check = background_server_check(&config).await;
|
||||
let details = check
|
||||
.details
|
||||
.iter()
|
||||
.filter(|detail| {
|
||||
detail.starts_with("automatic updates:")
|
||||
|| detail.starts_with("update interval:")
|
||||
|| detail.starts_with("update-loop pid file:")
|
||||
|| detail.starts_with("dedicated")
|
||||
})
|
||||
.map(|detail| {
|
||||
detail
|
||||
.replace(&temp.path().display().to_string(), "AKODE_HOME")
|
||||
.replace('\\', "/")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!("configured_updater", details);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_settings_are_not_reported_as_effective() {
|
||||
let temp = tempfile::tempdir().expect("tempdir");
|
||||
let path = temp.path().join(SETTINGS_FILE_NAME);
|
||||
for contents in [
|
||||
r#"{"updater":{"autoUpdateEnabled":"no"}}"#,
|
||||
r#"{"updater":{"updateIntervalMinutes":0}}"#,
|
||||
] {
|
||||
std::fs::write(&path, contents).expect("settings");
|
||||
let mut details = Vec::new();
|
||||
|
||||
push_configured_updater(&mut details, &path);
|
||||
|
||||
insta::allow_duplicates! {
|
||||
insta::assert_snapshot!(details.join("\n"), @"configured updater settings: unreadable or invalid");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
314
akode-rs/cli/src/doctor/desktop.rs
Normal file
314
akode-rs/cli/src/doctor/desktop.rs
Normal file
@@ -0,0 +1,314 @@
|
||||
use std::cmp::Reverse;
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::FixedOffset;
|
||||
use chrono::Utc;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos_security;
|
||||
pub(super) mod platform;
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
mod windows_security;
|
||||
|
||||
const MAX_DIRECTORY_ENTRIES: usize = 256;
|
||||
const MAX_LOG_FILES: usize = 64;
|
||||
const MAX_SESSION_LOG_FILES: usize = 8;
|
||||
const MAX_LOG_SEGMENT_BYTES: u64 = 10 * 1024 * 1024;
|
||||
const HANDSHAKE_CHECK_ID: &str = "desktop.app_server.handshake";
|
||||
|
||||
pub(super) struct DesktopDiagnostics {
|
||||
pub(super) checks: Vec<DoctorCheck>,
|
||||
}
|
||||
|
||||
struct DesktopLog {
|
||||
path: PathBuf,
|
||||
session_id: String,
|
||||
process_id: u32,
|
||||
modified: SystemTime,
|
||||
}
|
||||
|
||||
struct HandshakeEvent {
|
||||
timestamp: DateTime<FixedOffset>,
|
||||
outcome: HandshakeOutcome,
|
||||
websocket: bool,
|
||||
}
|
||||
|
||||
enum HandshakeOutcome {
|
||||
Success,
|
||||
Failure,
|
||||
}
|
||||
|
||||
enum DesktopLogEvent {
|
||||
ConnectionContext { local_websocket: bool },
|
||||
Handshake(HandshakeEvent),
|
||||
}
|
||||
|
||||
pub(super) async fn collect() -> Option<DesktopDiagnostics> {
|
||||
let application = match platform::installed_app().await {
|
||||
Ok(Some(application)) => application,
|
||||
Ok(None) => return None,
|
||||
Err(_) => {
|
||||
return Some(DesktopDiagnostics {
|
||||
checks: vec![
|
||||
unavailable(
|
||||
"desktop.app.version",
|
||||
"the desktop application installation could not be inspected",
|
||||
),
|
||||
#[cfg(target_os = "windows")]
|
||||
windows_security::collect().await,
|
||||
],
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let directory = desktop_log_root(application.identity);
|
||||
let (running, handshake) = match &directory {
|
||||
Some(root) => inspect_desktop_session(
|
||||
&root.join(Utc::now().format("%Y/%m/%d").to_string()),
|
||||
|pid| platform::application_running(&application, pid),
|
||||
),
|
||||
None => (false, stopped_desktop_check()),
|
||||
};
|
||||
let log_directory = directory
|
||||
.as_deref()
|
||||
.map_or_else(|| "unavailable".to_string(), redacted_path);
|
||||
let application_check = platform::desktop_check(
|
||||
"desktop.app.version",
|
||||
CheckStatus::Ok,
|
||||
"the desktop application is installed",
|
||||
)
|
||||
.detail(format!("version: {}", application.version))
|
||||
.detail(format!("running: {running}"))
|
||||
.detail(format!("log directory: {log_directory}"));
|
||||
|
||||
Some(DesktopDiagnostics {
|
||||
checks: vec![
|
||||
application_check,
|
||||
handshake,
|
||||
#[cfg(target_os = "macos")]
|
||||
macos_security::collect(&application.bundle).await,
|
||||
#[cfg(target_os = "windows")]
|
||||
windows_security::collect().await,
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn inspect_desktop_session(
|
||||
directory: &Path,
|
||||
application_running: impl Fn(u32) -> bool,
|
||||
) -> (bool, DoctorCheck) {
|
||||
let logs = discover_desktop_logs(directory);
|
||||
let Some(session) = logs.iter().find(|log| application_running(log.process_id)) else {
|
||||
return (false, stopped_desktop_check());
|
||||
};
|
||||
|
||||
let check = latest_session_handshake(&logs, &session.session_id).map_or_else(
|
||||
|| {
|
||||
platform::desktop_check(
|
||||
HANDSHAKE_CHECK_ID,
|
||||
CheckStatus::Ok,
|
||||
"no desktop app-server handshake was recorded",
|
||||
)
|
||||
},
|
||||
|event| event.outcome.into_check(),
|
||||
);
|
||||
|
||||
(true, check)
|
||||
}
|
||||
|
||||
fn desktop_log_root(identity: &str) -> Option<PathBuf> {
|
||||
let root = match env::consts::OS {
|
||||
"macos" => PathBuf::from(env::var_os("HOME")?)
|
||||
.join("Library/Logs")
|
||||
.join(identity),
|
||||
"windows" => {
|
||||
let local = env::var_os("LOCALAPPDATA").map(PathBuf::from).or_else(|| {
|
||||
env::var_os("USERPROFILE").map(|home| PathBuf::from(home).join("AppData/Local"))
|
||||
})?;
|
||||
local.join("Codex/Logs")
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
Some(root)
|
||||
}
|
||||
|
||||
fn discover_desktop_logs(directory: &Path) -> Vec<DesktopLog> {
|
||||
let Ok(entries) = fs::read_dir(directory) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut logs = entries
|
||||
.take(MAX_DIRECTORY_ENTRIES)
|
||||
.filter_map(Result::ok)
|
||||
.filter_map(DesktopLog::from_entry)
|
||||
.collect::<Vec<_>>();
|
||||
logs.sort_unstable_by_key(|log| Reverse(log.modified));
|
||||
logs.truncate(MAX_LOG_FILES);
|
||||
logs
|
||||
}
|
||||
|
||||
fn latest_session_handshake(logs: &[DesktopLog], session_id: &str) -> Option<HandshakeEvent> {
|
||||
let mut latest: Option<HandshakeEvent> = None;
|
||||
|
||||
for log in logs
|
||||
.iter()
|
||||
.filter(|log| log.session_id == session_id)
|
||||
.take(MAX_SESSION_LOG_FILES)
|
||||
{
|
||||
let Ok(contents) = read_log_segment(&log.path) else {
|
||||
continue;
|
||||
};
|
||||
let mut local_websocket = false;
|
||||
|
||||
for line in String::from_utf8_lossy(&contents).lines() {
|
||||
match DesktopLogEvent::parse(line) {
|
||||
Some(DesktopLogEvent::ConnectionContext {
|
||||
local_websocket: local,
|
||||
}) => {
|
||||
local_websocket = local;
|
||||
}
|
||||
Some(DesktopLogEvent::Handshake(event))
|
||||
if (!event.websocket || local_websocket)
|
||||
&& latest
|
||||
.as_ref()
|
||||
.is_none_or(|current| event.timestamp >= current.timestamp) =>
|
||||
{
|
||||
latest = Some(event);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
latest
|
||||
}
|
||||
|
||||
impl DesktopLog {
|
||||
fn from_entry(entry: fs::DirEntry) -> Option<Self> {
|
||||
let metadata = entry.metadata().ok()?;
|
||||
if !metadata.is_file() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let name = entry.file_name();
|
||||
let name = name
|
||||
.to_str()?
|
||||
.strip_prefix("codex-desktop-")?
|
||||
.strip_suffix(".log")?;
|
||||
let (session_and_pid, _) = name.split_once("-t")?;
|
||||
let (session_id, process_id) = session_and_pid.rsplit_once('-')?;
|
||||
|
||||
Some(Self {
|
||||
path: entry.path(),
|
||||
session_id: session_id.to_string(),
|
||||
process_id: process_id.parse().ok().filter(|pid| *pid > 0)?,
|
||||
modified: metadata.modified().ok()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn read_log_segment(path: &Path) -> io::Result<Vec<u8>> {
|
||||
let mut contents = Vec::new();
|
||||
fs::File::open(path)?
|
||||
.take(MAX_LOG_SEGMENT_BYTES)
|
||||
.read_to_end(&mut contents)?;
|
||||
Ok(contents)
|
||||
}
|
||||
|
||||
impl DesktopLogEvent {
|
||||
fn parse(line: &str) -> Option<Self> {
|
||||
let (timestamp, line) = line.split_once(' ')?;
|
||||
let timestamp = DateTime::parse_from_rfc3339(timestamp).ok()?;
|
||||
let (_, message) = line.split_once(" [AppServerConnection] ")?;
|
||||
|
||||
if let Some(fields) = message
|
||||
.strip_prefix("Starting app-server connection ")
|
||||
.or_else(|| message.strip_prefix("app_server_connection.state_changed "))
|
||||
{
|
||||
return Some(Self::ConnectionContext {
|
||||
local_websocket: log_field(fields, "hostId") == Some("local")
|
||||
&& log_field(fields, "transport") == Some("websocket"),
|
||||
});
|
||||
}
|
||||
|
||||
let fields = message.strip_prefix("initialize_handshake_result ")?;
|
||||
let outcome = match log_field(fields, "outcome")? {
|
||||
"success" => HandshakeOutcome::Success,
|
||||
"failure" => HandshakeOutcome::Failure,
|
||||
_ => return None,
|
||||
};
|
||||
let websocket = match log_field(fields, "transportKind")? {
|
||||
"stdio" => false,
|
||||
"websocket" => true,
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
Some(Self::Handshake(HandshakeEvent {
|
||||
timestamp,
|
||||
outcome,
|
||||
websocket,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl HandshakeOutcome {
|
||||
fn into_check(self) -> DoctorCheck {
|
||||
let (status, summary) = match self {
|
||||
Self::Success => (
|
||||
CheckStatus::Ok,
|
||||
"the desktop app-server initialized successfully",
|
||||
),
|
||||
Self::Failure => (
|
||||
CheckStatus::Fail,
|
||||
"the desktop app-server failed to initialize",
|
||||
),
|
||||
};
|
||||
|
||||
platform::desktop_check(HANDSHAKE_CHECK_ID, status, summary)
|
||||
}
|
||||
}
|
||||
|
||||
fn log_field<'a>(fields: &'a str, name: &str) -> Option<&'a str> {
|
||||
fields.split_whitespace().rev().find_map(|field| {
|
||||
let (key, value) = field.split_once('=')?;
|
||||
(key == name).then_some(value)
|
||||
})
|
||||
}
|
||||
|
||||
fn stopped_desktop_check() -> DoctorCheck {
|
||||
platform::desktop_check(
|
||||
HANDSHAKE_CHECK_ID,
|
||||
CheckStatus::Ok,
|
||||
"the desktop application is not running",
|
||||
)
|
||||
}
|
||||
|
||||
fn unavailable(id: &'static str, summary: &'static str) -> DoctorCheck {
|
||||
platform::desktop_check(id, CheckStatus::Warning, summary)
|
||||
.remediation("restore desktop diagnostic access and rerun akode doctor")
|
||||
}
|
||||
|
||||
fn redacted_path(path: &Path) -> String {
|
||||
for variable in ["HOME", "USERPROFILE"] {
|
||||
if let Some(home) = env::var_os(variable)
|
||||
&& let Ok(relative) = path.strip_prefix(Path::new(&home))
|
||||
{
|
||||
return Path::new("$HOME").join(relative).display().to_string();
|
||||
}
|
||||
}
|
||||
path.file_name()
|
||||
.unwrap_or(path.as_os_str())
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
}
|
||||
236
akode-rs/cli/src/doctor/desktop/macos_security.rs
Normal file
236
akode-rs/cli/src/doctor/desktop/macos_security.rs
Normal file
@@ -0,0 +1,236 @@
|
||||
use super::super::CheckStatus;
|
||||
use super::super::DoctorCheck;
|
||||
use super::platform::desktop_check;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::process::Output;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const MAX_OUTPUT_BYTES: usize = 256 * 1024;
|
||||
const SECURITY_LOG_PREDICATE: &str = concat!(
|
||||
"(process == 'syspolicyd' OR process == 'AppleSystemPolicy' ",
|
||||
"OR process BEGINSWITH 'XProtect' OR subsystem BEGINSWITH 'com.apple.syspolicy' ",
|
||||
"OR subsystem CONTAINS[c] 'XProtect' ",
|
||||
"OR subsystem == 'com.apple.security.assessment') AND ",
|
||||
"(eventMessage CONTAINS[c] 'codex' OR eventMessage CONTAINS[c] 'chatgpt' ",
|
||||
"OR eventMessage CONTAINS[c] '.plugin-appserver' ",
|
||||
"OR eventMessage CONTAINS[c] '100024' OR eventMessage CONTAINS[c] 'EMFILE' ",
|
||||
"OR eventMessage CONTAINS[c] 'ENFILE' ",
|
||||
"OR eventMessage CONTAINS[c] 'too many open files' ",
|
||||
"OR eventMessage CONTAINS[c] 'Unexpected Xprotect assessment')"
|
||||
);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
enum Evidence {
|
||||
Clear,
|
||||
Audit,
|
||||
Exhausted,
|
||||
Blocked,
|
||||
Malware,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
pub(super) async fn collect(bundle: &Path) -> DoctorCheck {
|
||||
let (gatekeeper, events) = tokio::join!(inspect_gatekeeper(bundle), inspect_security_events());
|
||||
enforcement_check(gatekeeper, events)
|
||||
}
|
||||
|
||||
async fn inspect_gatekeeper(bundle: &Path) -> Evidence {
|
||||
let mut command = Command::new("/usr/sbin/spctl");
|
||||
command
|
||||
.args(["--assess", "--type", "execute", "--verbose=2"])
|
||||
.arg(bundle);
|
||||
classify_gatekeeper(run_command(&mut command).await.as_ref())
|
||||
}
|
||||
|
||||
fn classify_gatekeeper(output: Option<&Output>) -> Evidence {
|
||||
let Some(output) = output.filter(|output| !is_truncated(output)) else {
|
||||
return Evidence::Unavailable;
|
||||
};
|
||||
if output.status.success() {
|
||||
return Evidence::Clear;
|
||||
}
|
||||
let error = String::from_utf8_lossy(&output.stderr).to_ascii_lowercase();
|
||||
if error.contains("rejected") || error.contains("no usable signature") {
|
||||
Evidence::Blocked
|
||||
} else {
|
||||
Evidence::Unavailable
|
||||
}
|
||||
}
|
||||
|
||||
async fn inspect_security_events() -> Evidence {
|
||||
let mut command = Command::new("/usr/bin/log");
|
||||
command.args([
|
||||
"show",
|
||||
"--last",
|
||||
"30m",
|
||||
"--info",
|
||||
"--style",
|
||||
"compact",
|
||||
"--predicate",
|
||||
SECURITY_LOG_PREDICATE,
|
||||
]);
|
||||
let Some(output) = run_command(&mut command)
|
||||
.await
|
||||
.filter(|output| output.status.success())
|
||||
else {
|
||||
return Evidence::Unavailable;
|
||||
};
|
||||
let evidence = classify_security_events(&String::from_utf8_lossy(&output.stdout));
|
||||
if is_truncated(&output) && evidence < Evidence::Exhausted {
|
||||
Evidence::Unavailable
|
||||
} else {
|
||||
evidence
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_security_events(output: &str) -> Evidence {
|
||||
let mut evidence = Evidence::Clear;
|
||||
for line in output.lines().map(str::to_ascii_lowercase) {
|
||||
let contains = |values: &[&str]| values.iter().any(|value| line.contains(value));
|
||||
if !contains(&[
|
||||
"com.openai.codex",
|
||||
"codex.app",
|
||||
"chatgpt.app",
|
||||
".plugin-appserver",
|
||||
"akode-command-runner",
|
||||
]) || contains(&["not blocked", "not denied"])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let event = if contains(&["100024", "emfile", "enfile", "too many open files"]) {
|
||||
Evidence::Exhausted
|
||||
} else if contains(&["would block", "would deny"]) {
|
||||
Evidence::Audit
|
||||
} else if contains(&[
|
||||
"xp_malware_detected",
|
||||
"xp_malware_remediated",
|
||||
"malware detected",
|
||||
"malware blocked",
|
||||
"malware removed",
|
||||
"remediat",
|
||||
]) {
|
||||
Evidence::Malware
|
||||
} else if contains(&[
|
||||
"blocked",
|
||||
"denied",
|
||||
"rejected",
|
||||
"notarization failed",
|
||||
"signature invalid",
|
||||
"execution prevented",
|
||||
"unexpected xprotect assessment",
|
||||
"damaged and",
|
||||
]) {
|
||||
Evidence::Blocked
|
||||
} else if contains(&["audit"]) {
|
||||
Evidence::Audit
|
||||
} else {
|
||||
Evidence::Clear
|
||||
};
|
||||
evidence = evidence.max(event);
|
||||
}
|
||||
evidence
|
||||
}
|
||||
|
||||
fn enforcement_check(gatekeeper: Evidence, events: Evidence) -> DoctorCheck {
|
||||
let id = "desktop.security.enforcement";
|
||||
let (status, summary, remedy) = if events == Evidence::Malware {
|
||||
(
|
||||
CheckStatus::Fail,
|
||||
"macos XProtect blocked or remediated the desktop application",
|
||||
"collect the XProtect detection and ask your security administrator to review the official aKode installation",
|
||||
)
|
||||
} else if gatekeeper == Evidence::Blocked {
|
||||
(
|
||||
CheckStatus::Fail,
|
||||
"macos gatekeeper rejected the desktop application",
|
||||
"ask your security administrator to review the application policy",
|
||||
)
|
||||
} else if events == Evidence::Blocked {
|
||||
(
|
||||
CheckStatus::Fail,
|
||||
"a recent macos security event blocked the desktop application",
|
||||
"ask your security administrator to review the matching prevention event",
|
||||
)
|
||||
} else if events == Evidence::Exhausted {
|
||||
(
|
||||
CheckStatus::Warning,
|
||||
"macos system-policy diagnostics indicate file descriptor exhaustion",
|
||||
"restart your Mac, retry aKode once, and contact support if the problem returns",
|
||||
)
|
||||
} else if events == Evidence::Audit {
|
||||
(
|
||||
CheckStatus::Warning,
|
||||
"recent desktop security events are audit-only",
|
||||
"ask your security administrator to verify the application policy",
|
||||
)
|
||||
} else if gatekeeper == Evidence::Unavailable {
|
||||
(
|
||||
CheckStatus::Warning,
|
||||
"the desktop security assessment was unavailable",
|
||||
"check access to macos gatekeeper diagnostics",
|
||||
)
|
||||
} else if events == Evidence::Unavailable {
|
||||
(
|
||||
CheckStatus::Warning,
|
||||
"recent macos security enforcement history was unavailable",
|
||||
"check access to macos unified security logs and rerun akode doctor",
|
||||
)
|
||||
} else {
|
||||
return desktop_check(
|
||||
id,
|
||||
CheckStatus::Ok,
|
||||
"the desktop application passed available macos security assessments",
|
||||
)
|
||||
.detail("gatekeeper: accepted");
|
||||
};
|
||||
desktop_check(id, status, summary).remediation(remedy)
|
||||
}
|
||||
|
||||
fn is_truncated(output: &Output) -> bool {
|
||||
output.stdout.len() > MAX_OUTPUT_BYTES || output.stderr.len() > MAX_OUTPUT_BYTES
|
||||
}
|
||||
|
||||
async fn run_command(command: &mut Command) -> Option<Output> {
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
let mut child = command.spawn().ok()?;
|
||||
let (stdout, stderr) = (child.stdout.take()?, child.stderr.take()?);
|
||||
timeout(PROBE_TIMEOUT, async {
|
||||
let (stdout, stderr, status) =
|
||||
tokio::join!(read_bounded(stdout), read_bounded(stderr), child.wait());
|
||||
Some(Output {
|
||||
status: status.ok()?,
|
||||
stdout: stdout.ok()?,
|
||||
stderr: stderr.ok()?,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
async fn read_bounded<R: AsyncRead + Unpin>(mut reader: R) -> io::Result<Vec<u8>> {
|
||||
let mut bytes = Vec::new();
|
||||
(&mut reader)
|
||||
.take(MAX_OUTPUT_BYTES as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.await?;
|
||||
if bytes.len() > MAX_OUTPUT_BYTES {
|
||||
tokio::io::copy(&mut reader, &mut tokio::io::sink()).await?;
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "macos_security_tests.rs"]
|
||||
mod tests;
|
||||
67
akode-rs/cli/src/doctor/desktop/macos_security_tests.rs
Normal file
67
akode-rs/cli/src/doctor/desktop/macos_security_tests.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
use super::CheckStatus;
|
||||
use super::Evidence;
|
||||
use super::classify_gatekeeper;
|
||||
use super::classify_security_events;
|
||||
use super::enforcement_check;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
use std::process::ExitStatus;
|
||||
use std::process::Output;
|
||||
|
||||
#[test]
|
||||
fn only_matching_enforced_apple_security_events_are_failures() {
|
||||
for (event, expected) in [
|
||||
("denied com.openai.codex", Evidence::Blocked),
|
||||
(
|
||||
"denied /Applications/Codex.app/Contents/MacOS/Codex",
|
||||
Evidence::Blocked,
|
||||
),
|
||||
("malware detected ChatGPT.app", Evidence::Malware),
|
||||
("audit token blocked ChatGPT.app", Evidence::Blocked),
|
||||
(
|
||||
"audit token XP_MALWARE_DETECTED ChatGPT.app",
|
||||
Evidence::Malware,
|
||||
),
|
||||
("XP_MALWARE_REMEDIATED ChatGPT.app", Evidence::Malware),
|
||||
("denied .plugin-appserver", Evidence::Blocked),
|
||||
("audit would block ChatGPT.app", Evidence::Audit),
|
||||
("OSStatus 100024 ChatGPT.app", Evidence::Exhausted),
|
||||
("not blocked ChatGPT.app", Evidence::Clear),
|
||||
("denied EMFILE com.example.other", Evidence::Clear),
|
||||
("EMFILE\nmalware detected ChatGPT.app", Evidence::Malware),
|
||||
] {
|
||||
assert_eq!(classify_security_events(event), expected, "{event}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gatekeeper_failures_require_actionable_security_evidence() {
|
||||
for (message, expected) in [
|
||||
("ChatGPT.app: rejected", Evidence::Blocked),
|
||||
("operation not permitted", Evidence::Unavailable),
|
||||
] {
|
||||
let output = Output {
|
||||
status: ExitStatus::from_raw(1 << 8),
|
||||
stdout: Vec::new(),
|
||||
stderr: message.as_bytes().to_vec(),
|
||||
};
|
||||
assert_eq!(classify_gatekeeper(Some(&output)), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exhaustion_and_unavailable_history_have_actionable_warnings() {
|
||||
for (events, remedy) in [
|
||||
(Evidence::Exhausted, "restart"),
|
||||
(Evidence::Unavailable, "unified security logs"),
|
||||
] {
|
||||
let check = enforcement_check(Evidence::Clear, events);
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert!(
|
||||
check
|
||||
.remediation
|
||||
.as_deref()
|
||||
.is_some_and(|value| value.contains(remedy))
|
||||
);
|
||||
}
|
||||
}
|
||||
275
akode-rs/cli/src/doctor/desktop/platform.rs
Normal file
275
akode-rs/cli/src/doctor/desktop/platform.rs
Normal file
@@ -0,0 +1,275 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::ffi::CStr;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::ffi::OsStr;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::fs;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::path::Path;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::path::PathBuf;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::process::Stdio;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use serde_json::Value;
|
||||
#[cfg(target_os = "macos")]
|
||||
use tokio::process::Command;
|
||||
#[cfg(target_os = "macos")]
|
||||
use tokio::time::timeout;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Storage::Packaging::Appx::FindPackagesByPackageFamily;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Storage::Packaging::Appx::GetPackageFamilyName;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Storage::Packaging::Appx::PACKAGE_FILTER_HEAD;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::System::Threading::OpenProcess;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
|
||||
|
||||
use super::super::CheckStatus;
|
||||
use super::super::DoctorCheck;
|
||||
|
||||
pub(in crate::doctor) struct InstalledApp {
|
||||
pub(in crate::doctor) identity: &'static str,
|
||||
pub(in crate::doctor) version: String,
|
||||
#[cfg(target_os = "windows")]
|
||||
package_family: &'static str,
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::doctor) bundle: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(in crate::doctor) struct DiscoveryError;
|
||||
|
||||
pub(super) async fn installed_app() -> Result<Option<InstalledApp>, DiscoveryError> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
installed_windows_app()
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
installed_macos_app().await
|
||||
}
|
||||
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(super) fn application_running(application: &InstalledApp, candidate_pid: u32) -> bool {
|
||||
process_executable_path(candidate_pid)
|
||||
.is_some_and(|path| path.starts_with(application.bundle.join("Contents/MacOS")))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn process_executable_path(pid: u32) -> Option<PathBuf> {
|
||||
let pid = i32::try_from(pid).ok()?;
|
||||
let mut buffer = [0_u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];
|
||||
let result =
|
||||
unsafe { libc::proc_pidpath(pid, buffer.as_mut_ptr().cast(), buffer.len() as u32) };
|
||||
if result <= 0 {
|
||||
return None;
|
||||
}
|
||||
let executable = CStr::from_bytes_until_nul(&buffer).ok()?;
|
||||
Some(PathBuf::from(OsStr::from_bytes(executable.to_bytes())))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(super) fn application_running(application: &InstalledApp, candidate_pid: u32) -> bool {
|
||||
process_package_family(candidate_pid).as_deref() == Some(application.package_family)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn process_package_family(pid: u32) -> Option<String> {
|
||||
let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
|
||||
if handle.is_null() {
|
||||
return None;
|
||||
}
|
||||
let process = unsafe { OwnedHandle::from_raw_handle(handle) };
|
||||
|
||||
let mut family_length = 0;
|
||||
let result = unsafe {
|
||||
GetPackageFamilyName(
|
||||
process.as_raw_handle(),
|
||||
&mut family_length,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if result != ERROR_INSUFFICIENT_BUFFER || family_length == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut family = vec![0_u16; family_length as usize];
|
||||
let result = unsafe {
|
||||
GetPackageFamilyName(
|
||||
process.as_raw_handle(),
|
||||
&mut family_length,
|
||||
family.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
if result != ERROR_SUCCESS {
|
||||
return None;
|
||||
}
|
||||
|
||||
let end = family.iter().position(|value| *value == 0)?;
|
||||
String::from_utf16(&family[..end]).ok()
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
|
||||
pub(super) fn application_running(_application: &InstalledApp, _candidate_pid: u32) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(super) fn desktop_check(
|
||||
id: impl Into<String>,
|
||||
status: CheckStatus,
|
||||
summary: impl Into<String>,
|
||||
) -> DoctorCheck {
|
||||
DoctorCheck::new(id, "desktop", status, summary)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn installed_windows_app() -> Result<Option<InstalledApp>, DiscoveryError> {
|
||||
const PACKAGE_FAMILY: &str = "OpenAI.Codex_2p2nqsd0c76g0";
|
||||
|
||||
let family = PACKAGE_FAMILY
|
||||
.encode_utf16()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
let mut count = 0;
|
||||
let mut length = 0;
|
||||
let result = unsafe {
|
||||
FindPackagesByPackageFamily(
|
||||
family.as_ptr(),
|
||||
PACKAGE_FILTER_HEAD,
|
||||
&mut count,
|
||||
std::ptr::null_mut(),
|
||||
&mut length,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if result == ERROR_SUCCESS && count == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
if result != ERROR_INSUFFICIENT_BUFFER {
|
||||
return Err(DiscoveryError);
|
||||
}
|
||||
|
||||
let mut names = vec![std::ptr::null_mut(); count as usize];
|
||||
let mut buffer = vec![0_u16; length as usize];
|
||||
let result = unsafe {
|
||||
FindPackagesByPackageFamily(
|
||||
family.as_ptr(),
|
||||
PACKAGE_FILTER_HEAD,
|
||||
&mut count,
|
||||
names.as_mut_ptr(),
|
||||
&mut length,
|
||||
buffer.as_mut_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if result != ERROR_SUCCESS {
|
||||
return Err(DiscoveryError);
|
||||
}
|
||||
if count == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let end = buffer
|
||||
.iter()
|
||||
.position(|value| *value == 0)
|
||||
.ok_or(DiscoveryError)?;
|
||||
let package = String::from_utf16(&buffer[..end]).map_err(|_| DiscoveryError)?;
|
||||
let version = package
|
||||
.strip_prefix("OpenAI.Codex_")
|
||||
.and_then(|name| name.split('_').next())
|
||||
.filter(|version| {
|
||||
version
|
||||
.split('.')
|
||||
.all(|part| !part.is_empty() && part.bytes().all(|digit| digit.is_ascii_digit()))
|
||||
})
|
||||
.ok_or(DiscoveryError)?;
|
||||
|
||||
Ok(Some(InstalledApp {
|
||||
identity: "OpenAI.Codex",
|
||||
version: version.to_string(),
|
||||
package_family: PACKAGE_FAMILY,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
async fn installed_macos_app() -> Result<Option<InstalledApp>, DiscoveryError> {
|
||||
let applications = std::iter::once(PathBuf::from("/Applications"))
|
||||
.chain(std::env::var_os("HOME").map(|home| PathBuf::from(home).join("Applications")))
|
||||
.flat_map(|directory| {
|
||||
["ChatGPT.app", "Codex.app"]
|
||||
.into_iter()
|
||||
.map(move |application| directory.join(application))
|
||||
});
|
||||
|
||||
for bundle in applications {
|
||||
match fs::metadata(&bundle) {
|
||||
Ok(metadata) if metadata.is_dir() => {}
|
||||
Ok(_) => continue,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
|
||||
Err(_) => return Err(DiscoveryError),
|
||||
}
|
||||
if let Some(application) = inspect_macos_bundle(&bundle).await? {
|
||||
return Ok(Some(application));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::doctor) async fn inspect_macos_bundle(
|
||||
bundle: &Path,
|
||||
) -> Result<Option<InstalledApp>, DiscoveryError> {
|
||||
let mut command = Command::new("/usr/bin/plutil");
|
||||
command
|
||||
.args(["-convert", "json", "-o", "-"])
|
||||
.arg(bundle.join("Contents/Info.plist"))
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true);
|
||||
let output = timeout(Duration::from_secs(5), command.output())
|
||||
.await
|
||||
.map_err(|_| DiscoveryError)?
|
||||
.map_err(|_| DiscoveryError)?;
|
||||
if !output.status.success() || output.stdout.len() > 64 * 1024 {
|
||||
return Err(DiscoveryError);
|
||||
}
|
||||
let metadata: Value = serde_json::from_slice(&output.stdout).map_err(|_| DiscoveryError)?;
|
||||
if metadata.get("CFBundleIdentifier").and_then(Value::as_str) != Some("com.openai.codex") {
|
||||
return Ok(None);
|
||||
}
|
||||
let version = metadata
|
||||
.get("CFBundleShortVersionString")
|
||||
.or_else(|| metadata.get("CFBundleVersion"))
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(DiscoveryError)?;
|
||||
|
||||
Ok(Some(InstalledApp {
|
||||
identity: "com.openai.codex",
|
||||
version: version.to_string(),
|
||||
bundle: bundle.to_path_buf(),
|
||||
}))
|
||||
}
|
||||
232
akode-rs/cli/src/doctor/desktop/windows_security.rs
Normal file
232
akode-rs/cli/src/doctor/desktop/windows_security.rs
Normal file
@@ -0,0 +1,232 @@
|
||||
use std::env;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::super::CheckStatus;
|
||||
use super::super::DoctorCheck;
|
||||
use super::platform::desktop_check;
|
||||
|
||||
const MAX_EVENTS_PER_CHANNEL: usize = 256;
|
||||
const MAX_RENDERED_EVENTS: usize = 16;
|
||||
const MAX_EVENT_OUTPUT_BYTES: usize = 2 * 1024 * 1024;
|
||||
type Channel = (&'static str, &'static str, &'static [u32]);
|
||||
type Evidence = (CheckStatus, String);
|
||||
|
||||
const CHANNELS: [Channel; 5] = [
|
||||
(
|
||||
"microsoft_defender",
|
||||
"Microsoft-Windows-Windows Defender/Operational",
|
||||
&[
|
||||
1006, 1007, 1116, 1117, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128,
|
||||
],
|
||||
),
|
||||
(
|
||||
"applocker",
|
||||
"Microsoft-Windows-AppLocker/EXE and DLL",
|
||||
&[8003, 8004],
|
||||
),
|
||||
(
|
||||
"applocker",
|
||||
"Microsoft-Windows-AppLocker/Packaged app-Execution",
|
||||
&[8021, 8022],
|
||||
),
|
||||
(
|
||||
"applocker",
|
||||
"Microsoft-Windows-AppLocker/MSI and Script",
|
||||
&[8006, 8007],
|
||||
),
|
||||
(
|
||||
"windows_app_control",
|
||||
"Microsoft-Windows-CodeIntegrity/Operational",
|
||||
&[3076, 3077],
|
||||
),
|
||||
];
|
||||
|
||||
pub(super) async fn collect() -> DoctorCheck {
|
||||
let Some(system_root) = env::var_os("SystemRoot") else {
|
||||
return classify(&[]);
|
||||
};
|
||||
let wevtutil = Path::new(&system_root).join("System32/wevtutil.exe");
|
||||
let mut channels = Vec::with_capacity(CHANNELS.len());
|
||||
for pair in CHANNELS.chunks(/*chunk_size*/ 2) {
|
||||
let first = query_channel(&wevtutil, pair[0]);
|
||||
if let Some(second) = pair.get(/*index*/ 1) {
|
||||
let (first, second) = tokio::join!(first, query_channel(&wevtutil, *second));
|
||||
channels.extend([first, second]);
|
||||
} else {
|
||||
channels.push(first.await);
|
||||
}
|
||||
}
|
||||
classify(&channels)
|
||||
}
|
||||
|
||||
async fn query_channel(wevtutil: &Path, channel: Channel) -> Option<Vec<Evidence>> {
|
||||
let events = channel
|
||||
.2
|
||||
.iter()
|
||||
.map(|id| format!("EventID={id}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" or ");
|
||||
let mut child = Command::from(akode_utils_process::background_command(wevtutil))
|
||||
.args(["qe", channel.1])
|
||||
.arg(format!(
|
||||
"/q:*[System[({events}) and TimeCreated[timediff(@SystemTime) <= 604800000]]]"
|
||||
))
|
||||
.arg(format!("/c:{MAX_EVENTS_PER_CHANNEL}"))
|
||||
.args(["/rd:true", "/f:xml"])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.ok()?;
|
||||
let mut output = Vec::new();
|
||||
let status = timeout(Duration::from_secs(10), async {
|
||||
let mut reader = child.stdout.take()?.take(MAX_EVENT_OUTPUT_BYTES as u64 + 1);
|
||||
reader.read_to_end(&mut output).await.ok()?;
|
||||
if output.len() > MAX_EVENT_OUTPUT_BYTES {
|
||||
return None;
|
||||
}
|
||||
child.wait().await.ok()
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()?;
|
||||
status
|
||||
.success()
|
||||
.then(|| parse_events(&String::from_utf8_lossy(&output), channel))
|
||||
}
|
||||
|
||||
fn parse_events(xml: &str, (source, _, ids): Channel) -> Vec<Evidence> {
|
||||
xml.split("</Event>")
|
||||
.take(MAX_EVENTS_PER_CHANNEL)
|
||||
.filter_map(|event| {
|
||||
let id = element(event, "EventID")?.parse().ok()?;
|
||||
if !ids.contains(&id) {
|
||||
return None;
|
||||
}
|
||||
let target = event
|
||||
.split("<Data")
|
||||
.skip(/*n*/ 1)
|
||||
.filter_map(|data| data.split_once('>')?.1.split_once("</Data>").map(|v| v.0))
|
||||
.chain(
|
||||
["FilePath", "FileName", "Image", "PackageName", "PackageFamilyName"]
|
||||
.into_iter()
|
||||
.filter_map(|name| element(event, name)),
|
||||
)
|
||||
.find_map(event_target)?;
|
||||
let timestamp = event.split_once("SystemTime=\"")?.1.split_once('"')?.0;
|
||||
let (status, action) = match id {
|
||||
1121 | 1123 | 1126 | 1127 | 8004 | 8007 | 8022 | 3077 => {
|
||||
(CheckStatus::Fail, "blocked")
|
||||
}
|
||||
1122 | 1124 | 1125 | 1128 | 8003 | 8006 | 8021 | 3076 => {
|
||||
(CheckStatus::Warning, "audited")
|
||||
}
|
||||
1006 | 1116 => (CheckStatus::Warning, "detected"),
|
||||
1007 | 1117 => defender_action(event),
|
||||
_ => return None,
|
||||
};
|
||||
Some((
|
||||
status,
|
||||
format!(
|
||||
"source: {source}; event: {id}; target: {target}; action: {action}; time: {timestamp}"
|
||||
),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn event_target(value: &str) -> Option<&'static str> {
|
||||
let value = value.to_ascii_lowercase();
|
||||
let parts = value.split(['\\', '/']).map(str::trim).collect::<Vec<_>>();
|
||||
let name = *parts.last()?;
|
||||
let package = parts.iter().any(|part| part.starts_with("openai.codex_"));
|
||||
let trusted = package || parts.windows(2).any(|pair| pair == ["openai", "codex"]);
|
||||
match name {
|
||||
"akode-windows-sandbox-setup.exe" => Some("sandbox_setup"),
|
||||
"akode-command-runner.exe" => Some("command_runner"),
|
||||
"akode.exe" => Some("codex"),
|
||||
"codex-desktop.exe" => Some("codex_desktop"),
|
||||
"chatgpt.exe" | "electron.exe" if trusted => Some("codex_desktop"),
|
||||
"rg.exe" if trusted => Some("ripgrep"),
|
||||
_ if package => Some("codex_desktop_package"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn defender_action(event: &str) -> (CheckStatus, &'static str) {
|
||||
let action = [
|
||||
"Action Name",
|
||||
"ActionName",
|
||||
"Action",
|
||||
"Action ID",
|
||||
"ActionID",
|
||||
]
|
||||
.into_iter()
|
||||
.find_map(|name| data_value(event, name))
|
||||
.or_else(|| element(event, "ActionName"))
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
match action.as_str() {
|
||||
"quarantine" | "2" => (CheckStatus::Fail, "quarantined"),
|
||||
"clean" | "remove" | "block" | "1" | "3" | "10" => (CheckStatus::Fail, "blocked"),
|
||||
"allow" | "ignore" | "none" | "no action" | "user defined" | "6" | "8" | "9" | "11" => {
|
||||
(CheckStatus::Ok, "allowed")
|
||||
}
|
||||
_ => (CheckStatus::Warning, "detected"),
|
||||
}
|
||||
}
|
||||
|
||||
fn classify(channels: &[Option<Vec<Evidence>>]) -> DoctorCheck {
|
||||
let visible = channels.iter().any(Option::is_some);
|
||||
let mut status = if visible {
|
||||
CheckStatus::Ok
|
||||
} else {
|
||||
CheckStatus::Warning
|
||||
};
|
||||
let mut details = Vec::new();
|
||||
for (event_status, detail) in channels.iter().flatten().flatten() {
|
||||
status = status.max(*event_status);
|
||||
if details.len() < MAX_RENDERED_EVENTS {
|
||||
details.push(detail.clone());
|
||||
}
|
||||
}
|
||||
let summary = match (status, visible) {
|
||||
(CheckStatus::Ok, _) if channels.contains(&None) => "security event coverage is incomplete",
|
||||
(CheckStatus::Ok, _) => "no locally visible recent aKode security enforcement was found",
|
||||
(CheckStatus::Warning, false) => "security event channels could not be inspected",
|
||||
(CheckStatus::Warning, true) => "recent aKode security audit or detection requires review",
|
||||
(CheckStatus::Fail, _) => "endpoint security blocked or quarantined an aKode executable",
|
||||
};
|
||||
let mut check = desktop_check("desktop.security.enforcement", status, summary).details(details);
|
||||
if status != CheckStatus::Ok {
|
||||
check = check.remediation(
|
||||
"ask your organization's security administrator to review endpoint security events and the approved aKode application policy",
|
||||
);
|
||||
}
|
||||
check
|
||||
}
|
||||
|
||||
fn element<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
|
||||
let body = xml.split_once(&format!("<{name}"))?.1.split_once('>')?.1;
|
||||
Some(body.split_once(&format!("</{name}>"))?.0.trim())
|
||||
}
|
||||
|
||||
fn data_value<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
|
||||
let body = xml
|
||||
.split_once(&format!("Name=\"{name}\""))?
|
||||
.1
|
||||
.split_once('>')?
|
||||
.1;
|
||||
Some(body.split_once("</Data>")?.0.trim())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "windows_security_tests.rs"]
|
||||
mod tests;
|
||||
85
akode-rs/cli/src/doctor/desktop/windows_security_tests.rs
Normal file
85
akode-rs/cli/src/doctor/desktop/windows_security_tests.rs
Normal file
@@ -0,0 +1,85 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::CHANNELS;
|
||||
use super::CheckStatus;
|
||||
use super::MAX_RENDERED_EVENTS;
|
||||
use super::classify;
|
||||
use super::parse_events;
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
#[tokio::test]
|
||||
async fn an_unavailable_reader_is_not_reported_as_clean() {
|
||||
assert_eq!(super::collect().await.status, CheckStatus::Warning);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_source_distinguishes_audits_from_blocks() {
|
||||
for (channel, audit, block) in [
|
||||
(0, 1122, 1121),
|
||||
(0, 1125, 1126),
|
||||
(1, 8003, 8004),
|
||||
(2, 8021, 8022),
|
||||
(3, 8006, 8007),
|
||||
(4, 3076, 3077),
|
||||
] {
|
||||
for (id, expected) in [(audit, CheckStatus::Warning), (block, CheckStatus::Fail)] {
|
||||
let events = parse_events(&fixture(id, "akode.exe", &[]), CHANNELS[channel]);
|
||||
assert_eq!(events[0].0, expected, "misclassified event {id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defender_distinguishes_detection_and_remediation() {
|
||||
for (id, action, expected) in [
|
||||
(1116, "", CheckStatus::Warning),
|
||||
(1117, "Allow", CheckStatus::Ok),
|
||||
(1117, "Quarantine", CheckStatus::Fail),
|
||||
(1117, "Remove", CheckStatus::Fail),
|
||||
] {
|
||||
let events = parse_events(
|
||||
&fixture(id, "akode.exe", &[("Action Name", action)]),
|
||||
CHANNELS[0],
|
||||
);
|
||||
assert_eq!(classify(&[Some(events)]).status, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_trusted_codex_executables_are_reported() {
|
||||
for (path, expected) in [
|
||||
("akode.exe", true),
|
||||
(r"OpenAI.Codex_2p2nqsd0c76g0\ChatGPT.exe", true),
|
||||
("evil-codex.exe", false),
|
||||
(r"C:\Other\ChatGPT.exe", false),
|
||||
(r"OpenAI.CodexEvil_1\ChatGPT.exe", false),
|
||||
] {
|
||||
let events = parse_events(&fixture(/*id*/ 1121, path, &[]), CHANNELS[0]);
|
||||
assert_eq!(!events.is_empty(), expected, "misclassified {path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evidence_is_bounded_redacted_and_correctly_classified() {
|
||||
assert_eq!(classify(&[None]).status, CheckStatus::Warning);
|
||||
assert_eq!(classify(&[Some(Vec::new()), None]).status, CheckStatus::Ok);
|
||||
let audits = fixture(/*id*/ 1122, "akode.exe", &[]).repeat(MAX_RENDERED_EVENTS);
|
||||
let secret = "private-customer-secret";
|
||||
let block = fixture(/*id*/ 1121, "akode.exe", &[("User", secret)]);
|
||||
let events = parse_events(&format!("{audits}{block}"), CHANNELS[0]);
|
||||
let check = classify(&[Some(events)]);
|
||||
assert_eq!(check.id, "desktop.security.enforcement");
|
||||
assert_eq!(check.status, CheckStatus::Fail);
|
||||
assert_eq!(check.details.len(), MAX_RENDERED_EVENTS);
|
||||
assert!(!serde_json::to_string(&check).unwrap().contains(secret));
|
||||
}
|
||||
|
||||
fn fixture(id: u32, path: &str, fields: &[(&str, &str)]) -> String {
|
||||
let data = fields
|
||||
.iter()
|
||||
.map(|(name, value)| format!("<Data Name=\"{name}\">{value}</Data>"))
|
||||
.collect::<String>();
|
||||
format!(
|
||||
"<Event><System><EventID>{id}</EventID><TimeCreated SystemTime=\"2026-01-01T00:00:00Z\"/></System><EventData><Data Name=\"Path\">{path}</Data>{data}</EventData></Event>"
|
||||
)
|
||||
}
|
||||
97
akode-rs/cli/src/doctor/desktop_tests.rs
Normal file
97
akode-rs/cli/src/doctor/desktop_tests.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::desktop::inspect_desktop_session;
|
||||
|
||||
const CURRENT_SESSION: &str = "12345678-1234-1234-1234-123456789abc";
|
||||
const CURRENT_PROCESS: u32 = 12345;
|
||||
|
||||
#[test]
|
||||
fn current_desktop_session_reports_the_latest_local_handshake() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory should be created");
|
||||
write_log(
|
||||
directory.path(),
|
||||
concat!(
|
||||
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n",
|
||||
"2026-08-07T12:01:00.000Z info [AppServerConnection] Starting app-server connection hostId=local transport=websocket\n",
|
||||
"2026-08-07T12:02:00.000Z info [AppServerConnection] initialize_handshake_result outcome=success transportKind=websocket\n",
|
||||
"2026-08-07T12:03:00.000Z info [AppServerConnection] app_server_connection.state_changed hostId=remote transport=websocket\n",
|
||||
"2026-08-07T12:04:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=websocket\n",
|
||||
),
|
||||
);
|
||||
|
||||
let (running, check) = inspect_desktop_session(directory.path(), |pid| pid == CURRENT_PROCESS);
|
||||
|
||||
assert!(running);
|
||||
assert_eq!(check.id, "desktop.app_server.handshake");
|
||||
assert_eq!(check.status, CheckStatus::Ok);
|
||||
assert_eq!(
|
||||
check.summary,
|
||||
"the desktop app-server initialized successfully"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_handshake_does_not_expose_sensitive_log_fields() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory should be created");
|
||||
write_log(
|
||||
directory.path(),
|
||||
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result errorMessage=\"desktop-secret outcome=success\" outcome=failure transportKind=stdio\n",
|
||||
);
|
||||
|
||||
let (running, check) = inspect_desktop_session(directory.path(), |_| true);
|
||||
|
||||
assert!(running);
|
||||
assert_eq!(check.status, CheckStatus::Fail);
|
||||
assert_eq!(check.summary, "the desktop app-server failed to initialize");
|
||||
assert!(
|
||||
!serde_json::to_string(&check)
|
||||
.unwrap()
|
||||
.contains("desktop-secret")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_failure_in_the_middle_of_a_log_segment_is_detected() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory should be created");
|
||||
let padding = "x".repeat(96 * 1024);
|
||||
write_log(
|
||||
directory.path(),
|
||||
&format!(
|
||||
"{padding}\n2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n{padding}"
|
||||
),
|
||||
);
|
||||
|
||||
let (running, check) = inspect_desktop_session(directory.path(), |_| true);
|
||||
|
||||
assert!(running);
|
||||
assert_eq!(check.status, CheckStatus::Fail);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopped_desktop_does_not_report_a_failure() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory should be created");
|
||||
write_log(
|
||||
directory.path(),
|
||||
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n",
|
||||
);
|
||||
|
||||
let (running, check) = inspect_desktop_session(directory.path(), |_| false);
|
||||
|
||||
assert!(!running);
|
||||
assert_eq!(check.status, CheckStatus::Ok);
|
||||
assert_eq!(check.summary, "the desktop application is not running");
|
||||
}
|
||||
|
||||
fn write_log(directory: &Path, contents: &str) {
|
||||
fs::write(
|
||||
directory.join(format!(
|
||||
"codex-desktop-{CURRENT_SESSION}-{CURRENT_PROCESS}-t0-i0-120000-0.log"
|
||||
)),
|
||||
contents,
|
||||
)
|
||||
.expect("desktop log fixture should be created");
|
||||
}
|
||||
178
akode-rs/cli/src/doctor/disk.rs
Normal file
178
akode-rs/cli/src/doctor/disk.rs
Normal file
@@ -0,0 +1,178 @@
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
use akode_core::config::Config;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
use super::DoctorIssue;
|
||||
use super::find_codex_home;
|
||||
|
||||
const GIB: u64 = 1024 * 1024 * 1024;
|
||||
const FAIL_THRESHOLD: u64 = GIB;
|
||||
const WARNING_THRESHOLD: u64 = 5 * GIB;
|
||||
|
||||
pub(super) fn check(config: Option<&Config>, cwd: &Path) -> DoctorCheck {
|
||||
let home = config
|
||||
.map(|config| config.codex_home.as_path().to_path_buf())
|
||||
.or_else(|| find_codex_home().ok().map(Into::into))
|
||||
.or_else(|| std::env::var_os("AKODE_HOME").map(Into::into));
|
||||
|
||||
check_with_paths(home.as_deref(), cwd, available_space)
|
||||
}
|
||||
|
||||
fn check_with_paths(
|
||||
home: Option<&Path>,
|
||||
cwd: &Path,
|
||||
measure: impl Fn(&Path) -> io::Result<u64>,
|
||||
) -> DoctorCheck {
|
||||
let home = home.and_then(|path| std::path::absolute(path).ok());
|
||||
let mut check = DoctorCheck::new(
|
||||
"system.disk",
|
||||
"disk",
|
||||
CheckStatus::Ok,
|
||||
"sufficient free disk space",
|
||||
)
|
||||
.detail(format!(
|
||||
"warning threshold: {}",
|
||||
format_capacity(WARNING_THRESHOLD)
|
||||
))
|
||||
.detail(format!(
|
||||
"failure threshold: {}",
|
||||
format_capacity(FAIL_THRESHOLD)
|
||||
));
|
||||
let mut lowest = None;
|
||||
|
||||
for (label, path) in [("AKODE_HOME", home.as_deref()), ("worktree", Some(cwd))] {
|
||||
let field = format!("{label} available");
|
||||
let available = path
|
||||
.and_then(|path| path.ancestors().find(|ancestor| ancestor.is_dir()))
|
||||
.map(&measure)
|
||||
.unwrap_or_else(|| Err(io::ErrorKind::NotFound.into()));
|
||||
match available {
|
||||
Ok(available) => {
|
||||
let measured = format_capacity(available);
|
||||
check = check.detail(format!("{field}: {measured}"));
|
||||
lowest = Some(lowest.map_or(available, |lowest: u64| lowest.min(available)));
|
||||
|
||||
let status = match available {
|
||||
0..FAIL_THRESHOLD => CheckStatus::Fail,
|
||||
FAIL_THRESHOLD..WARNING_THRESHOLD => CheckStatus::Warning,
|
||||
WARNING_THRESHOLD.. => CheckStatus::Ok,
|
||||
};
|
||||
if status != CheckStatus::Ok {
|
||||
check.status = check.status.max(status);
|
||||
check = check.issue(
|
||||
DoctorIssue::new(status, format!("{label} has insufficient disk space"))
|
||||
.measured(measured)
|
||||
.expected(format!("at least {}", format_capacity(WARNING_THRESHOLD)))
|
||||
.remedy("Free disk space or move the worktree to a larger volume.")
|
||||
.field(field),
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
check.status = check.status.max(CheckStatus::Warning);
|
||||
check = check
|
||||
.detail(format!("{field}: unavailable ({:?})", error.kind()))
|
||||
.issue(
|
||||
DoctorIssue::new(
|
||||
CheckStatus::Warning,
|
||||
format!("disk space for {label} could not be checked"),
|
||||
)
|
||||
.measured(format!("{:?}", error.kind()))
|
||||
.expected("readable filesystem capacity")
|
||||
.remedy("Check filesystem access and available disk space.")
|
||||
.field(field),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
check.summary = match (check.status, lowest) {
|
||||
(CheckStatus::Fail, Some(available)) => {
|
||||
format!("critically low disk space ({})", format_capacity(available))
|
||||
}
|
||||
(CheckStatus::Warning, Some(available)) if available < WARNING_THRESHOLD => {
|
||||
format!("low disk space ({})", format_capacity(available))
|
||||
}
|
||||
(CheckStatus::Warning, _) => "disk capacity could not be fully verified".to_string(),
|
||||
(CheckStatus::Ok, Some(available)) => {
|
||||
format!(
|
||||
"sufficient free disk space ({})",
|
||||
format_capacity(available)
|
||||
)
|
||||
}
|
||||
(CheckStatus::Ok | CheckStatus::Fail, None) => {
|
||||
"disk capacity could not be verified".to_string()
|
||||
}
|
||||
};
|
||||
|
||||
check
|
||||
}
|
||||
|
||||
fn format_capacity(bytes: u64) -> String {
|
||||
if bytes >= GIB {
|
||||
format!("{:.1} GiB", bytes as f64 / GIB as f64)
|
||||
} else {
|
||||
format!("{:.1} MiB", bytes as f64 / (1024 * 1024) as f64)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn available_space(path: &Path) -> io::Result<u64> {
|
||||
use std::ffi::CString;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
let path = CString::new(path.as_os_str().as_bytes())
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL"))?;
|
||||
let mut stats = MaybeUninit::<libc::statvfs>::uninit();
|
||||
if unsafe { libc::statvfs(path.as_ptr(), stats.as_mut_ptr()) } != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let stats = unsafe { stats.assume_init() };
|
||||
if stats.f_files > 0 && stats.f_favail == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
u64::try_from(u128::from(stats.f_bavail) * u128::from(stats.f_frsize))
|
||||
.map_err(|_| io::Error::other("available disk space exceeds u64"))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn available_space(path: &Path) -> io::Result<u64> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
|
||||
|
||||
let mut path = path.as_os_str().encode_wide().collect::<Vec<_>>();
|
||||
if path.last() != Some(&u16::from(b'\\')) {
|
||||
path.push(u16::from(b'\\'));
|
||||
}
|
||||
path.push(0);
|
||||
let mut available = 0;
|
||||
if unsafe {
|
||||
GetDiskFreeSpaceExW(
|
||||
path.as_ptr(),
|
||||
&mut available,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
Ok(available)
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn available_space(_path: &Path) -> io::Result<u64> {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"filesystem capacity is unavailable on this platform",
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "disk_tests.rs"]
|
||||
mod tests;
|
||||
160
akode-rs/cli/src/doctor/disk_tests.rs
Normal file
160
akode-rs/cli/src/doctor/disk_tests.rs
Normal file
@@ -0,0 +1,160 @@
|
||||
use std::cell::RefCell;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::FAIL_THRESHOLD;
|
||||
use super::GIB;
|
||||
use super::WARNING_THRESHOLD;
|
||||
use super::check;
|
||||
use super::check_with_paths;
|
||||
|
||||
#[test]
|
||||
fn disk_capacity_is_reported_without_loaded_configuration() {
|
||||
let check = check(/*config*/ None, Path::new("."));
|
||||
|
||||
for label in ["AKODE_HOME available: ", "worktree available: "] {
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.iter()
|
||||
.any(|detail| detail.starts_with(label) && !detail.contains("unavailable"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disk_capacity_thresholds_produce_complete_diagnostics() {
|
||||
for (available, status, measured, summary) in [
|
||||
(0, "fail", "0.0 MiB", "critically low disk space (0.0 MiB)"),
|
||||
(
|
||||
FAIL_THRESHOLD - 1,
|
||||
"fail",
|
||||
"1024.0 MiB",
|
||||
"critically low disk space (1024.0 MiB)",
|
||||
),
|
||||
(
|
||||
FAIL_THRESHOLD,
|
||||
"warning",
|
||||
"1.0 GiB",
|
||||
"low disk space (1.0 GiB)",
|
||||
),
|
||||
(
|
||||
WARNING_THRESHOLD - 1,
|
||||
"warning",
|
||||
"5.0 GiB",
|
||||
"low disk space (5.0 GiB)",
|
||||
),
|
||||
(
|
||||
WARNING_THRESHOLD,
|
||||
"ok",
|
||||
"5.0 GiB",
|
||||
"sufficient free disk space (5.0 GiB)",
|
||||
),
|
||||
(
|
||||
WARNING_THRESHOLD + GIB,
|
||||
"ok",
|
||||
"6.0 GiB",
|
||||
"sufficient free disk space (6.0 GiB)",
|
||||
),
|
||||
] {
|
||||
let issues = ["AKODE_HOME", "worktree"]
|
||||
.into_iter()
|
||||
.filter(|_| status != "ok")
|
||||
.map(|label| {
|
||||
json!({
|
||||
"severity": status,
|
||||
"cause": format!("{label} has insufficient disk space"),
|
||||
"measured": measured,
|
||||
"expected": "at least 5.0 GiB",
|
||||
"remedy": "Free disk space or move the worktree to a larger volume.",
|
||||
"fields": [format!("{label} available")],
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let check = check_with_paths(Some(Path::new(".")), Path::new("."), |_| Ok(available));
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(check).unwrap(),
|
||||
json!({
|
||||
"id": "system.disk",
|
||||
"category": "disk",
|
||||
"status": status,
|
||||
"summary": summary,
|
||||
"details": [
|
||||
"warning threshold: 5.0 GiB",
|
||||
"failure threshold: 1.0 GiB",
|
||||
format!("AKODE_HOME available: {measured}"),
|
||||
format!("worktree available: {measured}"),
|
||||
],
|
||||
"issues": issues,
|
||||
"remediation": null,
|
||||
"durationMs": 0,
|
||||
}),
|
||||
"available bytes: {available}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disk_measurement_errors_produce_complete_warning_diagnostics() {
|
||||
let check = check_with_paths(Some(Path::new(".")), Path::new("."), |_| {
|
||||
Err(io::ErrorKind::PermissionDenied.into())
|
||||
});
|
||||
|
||||
let issues = ["AKODE_HOME", "worktree"]
|
||||
.into_iter()
|
||||
.map(|label| {
|
||||
json!({
|
||||
"severity": "warning",
|
||||
"cause": format!("disk space for {label} could not be checked"),
|
||||
"measured": "PermissionDenied",
|
||||
"expected": "readable filesystem capacity",
|
||||
"remedy": "Check filesystem access and available disk space.",
|
||||
"fields": [format!("{label} available")],
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(check).unwrap(),
|
||||
json!({
|
||||
"id": "system.disk",
|
||||
"category": "disk",
|
||||
"status": "warning",
|
||||
"summary": "disk capacity could not be fully verified",
|
||||
"details": [
|
||||
"warning threshold: 5.0 GiB",
|
||||
"failure threshold: 1.0 GiB",
|
||||
"AKODE_HOME available: unavailable (PermissionDenied)",
|
||||
"worktree available: unavailable (PermissionDenied)",
|
||||
],
|
||||
"issues": issues,
|
||||
"remediation": null,
|
||||
"durationMs": 0,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonexistent_relative_codex_home_uses_current_directory_capacity() {
|
||||
let measured_paths = RefCell::new(Vec::new());
|
||||
let check = check_with_paths(
|
||||
Some(Path::new("doctor-nonexistent-relative-home/nested")),
|
||||
Path::new("."),
|
||||
|path| {
|
||||
measured_paths.borrow_mut().push(path.to_path_buf());
|
||||
Ok(WARNING_THRESHOLD)
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Ok);
|
||||
assert_eq!(
|
||||
measured_paths.into_inner(),
|
||||
[std::env::current_dir().unwrap(), Path::new(".").into()]
|
||||
);
|
||||
}
|
||||
385
akode-rs/cli/src/doctor/filesystem_paths.rs
Normal file
385
akode-rs/cli/src/doctor/filesystem_paths.rs
Normal file
@@ -0,0 +1,385 @@
|
||||
//! Checks literal sandbox grants without traversing directory trees or probing deny rules.
|
||||
//!
|
||||
//! Filesystem calls run in disposable copies of this executable: a blocked mount
|
||||
//! must not occupy a Tokio blocking worker and delay doctor's runtime shutdown.
|
||||
//! Budgets bound helper waits, not synchronous process launch; policy is unchanged.
|
||||
//! Windows only lists paths: even local-looking paths can redirect to network shares.
|
||||
//! Restricted-read policies also only list paths: lexical checks cannot constrain symlinks.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use akode_config::ConfigPathContext;
|
||||
use akode_config::format_config_layer_source;
|
||||
use akode_config::permissions_toml::FilesystemPermissionToml;
|
||||
use akode_core::config::Config;
|
||||
use akode_protocol::permissions::FileSystemAccessMode;
|
||||
use akode_protocol::permissions::FileSystemPath;
|
||||
use akode_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use akode_protocol::permissions::FileSystemSandboxPolicyContext;
|
||||
use akode_protocol::permissions::ReadDenyMatcher;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_absolute_path::AbsolutePathBufGuard;
|
||||
use akode_utils_path_uri::PathConvention;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use tokio::process::Command;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
use super::DoctorIssue;
|
||||
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
const TOTAL_TIMEOUT: Duration = Duration::from_secs(8);
|
||||
const SLOW_PROBE: Duration = Duration::from_secs(1);
|
||||
const MAX_PATHS: usize = 32;
|
||||
|
||||
pub(super) async fn check(config: &Config) -> DoctorCheck {
|
||||
let mut check = DoctorCheck::new(
|
||||
"sandbox.filesystem_paths",
|
||||
"sandbox",
|
||||
CheckStatus::Ok,
|
||||
"configured filesystem paths respond promptly",
|
||||
);
|
||||
// Resolve policy semantics lexically, without querying the configured paths.
|
||||
let policy = config
|
||||
.permissions
|
||||
.permission_profile()
|
||||
.file_system_sandbox_policy();
|
||||
let cwd = PathUri::from_abs_path(&config.cwd);
|
||||
let roots = config.effective_workspace_roots();
|
||||
let home = AbsolutePathBufGuard::home_directory()
|
||||
.and_then(|home| PathUri::from_host_native_path(home).ok());
|
||||
let temporary_directories = std::env::var_os("TMPDIR")
|
||||
.filter(|path| !path.is_empty())
|
||||
.and_then(|path| AbsolutePathBuf::from_absolute_path(path).ok())
|
||||
.map(PathUri::from)
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd: &cwd,
|
||||
workspace_roots: &roots,
|
||||
user_home_dir: home.as_ref(),
|
||||
temporary_directories: Some(&temporary_directories),
|
||||
};
|
||||
let paths = literal_paths(&policy, &context);
|
||||
if paths.is_empty() {
|
||||
check.summary = "no explicit filesystem paths to probe".to_string();
|
||||
return check;
|
||||
}
|
||||
let read_restricted = !policy.has_full_disk_read_access();
|
||||
if read_restricted {
|
||||
check.summary =
|
||||
"configured filesystem paths listed; read restrictions prevent probes".to_string();
|
||||
} else if cfg!(windows) {
|
||||
check.summary =
|
||||
"configured filesystem paths listed; probes disabled on Windows".to_string();
|
||||
}
|
||||
if let Some(profile) = config.permissions.active_permission_profile() {
|
||||
check
|
||||
.details
|
||||
.push(format!("permission profile: {}", profile.id));
|
||||
}
|
||||
check
|
||||
.details
|
||||
.push("operation: resolve paths only; read/write access is not tested".to_string());
|
||||
check
|
||||
.details
|
||||
.push("probe budgets: 2 seconds per path, 8 seconds total, at most 32 paths".to_string());
|
||||
let started = Instant::now();
|
||||
let mut checked = 0;
|
||||
for (path, access) in paths.iter().take(MAX_PATHS) {
|
||||
let remaining = TOTAL_TIMEOUT.saturating_sub(started.elapsed());
|
||||
if remaining.is_zero() {
|
||||
break;
|
||||
}
|
||||
let label = format!("path {}", checked + 1);
|
||||
let probe_started = Instant::now();
|
||||
let outcome = match path.to_abs_path() {
|
||||
Ok(_) if read_restricted => ProbeResult::SkippedReadRestrictions,
|
||||
Ok(_) if cfg!(windows) => ProbeResult::SkippedWindows,
|
||||
Ok(native) => {
|
||||
let executable = match std::env::current_exe() {
|
||||
Ok(executable) => executable,
|
||||
Err(_) => {
|
||||
check.status = CheckStatus::Warning;
|
||||
check.summary =
|
||||
"filesystem path probes unavailable: cannot locate aKode executable"
|
||||
.to_string();
|
||||
return check;
|
||||
}
|
||||
};
|
||||
let mut command = Command::new(&executable);
|
||||
command
|
||||
.arg("doctor")
|
||||
.arg("--probe-filesystem-path")
|
||||
.arg(native.as_path());
|
||||
probe(&mut command, remaining.min(PROBE_TIMEOUT)).await
|
||||
}
|
||||
Err(_) => ProbeResult::Unsupported,
|
||||
};
|
||||
let slow = probe_started.elapsed() >= SLOW_PROBE;
|
||||
checked += 1;
|
||||
let access = access
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
check.details.push(format!(
|
||||
"{label}: {} ({access}); {}",
|
||||
path.inferred_native_path_string(),
|
||||
outcome.description()
|
||||
));
|
||||
if slow {
|
||||
check.details.push(format!(
|
||||
"{label} latency: over 1 second (includes helper startup)"
|
||||
));
|
||||
}
|
||||
check
|
||||
.details
|
||||
.push(format!("{label} source: {}", source(config, path)));
|
||||
if !matches!(
|
||||
outcome,
|
||||
ProbeResult::Resolved
|
||||
| ProbeResult::Missing
|
||||
| ProbeResult::SkippedWindows
|
||||
| ProbeResult::SkippedReadRestrictions
|
||||
) || slow
|
||||
{
|
||||
check.status = CheckStatus::Warning;
|
||||
check.summary =
|
||||
"some configured filesystem paths are slow or could not be checked".to_string();
|
||||
check.issues.push(
|
||||
DoctorIssue::new(CheckStatus::Warning, format!("{label}: {}{}", outcome.description(), if slow { "; slow path probe" } else { "" }))
|
||||
.field(label)
|
||||
.remedy("Check this path's mount and host permissions. Ask your administrator whether the entry is needed on this machine; do not remove required restrictions."),
|
||||
);
|
||||
}
|
||||
}
|
||||
if checked < paths.len() {
|
||||
check.status = CheckStatus::Warning;
|
||||
check.summary = "filesystem path check is incomplete".to_string();
|
||||
check.details.push(format!(
|
||||
"unchecked paths: {} (probe budget exhausted)",
|
||||
paths.len() - checked
|
||||
));
|
||||
}
|
||||
check
|
||||
.details
|
||||
.push(format!("paths checked: {checked} of {}", paths.len()));
|
||||
check
|
||||
}
|
||||
|
||||
fn literal_paths(
|
||||
policy: &FileSystemSandboxPolicy,
|
||||
context: &FileSystemSandboxPolicyContext<'_>,
|
||||
) -> Vec<(PathUri, BTreeSet<FileSystemAccessMode>)> {
|
||||
let mut paths = HashMap::<_, BTreeSet<_>>::new();
|
||||
let denials = ReadDenyMatcher::from_context(policy, context);
|
||||
for entry in &policy.entries {
|
||||
// Deny rules can contain private managed-policy paths. Doctor only
|
||||
// reports their counts in the existing sandbox check.
|
||||
if entry.access == FileSystemAccessMode::Deny {
|
||||
continue;
|
||||
}
|
||||
match &entry.path {
|
||||
FileSystemPath::Path { path } => {
|
||||
if policy.can_read_path(path, context)
|
||||
&& !denials
|
||||
.as_ref()
|
||||
.is_some_and(|matcher| matcher.is_read_denied_uri(path, context))
|
||||
{
|
||||
paths.entry(path.clone()).or_default().insert(entry.access);
|
||||
}
|
||||
}
|
||||
FileSystemPath::GlobPattern { .. } | FileSystemPath::Special { .. } => {}
|
||||
}
|
||||
}
|
||||
let mut paths = paths.into_iter().collect::<Vec<_>>();
|
||||
paths.sort_by_cached_key(|(path, _)| path.to_string());
|
||||
paths
|
||||
}
|
||||
|
||||
fn source(config: &Config, path: &PathUri) -> String {
|
||||
let active = config.permissions.active_permission_profile();
|
||||
let context = ConfigPathContext::new(
|
||||
PathConvention::native(),
|
||||
Some(PathUri::from_abs_path(&config.cwd)),
|
||||
AbsolutePathBufGuard::home_directory()
|
||||
.and_then(|home| PathUri::from_host_native_path(home).ok()),
|
||||
);
|
||||
let effective = config.config_layer_stack.effective_config();
|
||||
let managed = config
|
||||
.config_layer_stack
|
||||
.requirements_toml()
|
||||
.permissions
|
||||
.as_ref();
|
||||
let matches_path = |base: &str, subpath: Option<&str>| {
|
||||
let base = if subpath.is_none() {
|
||||
base.strip_suffix("/**").unwrap_or(base)
|
||||
} else {
|
||||
base
|
||||
};
|
||||
let Ok(base) = context.resolve_path(base) else {
|
||||
return false;
|
||||
};
|
||||
match subpath.map(|subpath| subpath.strip_suffix("/**").unwrap_or(subpath)) {
|
||||
None | Some(".") => base == *path,
|
||||
Some(subpath) => context
|
||||
.resolve_against(subpath, &base)
|
||||
.is_ok_and(|resolved| resolved == *path),
|
||||
}
|
||||
};
|
||||
let mut profiles = Vec::new();
|
||||
let mut next = active.as_ref().map(|profile| profile.id.as_str());
|
||||
while let Some(profile) = next {
|
||||
if profiles.contains(&profile) {
|
||||
break;
|
||||
}
|
||||
profiles.push(profile);
|
||||
next = effective
|
||||
.get("permissions")
|
||||
.and_then(|permissions| permissions.get(profile))
|
||||
.and_then(|profile| profile.get("extends"))
|
||||
.and_then(toml::Value::as_str)
|
||||
.or_else(|| managed?.profiles.get(profile)?.extends.as_deref());
|
||||
}
|
||||
for profile in profiles {
|
||||
// Managed grants have no config-layer origin and can shadow a parent's grant.
|
||||
if managed
|
||||
.and_then(|managed| managed.profiles.get(profile))
|
||||
.and_then(|profile| profile.filesystem.as_ref())
|
||||
.is_some_and(|filesystem| {
|
||||
filesystem.entries.iter().any(|(base, entry)| match entry {
|
||||
FilesystemPermissionToml::Access(access) => {
|
||||
*access != FileSystemAccessMode::Deny
|
||||
&& matches_path(base, /*subpath*/ None)
|
||||
}
|
||||
FilesystemPermissionToml::Scoped(entries) => {
|
||||
entries.iter().any(|(subpath, access)| {
|
||||
*access != FileSystemAccessMode::Deny
|
||||
&& matches_path(base, Some(subpath))
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
{
|
||||
break;
|
||||
}
|
||||
let origins = config
|
||||
.config_layer_stack
|
||||
.origins_with_path_filter(|segments| {
|
||||
if segments.len() < 4 || segments[0] != "permissions" || segments[2] != "filesystem"
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if profile != segments[1] {
|
||||
return false;
|
||||
}
|
||||
// Origins can retain leaves removed by a table/scalar replacement.
|
||||
if !matches!(
|
||||
segments
|
||||
.iter()
|
||||
.try_fold(&effective, |value, segment| value.get(segment))
|
||||
.and_then(toml::Value::as_str),
|
||||
Some("read" | "write")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
matches_path(&segments[3], segments.get(4).map(String::as_str))
|
||||
});
|
||||
let sources = origins
|
||||
.into_iter()
|
||||
.map(|(key, origin)| {
|
||||
format!(
|
||||
"{key} in {}",
|
||||
format_config_layer_source(&origin.name, akode_config::CONFIG_TOML_FILE)
|
||||
)
|
||||
})
|
||||
.collect::<BTreeSet<_>>();
|
||||
if !sources.is_empty() {
|
||||
return sources.into_iter().collect::<Vec<_>>().join("; ");
|
||||
}
|
||||
}
|
||||
// Compiled requirements, legacy config, and runtime-added entries do not
|
||||
// retain per-entry provenance. Do not misattribute them to a config file.
|
||||
"effective filesystem policy (entry provenance unavailable)".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum ProbeResult {
|
||||
Resolved,
|
||||
Missing,
|
||||
Denied,
|
||||
TimedOut,
|
||||
Failed,
|
||||
Unsupported,
|
||||
SkippedWindows,
|
||||
SkippedReadRestrictions,
|
||||
}
|
||||
|
||||
impl ProbeResult {
|
||||
fn description(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Resolved => "path resolved (read/write access not tested)",
|
||||
Self::Missing => "missing (may be intentional)",
|
||||
Self::Denied => "access denied to doctor",
|
||||
Self::TimedOut => "path probe timed out",
|
||||
Self::Failed => "path probe failed",
|
||||
Self::Unsupported => "path is not native to this host; not probed",
|
||||
Self::SkippedWindows => "not probed on Windows (network authentication risk)",
|
||||
Self::SkippedReadRestrictions => "not probed (filesystem read restrictions apply)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn probe(command: &mut Command, budget: Duration) -> ProbeResult {
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(/*kill_on_drop*/ true);
|
||||
let Ok(mut child) = command.spawn() else {
|
||||
return ProbeResult::Failed;
|
||||
};
|
||||
match tokio::time::timeout(budget, child.wait()).await {
|
||||
Ok(Ok(status)) => match status.code() {
|
||||
Some(0) => ProbeResult::Resolved,
|
||||
Some(2) => ProbeResult::Missing,
|
||||
Some(3) => ProbeResult::Denied,
|
||||
Some(5) => ProbeResult::SkippedWindows,
|
||||
_ => ProbeResult::Failed,
|
||||
},
|
||||
Ok(Err(_)) => ProbeResult::Failed,
|
||||
Err(_) => {
|
||||
// Do not await termination: an uninterruptible filesystem syscall
|
||||
// can delay even SIGKILL. Tokio reaps the child when it can exit.
|
||||
let _ = child.start_kill();
|
||||
ProbeResult::TimedOut
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn probe_exit_code(path: &Path) -> i32 {
|
||||
// Even drive-qualified paths can traverse reparse points to network shares.
|
||||
// Do not initiate filesystem access on Windows from this unsandboxed helper.
|
||||
if cfg!(windows) {
|
||||
return 5;
|
||||
}
|
||||
match std::fs::canonicalize(path) {
|
||||
Ok(_) => 0,
|
||||
Err(error) => match error.kind() {
|
||||
io::ErrorKind::NotFound => 2,
|
||||
io::ErrorKind::PermissionDenied => 3,
|
||||
_ => 4,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "filesystem_paths_tests.rs"]
|
||||
mod tests;
|
||||
286
akode-rs/cli/src/doctor/filesystem_paths_tests.rs
Normal file
286
akode-rs/cli/src/doctor/filesystem_paths_tests.rs
Normal file
@@ -0,0 +1,286 @@
|
||||
use std::collections::BTreeSet;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use akode_config::LoaderOverrides;
|
||||
use akode_core::config::ConfigBuilder;
|
||||
use akode_protocol::permissions::FileSystemAccessMode;
|
||||
use akode_protocol::permissions::FileSystemPath;
|
||||
use akode_protocol::permissions::FileSystemSandboxEntry;
|
||||
use akode_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use akode_protocol::permissions::FileSystemSandboxPolicyContext;
|
||||
use akode_protocol::permissions::FileSystemSpecialPath;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::process::Command;
|
||||
|
||||
use super::ProbeResult;
|
||||
use super::literal_paths;
|
||||
use super::probe;
|
||||
use super::source;
|
||||
|
||||
#[test]
|
||||
fn deduplicates_literal_paths_without_expanding_globs_or_special_paths() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = PathUri::from_host_native_path(temp.path()).unwrap();
|
||||
let mut policy = FileSystemSandboxPolicy {
|
||||
entries: vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: path.clone().into(),
|
||||
access: FileSystemAccessMode::Read,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
FileSystemSandboxEntry {
|
||||
path: path.clone().into(),
|
||||
access: FileSystemAccessMode::Write,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
FileSystemSandboxEntry {
|
||||
path: PathUri::from_host_native_path(temp.path().join("private-policy-path"))
|
||||
.unwrap()
|
||||
.into(),
|
||||
access: FileSystemAccessMode::Deny,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::GlobPattern {
|
||||
pattern: format!("{}/**/*.env", temp.path().display()),
|
||||
},
|
||||
access: FileSystemAccessMode::Deny,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
access: FileSystemAccessMode::Read,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
// Equal-specificity denials, denied ancestors, and deny globs all override grants.
|
||||
for suffix in [
|
||||
"private-policy-path",
|
||||
"private-policy-path/child",
|
||||
"secret.env",
|
||||
] {
|
||||
policy.entries.push(FileSystemSandboxEntry {
|
||||
path: PathUri::from_host_native_path(temp.path().join(suffix))
|
||||
.unwrap()
|
||||
.into(),
|
||||
access: FileSystemAccessMode::Read,
|
||||
missing_path_behavior: None,
|
||||
});
|
||||
}
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd: &path,
|
||||
workspace_roots: std::slice::from_ref(&path),
|
||||
user_home_dir: None,
|
||||
temporary_directories: Some(&[]),
|
||||
};
|
||||
assert_eq!(
|
||||
literal_paths(&policy, &context),
|
||||
vec![(
|
||||
path,
|
||||
BTreeSet::from([FileSystemAccessMode::Read, FileSystemAccessMode::Write])
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attributes_paths_inherited_through_managed_profiles_to_their_config_layer() {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let configured = home.path().join("unavailable");
|
||||
let config_file = home.path().join("config.toml");
|
||||
let base = toml::Value::String(configured.display().to_string());
|
||||
std::fs::write(
|
||||
&config_file,
|
||||
format!(
|
||||
r#"
|
||||
default_permissions = "diagnostic"
|
||||
[permissions.diagnostic]
|
||||
extends = "middle"
|
||||
[permissions.diagnostic.filesystem.{base}]
|
||||
"." = "read"
|
||||
[permissions.base]
|
||||
extends = ":workspace"
|
||||
[permissions.base.filesystem.{base}]
|
||||
"." = "write"
|
||||
".git" = "write"
|
||||
"subtree/**" = "read"
|
||||
"overridden" = "read"
|
||||
"#
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let requirements_file = home.path().join("requirements.toml");
|
||||
std::fs::write(
|
||||
&requirements_file,
|
||||
format!(
|
||||
r#"
|
||||
[permissions.middle]
|
||||
extends = "base"
|
||||
[permissions.middle.filesystem.{base}]
|
||||
".git/**" = "deny"
|
||||
"overridden" = "write"
|
||||
"#
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let mut overrides = LoaderOverrides::without_managed_config_for_tests();
|
||||
overrides.system_requirements_path = Some(requirements_file);
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.loader_overrides(overrides)
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
let path = PathUri::from_host_native_path(configured.join(".git")).unwrap();
|
||||
assert_eq!(
|
||||
source(&config, &path),
|
||||
format!(
|
||||
"permissions.base.filesystem.{}..git in user ({})",
|
||||
configured.display(),
|
||||
config_file.display()
|
||||
)
|
||||
);
|
||||
let subtree = PathUri::from_host_native_path(configured.join("subtree")).unwrap();
|
||||
assert_eq!(
|
||||
source(&config, &subtree),
|
||||
format!(
|
||||
"permissions.base.filesystem.{}.subtree/** in user ({})",
|
||||
configured.display(),
|
||||
config_file.display()
|
||||
)
|
||||
);
|
||||
let overridden = PathUri::from_host_native_path(configured.join("overridden")).unwrap();
|
||||
assert_eq!(
|
||||
source(&config, &overridden),
|
||||
"effective filesystem policy (entry provenance unavailable)"
|
||||
);
|
||||
let base_path = PathUri::from_host_native_path(&configured).unwrap();
|
||||
assert_eq!(
|
||||
source(&config, &base_path),
|
||||
format!(
|
||||
"permissions.diagnostic.filesystem.{}.. in user ({})",
|
||||
configured.display(),
|
||||
config_file.display()
|
||||
)
|
||||
);
|
||||
let mut check = super::check(&config).await;
|
||||
for detail in &mut check.details {
|
||||
*detail = detail
|
||||
.replace(&home.path().display().to_string(), "FIXTURE")
|
||||
.replace('\\', "/");
|
||||
}
|
||||
let report = super::super::DoctorReport {
|
||||
schema_version: 1,
|
||||
generated_at: "2026-01-01T00:00:00Z".to_string(),
|
||||
overall_status: check.status,
|
||||
codex_version: "test".to_string(),
|
||||
checks: vec![check],
|
||||
};
|
||||
insta::assert_snapshot!(
|
||||
"doctor_read_restricted_filesystem_paths",
|
||||
super::super::render_human_report(
|
||||
&report,
|
||||
super::super::HumanOutputOptions {
|
||||
show_details: true,
|
||||
show_all: false,
|
||||
ascii: true,
|
||||
color_enabled: false,
|
||||
},
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn returns_when_a_probe_process_does_not_exit() {
|
||||
let mut command = Command::new(std::env::current_exe().unwrap());
|
||||
command.args([
|
||||
"--ignored",
|
||||
"--exact",
|
||||
"doctor::filesystem_paths::tests::blocked_probe_fixture",
|
||||
]);
|
||||
let started = Instant::now();
|
||||
assert_eq!(
|
||||
probe(&mut command, Duration::from_millis(/*millis*/ 150)).await,
|
||||
ProbeResult::TimedOut
|
||||
);
|
||||
assert!(started.elapsed() < Duration::from_secs(/*secs*/ 5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "subprocess fixture for the bounded filesystem probe test"]
|
||||
fn blocked_probe_fixture() {
|
||||
std::thread::sleep(Duration::from_secs(/*secs*/ 30));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn attributes_home_relative_subtree_paths_to_their_config_layer() {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let config_file = home.path().join("config.toml");
|
||||
std::fs::write(
|
||||
&config_file,
|
||||
r#"
|
||||
default_permissions = "diagnostic"
|
||||
[permissions.diagnostic]
|
||||
extends = ":read-only"
|
||||
[permissions.diagnostic.filesystem]
|
||||
"~/doctor-provenance/**" = "read"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
let user_home = akode_utils_absolute_path::AbsolutePathBufGuard::home_directory().unwrap();
|
||||
let path = PathUri::from_host_native_path(user_home.join("doctor-provenance")).unwrap();
|
||||
assert_eq!(
|
||||
source(&config, &path),
|
||||
format!(
|
||||
"permissions.diagnostic.filesystem.~/doctor-provenance/** in user ({})",
|
||||
config_file.display()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn excludes_scoped_origins_replaced_by_a_scalar_grant() {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let configured = home.path().join("cache.v1");
|
||||
let base = toml::Value::String(configured.display().to_string());
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
format!(
|
||||
r#"
|
||||
default_permissions = "diagnostic"
|
||||
[permissions.diagnostic]
|
||||
extends = ":read-only"
|
||||
[permissions.diagnostic.filesystem.{base}]
|
||||
"." = "read"
|
||||
"#
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.cli_overrides(vec![(
|
||||
"permissions.diagnostic.filesystem".to_string(),
|
||||
format!("{{ {base} = \"write\" }}").parse().unwrap(),
|
||||
)])
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
let path = PathUri::from_host_native_path(&configured).unwrap();
|
||||
assert_eq!(
|
||||
source(&config, &path),
|
||||
format!(
|
||||
"permissions.diagnostic.filesystem.{} in session-flags",
|
||||
configured.display()
|
||||
)
|
||||
);
|
||||
}
|
||||
160
akode-rs/cli/src/doctor/git.rs
Normal file
160
akode-rs/cli/src/doctor/git.rs
Normal file
@@ -0,0 +1,160 @@
|
||||
//! Inspects Git executable locations and repository metadata without running Git.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use akode_git_utils::get_git_repo_root;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
use super::DoctorIssue;
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
struct GitCheckInputs {
|
||||
selected_git: Option<PathBuf>,
|
||||
git_candidates: Vec<PathBuf>,
|
||||
repo_root: Option<PathBuf>,
|
||||
git_entry: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) fn git_check(cwd: &Path) -> DoctorCheck {
|
||||
let selected_git = which::which("git").ok();
|
||||
let git_candidates = git_candidates();
|
||||
let repo_root = get_git_repo_root(cwd);
|
||||
|
||||
git_check_from_inputs(GitCheckInputs {
|
||||
selected_git,
|
||||
git_candidates,
|
||||
git_entry: repo_root.as_deref().map(git_entry_summary),
|
||||
repo_root,
|
||||
})
|
||||
}
|
||||
|
||||
fn git_check_from_inputs(inputs: GitCheckInputs) -> DoctorCheck {
|
||||
let mut details = Vec::new();
|
||||
match inputs.selected_git.as_deref() {
|
||||
Some(path) => details.push(format!("selected git: {}", path.display())),
|
||||
None => details.push("selected git: not found".to_string()),
|
||||
}
|
||||
details.push(format!("PATH git entries: {}", inputs.git_candidates.len()));
|
||||
for (index, path) in inputs.git_candidates.iter().enumerate() {
|
||||
details.push(format!("PATH git #{}: {}", index + 1, path.display()));
|
||||
}
|
||||
match inputs.repo_root.as_deref() {
|
||||
Some(root) => {
|
||||
details.push("repo detected: true".to_string());
|
||||
details.push(format!("repo root: {}", root.display()));
|
||||
}
|
||||
None => details.push("repo detected: false".to_string()),
|
||||
}
|
||||
if let Some(entry) = inputs.git_entry.as_deref() {
|
||||
details.push(format!(".git entry: {entry}"));
|
||||
}
|
||||
details.push("git execution: not inspected (PATH helpers are not executed)".to_string());
|
||||
|
||||
let mut check = DoctorCheck::new(
|
||||
"git.environment",
|
||||
"git",
|
||||
CheckStatus::Ok,
|
||||
if inputs.selected_git.is_some() {
|
||||
"git executable found; execution not verified"
|
||||
} else {
|
||||
"git executable not found"
|
||||
},
|
||||
)
|
||||
.details(details);
|
||||
|
||||
if inputs.selected_git.is_none() && inputs.repo_root.is_some() {
|
||||
check.status = CheckStatus::Warning;
|
||||
check.summary = "Git repository detected but git executable was not found".to_string();
|
||||
check = check.issue(
|
||||
DoctorIssue::new(
|
||||
CheckStatus::Warning,
|
||||
"Git repository detected but git executable was not found",
|
||||
)
|
||||
.expected("git available on PATH")
|
||||
.remedy("Install Git or fix PATH so aKode can inspect repository metadata.")
|
||||
.field("selected git"),
|
||||
);
|
||||
}
|
||||
|
||||
check
|
||||
}
|
||||
|
||||
fn git_candidates() -> Vec<PathBuf> {
|
||||
let Ok(candidates) = which::which_all("git") else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut seen = BTreeSet::new();
|
||||
candidates
|
||||
.filter(|candidate| seen.insert(candidate.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn git_entry_summary(repo_root: &Path) -> String {
|
||||
let entry = repo_root.join(".git");
|
||||
match std::fs::metadata(&entry) {
|
||||
Ok(metadata) if metadata.is_dir() => "directory".to_string(),
|
||||
Ok(metadata) if metadata.is_file() => std::fs::read_to_string(&entry)
|
||||
.ok()
|
||||
.and_then(|contents| {
|
||||
contents
|
||||
.strip_prefix("gitdir:")
|
||||
.map(str::trim)
|
||||
.map(|path| format!("file -> {path}"))
|
||||
})
|
||||
.unwrap_or_else(|| "file".to_string()),
|
||||
Ok(_) => "other".to_string(),
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => "missing".to_string(),
|
||||
Err(err) => format!("unreadable ({err})"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn warns_when_git_repo_has_no_git_executable() {
|
||||
let check = git_check_from_inputs(GitCheckInputs {
|
||||
repo_root: Some(PathBuf::from("/repo")),
|
||||
..GitCheckInputs::default()
|
||||
});
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert_eq!(
|
||||
check.summary,
|
||||
"Git repository detected but git executable was not found"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_git_candidates_and_repo_metadata() {
|
||||
let check = git_check_from_inputs(GitCheckInputs {
|
||||
selected_git: Some(PathBuf::from("/usr/bin/git")),
|
||||
git_candidates: vec![PathBuf::from("/usr/bin/git"), PathBuf::from("/opt/bin/git")],
|
||||
repo_root: Some(PathBuf::from("/repo")),
|
||||
git_entry: Some("directory".to_string()),
|
||||
});
|
||||
|
||||
let report = super::super::DoctorReport {
|
||||
schema_version: 1,
|
||||
generated_at: "2026-01-01T00:00:00Z".to_string(),
|
||||
overall_status: check.status,
|
||||
codex_version: "test".to_string(),
|
||||
checks: vec![check],
|
||||
};
|
||||
insta::assert_snapshot!(super::super::render_human_report(
|
||||
&report,
|
||||
super::super::HumanOutputOptions {
|
||||
show_details: true,
|
||||
show_all: false,
|
||||
ascii: true,
|
||||
color_enabled: false,
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
223
akode-rs/cli/src/doctor/network.rs
Normal file
223
akode-rs/cli/src/doctor/network.rs
Normal file
@@ -0,0 +1,223 @@
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use akode_arg0::Arg0DispatchPaths;
|
||||
use akode_core::config::Config;
|
||||
#[cfg(target_os = "macos")]
|
||||
use akode_http_client::MacosSystemProxyConfiguration;
|
||||
use akode_http_client::RouteAwareClientPool;
|
||||
use akode_http_client::RouteAwareRequestError;
|
||||
use akode_http_client::RouteFailureClass;
|
||||
#[cfg(target_os = "macos")]
|
||||
use akode_http_client::macos_system_proxy_configuration;
|
||||
use akode_login::default_client::create_client_without_request_logging;
|
||||
use akode_tui::Cli as TuiCli;
|
||||
use akode_utils_cli::CliConfigOverrides;
|
||||
use http::HeaderMap;
|
||||
use http::Method;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
use super::DoctorProgress;
|
||||
use super::push_proxy_env_details;
|
||||
use super::read_probe_file;
|
||||
|
||||
pub(super) async fn checks(
|
||||
overrides: CliConfigOverrides,
|
||||
interactive: &TuiCli,
|
||||
arg0_paths: &Arg0DispatchPaths,
|
||||
progress: &Arc<dyn DoctorProgress>,
|
||||
) -> Vec<DoctorCheck> {
|
||||
progress.begin("config");
|
||||
let config_started = Instant::now();
|
||||
let config = match super::load_config(overrides, interactive, arg0_paths).await {
|
||||
Ok(config) => config,
|
||||
Err(error) => {
|
||||
let check = super::config_load_failure(&error)
|
||||
.detail("network diagnostics: effective network configuration is unavailable");
|
||||
progress.finish("config", check.status);
|
||||
return vec![check];
|
||||
}
|
||||
};
|
||||
let config_duration = config_started.elapsed();
|
||||
let mut config_check = super::config_check(&config).detail(format!(
|
||||
"configuration load ms: {}",
|
||||
config_duration.as_millis()
|
||||
));
|
||||
config_check.duration_ms = config_duration.as_millis().try_into().unwrap_or(u64::MAX);
|
||||
progress.finish("config", config_check.status);
|
||||
let auth_manager = akode_login::AuthManager::shared_from_config(
|
||||
&config, /*enable_codex_api_key_env*/ true,
|
||||
)
|
||||
.await
|
||||
.ok();
|
||||
let plan = super::provider_reachability_plan(&config);
|
||||
#[cfg(target_os = "macos")]
|
||||
let url = plan.endpoints.first().map(|endpoint| endpoint.url.clone());
|
||||
let (network, websocket, reachability) = tokio::join!(
|
||||
async { super::run_sync_check("network", progress.clone(), || check(Some(&config))) },
|
||||
super::run_async_check(
|
||||
"websocket",
|
||||
progress.clone(),
|
||||
super::websocket_reachability_check(&config, auth_manager)
|
||||
),
|
||||
super::run_async_check(
|
||||
"provider reachability",
|
||||
progress.clone(),
|
||||
super::provider_reachability_check(plan)
|
||||
),
|
||||
);
|
||||
#[cfg(target_os = "macos")]
|
||||
let reachability = with_system_proxy_remediation(reachability, &config, url.as_deref());
|
||||
vec![config_check, network, websocket, reachability]
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
pub(super) const SYSTEM_PROXY_REMEDIATION: &str = "A macOS system proxy is configured but unused. If your organization requires it, ask your administrator whether to enable the experimental System proxy setting in `/experimental` or with `akode features enable respect_system_proxy`. Restart aKode after changing this setting.";
|
||||
|
||||
pub(super) fn check(config: Option<&Config>) -> DoctorCheck {
|
||||
let mut details = Vec::new();
|
||||
push_proxy_env_details(&mut details);
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let request_url = config
|
||||
.and_then(|config| config.model_provider.base_url.as_deref())
|
||||
.unwrap_or("http://localhost/");
|
||||
let configuration = match macos_system_proxy_configuration(request_url) {
|
||||
MacosSystemProxyConfiguration::Automatic => "automatic (PAC)",
|
||||
MacosSystemProxyConfiguration::Manual => "manual",
|
||||
MacosSystemProxyConfiguration::Direct => "direct",
|
||||
MacosSystemProxyConfiguration::Unavailable => "unavailable",
|
||||
};
|
||||
details.push(format!("system proxy: {configuration}"));
|
||||
}
|
||||
if let Some(config) = config {
|
||||
let enabled = |value| if value { "enabled" } else { "disabled" };
|
||||
details.push(format!(
|
||||
"respect system proxy: {}",
|
||||
enabled(config.respect_system_proxy)
|
||||
));
|
||||
if config.permissions.network.is_some() {
|
||||
details.push("managed proxy: configured".to_string());
|
||||
} else {
|
||||
details.push("managed proxy: not configured".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let mut status = CheckStatus::Ok;
|
||||
let mut summary = "network-related environment looks readable".to_string();
|
||||
for name in ["AKODE_CA_CERTIFICATE", "SSL_CERT_FILE"] {
|
||||
if let Some(raw) = env::var_os(name) {
|
||||
let path = PathBuf::from(raw);
|
||||
match std::fs::metadata(&path) {
|
||||
Ok(metadata) if metadata.is_file() => {
|
||||
if let Err(error) = read_probe_file(&path) {
|
||||
status = CheckStatus::Warning;
|
||||
summary = "custom CA env var points at an unreadable file".to_string();
|
||||
details.push(format!("{name}: {} ({error})", path.display()));
|
||||
} else {
|
||||
details.push(format!("{name}: readable file {}", path.display()));
|
||||
}
|
||||
}
|
||||
Ok(_) => {
|
||||
status = CheckStatus::Warning;
|
||||
summary = "custom CA env var does not point at a file".to_string();
|
||||
details.push(format!("{name}: not a file {}", path.display()));
|
||||
}
|
||||
Err(error) => {
|
||||
status = CheckStatus::Warning;
|
||||
summary = "custom CA env var points at an unreadable path".to_string();
|
||||
details.push(format!("{name}: {} ({error})", path.display()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DoctorCheck::new("network.env", "network", status, summary).details(details)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(super) fn with_system_proxy_remediation(
|
||||
mut check: DoctorCheck,
|
||||
config: &Config,
|
||||
request_url: Option<&str>,
|
||||
) -> DoctorCheck {
|
||||
if check.status == CheckStatus::Fail
|
||||
&& !config.respect_system_proxy
|
||||
&& config.permissions.network.is_none()
|
||||
&& config
|
||||
.config_layer_stack
|
||||
.requirements()
|
||||
.feature_requirements
|
||||
.as_ref()
|
||||
.and_then(|requirements| requirements.value.entries.get("respect_system_proxy"))
|
||||
.is_none_or(|enabled| *enabled)
|
||||
&& !super::PROXY_ENV_VARS
|
||||
.iter()
|
||||
.any(|name| !name.eq_ignore_ascii_case("NO_PROXY") && super::env_var_present(name))
|
||||
&& request_url.is_some_and(|url| {
|
||||
matches!(
|
||||
macos_system_proxy_configuration(url),
|
||||
MacosSystemProxyConfiguration::Automatic | MacosSystemProxyConfiguration::Manual
|
||||
)
|
||||
})
|
||||
{
|
||||
check.remediation = Some(SYSTEM_PROXY_REMEDIATION.to_string());
|
||||
}
|
||||
check
|
||||
}
|
||||
|
||||
pub(super) async fn probe_status(
|
||||
client: &RouteAwareClientPool,
|
||||
url: &str,
|
||||
method: Method,
|
||||
headers: HeaderMap,
|
||||
) -> Result<u16, String> {
|
||||
let response = if env::var("AKODE_SANDBOX").as_deref() == Ok("seatbelt") {
|
||||
create_client_without_request_logging()
|
||||
.request(method, url)
|
||||
.headers(headers)
|
||||
.timeout(Duration::from_secs(8))
|
||||
.send()
|
||||
.await
|
||||
} else {
|
||||
client
|
||||
.request(method, url)
|
||||
.headers(headers)
|
||||
// Allow five seconds for PAC resolution before the three-second HTTP budget.
|
||||
.timeout(Duration::from_secs(8))
|
||||
.send()
|
||||
.await
|
||||
}
|
||||
.map_err(request_error)?;
|
||||
let status = response.status().as_u16();
|
||||
if status == 407 {
|
||||
return Err("proxy authentication required (HTTP 407)".to_string());
|
||||
}
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
pub(super) fn request_error(error: RouteAwareRequestError) -> String {
|
||||
match error.failure_class() {
|
||||
Some(RouteFailureClass::TlsError) => "TLS handshake or certificate validation failed",
|
||||
Some(RouteFailureClass::ProxyAuthenticationRequired) => "proxy authentication required",
|
||||
Some(RouteFailureClass::InvalidProxyConfig) => "invalid proxy configuration",
|
||||
Some(RouteFailureClass::ProxyResolutionUnavailable) => {
|
||||
"system proxy configuration unavailable"
|
||||
}
|
||||
Some(RouteFailureClass::ConnectTimeout) => "request timed out",
|
||||
Some(RouteFailureClass::UnsupportedProxyScheme) => "unsupported proxy configuration",
|
||||
Some(RouteFailureClass::ResolverError) => "proxy resolution failed",
|
||||
None if error.is_timeout() => "request timed out",
|
||||
None if error.is_connect() => "connect failed",
|
||||
None => "request failed",
|
||||
}
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "network_tests.rs"]
|
||||
mod tests;
|
||||
35
akode-rs/cli/src/doctor/network_tests.rs
Normal file
35
akode-rs/cli/src/doctor/network_tests.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
|
||||
use super::super::CheckStatus;
|
||||
use super::super::ProviderAuthReachabilityMode;
|
||||
use super::super::provider_reachability_check;
|
||||
use super::super::provider_reachability_plan_from_parts;
|
||||
|
||||
#[tokio::test]
|
||||
async fn provider_reachability_rejects_proxy_authentication_challenges() {
|
||||
let proxy = MockServer::start().await;
|
||||
Mock::given(method("HEAD"))
|
||||
.respond_with(ResponseTemplate::new(407))
|
||||
.mount(&proxy)
|
||||
.await;
|
||||
let plan = provider_reachability_plan_from_parts(
|
||||
ProviderAuthReachabilityMode::NotRequired,
|
||||
"local",
|
||||
"Local",
|
||||
Some(&format!("{}/v1", proxy.uri())),
|
||||
/*provider_query_params*/ None,
|
||||
);
|
||||
|
||||
let check = provider_reachability_check(plan).await;
|
||||
assert_eq!(check.status, CheckStatus::Fail);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.join(" ")
|
||||
.contains("proxy authentication required (HTTP 407)")
|
||||
);
|
||||
}
|
||||
2017
akode-rs/cli/src/doctor/output.rs
Normal file
2017
akode-rs/cli/src/doctor/output.rs
Normal file
File diff suppressed because it is too large
Load Diff
791
akode-rs/cli/src/doctor/output/detail.rs
Normal file
791
akode-rs/cli/src/doctor/output/detail.rs
Normal file
@@ -0,0 +1,791 @@
|
||||
//! Converts raw doctor detail strings into human-oriented rows.
|
||||
//!
|
||||
//! Checks intentionally store details as simple redacted `label: value` strings
|
||||
//! so JSON serialization and human rendering share the same source data. This
|
||||
//! module owns the presentation-only transformations: collapsing noisy booleans,
|
||||
//! truncating long paths for terminal output, grouping repeated values, and
|
||||
//! keeping the `--all` expansion behavior out of check construction.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::env;
|
||||
|
||||
use super::DoctorCheck;
|
||||
use super::HumanOutputOptions;
|
||||
use super::redact_detail;
|
||||
|
||||
const LIST_LIMIT: usize = 7;
|
||||
const PATH_LIMIT: usize = 48;
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(super) enum HumanDetail {
|
||||
Row {
|
||||
label: String,
|
||||
value: String,
|
||||
expected: Option<String>,
|
||||
},
|
||||
Continuation(String),
|
||||
Bullet(String),
|
||||
Remedy(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
struct ParsedDetail {
|
||||
label: String,
|
||||
value: String,
|
||||
}
|
||||
|
||||
pub(super) fn detail_lines(check: &DoctorCheck, options: HumanOutputOptions) -> Vec<HumanDetail> {
|
||||
let parsed = parsed_details(check);
|
||||
let details = match check.category.as_str() {
|
||||
"system" => system_details(&parsed),
|
||||
"runtime" => runtime_details(&parsed),
|
||||
"install" => install_details(&parsed, options),
|
||||
"git" => git_details(&parsed, options),
|
||||
"title" => title_details(&parsed),
|
||||
"config" => config_details(&parsed, options),
|
||||
"state" => state_details(&parsed),
|
||||
_ => generic_details(&parsed),
|
||||
};
|
||||
let mut details = details
|
||||
.into_iter()
|
||||
.map(|detail| attach_issue_metadata(detail, check))
|
||||
.map(|detail| humanize_detail(detail, options))
|
||||
.collect::<Vec<_>>();
|
||||
details.extend(issue_remedies(check));
|
||||
details
|
||||
}
|
||||
|
||||
fn system_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
|
||||
let mut out = Vec::new();
|
||||
push_row_if_present(&mut out, parsed, "os", "os");
|
||||
push_row_if_present(&mut out, parsed, "os language", "OS language");
|
||||
push_row_if_present(&mut out, parsed, "LC_ALL", "LC_ALL");
|
||||
push_row_if_present(&mut out, parsed, "LC_CTYPE", "LC_CTYPE");
|
||||
push_row_if_present(&mut out, parsed, "LANG", "LANG");
|
||||
push_row_if_present(&mut out, parsed, "VISUAL", "VISUAL");
|
||||
push_row_if_present(&mut out, parsed, "EDITOR", "EDITOR");
|
||||
push_row_if_present(&mut out, parsed, "PAGER", "PAGER");
|
||||
push_row_if_present(&mut out, parsed, "GIT_PAGER", "GIT_PAGER");
|
||||
push_row_if_present(&mut out, parsed, "GH_PAGER", "GH_PAGER");
|
||||
push_row_if_present(&mut out, parsed, "LESS", "LESS");
|
||||
push_remaining(
|
||||
&mut out,
|
||||
parsed,
|
||||
&[
|
||||
"os",
|
||||
"os type",
|
||||
"os version",
|
||||
"os language",
|
||||
"LC_ALL",
|
||||
"LC_CTYPE",
|
||||
"LANG",
|
||||
"VISUAL",
|
||||
"EDITOR",
|
||||
"PAGER",
|
||||
"GIT_PAGER",
|
||||
"GH_PAGER",
|
||||
"LESS",
|
||||
],
|
||||
&[],
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
pub(super) fn detail_value(check: &DoctorCheck, label: &str) -> Option<String> {
|
||||
parsed_details(check)
|
||||
.into_iter()
|
||||
.find(|detail| detail.label == label)
|
||||
.map(|detail| detail.value)
|
||||
}
|
||||
|
||||
pub(super) fn rollout_summary(value: &str) -> Option<String> {
|
||||
let (files, rest) = value.split_once(" files, ")?;
|
||||
let (total_bytes, rest) = rest.split_once(" total bytes, ")?;
|
||||
let (average_bytes, _) = rest.split_once(" average bytes")?;
|
||||
let files = files.trim().parse::<u64>().ok()?;
|
||||
let total_bytes = total_bytes.trim().parse::<u64>().ok()?;
|
||||
let average_bytes = average_bytes.trim().parse::<u64>().ok()?;
|
||||
Some(format!(
|
||||
"{} files · {} (avg {})",
|
||||
format_count(files),
|
||||
format_bytes(total_bytes),
|
||||
format_bytes(average_bytes)
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn rollout_files_and_bytes(value: &str) -> Option<(u64, u64)> {
|
||||
let (files, rest) = value.split_once(" files, ")?;
|
||||
let (total_bytes, _) = rest.split_once(" total bytes, ")?;
|
||||
Some((
|
||||
files.trim().parse::<u64>().ok()?,
|
||||
total_bytes.trim().parse::<u64>().ok()?,
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn format_bytes(bytes: u64) -> String {
|
||||
const KIB: f64 = 1024.0;
|
||||
const MIB: f64 = KIB * 1024.0;
|
||||
const GIB: f64 = MIB * 1024.0;
|
||||
|
||||
let bytes = bytes as f64;
|
||||
if bytes >= GIB {
|
||||
format!("{:.2} GB", bytes / GIB)
|
||||
} else if bytes >= MIB {
|
||||
format!("{:.2} MB", bytes / MIB)
|
||||
} else if bytes >= KIB {
|
||||
format!("{:.2} KB", bytes / KIB)
|
||||
} else {
|
||||
format!("{} B", bytes as u64)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn format_count(count: u64) -> String {
|
||||
let mut digits = count.to_string();
|
||||
let mut out = String::new();
|
||||
while digits.len() > 3 {
|
||||
let tail = digits.split_off(digits.len() - 3);
|
||||
if out.is_empty() {
|
||||
out = tail;
|
||||
} else {
|
||||
out = format!("{tail},{out}");
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
digits
|
||||
} else {
|
||||
format!("{digits},{out}")
|
||||
}
|
||||
}
|
||||
|
||||
fn parsed_details(check: &DoctorCheck) -> Vec<ParsedDetail> {
|
||||
check
|
||||
.details
|
||||
.iter()
|
||||
.map(|detail| redact_detail(detail))
|
||||
.map(|detail| {
|
||||
detail
|
||||
.split_once(": ")
|
||||
.map(|(label, value)| ParsedDetail {
|
||||
label: label.to_string(),
|
||||
value: value.to_string(),
|
||||
})
|
||||
.unwrap_or_else(|| ParsedDetail {
|
||||
label: String::new(),
|
||||
value: detail,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn runtime_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
|
||||
let mut out = Vec::new();
|
||||
push_row_if_present(&mut out, parsed, "version", "version");
|
||||
push_row_if_present(&mut out, parsed, "install method", "install method");
|
||||
push_row_if_present(&mut out, parsed, "commit", "commit");
|
||||
push_row_if_present(&mut out, parsed, "current executable", "executable");
|
||||
push_remaining(
|
||||
&mut out,
|
||||
parsed,
|
||||
&[
|
||||
"version",
|
||||
"platform",
|
||||
"install method",
|
||||
"commit",
|
||||
"current executable",
|
||||
],
|
||||
&[],
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn install_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<HumanDetail> {
|
||||
let mut out = Vec::new();
|
||||
push_row_if_present(&mut out, parsed, "install context", "context");
|
||||
if parsed.iter().any(|detail| {
|
||||
detail.value == "ignored inherited package-manager launch env for cargo-built binary"
|
||||
}) {
|
||||
out.push(HumanDetail::Bullet(
|
||||
"ignored inherited package-manager launch env for cargo-built binary".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let managed_by_npm = value(parsed, "managed by npm").unwrap_or("false");
|
||||
let managed_by_bun = value(parsed, "managed by bun").unwrap_or("false");
|
||||
let managed_by_pnpm = value(parsed, "managed by pnpm").unwrap_or("false");
|
||||
let managed_by_vite_plus = value(parsed, "managed by Vite+").unwrap_or("false");
|
||||
let package_root = value(parsed, "managed package root").unwrap_or("not set");
|
||||
out.push(HumanDetail::Row {
|
||||
label: "managed by".to_string(),
|
||||
value: format!(
|
||||
"npm: {} · bun: {} · pnpm: {} · Vite+: {} · package root {}",
|
||||
yes_no(managed_by_npm),
|
||||
yes_no(managed_by_bun),
|
||||
yes_no(managed_by_pnpm),
|
||||
yes_no(managed_by_vite_plus),
|
||||
if is_falsy(package_root) {
|
||||
"—".to_string()
|
||||
} else {
|
||||
package_root.to_string()
|
||||
}
|
||||
),
|
||||
expected: None,
|
||||
});
|
||||
|
||||
let path_entries = numbered_values(parsed, "PATH codex #");
|
||||
if !path_entries.is_empty() {
|
||||
let total = path_entries.len();
|
||||
let shown = if options.show_all {
|
||||
total
|
||||
} else {
|
||||
total.min(3)
|
||||
};
|
||||
out.push(HumanDetail::Row {
|
||||
label: format!("PATH entries ({total})"),
|
||||
value: path_entries[0].clone(),
|
||||
expected: None,
|
||||
});
|
||||
out.extend(
|
||||
path_entries
|
||||
.iter()
|
||||
.skip(1)
|
||||
.take(shown.saturating_sub(1))
|
||||
.cloned()
|
||||
.map(HumanDetail::Continuation),
|
||||
);
|
||||
if shown < total {
|
||||
out.push(HumanDetail::Continuation(
|
||||
"… (full list with --all)".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
push_remaining(
|
||||
&mut out,
|
||||
parsed,
|
||||
&[
|
||||
"current executable",
|
||||
"install context",
|
||||
"managed by npm",
|
||||
"managed by bun",
|
||||
"managed by pnpm",
|
||||
"managed by Vite+",
|
||||
"managed package root",
|
||||
"PATH codex entries",
|
||||
],
|
||||
&["PATH codex #"],
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn git_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<HumanDetail> {
|
||||
let mut out = Vec::new();
|
||||
push_row_if_present(&mut out, parsed, "selected git", "selected git");
|
||||
push_row_if_present(&mut out, parsed, "git version", "version");
|
||||
push_row_if_present(&mut out, parsed, "git exec path", "exec path");
|
||||
push_row_if_present(&mut out, parsed, "repo detected", "repo detected");
|
||||
push_row_if_present(&mut out, parsed, "repo root", "repo root");
|
||||
push_row_if_present(&mut out, parsed, ".git entry", ".git entry");
|
||||
push_row_if_present(&mut out, parsed, "git branch", "branch");
|
||||
push_row_if_present(&mut out, parsed, "core.fsmonitor", "core.fsmonitor");
|
||||
|
||||
let path_entries = numbered_values(parsed, "PATH git #");
|
||||
if !path_entries.is_empty() {
|
||||
let total = path_entries.len();
|
||||
let shown = if options.show_all {
|
||||
total
|
||||
} else {
|
||||
total.min(3)
|
||||
};
|
||||
out.push(HumanDetail::Row {
|
||||
label: format!("PATH entries ({total})"),
|
||||
value: path_entries[0].clone(),
|
||||
expected: None,
|
||||
});
|
||||
out.extend(
|
||||
path_entries
|
||||
.iter()
|
||||
.skip(1)
|
||||
.take(shown.saturating_sub(1))
|
||||
.cloned()
|
||||
.map(HumanDetail::Continuation),
|
||||
);
|
||||
if shown < total {
|
||||
out.push(HumanDetail::Continuation(
|
||||
"… (full list with --all)".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
push_remaining(
|
||||
&mut out,
|
||||
parsed,
|
||||
&[
|
||||
"selected git",
|
||||
"PATH git entries",
|
||||
"git version",
|
||||
"git exec path",
|
||||
"git build options",
|
||||
"repo detected",
|
||||
"repo root",
|
||||
".git entry",
|
||||
"git branch",
|
||||
"core.fsmonitor",
|
||||
],
|
||||
&["PATH git #"],
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn title_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
|
||||
let mut out = Vec::new();
|
||||
push_row_if_present(&mut out, parsed, "terminal title source", "title source");
|
||||
push_row_if_present(&mut out, parsed, "terminal title items", "title items");
|
||||
push_row_if_present(&mut out, parsed, "terminal title activity", "activity item");
|
||||
push_row_if_present(
|
||||
&mut out,
|
||||
parsed,
|
||||
"terminal title project source",
|
||||
"project source",
|
||||
);
|
||||
push_row_if_present(
|
||||
&mut out,
|
||||
parsed,
|
||||
"terminal title project value",
|
||||
"project value",
|
||||
);
|
||||
push_remaining(
|
||||
&mut out,
|
||||
parsed,
|
||||
&[
|
||||
"terminal title source",
|
||||
"terminal title items",
|
||||
"terminal title activity",
|
||||
"terminal title project source",
|
||||
"terminal title project value",
|
||||
],
|
||||
&[],
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn config_details(parsed: &[ParsedDetail], options: HumanOutputOptions) -> Vec<HumanDetail> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(model) = value(parsed, "model") {
|
||||
let value = value(parsed, "model provider").map_or_else(
|
||||
|| model.to_string(),
|
||||
|provider| format!("{model} · {provider}"),
|
||||
);
|
||||
out.push(HumanDetail::Row {
|
||||
label: "model".to_string(),
|
||||
value,
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
push_row_if_present(&mut out, parsed, "cwd", "cwd");
|
||||
push_row_if_present(&mut out, parsed, "config.toml", "config.toml");
|
||||
push_row_if_present(&mut out, parsed, "config.toml parse", "config.toml parse");
|
||||
push_row_if_present(&mut out, parsed, "config.toml read", "config.toml read");
|
||||
push_row_if_present(&mut out, parsed, "mcp servers", "MCP servers");
|
||||
push_feature_flags(&mut out, parsed, options);
|
||||
|
||||
for detail in parsed
|
||||
.iter()
|
||||
.filter(|detail| detail.label == "legacy feature flag")
|
||||
{
|
||||
out.push(HumanDetail::Row {
|
||||
label: "legacy alias".to_string(),
|
||||
value: detail.value.clone(),
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
|
||||
push_remaining(
|
||||
&mut out,
|
||||
parsed,
|
||||
&[
|
||||
"AKODE_HOME",
|
||||
"cwd",
|
||||
"model",
|
||||
"model provider",
|
||||
"log dir",
|
||||
"sqlite home",
|
||||
"mcp servers",
|
||||
"feature flags enabled",
|
||||
"enabled feature flags",
|
||||
"feature flag overrides",
|
||||
"legacy feature flag",
|
||||
"config.toml",
|
||||
"config.toml parse",
|
||||
"config.toml read",
|
||||
],
|
||||
&[],
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn state_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
|
||||
let mut out = Vec::new();
|
||||
push_row_if_present(&mut out, parsed, "AKODE_HOME", "AKODE_HOME");
|
||||
push_row_if_present(&mut out, parsed, "log dir", "log dir");
|
||||
push_row_if_present(&mut out, parsed, "sqlite home", "sqlite home");
|
||||
push_database_row(&mut out, parsed, "state DB");
|
||||
push_database_row(&mut out, parsed, "log DB");
|
||||
push_database_row(&mut out, parsed, "goals DB");
|
||||
push_database_row(&mut out, parsed, "memories DB");
|
||||
|
||||
for (source, label) in [
|
||||
("active rollout files", "active rollouts"),
|
||||
("archived rollout files", "archived rollouts"),
|
||||
] {
|
||||
if let Some(value) = value(parsed, source) {
|
||||
out.push(HumanDetail::Row {
|
||||
label: label.to_string(),
|
||||
value: rollout_summary(value).unwrap_or_else(|| value.to_string()),
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
push_remaining(
|
||||
&mut out,
|
||||
parsed,
|
||||
&[
|
||||
"AKODE_HOME",
|
||||
"log dir",
|
||||
"sqlite home",
|
||||
"state DB",
|
||||
"log DB",
|
||||
"goals DB",
|
||||
"state DB integrity",
|
||||
"log DB integrity",
|
||||
"goals DB integrity",
|
||||
"memories DB",
|
||||
"memories DB integrity",
|
||||
"active rollout files",
|
||||
"archived rollout files",
|
||||
],
|
||||
&[],
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
fn generic_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
|
||||
parsed
|
||||
.iter()
|
||||
.map(|detail| {
|
||||
if detail.label.is_empty() {
|
||||
HumanDetail::Bullet(detail.value.clone())
|
||||
} else {
|
||||
HumanDetail::Row {
|
||||
label: display_label(&detail.label),
|
||||
value: detail.value.clone(),
|
||||
expected: None,
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn push_feature_flags(
|
||||
out: &mut Vec<HumanDetail>,
|
||||
parsed: &[ParsedDetail],
|
||||
options: HumanOutputOptions,
|
||||
) {
|
||||
let enabled_count = value(parsed, "feature flags enabled")
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.unwrap_or_default();
|
||||
let overrides = list_items(value(parsed, "feature flag overrides").unwrap_or("none"));
|
||||
let override_count = overrides.len();
|
||||
let hint = if !options.show_all && enabled_count > 0 {
|
||||
" (full list with --all)"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
out.push(HumanDetail::Row {
|
||||
label: "feature flags".to_string(),
|
||||
value: format!("{enabled_count} enabled · {override_count} overridden{hint}"),
|
||||
expected: None,
|
||||
});
|
||||
|
||||
if !overrides.is_empty() {
|
||||
push_list_row(out, "overrides", &override_names(&overrides), options);
|
||||
}
|
||||
if options.show_all {
|
||||
let enabled = list_items(value(parsed, "enabled feature flags").unwrap_or("none"));
|
||||
if !enabled.is_empty() {
|
||||
push_list_row(out, "enabled flags", &enabled, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_list_row(
|
||||
out: &mut Vec<HumanDetail>,
|
||||
label: &str,
|
||||
items: &[String],
|
||||
options: HumanOutputOptions,
|
||||
) {
|
||||
let limit = if options.show_all {
|
||||
items.len()
|
||||
} else {
|
||||
items.len().min(LIST_LIMIT)
|
||||
};
|
||||
let mut value = items
|
||||
.iter()
|
||||
.take(limit)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
if limit < items.len() {
|
||||
value.push_str(", … (full list with --all)");
|
||||
}
|
||||
out.push(HumanDetail::Row {
|
||||
label: label.to_string(),
|
||||
value,
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
|
||||
fn push_database_row(out: &mut Vec<HumanDetail>, parsed: &[ParsedDetail], label: &str) {
|
||||
let Some(path) = value(parsed, label) else {
|
||||
return;
|
||||
};
|
||||
let integrity = value(parsed, &format!("{label} integrity"));
|
||||
let value = integrity.map_or_else(
|
||||
|| path.to_string(),
|
||||
|integrity| format!("{path} · integrity {integrity}"),
|
||||
);
|
||||
out.push(HumanDetail::Row {
|
||||
label: label.to_string(),
|
||||
value,
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
|
||||
fn push_row_if_present(
|
||||
out: &mut Vec<HumanDetail>,
|
||||
parsed: &[ParsedDetail],
|
||||
source_label: &str,
|
||||
display_label: &str,
|
||||
) {
|
||||
if let Some(value) = value(parsed, source_label) {
|
||||
out.push(HumanDetail::Row {
|
||||
label: display_label.to_string(),
|
||||
value: value.to_string(),
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn push_remaining(
|
||||
out: &mut Vec<HumanDetail>,
|
||||
parsed: &[ParsedDetail],
|
||||
consumed_labels: &[&str],
|
||||
consumed_prefixes: &[&str],
|
||||
) {
|
||||
for detail in parsed {
|
||||
if detail.value == "ignored inherited package-manager launch env for cargo-built binary" {
|
||||
continue;
|
||||
}
|
||||
if consumed_labels.contains(&detail.label.as_str())
|
||||
|| consumed_prefixes
|
||||
.iter()
|
||||
.any(|prefix| detail.label.starts_with(prefix))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if detail.label.is_empty() {
|
||||
out.push(HumanDetail::Bullet(detail.value.clone()));
|
||||
} else {
|
||||
out.push(HumanDetail::Row {
|
||||
label: display_label(&detail.label),
|
||||
value: detail.value.clone(),
|
||||
expected: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn humanize_detail(detail: HumanDetail, options: HumanOutputOptions) -> HumanDetail {
|
||||
match detail {
|
||||
HumanDetail::Row {
|
||||
label,
|
||||
value,
|
||||
expected,
|
||||
} => HumanDetail::Row {
|
||||
label,
|
||||
value: humanize_value(&value, options),
|
||||
expected,
|
||||
},
|
||||
HumanDetail::Continuation(value) => {
|
||||
HumanDetail::Continuation(humanize_value(&value, options))
|
||||
}
|
||||
HumanDetail::Bullet(value) => HumanDetail::Bullet(humanize_value(&value, options)),
|
||||
HumanDetail::Remedy(value) => HumanDetail::Remedy(value),
|
||||
}
|
||||
}
|
||||
|
||||
fn attach_issue_metadata(detail: HumanDetail, check: &DoctorCheck) -> HumanDetail {
|
||||
let HumanDetail::Row {
|
||||
label,
|
||||
value,
|
||||
expected,
|
||||
} = detail
|
||||
else {
|
||||
return detail;
|
||||
};
|
||||
let expected = expected.or_else(|| issue_expected_for_label(check, &label));
|
||||
HumanDetail::Row {
|
||||
label,
|
||||
value,
|
||||
expected,
|
||||
}
|
||||
}
|
||||
|
||||
fn issue_expected_for_label(check: &DoctorCheck, label: &str) -> Option<String> {
|
||||
check
|
||||
.issues
|
||||
.iter()
|
||||
.find(|issue| {
|
||||
issue
|
||||
.fields
|
||||
.iter()
|
||||
.any(|field| display_label(field) == label || field == label)
|
||||
})
|
||||
.and_then(|issue| issue.expected.clone())
|
||||
}
|
||||
|
||||
fn issue_remedies(check: &DoctorCheck) -> Vec<HumanDetail> {
|
||||
let mut seen = BTreeSet::new();
|
||||
check
|
||||
.issues
|
||||
.iter()
|
||||
.filter_map(|issue| issue.remedy.as_ref())
|
||||
.filter(|remedy| seen.insert((*remedy).clone()))
|
||||
.cloned()
|
||||
.map(HumanDetail::Remedy)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn humanize_value(value: &str, _options: HumanOutputOptions) -> String {
|
||||
if looks_like_path(value) {
|
||||
return shorten_path_prefix(value);
|
||||
}
|
||||
if let Some(timestamp) = humanize_timestamp(value) {
|
||||
return timestamp;
|
||||
}
|
||||
value.to_string()
|
||||
}
|
||||
|
||||
fn humanize_timestamp(value: &str) -> Option<String> {
|
||||
if value.len() < 17 || !value.ends_with('Z') {
|
||||
return None;
|
||||
}
|
||||
let (date, time) = value.split_once('T')?;
|
||||
let hour_minute = time.get(..5)?;
|
||||
Some(format!("{date} {hour_minute} UTC"))
|
||||
}
|
||||
|
||||
fn shorten_path_prefix(value: &str) -> String {
|
||||
let (path, suffix) = value.split_once(" (").map_or_else(
|
||||
|| (value, String::new()),
|
||||
|(path, suffix)| (path, format!(" ({suffix}")),
|
||||
);
|
||||
let home_shortened = home_shortened_path(path);
|
||||
let shortened = middle_truncate(&home_shortened, PATH_LIMIT);
|
||||
format!("{shortened}{suffix}")
|
||||
}
|
||||
|
||||
fn home_shortened_path(path: &str) -> String {
|
||||
let Some(home) = env::var_os("HOME").and_then(|home| home.into_string().ok()) else {
|
||||
return path.to_string();
|
||||
};
|
||||
if path == home {
|
||||
"~".to_string()
|
||||
} else {
|
||||
path.strip_prefix(&format!("{home}/"))
|
||||
.map_or_else(|| path.to_string(), |tail| format!("~/{tail}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn middle_truncate(value: &str, max_chars: usize) -> String {
|
||||
let char_count = value.chars().count();
|
||||
if char_count <= max_chars {
|
||||
return value.to_string();
|
||||
}
|
||||
let head_len = max_chars / 2;
|
||||
let tail_len = max_chars.saturating_sub(head_len + 1);
|
||||
let head = value.chars().take(head_len).collect::<String>();
|
||||
let tail = value
|
||||
.chars()
|
||||
.rev()
|
||||
.take(tail_len)
|
||||
.collect::<String>()
|
||||
.chars()
|
||||
.rev()
|
||||
.collect::<String>();
|
||||
format!("{head}…{tail}")
|
||||
}
|
||||
|
||||
fn looks_like_path(value: &str) -> bool {
|
||||
value.starts_with('/')
|
||||
|| value.starts_with("~/")
|
||||
|| value.starts_with("./")
|
||||
|| value.starts_with("../")
|
||||
}
|
||||
|
||||
fn numbered_values(parsed: &[ParsedDetail], prefix: &str) -> Vec<String> {
|
||||
parsed
|
||||
.iter()
|
||||
.filter(|detail| detail.label.starts_with(prefix))
|
||||
.map(|detail| detail.value.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn value<'a>(parsed: &'a [ParsedDetail], label: &str) -> Option<&'a str> {
|
||||
parsed
|
||||
.iter()
|
||||
.find(|detail| detail.label == label)
|
||||
.map(|detail| detail.value.as_str())
|
||||
}
|
||||
|
||||
fn display_label(label: &str) -> String {
|
||||
match label {
|
||||
"auth file" => "auth.json path (file backend/fallback)",
|
||||
"akode-linux-sandbox helper" => "linux helper",
|
||||
"optional reachability failed" => "optional reachability",
|
||||
"check for update on startup" => "startup update check",
|
||||
other => other,
|
||||
}
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn list_items(value: &str) -> Vec<String> {
|
||||
if is_falsy(value) {
|
||||
return Vec::new();
|
||||
}
|
||||
value
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|item| !item.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn override_names(items: &[String]) -> Vec<String> {
|
||||
items
|
||||
.iter()
|
||||
.map(|item| item.split_once('=').map_or(item.as_str(), |(name, _)| name))
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn yes_no(value: &str) -> &'static str {
|
||||
if value == "true" { "yes" } else { "no" }
|
||||
}
|
||||
|
||||
pub(super) fn is_falsy(value: &str) -> bool {
|
||||
matches!(
|
||||
value.trim().to_ascii_lowercase().as_str(),
|
||||
"" | "false" | "none" | "not set" | "unknown" | "missing" | "absent" | "no" | "—" | "-"
|
||||
)
|
||||
}
|
||||
139
akode-rs/cli/src/doctor/progress.rs
Normal file
139
akode-rs/cli/src/doctor/progress.rs
Normal file
@@ -0,0 +1,139 @@
|
||||
use std::io;
|
||||
use std::io::IsTerminal;
|
||||
use std::io::Write;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use super::CheckStatus;
|
||||
|
||||
/// Receives check lifecycle events while doctor builds the final report.
|
||||
///
|
||||
/// Progress implementations must not write to stdout. The final report owns
|
||||
/// stdout so JSON and redirected human reports stay clean.
|
||||
pub(super) trait DoctorProgress: Send + Sync {
|
||||
fn begin(&self, label: &'static str);
|
||||
fn heartbeat(&self, label: &'static str, elapsed: Duration);
|
||||
fn finish(&self, label: &'static str, status: CheckStatus);
|
||||
fn settle(&self);
|
||||
}
|
||||
|
||||
/// Selects the progress implementation for the current output mode.
|
||||
///
|
||||
/// JSON output is always quiet so stdout remains valid JSON. Human output uses a
|
||||
/// transient stderr line only for interactive terminals, then clears it before
|
||||
/// the final report is printed.
|
||||
pub(super) fn doctor_progress(json: bool) -> std::sync::Arc<dyn DoctorProgress> {
|
||||
if should_show_progress(
|
||||
json,
|
||||
std::env::var("TERM").ok().as_deref(),
|
||||
io::stderr().is_terminal(),
|
||||
) {
|
||||
std::sync::Arc::new(StderrProgress::default())
|
||||
} else {
|
||||
std::sync::Arc::new(QuietProgress)
|
||||
}
|
||||
}
|
||||
|
||||
fn should_show_progress(json: bool, term: Option<&str>, stderr_is_tty: bool) -> bool {
|
||||
!json && stderr_is_tty && term != Some("dumb")
|
||||
}
|
||||
|
||||
struct QuietProgress;
|
||||
|
||||
impl DoctorProgress for QuietProgress {
|
||||
fn begin(&self, _label: &'static str) {}
|
||||
|
||||
fn heartbeat(&self, _label: &'static str, _elapsed: Duration) {}
|
||||
|
||||
fn finish(&self, _label: &'static str, _status: CheckStatus) {}
|
||||
|
||||
fn settle(&self) {}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct StderrProgress {
|
||||
state: Mutex<StderrProgressState>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct StderrProgressState {
|
||||
wrote_line: bool,
|
||||
}
|
||||
|
||||
impl StderrProgress {
|
||||
fn render(&self, message: String) {
|
||||
let Ok(mut state) = self.state.lock() else {
|
||||
return;
|
||||
};
|
||||
let mut stderr = io::stderr().lock();
|
||||
let _ = write!(stderr, "\r\x1b[2K{message}");
|
||||
let _ = stderr.flush();
|
||||
state.wrote_line = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl DoctorProgress for StderrProgress {
|
||||
fn begin(&self, label: &'static str) {
|
||||
self.render(format!("Checking {label}..."));
|
||||
}
|
||||
|
||||
fn heartbeat(&self, label: &'static str, elapsed: Duration) {
|
||||
self.render(format!("Still checking {label}... {}s", elapsed.as_secs()));
|
||||
}
|
||||
|
||||
fn finish(&self, _label: &'static str, _status: CheckStatus) {}
|
||||
|
||||
fn settle(&self) {
|
||||
let Ok(mut state) = self.state.lock() else {
|
||||
return;
|
||||
};
|
||||
if !state.wrote_line {
|
||||
return;
|
||||
}
|
||||
let mut stderr = io::stderr().lock();
|
||||
let _ = write!(stderr, "\r\x1b[2K");
|
||||
let _ = stderr.flush();
|
||||
state.wrote_line = false;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn progress_is_quiet_for_json() {
|
||||
assert!(!should_show_progress(
|
||||
/*json*/ true,
|
||||
Some("xterm-256color"),
|
||||
/*stderr_is_tty*/ true,
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_is_quiet_for_non_tty() {
|
||||
assert!(!should_show_progress(
|
||||
/*json*/ false,
|
||||
Some("xterm-256color"),
|
||||
/*stderr_is_tty*/ false,
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_is_quiet_for_dumb_terminal() {
|
||||
assert!(!should_show_progress(
|
||||
/*json*/ false,
|
||||
Some("dumb"),
|
||||
/*stderr_is_tty*/ true,
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_is_shown_for_human_tty_output() {
|
||||
assert!(should_show_progress(
|
||||
/*json*/ false,
|
||||
Some("xterm-256color"),
|
||||
/*stderr_is_tty*/ true,
|
||||
));
|
||||
}
|
||||
}
|
||||
145
akode-rs/cli/src/doctor/runtime.rs
Normal file
145
akode-rs/cli/src/doctor/runtime.rs
Normal file
@@ -0,0 +1,145 @@
|
||||
//! Captures how this Codex process was launched.
|
||||
//!
|
||||
//! Runtime diagnostics answer provenance questions that are hard to infer from
|
||||
//! user reports: which binary is running, which install channel it resembles,
|
||||
//! which platform it targets, and whether the search command comes from bundled
|
||||
//! package files or from PATH.
|
||||
|
||||
use std::env;
|
||||
|
||||
use akode_install_context::InstallContext;
|
||||
use akode_install_context::InstallMethod;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
use super::describe_install_context;
|
||||
use super::doctor_install_context;
|
||||
use super::push_path_detail;
|
||||
|
||||
/// Builds the process provenance row for the current Codex executable.
|
||||
///
|
||||
/// This check is informational and should not fail on its own; inconsistent
|
||||
/// install state is reported by the installation and update checks instead.
|
||||
pub(super) fn runtime_check() -> DoctorCheck {
|
||||
let current_exe = env::current_exe().ok();
|
||||
let install_context = doctor_install_context(current_exe.as_deref());
|
||||
let os = env::consts::OS;
|
||||
let arch = env::consts::ARCH;
|
||||
let platform = format!("{os}-{arch}");
|
||||
let install_method = install_method_name(&install_context);
|
||||
let mut details = vec![
|
||||
format!("version: {}", env!("CARGO_PKG_VERSION")),
|
||||
format!("platform: {platform}"),
|
||||
format!(
|
||||
"install method: {}",
|
||||
describe_install_context(&install_context)
|
||||
),
|
||||
format!("commit: {}", build_commit()),
|
||||
];
|
||||
push_path_detail(&mut details, "current executable", current_exe.as_deref());
|
||||
|
||||
DoctorCheck::new(
|
||||
"runtime.provenance",
|
||||
"runtime",
|
||||
CheckStatus::Ok,
|
||||
format!("running {install_method} on {platform}"),
|
||||
)
|
||||
.details(details)
|
||||
}
|
||||
|
||||
/// Inspects the search command selected by the install context without executing it.
|
||||
///
|
||||
/// Package-layout installs should point at a bundled ripgrep binary, while local
|
||||
/// installs without that layout usually resolve rg from PATH. A warning here
|
||||
/// means features that depend on file search may degrade even when the CLI
|
||||
/// launches.
|
||||
pub(super) fn search_check() -> DoctorCheck {
|
||||
let current_exe = env::current_exe().ok();
|
||||
let install_context = doctor_install_context(current_exe.as_deref());
|
||||
let rg_command = install_context.rg_command();
|
||||
let provider = search_provider(&install_context);
|
||||
let mut details = vec![
|
||||
format!("search command: {}", rg_command.display()),
|
||||
format!("search provider: {provider}"),
|
||||
];
|
||||
|
||||
let status = if rg_command.components().count() > 1 {
|
||||
match std::fs::metadata(&rg_command) {
|
||||
Ok(metadata) if metadata.is_file() => {
|
||||
details.push("search command readiness: file exists".to_string());
|
||||
CheckStatus::Ok
|
||||
}
|
||||
Ok(_) => {
|
||||
details.push("search command readiness: path is not a file".to_string());
|
||||
CheckStatus::Warning
|
||||
}
|
||||
Err(err) => {
|
||||
details.push(format!("search command readiness: {err}"));
|
||||
CheckStatus::Warning
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match which::which(&rg_command) {
|
||||
Ok(path) => {
|
||||
details.push(format!("search command path: {}", path.display()));
|
||||
details.push("search command readiness: found; execution not verified".to_string());
|
||||
CheckStatus::Ok
|
||||
}
|
||||
Err(err) => {
|
||||
details.push(format!("search command readiness: {err}"));
|
||||
CheckStatus::Warning
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let summary = match status {
|
||||
CheckStatus::Ok => format!("search command found ({provider}); execution not verified"),
|
||||
CheckStatus::Warning => "search command could not be verified".to_string(),
|
||||
CheckStatus::Fail => unreachable!(),
|
||||
};
|
||||
let mut check = DoctorCheck::new("runtime.search", "search", status, summary).details(details);
|
||||
if status != CheckStatus::Ok {
|
||||
check = check.remediation("Install ripgrep or repair the bundled aKode package.");
|
||||
}
|
||||
check
|
||||
}
|
||||
|
||||
fn install_method_name(context: &InstallContext) -> &'static str {
|
||||
match &context.method {
|
||||
InstallMethod::Standalone { .. } => "standalone",
|
||||
InstallMethod::Npm => "npm",
|
||||
InstallMethod::Bun => "bun",
|
||||
InstallMethod::VitePlus => "vite+",
|
||||
InstallMethod::Pnpm => "pnpm",
|
||||
InstallMethod::Brew => "brew",
|
||||
InstallMethod::Other => "local build",
|
||||
}
|
||||
}
|
||||
|
||||
fn search_provider(context: &InstallContext) -> &'static str {
|
||||
let rg_command = context.rg_command();
|
||||
let from_package_layout = context
|
||||
.package_layout
|
||||
.as_ref()
|
||||
.and_then(|package_layout| package_layout.path_dir.as_ref())
|
||||
.is_some_and(|path_dir| rg_command.starts_with(path_dir));
|
||||
let from_legacy_standalone = matches!(
|
||||
&context.method,
|
||||
InstallMethod::Standalone {
|
||||
resources_dir: Some(resources_dir),
|
||||
..
|
||||
} if rg_command.starts_with(resources_dir)
|
||||
);
|
||||
|
||||
if from_package_layout || from_legacy_standalone {
|
||||
"bundled"
|
||||
} else {
|
||||
"system"
|
||||
}
|
||||
}
|
||||
|
||||
fn build_commit() -> &'static str {
|
||||
option_env!("AKODE_BUILD_COMMIT")
|
||||
.or(option_env!("GIT_COMMIT"))
|
||||
.unwrap_or("unknown")
|
||||
}
|
||||
356
akode-rs/cli/src/doctor/sandbox.rs
Normal file
356
akode-rs/cli/src/doctor/sandbox.rs
Normal file
@@ -0,0 +1,356 @@
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::fs;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::io;
|
||||
|
||||
use akode_arg0::Arg0DispatchPaths;
|
||||
use akode_config::RequirementSource;
|
||||
use akode_core::config::Config;
|
||||
#[cfg(target_os = "windows")]
|
||||
use akode_core::windows_sandbox::WindowsSandboxLevelExt;
|
||||
#[cfg(target_os = "windows")]
|
||||
use akode_protocol::config_types::WindowsSandboxLevel;
|
||||
use akode_protocol::permissions::FileSystemAccessMode;
|
||||
use akode_protocol::permissions::FileSystemPath;
|
||||
#[cfg(target_os = "windows")]
|
||||
use akode_sandboxing::windows_sandbox_uses_elevated_backend;
|
||||
#[cfg(target_os = "windows")]
|
||||
use akode_windows_sandbox::SetupErrorCode;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement::NERR_Success as NERR_SUCCESS;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement::NERR_UserNotFound as NERR_USER_NOT_FOUND;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement::NetApiBufferFree;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement::NetUserGetInfo;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement::UF_ACCOUNTDISABLE;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement::UF_LOCKOUT;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement::UF_PASSWORD_EXPIRED;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::NetworkManagement::NetManagement::USER_INFO_23;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
#[cfg(target_os = "windows")]
|
||||
use super::DoctorIssue;
|
||||
use super::push_path_detail;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
const WINDOWS_SETUP_REMEDIATION: &str = "run akode sandbox setup --elevated --user <end-user> --codex-home <authoritative-home> from an elevated shell";
|
||||
|
||||
pub(super) fn sandbox_check(config: &Config, arg0_paths: &Arg0DispatchPaths) -> DoctorCheck {
|
||||
let mut details = Vec::new();
|
||||
details.push(format!(
|
||||
"approval policy: {:?}",
|
||||
config.permissions.approval_policy.value()
|
||||
));
|
||||
let file_system_sandbox = config.permissions.file_system_sandbox_policy();
|
||||
details.push(format!("filesystem sandbox: {}", file_system_sandbox.kind));
|
||||
let denied_entries = file_system_sandbox
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|entry| entry.access == FileSystemAccessMode::Deny);
|
||||
details.push(format!(
|
||||
"denied-read rules: {}",
|
||||
denied_entries.clone().count()
|
||||
));
|
||||
details.push(format!(
|
||||
"denied-read glob rules: {}",
|
||||
denied_entries
|
||||
.filter(|entry| matches!(entry.path, FileSystemPath::GlobPattern { .. }))
|
||||
.count()
|
||||
));
|
||||
details.push(format!(
|
||||
"glob scan max depth: {}",
|
||||
file_system_sandbox
|
||||
.glob_scan_max_depth
|
||||
.map_or_else(|| "unbounded".to_string(), |depth| depth.to_string())
|
||||
));
|
||||
details.push(format!(
|
||||
"managed filesystem source: {}",
|
||||
match config
|
||||
.config_layer_stack
|
||||
.requirements()
|
||||
.filesystem
|
||||
.as_ref()
|
||||
.map(|value| &value.source)
|
||||
{
|
||||
None => "none",
|
||||
Some(RequirementSource::Unknown) => "unknown",
|
||||
Some(RequirementSource::Composite { .. }) => "multiple layers",
|
||||
Some(RequirementSource::MdmManagedPreferences { .. }) => "MDM",
|
||||
Some(RequirementSource::SystemRequirementsToml { .. }) => "system",
|
||||
Some(RequirementSource::LegacyManagedConfigTomlFromFile { .. }) => "legacy file",
|
||||
Some(RequirementSource::LegacyManagedConfigTomlFromMdm) => "legacy MDM",
|
||||
}
|
||||
));
|
||||
details.push(format!(
|
||||
"network sandbox: {}",
|
||||
config.permissions.network_sandbox_policy()
|
||||
));
|
||||
push_path_detail(
|
||||
&mut details,
|
||||
"akode-linux-sandbox helper",
|
||||
arg0_paths.codex_linux_sandbox_exe.as_deref(),
|
||||
);
|
||||
|
||||
let mut status = CheckStatus::Ok;
|
||||
let mut summary = "sandbox configuration is readable".to_string();
|
||||
if let Some(helper) = arg0_paths.codex_linux_sandbox_exe.as_deref()
|
||||
&& !helper.exists()
|
||||
{
|
||||
status = CheckStatus::Warning;
|
||||
summary = "Linux sandbox helper path does not exist".to_string();
|
||||
}
|
||||
|
||||
let check = DoctorCheck::new("sandbox.helpers", "sandbox", status, summary).details(details);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
let mut check = check;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let configured_level = WindowsSandboxLevel::from_config(config);
|
||||
let mxc = config.effective_local_windows_sandbox_type()
|
||||
== akode_protocol::sandbox::SandboxType::WindowsMxc;
|
||||
let elevated = !mxc
|
||||
&& configured_level != WindowsSandboxLevel::Disabled
|
||||
&& windows_sandbox_uses_elevated_backend(configured_level);
|
||||
let backend = if mxc {
|
||||
"mxc".to_string()
|
||||
} else if elevated {
|
||||
WindowsSandboxLevel::Elevated.to_string()
|
||||
} else {
|
||||
configured_level.to_string()
|
||||
};
|
||||
let denied = !file_system_sandbox.has_full_disk_read_access();
|
||||
|
||||
check.details.push(format!("sandbox backend: {backend}"));
|
||||
check
|
||||
.details
|
||||
.push(format!("denied-read restrictions: {denied}"));
|
||||
|
||||
if denied && !elevated && !mxc {
|
||||
check.issues.push(
|
||||
DoctorIssue::new(
|
||||
CheckStatus::Fail,
|
||||
"managed denied-read requirements need the elevated Windows sandbox backend",
|
||||
)
|
||||
.measured(format!("{backend} backend"))
|
||||
.expected("elevated backend")
|
||||
.remedy("enable the elevated Windows sandbox backend permitted by managed policy")
|
||||
.field("sandbox backend")
|
||||
.field("denied-read restrictions"),
|
||||
);
|
||||
}
|
||||
|
||||
if elevated {
|
||||
let home = config.codex_home.as_path();
|
||||
let path = akode_windows_sandbox::setup_error_path(home);
|
||||
let report = match fs::metadata(&path) {
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
|
||||
Ok(metadata) if metadata.is_file() && metadata.len() <= 64 * 1024 => {
|
||||
akode_windows_sandbox::read_setup_error_report(home)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
Ok(metadata) if !metadata.is_file() => Err("not a regular file".to_string()),
|
||||
Ok(_) => Err("larger than 64 KiB".to_string()),
|
||||
Err(error) => Err(error.to_string()),
|
||||
};
|
||||
let report = match report {
|
||||
Ok(report) => report,
|
||||
Err(error) => {
|
||||
check
|
||||
.details
|
||||
.push("setup failure report: unreadable".to_string());
|
||||
check.issues.push(
|
||||
DoctorIssue::new(
|
||||
CheckStatus::Warning,
|
||||
"Windows sandbox setup failure report could not be read",
|
||||
)
|
||||
.measured(error)
|
||||
.expected("readable setup failure report no larger than 64 KiB")
|
||||
.remedy(WINDOWS_SETUP_REMEDIATION)
|
||||
.field("setup failure report"),
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
if report.is_none() && akode_windows_sandbox::sandbox_setup_is_complete(home) {
|
||||
check
|
||||
.details
|
||||
.push("sandbox provisioning: complete".to_string());
|
||||
|
||||
for username in [
|
||||
akode_windows_sandbox::OFFLINE_USERNAME,
|
||||
akode_windows_sandbox::ONLINE_USERNAME,
|
||||
] {
|
||||
let username_wide = username.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
|
||||
let mut buffer = std::ptr::null_mut();
|
||||
let status = unsafe {
|
||||
NetUserGetInfo(
|
||||
std::ptr::null(),
|
||||
username_wide.as_ptr(),
|
||||
/*level*/ 23,
|
||||
&mut buffer,
|
||||
)
|
||||
};
|
||||
let flags = if status == NERR_SUCCESS && !buffer.is_null() {
|
||||
Some(unsafe { (*(buffer as *const USER_INFO_23)).usri23_flags })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if !buffer.is_null() {
|
||||
unsafe { NetApiBufferFree(buffer.cast()) };
|
||||
}
|
||||
|
||||
let (severity, cause, remediation) = match (status, flags) {
|
||||
(NERR_USER_NOT_FOUND, _) => (
|
||||
CheckStatus::Fail,
|
||||
"a Windows sandbox account is missing",
|
||||
WINDOWS_SETUP_REMEDIATION,
|
||||
),
|
||||
(NERR_SUCCESS, Some(flags)) if flags & UF_LOCKOUT != 0 => (
|
||||
CheckStatus::Fail,
|
||||
"a Windows sandbox account is locked",
|
||||
"stop sandbox retries and ask IT to unlock the account",
|
||||
),
|
||||
(NERR_SUCCESS, Some(flags)) if flags & UF_ACCOUNTDISABLE != 0 => (
|
||||
CheckStatus::Fail,
|
||||
"a Windows sandbox account is disabled",
|
||||
"ask IT to enable the sandbox account before rerunning setup",
|
||||
),
|
||||
(NERR_SUCCESS, Some(flags)) if flags & UF_PASSWORD_EXPIRED != 0 => (
|
||||
CheckStatus::Fail,
|
||||
"a Windows sandbox account password has expired",
|
||||
WINDOWS_SETUP_REMEDIATION,
|
||||
),
|
||||
(NERR_SUCCESS, Some(_)) => continue,
|
||||
(ERROR_ACCESS_DENIED, _) => (
|
||||
CheckStatus::Warning,
|
||||
"Windows sandbox account status could not be inspected",
|
||||
"ask IT to inspect access to the local sandbox accounts",
|
||||
),
|
||||
_ => (
|
||||
CheckStatus::Warning,
|
||||
"Windows sandbox account status could not be inspected",
|
||||
"ask IT to inspect the local sandbox accounts",
|
||||
),
|
||||
};
|
||||
check.details.push(format!("sandbox account: {username}"));
|
||||
if !matches!(
|
||||
status,
|
||||
NERR_SUCCESS | NERR_USER_NOT_FOUND | ERROR_ACCESS_DENIED
|
||||
) {
|
||||
check
|
||||
.details
|
||||
.push(format!("account query status: {status}"));
|
||||
}
|
||||
check.issues.push(
|
||||
DoctorIssue::new(severity, cause)
|
||||
.measured(username)
|
||||
.expected("enabled, unlocked local sandbox account")
|
||||
.remedy(remediation)
|
||||
.field("sandbox account"),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
check.details.push(if report.is_some() {
|
||||
"sandbox provisioning: failed".to_string()
|
||||
} else {
|
||||
"sandbox provisioning: incomplete".to_string()
|
||||
});
|
||||
if let Some(report) = report {
|
||||
let remediation = match report.code {
|
||||
SetupErrorCode::OrchestratorElevationCheckFailed
|
||||
| SetupErrorCode::OrchestratorElevationRequired
|
||||
| SetupErrorCode::OrchestratorHelperLaunchCanceled => {
|
||||
"use an elevated shell or your organization's approved elevation workflow"
|
||||
}
|
||||
SetupErrorCode::OrchestratorHelperLaunchFailed
|
||||
| SetupErrorCode::OrchestratorHelperExitNonzero
|
||||
| SetupErrorCode::OrchestratorHelperReportReadFailed
|
||||
| SetupErrorCode::OrchestratorHelperIncomplete
|
||||
| SetupErrorCode::HelperReadAclHelperSpawnFailed => {
|
||||
"repair the installed aKode helpers or ask IT to allow their execution"
|
||||
}
|
||||
SetupErrorCode::HelperUserProvisionFailed
|
||||
| SetupErrorCode::HelperUsersGroupCreateFailed
|
||||
| SetupErrorCode::HelperUserCreateOrUpdateFailed
|
||||
| SetupErrorCode::HelperSidResolveFailed
|
||||
| SetupErrorCode::HelperCapabilitySidFailed => {
|
||||
"ask IT to allow the managed local sandbox accounts and group"
|
||||
}
|
||||
SetupErrorCode::OrchestratorSandboxDirCreateFailed
|
||||
| SetupErrorCode::HelperSandboxDirCreateFailed
|
||||
| SetupErrorCode::HelperLogFailed
|
||||
| SetupErrorCode::HelperDpapiProtectFailed
|
||||
| SetupErrorCode::HelperUsersFileWriteFailed
|
||||
| SetupErrorCode::HelperSetupMarkerWriteFailed
|
||||
| SetupErrorCode::HelperSandboxLockFailed => {
|
||||
"rerun elevated setup for the authoritative aKode home or ask IT"
|
||||
}
|
||||
SetupErrorCode::HelperFirewallComInitFailed
|
||||
| SetupErrorCode::HelperFirewallPolicyAccessFailed
|
||||
| SetupErrorCode::HelperFirewallPolicyIneffective
|
||||
| SetupErrorCode::HelperFirewallRuleCreateOrAddFailed
|
||||
| SetupErrorCode::HelperFirewallRuleVerifyFailed => {
|
||||
"ask IT to allow aKode sandbox rules in managed Windows Firewall policy"
|
||||
}
|
||||
SetupErrorCode::OrchestratorPayloadSerializeFailed
|
||||
| SetupErrorCode::HelperRequestArgsFailed
|
||||
| SetupErrorCode::HelperUnknownError => {
|
||||
"repair or reinstall the aKode CLI from an approved distribution"
|
||||
}
|
||||
};
|
||||
check
|
||||
.details
|
||||
.push(format!("error code: {}", report.code.as_str()));
|
||||
check.issues.push(
|
||||
DoctorIssue::new(
|
||||
CheckStatus::Fail,
|
||||
"elevated Windows sandbox provisioning recorded a structured failure",
|
||||
)
|
||||
.measured(report.code.as_str())
|
||||
.remedy(remediation)
|
||||
.field("error code"),
|
||||
);
|
||||
} else {
|
||||
check.issues.push(
|
||||
DoctorIssue::new(
|
||||
CheckStatus::Warning,
|
||||
"elevated Windows sandbox provisioning is incomplete or outdated",
|
||||
)
|
||||
.remedy(WINDOWS_SETUP_REMEDIATION)
|
||||
.field("sandbox provisioning"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(severity) = check.issues.iter().map(|issue| issue.severity).max() {
|
||||
check.status = check.status.max(severity);
|
||||
check.summary = if check.issues.len() == 1 {
|
||||
check.issues[0].cause.clone()
|
||||
} else {
|
||||
"Windows sandbox has multiple configuration or provisioning issues".to_string()
|
||||
};
|
||||
if check.remediation.is_none() {
|
||||
check.remediation = check.issues.iter().find_map(|issue| issue.remedy.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
check
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "sandbox_tests.rs"]
|
||||
mod tests;
|
||||
160
akode-rs/cli/src/doctor/sandbox_tests.rs
Normal file
160
akode-rs/cli/src/doctor/sandbox_tests.rs
Normal file
@@ -0,0 +1,160 @@
|
||||
use akode_arg0::Arg0DispatchPaths;
|
||||
use akode_core::config::ConfigBuilder;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::sandbox_check;
|
||||
|
||||
#[tokio::test]
|
||||
async fn reports_missing_linux_sandbox_helper() {
|
||||
let home = tempfile::tempdir().expect("create Codex home");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.expect("load sandbox config");
|
||||
let arg0_paths = Arg0DispatchPaths {
|
||||
codex_linux_sandbox_exe: Some(home.path().join("missing-linux-helper")),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let check = sandbox_check(&config, &arg0_paths);
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert_eq!(check.summary, "Linux sandbox helper path does not exist");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[tokio::test]
|
||||
async fn reports_refresh_failure_after_setup_completed() {
|
||||
let home = tempfile::tempdir().expect("create Codex home");
|
||||
let version = akode_windows_sandbox::SETUP_VERSION;
|
||||
for (path, contents) in [
|
||||
(
|
||||
".sandbox/setup_marker.json",
|
||||
serde_json::json!({
|
||||
"version": version,
|
||||
"offline_username": akode_windows_sandbox::OFFLINE_USERNAME,
|
||||
"online_username": akode_windows_sandbox::ONLINE_USERNAME,
|
||||
}),
|
||||
),
|
||||
(
|
||||
".sandbox-secrets/sandbox_users.json",
|
||||
serde_json::json!({
|
||||
"version": version,
|
||||
"offline": {
|
||||
"username": akode_windows_sandbox::OFFLINE_USERNAME,
|
||||
"password": "",
|
||||
},
|
||||
"online": {
|
||||
"username": akode_windows_sandbox::ONLINE_USERNAME,
|
||||
"password": "",
|
||||
},
|
||||
}),
|
||||
),
|
||||
] {
|
||||
let path = home.path().join(path);
|
||||
std::fs::create_dir_all(path.parent().expect("fixture parent"))
|
||||
.expect("create fixture directory");
|
||||
std::fs::write(path, contents.to_string()).expect("write sandbox fixture");
|
||||
}
|
||||
assert!(akode_windows_sandbox::sandbox_setup_is_complete(
|
||||
home.path()
|
||||
));
|
||||
akode_windows_sandbox::write_setup_error_report(
|
||||
home.path(),
|
||||
&akode_windows_sandbox::SetupErrorReport {
|
||||
code: akode_windows_sandbox::SetupErrorCode::HelperFirewallPolicyIneffective,
|
||||
message: "firewall policy rejected the refresh".to_string(),
|
||||
},
|
||||
)
|
||||
.expect("write refresh failure");
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"[windows]\nsandbox = \"elevated\"\n",
|
||||
)
|
||||
.expect("write elevated sandbox config");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.expect("load sandbox config");
|
||||
|
||||
let check = sandbox_check(&config, &Arg0DispatchPaths::default());
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Fail);
|
||||
assert_eq!(
|
||||
check.issues[0].measured.as_deref(),
|
||||
Some("helper_firewall_policy_ineffective")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[tokio::test]
|
||||
async fn rejects_oversized_setup_failure_reports() {
|
||||
let home = tempfile::tempdir().expect("create Codex home");
|
||||
akode_windows_sandbox::write_setup_error_report(
|
||||
home.path(),
|
||||
&akode_windows_sandbox::SetupErrorReport {
|
||||
code: akode_windows_sandbox::SetupErrorCode::HelperFirewallPolicyIneffective,
|
||||
message: "x".repeat(64 * 1024),
|
||||
},
|
||||
)
|
||||
.expect("write oversized setup failure");
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"[windows]\nsandbox = \"elevated\"\n",
|
||||
)
|
||||
.expect("write elevated sandbox config");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.expect("load sandbox config");
|
||||
|
||||
let check = sandbox_check(&config, &Arg0DispatchPaths::default());
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"setup failure report: unreadable".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
check.issues[0].cause,
|
||||
"Windows sandbox setup failure report could not be read"
|
||||
);
|
||||
assert_eq!(
|
||||
check.issues[0].measured.as_deref(),
|
||||
Some("larger than 64 KiB")
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[tokio::test]
|
||||
async fn reports_malformed_setup_failure_reports() {
|
||||
let home = tempfile::tempdir().expect("create Codex home");
|
||||
let path = akode_windows_sandbox::setup_error_path(home.path());
|
||||
std::fs::create_dir_all(path.parent().expect("setup failure report parent"))
|
||||
.expect("create sandbox directory");
|
||||
std::fs::write(path, "{").expect("write malformed setup failure report");
|
||||
std::fs::write(
|
||||
home.path().join("config.toml"),
|
||||
"[windows]\nsandbox = \"elevated\"\n",
|
||||
)
|
||||
.expect("write elevated sandbox config");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.expect("load sandbox config");
|
||||
|
||||
let check = sandbox_check(&config, &Arg0DispatchPaths::default());
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert_eq!(
|
||||
check.issues[0].cause,
|
||||
"Windows sandbox setup failure report could not be read"
|
||||
);
|
||||
assert!(check.issues[0].measured.is_some());
|
||||
}
|
||||
254
akode-rs/cli/src/doctor/security.rs
Normal file
254
akode-rs/cli/src/doctor/security.rs
Normal file
@@ -0,0 +1,254 @@
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use std::ffi::OsStr;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::path::PathBuf;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use std::process::Output;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use std::process::Stdio;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use tokio::process::Command;
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
use super::DoctorIssue;
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
const PRODUCT_QUERY_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
const MAX_PRODUCT_OUTPUT_BYTES: usize = 64 * 1024;
|
||||
|
||||
pub(super) enum EndpointInspection {
|
||||
Complete(Vec<&'static str>),
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
Partial(Vec<&'static str>),
|
||||
#[cfg(any(target_os = "macos", target_os = "windows", test))]
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
pub(super) async fn check() -> DoctorCheck {
|
||||
endpoint_check(endpoint_products().await)
|
||||
}
|
||||
|
||||
pub(super) fn endpoint_check(inspection: EndpointInspection) -> DoctorCheck {
|
||||
let (products, visibility_incomplete) = match inspection {
|
||||
EndpointInspection::Complete(products) => (products, false),
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
EndpointInspection::Partial(products) => (products, true),
|
||||
#[cfg(any(target_os = "macos", target_os = "windows", test))]
|
||||
EndpointInspection::Unavailable => {
|
||||
return DoctorCheck::new(
|
||||
"security.endpoint",
|
||||
"security",
|
||||
CheckStatus::Warning,
|
||||
"endpoint protection inspection unavailable",
|
||||
)
|
||||
.detail("endpoint products: unavailable");
|
||||
}
|
||||
};
|
||||
|
||||
if products.is_empty() {
|
||||
let (summary, detail) = if cfg!(any(target_os = "macos", target_os = "windows")) {
|
||||
("no supported endpoint protection detected", "none detected")
|
||||
} else {
|
||||
(
|
||||
"endpoint protection is not inspected on this platform",
|
||||
"not inspected on this platform",
|
||||
)
|
||||
};
|
||||
return DoctorCheck::new("security.endpoint", "security", CheckStatus::Ok, summary)
|
||||
.detail(format!("endpoint products: {detail}"));
|
||||
}
|
||||
|
||||
let targets = if cfg!(target_os = "windows") {
|
||||
"signed Codex app; codex.exe; akode-windows-sandbox-setup.exe; akode-command-runner.exe; akode-code-mode-host.exe"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"signing team 2DC432GLL2 plus the installed Codex app identity, signed codex agent, and required helpers"
|
||||
} else {
|
||||
"verified Codex app, codex agent, and required helpers"
|
||||
};
|
||||
let mut check = DoctorCheck::new(
|
||||
"security.endpoint",
|
||||
"security",
|
||||
CheckStatus::Warning,
|
||||
"endpoint protection detected; aKode exclusions are unverified",
|
||||
)
|
||||
.detail(format!("endpoint products: {}", products.join(", ")))
|
||||
.detail(format!("exclusion targets: {targets}"))
|
||||
.detail("aKode exclusions: not verified")
|
||||
.remediation(
|
||||
"ask your security administrator to verify aKode exclusions and required helper allowances",
|
||||
);
|
||||
if visibility_incomplete {
|
||||
check = check.detail("additional endpoint products: unavailable");
|
||||
}
|
||||
|
||||
for product in products {
|
||||
let remedy = match product {
|
||||
"CrowdStrike Falcon" => {
|
||||
"CrowdStrike Falcon: Add a certificate or IOA exclusion for aKode. If sensor overhead continues, exclude the aKode agent from sensor visibility. Keep monitoring descendant processes."
|
||||
}
|
||||
"BeyondTrust Privilege Management" => {
|
||||
"BeyondTrust: Remove aKode from application blocking rules. Add allow rules for aKode helper executables. Do not grant administrator privileges."
|
||||
}
|
||||
"Microsoft Defender" => {
|
||||
"Microsoft Defender: Add a certificate or executable-path exclusion for aKode and its helpers. If Attack Surface Reduction blocks aKode, add a rule exclusion. If Controlled Folder Access blocks aKode, allow the app."
|
||||
}
|
||||
"SentinelOne" => {
|
||||
"SentinelOne: Add a signer, file-hash, or executable-path exclusion for aKode and its helpers."
|
||||
}
|
||||
"Jamf Protect" => {
|
||||
"Jamf Protect: Add an Override Threat Prevention exception for aKode app and helper signing identities. If analytics cause delays, add an Ignore System Events for Analytics exception."
|
||||
}
|
||||
_ => {
|
||||
"Add an exclusion for aKode and its helpers. Use the endpoint product instructions."
|
||||
}
|
||||
};
|
||||
check = check.issue(
|
||||
DoctorIssue::new(
|
||||
CheckStatus::Warning,
|
||||
format!("{product} can interfere with aKode. Verify aKode exclusions."),
|
||||
)
|
||||
.measured("not verified")
|
||||
.expected("aKode application and helper exclusions")
|
||||
.remedy(remedy)
|
||||
.field("aKode exclusions"),
|
||||
);
|
||||
}
|
||||
|
||||
check
|
||||
}
|
||||
|
||||
async fn endpoint_products() -> EndpointInspection {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let system32 = std::env::var_os("SystemRoot")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(r"C:\Windows"))
|
||||
.join("System32");
|
||||
let service = system32.join("sc.exe");
|
||||
let (crowdstrike, beyondtrust, defender, sentinelone) = tokio::join!(
|
||||
product_command(&service, &["query", "CSFalconService"]),
|
||||
product_command(&service, &["query", "DefendpointService"]),
|
||||
product_command(&service, &["query", "WinDefend"]),
|
||||
product_command(&service, &["query", "SentinelAgent"]),
|
||||
);
|
||||
|
||||
let mut products = Vec::new();
|
||||
let mut visibility_incomplete = false;
|
||||
for (product, output) in [
|
||||
("CrowdStrike Falcon", crowdstrike),
|
||||
("BeyondTrust Privilege Management", beyondtrust),
|
||||
("Microsoft Defender", defender),
|
||||
("SentinelOne", sentinelone),
|
||||
] {
|
||||
match output {
|
||||
Some(output) if output.status.success() => {
|
||||
if product != "Microsoft Defender"
|
||||
|| String::from_utf8_lossy(&output.stdout).lines().any(|line| {
|
||||
line.split_once(':').is_some_and(|(_, value)| {
|
||||
value.split_whitespace().next() == Some("4")
|
||||
})
|
||||
})
|
||||
{
|
||||
products.push(product);
|
||||
}
|
||||
}
|
||||
Some(output) if output.status.code() == Some(1060) => {}
|
||||
Some(_) | None => visibility_incomplete = true,
|
||||
}
|
||||
}
|
||||
|
||||
if visibility_incomplete {
|
||||
if products.is_empty() {
|
||||
EndpointInspection::Unavailable
|
||||
} else {
|
||||
EndpointInspection::Partial(products)
|
||||
}
|
||||
} else {
|
||||
EndpointInspection::Complete(products)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
const PRODUCTS: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"CrowdStrike Falcon",
|
||||
"X9E956P446",
|
||||
"com.crowdstrike.falcon.Agent",
|
||||
),
|
||||
(
|
||||
"BeyondTrust Privilege Management",
|
||||
"2ZS8T6NYB8",
|
||||
"com.beyondtrust.endpointsecurity",
|
||||
),
|
||||
(
|
||||
"Microsoft Defender",
|
||||
"UBF8T346G9",
|
||||
"com.microsoft.wdav.epsext",
|
||||
),
|
||||
(
|
||||
"SentinelOne",
|
||||
"4AYE5J54KN",
|
||||
"com.sentinelone.network-monitoring",
|
||||
),
|
||||
(
|
||||
"Jamf Protect",
|
||||
"483DWKW443",
|
||||
"com.jamf.protect.security-extension",
|
||||
),
|
||||
];
|
||||
let Some(output) = product_command("/usr/bin/systemextensionsctl", &["list"])
|
||||
.await
|
||||
.filter(|output| output.status.success())
|
||||
else {
|
||||
return EndpointInspection::Unavailable;
|
||||
};
|
||||
EndpointInspection::Complete(
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let mut columns = line.split_whitespace();
|
||||
if columns.next() != Some("*") || columns.next() != Some("*") {
|
||||
return None;
|
||||
}
|
||||
let team = columns.next()?;
|
||||
let bundle = columns.next()?;
|
||||
PRODUCTS.iter().find_map(|&(name, signer, identifier)| {
|
||||
(team == signer && bundle == identifier).then_some(name)
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
EndpointInspection::Complete(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
async fn product_command(program: impl AsRef<OsStr>, args: &[&str]) -> Option<Output> {
|
||||
let mut command = Command::from(akode_utils_process::background_command(program));
|
||||
command
|
||||
.args(args)
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true);
|
||||
timeout(PRODUCT_QUERY_TIMEOUT, command.output())
|
||||
.await
|
||||
.ok()?
|
||||
.ok()
|
||||
.filter(|output| output.stdout.len() <= MAX_PRODUCT_OUTPUT_BYTES)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "security_tests.rs"]
|
||||
mod tests;
|
||||
184
akode-rs/cli/src/doctor/security_tests.rs
Normal file
184
akode-rs/cli/src/doctor/security_tests.rs
Normal file
@@ -0,0 +1,184 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::super::redacted_json_check;
|
||||
use super::CheckStatus;
|
||||
use super::EndpointInspection;
|
||||
use super::endpoint_check;
|
||||
|
||||
#[test]
|
||||
fn no_endpoint_products_require_no_remediation() {
|
||||
let check = endpoint_check(EndpointInspection::Complete(Vec::new()));
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Ok);
|
||||
assert_eq!(check.remediation, None);
|
||||
assert!(check.issues.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_endpoint_inspection_does_not_require_remediation() {
|
||||
let check = endpoint_check(EndpointInspection::Unavailable);
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert!(check.summary.to_ascii_lowercase().contains("unavailable"));
|
||||
assert_eq!(check.details, vec!["endpoint products: unavailable"]);
|
||||
assert_eq!(check.remediation, None);
|
||||
assert!(check.issues.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_endpoint_product_requires_vendor_specific_app_exclusions() {
|
||||
let cases: [(&str, &[&str]); 5] = [
|
||||
("CrowdStrike Falcon", &["certificate", "ioa"]),
|
||||
("BeyondTrust Privilege Management", &["application"]),
|
||||
("Microsoft Defender", &["executable", "path", "certificate"]),
|
||||
("SentinelOne", &["signer", "hash", "path"]),
|
||||
("Jamf Protect", &["threat prevention"]),
|
||||
];
|
||||
|
||||
for (product, strategies) in cases {
|
||||
let check = endpoint_check(EndpointInspection::Complete(vec![product]));
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Warning, "{product}");
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.iter()
|
||||
.any(|detail| detail.starts_with("exclusion targets: ")),
|
||||
"{product}: {:?}",
|
||||
check.details
|
||||
);
|
||||
let remediation = check
|
||||
.remediation
|
||||
.as_deref()
|
||||
.expect("detected endpoint protection should require remediation")
|
||||
.to_ascii_lowercase();
|
||||
assert_eq!(
|
||||
remediation,
|
||||
"ask your security administrator to verify akode exclusions and required helper allowances",
|
||||
"{product}"
|
||||
);
|
||||
assert!(
|
||||
!serde_json::to_string(&redacted_json_check(&check))
|
||||
.expect("serialize endpoint check")
|
||||
.to_ascii_lowercase()
|
||||
.contains("chatgpt"),
|
||||
"{product}: endpoint diagnostics should only refer to Codex"
|
||||
);
|
||||
|
||||
assert_eq!(check.issues.len(), 1, "{product}");
|
||||
let issue = &check.issues[0];
|
||||
assert_eq!(issue.severity, CheckStatus::Warning, "{product}");
|
||||
assert!(
|
||||
issue
|
||||
.cause
|
||||
.to_ascii_lowercase()
|
||||
.contains(&product.to_ascii_lowercase()),
|
||||
"{product}: {}",
|
||||
issue.cause
|
||||
);
|
||||
assert!(
|
||||
issue.cause.contains("Verify aKode exclusions."),
|
||||
"{product}: {}",
|
||||
issue.cause
|
||||
);
|
||||
|
||||
let remedy = issue
|
||||
.remedy
|
||||
.as_deref()
|
||||
.expect("endpoint product should have vendor-specific guidance")
|
||||
.to_ascii_lowercase();
|
||||
assert!(
|
||||
strategies.iter().any(|strategy| remedy.contains(strategy)),
|
||||
"{product}: {remedy}"
|
||||
);
|
||||
assert!(!remedy.contains("administrator-approved"), "{product}");
|
||||
assert!(!remedy.contains(';'), "{product}");
|
||||
for sentence in remedy.split('.') {
|
||||
assert!(
|
||||
sentence.split_whitespace().count() <= 20,
|
||||
"{product}: {sentence}"
|
||||
);
|
||||
}
|
||||
|
||||
if product == "BeyondTrust Privilege Management" {
|
||||
assert!(remedy.contains("rule"), "{product}: {remedy}");
|
||||
assert!(remedy.contains("blocking"), "{product}: {remedy}");
|
||||
assert!(
|
||||
remedy.contains("do not grant administrator privileges"),
|
||||
"{product}: {remedy}"
|
||||
);
|
||||
}
|
||||
|
||||
if product == "Microsoft Defender" {
|
||||
assert!(
|
||||
remedy.contains("attack surface reduction"),
|
||||
"{product}: {remedy}"
|
||||
);
|
||||
assert!(
|
||||
remedy.contains("controlled folder access"),
|
||||
"{product}: {remedy}"
|
||||
);
|
||||
}
|
||||
|
||||
if product == "CrowdStrike Falcon" {
|
||||
assert!(remedy.contains("sensor visibility"), "{product}: {remedy}");
|
||||
assert!(remedy.contains("descendant"), "{product}: {remedy}");
|
||||
}
|
||||
|
||||
if product == "Jamf Protect" {
|
||||
assert!(remedy.contains("exception"), "{product}: {remedy}");
|
||||
assert!(remedy.contains("signing"), "{product}: {remedy}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_endpoint_products_each_get_distinct_guidance() {
|
||||
let products = ["CrowdStrike Falcon", "Microsoft Defender"];
|
||||
let check = endpoint_check(EndpointInspection::Complete(products.to_vec()));
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert_eq!(check.issues.len(), products.len());
|
||||
|
||||
for product in products {
|
||||
let matching_issues = check
|
||||
.issues
|
||||
.iter()
|
||||
.filter(|issue| {
|
||||
issue
|
||||
.cause
|
||||
.to_ascii_lowercase()
|
||||
.contains(&product.to_ascii_lowercase())
|
||||
})
|
||||
.count();
|
||||
|
||||
assert_eq!(matching_issues, 1, "{product}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endpoint_product_guidance_preserves_structured_json_contract() {
|
||||
let check = endpoint_check(EndpointInspection::Complete(vec!["Microsoft Defender"]));
|
||||
let json = serde_json::to_value(redacted_json_check(&check)).expect("serialize endpoint check");
|
||||
|
||||
assert_eq!(json["id"], "security.endpoint");
|
||||
assert_eq!(json["category"], "security");
|
||||
assert_eq!(json["status"], "warning");
|
||||
assert_eq!(json["details"]["endpoint products"], "Microsoft Defender");
|
||||
assert!(json["details"]["exclusion targets"].is_string());
|
||||
assert_eq!(json["issues"].as_array().map(Vec::len), Some(1));
|
||||
assert!(json["issues"][0]["remedy"].is_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detected_products_preserve_partial_inspection_visibility() {
|
||||
let check = endpoint_check(EndpointInspection::Partial(vec!["Microsoft Defender"]));
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"additional endpoint products: unavailable".to_string())
|
||||
);
|
||||
assert_eq!(check.issues.len(), 1);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
source: cli/src/doctor/background.rs
|
||||
expression: details
|
||||
---
|
||||
update-loop pid file: AKODE_HOME/app-server-daemon/app-server-updater.pid (missing)
|
||||
dedicated pid file: AKODE_HOME/app-server-daemon/daemon.pid (missing)
|
||||
dedicated update-loop pid file: AKODE_HOME/app-server-daemon/daemon-updater.pid (missing)
|
||||
automatic updates: disabled (configured)
|
||||
update interval: 90 minutes (configured)
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
source: cli/src/doctor/filesystem_paths_tests.rs
|
||||
expression: "super::super::render_human_report(&report, super::super::HumanOutputOptions\n{ show_details: true, show_all: false, ascii: true, color_enabled: false, },)"
|
||||
---
|
||||
aKode Doctor vtest
|
||||
|
||||
Configuration
|
||||
[ok] sandbox configured filesystem paths listed; read restrictions prevent probes
|
||||
permission profile diagnostic
|
||||
operation resolve paths only; read/write access is not tested
|
||||
probe budgets 2 seconds per path, 8 seconds total, at most 32 paths
|
||||
path 1 FIXTURE/unavailable (read); not probed (filesystem read restrictions apply)
|
||||
path 1 source permissions.diagnostic.filesystem.FIXTURE/unavailable.. in user (FIXTURE/config.toml)
|
||||
path 2 FIXTURE/unavailable/.git (write); not probed (filesystem read restrictions apply)
|
||||
path 2 source permissions.base.filesystem.FIXTURE/unavailable..git in user (FIXTURE/config.toml)
|
||||
path 3 FIXTURE/unavailable/overridden (write); not probed (filesystem read restrictions apply)
|
||||
path 3 source effective filesystem policy (entry provenance unavailable)
|
||||
path 4 FIXTURE/unavailable/subtree (read); not probed (filesystem read restrictions apply)
|
||||
path 4 source permissions.base.filesystem.FIXTURE/unavailable.subtree/** in user (FIXTURE/config.toml)
|
||||
paths checked 4 of 4
|
||||
|
||||
-------------------------------------------------------------
|
||||
1 ok | 0 warn | 0 fail ok
|
||||
|
||||
--summary compact output --all expand truncated lists
|
||||
--json redacted report
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
source: cli/src/doctor/git.rs
|
||||
assertion_line: 150
|
||||
expression: "super::super::render_human_report(&report, super::super::HumanOutputOptions\n{ show_details: true, show_all: false, ascii: true, color_enabled: false, },)"
|
||||
---
|
||||
aKode Doctor vtest
|
||||
|
||||
Environment
|
||||
[ok] git git executable found; execution not verified
|
||||
selected git /usr/bin/git
|
||||
repo detected true
|
||||
repo root /repo
|
||||
.git entry directory
|
||||
PATH entries (2) /usr/bin/git
|
||||
/opt/bin/git
|
||||
git execution not inspected (PATH helpers are not executed)
|
||||
|
||||
-------------------------------------------------------------
|
||||
1 ok | 0 warn | 0 fail ok
|
||||
|
||||
--summary compact output --all expand truncated lists
|
||||
--json redacted report
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
source: cli/src/doctor/output.rs
|
||||
expression: "rendered.replace('\\u{1b}', \"<ESC>\")"
|
||||
---
|
||||
<ESC>[38;5;10m✓<ESC>[39m state <ESC>[2m<ESC>[38;5;117m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;117m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m<ESC>[0m
|
||||
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;117m./logs<ESC>[39m, <ESC>[38;5;117m../goals<ESC>[39m. C:\logs, D:/goals. c:\logs, \\server\share\logs, \\?\C:\logs, \\?\UNC\server\share\logs, \\.\pipe\codex, \??\C:\logs, \DosDevices\C:\logs, \rooted. <ESC>[38;5;117mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;117mhttps://example.com<ESC>[39m; <ESC>[38;5;117mwss://example.com<ESC>[39m) and <ESC>[38;5;117m/tmp/my data/logs_2.sqlite<ESC>[39m
|
||||
<ESC>[38;5;214m⚠<ESC>[39m state <ESC>[38;5;117m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;117m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m
|
||||
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;117m./logs<ESC>[39m, <ESC>[38;5;117m../goals<ESC>[39m. C:\logs, D:/goals. c:\logs, \\server\share\logs, \\?\C:\logs, \\?\UNC\server\share\logs, \\.\pipe\codex, \??\C:\logs, \DosDevices\C:\logs, \rooted. <ESC>[38;5;117mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;117mhttps://example.com<ESC>[39m; <ESC>[38;5;117mwss://example.com<ESC>[39m) and <ESC>[38;5;117m/tmp/my data/logs_2.sqlite<ESC>[39m
|
||||
<ESC>[38;5;196m✗<ESC>[39m state <ESC>[38;5;196m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;196m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m
|
||||
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;196m./logs<ESC>[39m, <ESC>[38;5;196m../goals<ESC>[39m. C:\logs, D:/goals. c:\logs, \\server\share\logs, \\?\C:\logs, \\?\UNC\server\share\logs, \\.\pipe\codex, \??\C:\logs, \DosDevices\C:\logs, \rooted. <ESC>[38;5;196mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;196mhttps://example.com<ESC>[39m; <ESC>[38;5;196mwss://example.com<ESC>[39m) and <ESC>[38;5;196m/tmp/my data/logs_2.sqlite<ESC>[39m
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
source: cli/src/doctor/output.rs
|
||||
expression: "rendered.replace('\\u{1b}', \"<ESC>\")"
|
||||
---
|
||||
<ESC>[38;5;10m✓<ESC>[39m state <ESC>[2m<ESC>[38;5;117m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;117m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m<ESC>[0m
|
||||
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;117m./logs<ESC>[39m, <ESC>[38;5;117m../goals<ESC>[39m. <ESC>[38;5;117mC:\logs<ESC>[39m, <ESC>[38;5;117mD:/goals<ESC>[39m. <ESC>[38;5;117mc:\logs<ESC>[39m, <ESC>[38;5;117m\\server\share\logs<ESC>[39m, <ESC>[38;5;117m\\?\C:\logs<ESC>[39m, <ESC>[38;5;117m\\?\UNC\server\share\logs<ESC>[39m, <ESC>[38;5;117m\\.\pipe\codex<ESC>[39m, <ESC>[38;5;117m\??\C:\logs<ESC>[39m, \DosDevices\C:\logs, \rooted. <ESC>[38;5;117mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;117mhttps://example.com<ESC>[39m; <ESC>[38;5;117mwss://example.com<ESC>[39m) and <ESC>[38;5;117m/tmp/my data/logs_2.sqlite<ESC>[39m
|
||||
<ESC>[38;5;214m⚠<ESC>[39m state <ESC>[38;5;117m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;117m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m
|
||||
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;117m./logs<ESC>[39m, <ESC>[38;5;117m../goals<ESC>[39m. <ESC>[38;5;117mC:\logs<ESC>[39m, <ESC>[38;5;117mD:/goals<ESC>[39m. <ESC>[38;5;117mc:\logs<ESC>[39m, <ESC>[38;5;117m\\server\share\logs<ESC>[39m, <ESC>[38;5;117m\\?\C:\logs<ESC>[39m, <ESC>[38;5;117m\\?\UNC\server\share\logs<ESC>[39m, <ESC>[38;5;117m\\.\pipe\codex<ESC>[39m, <ESC>[38;5;117m\??\C:\logs<ESC>[39m, \DosDevices\C:\logs, \rooted. <ESC>[38;5;117mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;117mhttps://example.com<ESC>[39m; <ESC>[38;5;117mwss://example.com<ESC>[39m) and <ESC>[38;5;117m/tmp/my data/logs_2.sqlite<ESC>[39m
|
||||
<ESC>[38;5;196m✗<ESC>[39m state <ESC>[38;5;196m/tmp/logs_2.sqlite<ESC>[39m, <ESC>[38;5;196m~/goals_1.sqlite<ESC>[39m integrity check; try <ESC>[38;5;117m--summary<ESC>[39m or <ESC>[38;5;117mcodex doctor<ESC>[39m
|
||||
<ESC>[38;5;240mlocations <ESC>[39m see <ESC>[38;5;196m./logs<ESC>[39m, <ESC>[38;5;196m../goals<ESC>[39m. <ESC>[38;5;196mC:\logs<ESC>[39m, <ESC>[38;5;196mD:/goals<ESC>[39m. <ESC>[38;5;196mc:\logs<ESC>[39m, <ESC>[38;5;196m\\server\share\logs<ESC>[39m, <ESC>[38;5;196m\\?\C:\logs<ESC>[39m, <ESC>[38;5;196m\\?\UNC\server\share\logs<ESC>[39m, <ESC>[38;5;196m\\.\pipe\codex<ESC>[39m, <ESC>[38;5;196m\??\C:\logs<ESC>[39m, \DosDevices\C:\logs, \rooted. <ESC>[38;5;196mhttp://localhost:8080<ESC>[39m: <ESC>[38;5;196mhttps://example.com<ESC>[39m; <ESC>[38;5;196mwss://example.com<ESC>[39m) and <ESC>[38;5;196m/tmp/my data/logs_2.sqlite<ESC>[39m
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
source: cli/src/doctor/output.rs
|
||||
expression: "render_human_report(&report, detailed_no_color_unicode_options())"
|
||||
---
|
||||
aKode Doctor v0.0.0
|
||||
|
||||
Notes
|
||||
↑ desktop build 123 available (ready to install)
|
||||
⚠ terminal narrow terminal
|
||||
✗ auth token expired - Run `akode login`.
|
||||
✗ network provider is unreachable - A macOS system proxy is configured but unused. If your organization requires it, ask your administrator whether to enable the experimental System proxy setting in `/experimental` or with `akode features enable respect_system_proxy`. Restart aKode after changing this setting.
|
||||
⚠ git this worktree is not on a Windows Dev Drive - create a trusted Windows Dev Drive: https://learn.microsoft.com/en-us/windows/dev-drive/
|
||||
⚠ security Microsoft Defender can interfere with aKode. Verify aKode exclusions.
|
||||
─────────────────────────────────────────────────────────────
|
||||
|
||||
Environment
|
||||
✓ system en-US
|
||||
os macOS 15.0
|
||||
OS language en-US
|
||||
VISUAL code --wait
|
||||
EDITOR vim
|
||||
PAGER less -R
|
||||
GIT_PAGER delta
|
||||
GH_PAGER less
|
||||
LESS -FRX
|
||||
✓ disk sufficient free disk space (42.0 GiB)
|
||||
⚠ security Microsoft Defender can interfere with aKode. Verify aKode exclusions.
|
||||
endpoint products Microsoft Defender
|
||||
exclusion targets verified Codex app and required helpers
|
||||
▸ aKode exclusions not verified (expected aKode application and helper exclusions)
|
||||
→ Microsoft Defender: Add a certificate or executable-path exclusion for aKode and its helpers. If Attack Surface Reduction blocks aKode, add a rule exclusion. If Controlled Folder Access blocks aKode, allow the app.
|
||||
✓ runtime running local build on darwin-arm64
|
||||
✓ install consistent
|
||||
managed by npm: no · bun: no · pnpm: no · Vite+: no · package root —
|
||||
✓ search search is OK (bundled)
|
||||
✓ git git version 2.54.0
|
||||
selected git /usr/bin/git
|
||||
version git version 2.54.0
|
||||
repo detected true
|
||||
⚠ git this worktree is not on a Windows Dev Drive — create a trusted Windows Dev Drive: https://learn.microsoft.com/en-us/windows/dev-drive/
|
||||
⚠ terminal narrow terminal
|
||||
✓ title default · project codex
|
||||
title source default
|
||||
title items activity, project-name
|
||||
project value codex
|
||||
✓ state state paths inspectable
|
||||
|
||||
Configuration
|
||||
✓ config loaded
|
||||
feature flags 0 enabled · 0 overridden
|
||||
configured TUI mode fullscreen
|
||||
✗ auth token expired — Run `akode login`.
|
||||
OPENAI_API_KEY present
|
||||
|
||||
Desktop App
|
||||
✓ desktop the desktop application is installed
|
||||
version 1.2.3
|
||||
running true
|
||||
log directory $HOME/Library/Logs/com.openai.codex
|
||||
✓ desktop the desktop app-server initialized successfully
|
||||
|
||||
Updates
|
||||
✓ updates update configuration is locally consistent
|
||||
desktop update status ready to install
|
||||
desktop latest build 123
|
||||
|
||||
Connectivity
|
||||
✓ network network environment readable
|
||||
✗ network provider is unreachable — A macOS system proxy is configured but unused. If your organization requires it, ask your administrator whether to enable the experimental System proxy setting in `/experimental` or with `akode features enable respect_system_proxy`. Restart aKode after changing this setting.
|
||||
✓ websocket Responses WebSocket handshake succeeded
|
||||
✓ reachability active provider endpoints are reachable over HTTP
|
||||
|
||||
Background Server
|
||||
✓ app-server background server is not running
|
||||
|
||||
─────────────────────────────────────────────────────────────
|
||||
16 ok · 6 notes · 3 warn · 2 fail failed
|
||||
|
||||
--summary compact output --all expand truncated lists
|
||||
--json redacted report
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
source: cli/src/doctor/output.rs
|
||||
expression: "render_human_report(&report, detailed_all_no_color_unicode_options())"
|
||||
---
|
||||
aKode Doctor v0.0.0
|
||||
|
||||
Notes
|
||||
⚠ mcp missing inputs
|
||||
─────────────────────────────────────────────────────────────
|
||||
|
||||
Configuration
|
||||
⚠ mcp missing inputs
|
||||
demo bearer token env var DOCS_TOKEN is not set
|
||||
DEMO header env var DOCS_SECRET is not set
|
||||
stdio env var DOCS_TOKEN is not set
|
||||
npm:@modelcontextprotocol/server-sequential.thinking env var DOCS_TOKEN is not set
|
||||
typo bearer token env var <redacted> is not set
|
||||
|
||||
─────────────────────────────────────────────────────────────
|
||||
0 ok · 1 notes · 1 warn · 0 fail degraded
|
||||
|
||||
--summary compact output --all expand truncated lists
|
||||
--json redacted report
|
||||
182
akode-rs/cli/src/doctor/system.rs
Normal file
182
akode-rs/cli/src/doctor/system.rs
Normal file
@@ -0,0 +1,182 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::env;
|
||||
|
||||
use super::DoctorCheck;
|
||||
use super::LOCALE_ENV_VARS;
|
||||
|
||||
const EDITOR_ENV_VARS: &[&str] = &["VISUAL", "EDITOR"];
|
||||
const PAGER_ENV_VARS: &[&str] = &["PAGER", "GIT_PAGER", "GH_PAGER", "LESS"];
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
struct SystemCheckInputs {
|
||||
os: String,
|
||||
os_type: String,
|
||||
os_version: String,
|
||||
os_language: Option<String>,
|
||||
locale_env: BTreeMap<String, String>,
|
||||
editor_env: BTreeMap<String, String>,
|
||||
pager_env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl SystemCheckInputs {
|
||||
fn detect() -> Self {
|
||||
let info = os_info::get();
|
||||
let locale_env = LOCALE_ENV_VARS
|
||||
.iter()
|
||||
.filter_map(|name| {
|
||||
env::var(name)
|
||||
.ok()
|
||||
.map(|value| ((*name).to_string(), value))
|
||||
})
|
||||
.collect();
|
||||
let editor_env = EDITOR_ENV_VARS
|
||||
.iter()
|
||||
.map(|name| {
|
||||
let value = env::var_os(name)
|
||||
.map(|value| value.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| "not set".to_string());
|
||||
((*name).to_string(), value)
|
||||
})
|
||||
.collect();
|
||||
let pager_env = PAGER_ENV_VARS
|
||||
.iter()
|
||||
.filter_map(|name| {
|
||||
env::var_os(name)
|
||||
.map(|value| ((*name).to_string(), value.to_string_lossy().into_owned()))
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
os: info.to_string(),
|
||||
os_type: info.os_type().to_string(),
|
||||
os_version: info.version().to_string(),
|
||||
os_language: sys_locale::get_locale(),
|
||||
locale_env,
|
||||
editor_env,
|
||||
pager_env,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn system_check() -> DoctorCheck {
|
||||
system_check_from_inputs(SystemCheckInputs::detect())
|
||||
}
|
||||
|
||||
fn system_check_from_inputs(inputs: SystemCheckInputs) -> DoctorCheck {
|
||||
let mut details = vec![
|
||||
format!("os: {}", inputs.os),
|
||||
format!("os type: {}", inputs.os_type),
|
||||
format!("os version: {}", inputs.os_version),
|
||||
];
|
||||
if let Some(language) = inputs.os_language.as_deref() {
|
||||
details.push(format!("os language: {language}"));
|
||||
} else {
|
||||
details.push("os language: unavailable".to_string());
|
||||
}
|
||||
for name in LOCALE_ENV_VARS {
|
||||
if let Some(value) = inputs.locale_env.get(*name) {
|
||||
details.push(format!("{name}: {value}"));
|
||||
}
|
||||
}
|
||||
for name in EDITOR_ENV_VARS {
|
||||
if let Some(value) = inputs.editor_env.get(*name) {
|
||||
details.push(format!("{name}: {value}"));
|
||||
}
|
||||
}
|
||||
for name in PAGER_ENV_VARS {
|
||||
if let Some(value) = inputs.pager_env.get(*name) {
|
||||
details.push(format!("{name}: {value}"));
|
||||
}
|
||||
}
|
||||
|
||||
let summary = inputs
|
||||
.os_language
|
||||
.as_deref()
|
||||
.map(|language| format!("OS language {language}"))
|
||||
.unwrap_or_else(|| "OS language unavailable".to_string());
|
||||
DoctorCheck::new(
|
||||
"system.environment",
|
||||
"system",
|
||||
super::CheckStatus::Ok,
|
||||
summary,
|
||||
)
|
||||
.details(details)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn system_check_reports_os_language_locale_editor_and_pager_env() {
|
||||
let mut locale_env = BTreeMap::new();
|
||||
locale_env.insert("LANG".to_string(), "en_US.UTF-8".to_string());
|
||||
let editor_env = BTreeMap::from([
|
||||
("EDITOR".to_string(), "vim".to_string()),
|
||||
("VISUAL".to_string(), "code --wait".to_string()),
|
||||
]);
|
||||
let pager_env = BTreeMap::from([
|
||||
("GH_PAGER".to_string(), "less".to_string()),
|
||||
("GIT_PAGER".to_string(), "delta".to_string()),
|
||||
("LESS".to_string(), "-FRX".to_string()),
|
||||
("PAGER".to_string(), "less -R".to_string()),
|
||||
]);
|
||||
let check = system_check_from_inputs(SystemCheckInputs {
|
||||
os: "macOS 15.0".to_string(),
|
||||
os_type: "macos".to_string(),
|
||||
os_version: "15.0".to_string(),
|
||||
os_language: Some("en-US".to_string()),
|
||||
locale_env,
|
||||
editor_env,
|
||||
pager_env,
|
||||
});
|
||||
|
||||
assert_eq!(check.summary, "OS language en-US");
|
||||
assert_eq!(
|
||||
check.details,
|
||||
vec![
|
||||
"os: macOS 15.0",
|
||||
"os type: macos",
|
||||
"os version: 15.0",
|
||||
"os language: en-US",
|
||||
"LANG: en_US.UTF-8",
|
||||
"VISUAL: code --wait",
|
||||
"EDITOR: vim",
|
||||
"PAGER: less -R",
|
||||
"GIT_PAGER: delta",
|
||||
"GH_PAGER: less",
|
||||
"LESS: -FRX",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_check_handles_missing_os_language() {
|
||||
let check = system_check_from_inputs(SystemCheckInputs {
|
||||
os: "Linux".to_string(),
|
||||
os_type: "linux".to_string(),
|
||||
os_version: "unknown".to_string(),
|
||||
os_language: None,
|
||||
locale_env: BTreeMap::new(),
|
||||
editor_env: BTreeMap::from([
|
||||
("EDITOR".to_string(), "not set".to_string()),
|
||||
("VISUAL".to_string(), "not set".to_string()),
|
||||
]),
|
||||
pager_env: BTreeMap::new(),
|
||||
});
|
||||
|
||||
assert_eq!(check.summary, "OS language unavailable");
|
||||
assert_eq!(
|
||||
check.details,
|
||||
vec![
|
||||
"os: Linux",
|
||||
"os type: linux",
|
||||
"os version: unknown",
|
||||
"os language: unavailable",
|
||||
"VISUAL: not set",
|
||||
"EDITOR: not set",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
1434
akode-rs/cli/src/doctor/thread_inventory.rs
Normal file
1434
akode-rs/cli/src/doctor/thread_inventory.rs
Normal file
File diff suppressed because it is too large
Load Diff
423
akode-rs/cli/src/doctor/title.rs
Normal file
423
akode-rs/cli/src/doctor/title.rs
Normal file
@@ -0,0 +1,423 @@
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use akode_config::ConfigLayerSource;
|
||||
use akode_core::config::Config;
|
||||
use akode_git_utils::get_git_repo_root;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
|
||||
const DEFAULT_TERMINAL_TITLE_ITEMS: &[&str] = &["activity", "project-name"];
|
||||
const PROJECT_TITLE_MAX_CHARS: usize = 24;
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
struct TerminalTitleInputs {
|
||||
configured_items: Option<Vec<String>>,
|
||||
cwd: PathBuf,
|
||||
project_root: Option<ProjectTitleRoot>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
struct ProjectTitleRoot {
|
||||
source: &'static str,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
pub(super) fn terminal_title_check(config: &Config) -> DoctorCheck {
|
||||
terminal_title_check_from_inputs(TerminalTitleInputs {
|
||||
configured_items: config.tui_terminal_title.clone(),
|
||||
cwd: config.cwd.to_path_buf(),
|
||||
project_root: terminal_title_project_root(config, &config.cwd),
|
||||
})
|
||||
}
|
||||
|
||||
fn terminal_title_check_from_inputs(inputs: TerminalTitleInputs) -> DoctorCheck {
|
||||
let (source, items, invalid_items) = match inputs.configured_items {
|
||||
Some(items) if items.is_empty() => ("disabled", Vec::new(), Vec::new()),
|
||||
Some(items) => {
|
||||
let (items, invalid_items) = parse_terminal_title_items(items);
|
||||
("configured", items, invalid_items)
|
||||
}
|
||||
None => (
|
||||
"default",
|
||||
DEFAULT_TERMINAL_TITLE_ITEMS
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect(),
|
||||
Vec::new(),
|
||||
),
|
||||
};
|
||||
let mut details = vec![
|
||||
format!("terminal title source: {source}"),
|
||||
format!(
|
||||
"terminal title items: {}",
|
||||
if items.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
items.join(", ")
|
||||
}
|
||||
),
|
||||
format!("terminal title activity: {}", activity_enabled(&items)),
|
||||
];
|
||||
if !invalid_items.is_empty() {
|
||||
details.push(format!(
|
||||
"terminal title invalid items: {}",
|
||||
invalid_items.join(", ")
|
||||
));
|
||||
}
|
||||
|
||||
if project_title_selected(&items) {
|
||||
let (project_source, project_value) =
|
||||
project_title_candidate(inputs.project_root, &inputs.cwd);
|
||||
details.push(format!("terminal title project source: {project_source}"));
|
||||
if let Some(project_value) = project_value {
|
||||
details.push(format!("terminal title project value: {project_value}"));
|
||||
}
|
||||
}
|
||||
|
||||
let status = if invalid_items.is_empty() {
|
||||
CheckStatus::Ok
|
||||
} else {
|
||||
CheckStatus::Warning
|
||||
};
|
||||
let summary = if invalid_items.is_empty() {
|
||||
format!("terminal title {source}")
|
||||
} else {
|
||||
format!("terminal title {source} with invalid items")
|
||||
};
|
||||
let mut check = DoctorCheck::new("terminal.title", "title", status, summary).details(details);
|
||||
if !invalid_items.is_empty() {
|
||||
check = check.issue(
|
||||
super::DoctorIssue::new(
|
||||
CheckStatus::Warning,
|
||||
"terminal title configuration contains unknown item identifiers",
|
||||
)
|
||||
.measured(invalid_items.join(", "))
|
||||
.expected("known terminal title item identifiers")
|
||||
.remedy("Remove or replace the unknown entries in [tui].terminal_title.")
|
||||
.field("terminal title invalid items"),
|
||||
);
|
||||
}
|
||||
check
|
||||
}
|
||||
|
||||
fn parse_terminal_title_items(items: Vec<String>) -> (Vec<String>, Vec<String>) {
|
||||
let mut invalid = Vec::new();
|
||||
let mut invalid_seen = HashSet::new();
|
||||
let mut parsed = Vec::new();
|
||||
for item in items {
|
||||
match terminal_title_item_id(&item) {
|
||||
Some(id) => parsed.push(id.to_string()),
|
||||
None => {
|
||||
if invalid_seen.insert(item.clone()) {
|
||||
invalid.push(format!(r#""{item}""#));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(parsed, invalid)
|
||||
}
|
||||
|
||||
fn terminal_title_item_id(item: &str) -> Option<&'static str> {
|
||||
match item {
|
||||
"app-name" => Some("app-name"),
|
||||
"project-name" | "project" => Some("project-name"),
|
||||
"current-dir" => Some("current-dir"),
|
||||
"activity" | "spinner" => Some("activity"),
|
||||
"run-state" | "status" => Some("run-state"),
|
||||
"thread-title" | "thread" => Some("thread-title"),
|
||||
"git-branch" => Some("git-branch"),
|
||||
"context-remaining" => Some("context-remaining"),
|
||||
"context-used" | "context-usage" => Some("context-used"),
|
||||
"five-hour-limit" => Some("five-hour-limit"),
|
||||
"weekly-limit" => Some("weekly-limit"),
|
||||
"thread-credits" => Some("thread-credits"),
|
||||
"estimated-thread-cost" => Some("estimated-thread-cost"),
|
||||
"codex-version" => Some("codex-version"),
|
||||
"used-tokens" => Some("used-tokens"),
|
||||
"total-input-tokens" => Some("total-input-tokens"),
|
||||
"total-output-tokens" => Some("total-output-tokens"),
|
||||
"thread-id" | "session-id" => Some("thread-id"),
|
||||
"fast-mode" => Some("fast-mode"),
|
||||
"model" | "model-name" => Some("model"),
|
||||
"model-with-reasoning" => Some("model-with-reasoning"),
|
||||
"reasoning" => Some("reasoning"),
|
||||
"task-progress" => Some("task-progress"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn activity_enabled(items: &[String]) -> bool {
|
||||
items
|
||||
.iter()
|
||||
.any(|item| item == "activity" || item == "spinner")
|
||||
}
|
||||
|
||||
fn project_title_selected(items: &[String]) -> bool {
|
||||
items
|
||||
.iter()
|
||||
.any(|item| item == "project-name" || item == "project")
|
||||
}
|
||||
|
||||
fn terminal_title_project_root(config: &Config, cwd: &Path) -> Option<ProjectTitleRoot> {
|
||||
if let Some(repo_root) = get_git_repo_root(cwd) {
|
||||
return Some(ProjectTitleRoot {
|
||||
source: "git repo root",
|
||||
path: repo_root,
|
||||
});
|
||||
}
|
||||
|
||||
config
|
||||
.config_layer_stack
|
||||
.all_layers_low_to_high()
|
||||
.find_map(|layer| match &layer.name {
|
||||
ConfigLayerSource::Project { dot_codex_folder } => dot_codex_folder
|
||||
.as_path()
|
||||
.parent()
|
||||
.map(|root| ProjectTitleRoot {
|
||||
source: "project config",
|
||||
path: root.to_path_buf(),
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn project_title_candidate(
|
||||
project_root: Option<ProjectTitleRoot>,
|
||||
cwd: &Path,
|
||||
) -> (&'static str, Option<String>) {
|
||||
if let Some(project_root) = project_root {
|
||||
return (
|
||||
project_root.source,
|
||||
Some(truncate_title_part(path_display_name(&project_root.path))),
|
||||
);
|
||||
}
|
||||
("cwd", Some(truncate_title_part(path_display_name(cwd))))
|
||||
}
|
||||
|
||||
fn path_display_name(path: &Path) -> String {
|
||||
path.file_name()
|
||||
.map(|name| name.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| path.display().to_string())
|
||||
}
|
||||
|
||||
fn truncate_title_part(value: String) -> String {
|
||||
let mut graphemes = value.graphemes(true);
|
||||
let head = graphemes
|
||||
.by_ref()
|
||||
.take(PROJECT_TITLE_MAX_CHARS)
|
||||
.collect::<String>();
|
||||
if graphemes.next().is_none() || PROJECT_TITLE_MAX_CHARS <= 3 {
|
||||
return head;
|
||||
}
|
||||
|
||||
let mut truncated = head
|
||||
.graphemes(true)
|
||||
.take(PROJECT_TITLE_MAX_CHARS - 3)
|
||||
.collect::<String>();
|
||||
truncated.push_str("...");
|
||||
truncated
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn terminal_title_reports_default_items_and_git_project_name() {
|
||||
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
|
||||
configured_items: None,
|
||||
cwd: PathBuf::from("/repo/subdir"),
|
||||
project_root: Some(ProjectTitleRoot {
|
||||
source: "git repo root",
|
||||
path: PathBuf::from("/repo"),
|
||||
}),
|
||||
});
|
||||
|
||||
assert_eq!(check.summary, "terminal title default");
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"terminal title items: activity, project-name".to_string())
|
||||
);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"terminal title project source: git repo root".to_string())
|
||||
);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"terminal title project value: repo".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_title_reports_disabled_configuration() {
|
||||
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
|
||||
configured_items: Some(Vec::new()),
|
||||
cwd: PathBuf::from("/workspace"),
|
||||
project_root: None,
|
||||
});
|
||||
|
||||
assert_eq!(check.summary, "terminal title disabled");
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"terminal title items: none".to_string())
|
||||
);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"terminal title activity: false".to_string())
|
||||
);
|
||||
assert!(
|
||||
!check
|
||||
.details
|
||||
.iter()
|
||||
.any(|detail| detail.starts_with("terminal title project "))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_title_reports_project_config_fallback() {
|
||||
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
|
||||
configured_items: Some(vec!["project".to_string()]),
|
||||
cwd: PathBuf::from("/workspace/project/subdir"),
|
||||
project_root: Some(ProjectTitleRoot {
|
||||
source: "project config",
|
||||
path: PathBuf::from("/workspace/project"),
|
||||
}),
|
||||
});
|
||||
|
||||
assert_eq!(check.summary, "terminal title configured");
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"terminal title project source: project config".to_string())
|
||||
);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"terminal title project value: project".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_title_accepts_configured_items() {
|
||||
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
|
||||
configured_items: Some(vec![
|
||||
"thread-credits".to_string(),
|
||||
"estimated-thread-cost".to_string(),
|
||||
"fast-mode".to_string(),
|
||||
]),
|
||||
cwd: PathBuf::from("/workspace/project"),
|
||||
project_root: None,
|
||||
});
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Ok);
|
||||
assert_eq!(check.summary, "terminal title configured");
|
||||
assert!(check.details.contains(
|
||||
&"terminal title items: thread-credits, estimated-thread-cost, fast-mode".to_string()
|
||||
));
|
||||
assert!(check.issues.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_title_omits_project_when_project_item_is_not_selected() {
|
||||
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
|
||||
configured_items: Some(vec!["model".to_string()]),
|
||||
cwd: PathBuf::from("/workspace/project"),
|
||||
project_root: Some(ProjectTitleRoot {
|
||||
source: "project config",
|
||||
path: PathBuf::from("/workspace/project"),
|
||||
}),
|
||||
});
|
||||
|
||||
assert_eq!(check.summary, "terminal title configured");
|
||||
assert!(
|
||||
!check
|
||||
.details
|
||||
.iter()
|
||||
.any(|detail| detail.starts_with("terminal title project "))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_title_warns_for_invalid_configured_items() {
|
||||
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
|
||||
configured_items: Some(vec![
|
||||
"project".to_string(),
|
||||
"bogus".to_string(),
|
||||
"activity".to_string(),
|
||||
"bogus".to_string(),
|
||||
]),
|
||||
cwd: PathBuf::from("/workspace/project"),
|
||||
project_root: Some(ProjectTitleRoot {
|
||||
source: "project config",
|
||||
path: PathBuf::from("/workspace/project"),
|
||||
}),
|
||||
});
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert_eq!(
|
||||
check.summary,
|
||||
"terminal title configured with invalid items"
|
||||
);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"terminal title items: project-name, activity".to_string())
|
||||
);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&r#"terminal title invalid items: "bogus""#.to_string())
|
||||
);
|
||||
assert_eq!(check.issues.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_title_warns_when_all_configured_items_are_invalid() {
|
||||
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
|
||||
configured_items: Some(vec!["bogus".to_string()]),
|
||||
cwd: PathBuf::from("/workspace/project"),
|
||||
project_root: None,
|
||||
});
|
||||
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"terminal title items: none".to_string())
|
||||
);
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&r#"terminal title invalid items: "bogus""#.to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_title_project_value_uses_tui_truncation_shape() {
|
||||
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
|
||||
configured_items: Some(vec!["project".to_string()]),
|
||||
cwd: PathBuf::from("/workspace/abcdefghijklmnopqrstuvwxyz"),
|
||||
project_root: Some(ProjectTitleRoot {
|
||||
source: "project config",
|
||||
path: PathBuf::from("/workspace/abcdefghijklmnopqrstuvwxyz"),
|
||||
}),
|
||||
});
|
||||
|
||||
assert!(
|
||||
check
|
||||
.details
|
||||
.contains(&"terminal title project value: abcdefghijklmnopqrstu...".to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
121
akode-rs/cli/src/doctor/updates.rs
Normal file
121
akode-rs/cli/src/doctor/updates.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
//! Diagnoses whether Codex update paths target the running installation.
|
||||
//!
|
||||
//! aKode: diagnostics are local only (cached version metadata and install-channel hints).
|
||||
//! There are no latest-version probes (GitHub, Homebrew) and no desktop appcast probes.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use akode_core::config::Config;
|
||||
use akode_install_context::InstallContext;
|
||||
use akode_install_context::InstallMethod;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
use super::doctor_install_context;
|
||||
use super::doctor_managed_by_npm;
|
||||
|
||||
const VERSION_FILE_NAME: &str = "version.json";
|
||||
|
||||
/// Builds the update-health row for the current installation from local state only.
|
||||
pub(super) async fn updates_check(config: &Config) -> DoctorCheck {
|
||||
let current_exe = std::env::current_exe().ok();
|
||||
let install_context = doctor_install_context(current_exe.as_deref());
|
||||
let mut details = vec![
|
||||
format!(
|
||||
"check for update on startup: {}",
|
||||
config.check_for_update_on_startup
|
||||
),
|
||||
format!("update action: {}", update_action_label(&install_context)),
|
||||
];
|
||||
let version_file = config.codex_home.join(VERSION_FILE_NAME);
|
||||
push_cached_version_details(&mut details, &version_file);
|
||||
|
||||
if doctor_managed_by_npm(current_exe.as_deref()) {
|
||||
details
|
||||
.push("npm update target: not inspected (PATH helpers are not executed)".to_string());
|
||||
}
|
||||
details.push("latest version probe: disabled (no network update checks)".to_string());
|
||||
|
||||
DoctorCheck::new(
|
||||
"updates.status",
|
||||
"updates",
|
||||
CheckStatus::Ok,
|
||||
"update configuration is locally consistent",
|
||||
)
|
||||
.details(details)
|
||||
}
|
||||
|
||||
fn push_cached_version_details(details: &mut Vec<String>, version_file: &Path) {
|
||||
details.push(format!("version cache: {}", version_file.display()));
|
||||
match std::fs::read_to_string(version_file) {
|
||||
Ok(contents) => match serde_json::from_str::<VersionInfo>(&contents) {
|
||||
Ok(info) => {
|
||||
details.push(format!("cached latest version: {}", info.latest_version));
|
||||
if let Some(last_checked_at) = info.last_checked_at {
|
||||
details.push(format!("last checked at: {last_checked_at}"));
|
||||
}
|
||||
if let Some(dismissed_version) = info.dismissed_version {
|
||||
details.push(format!("dismissed version: {dismissed_version}"));
|
||||
}
|
||||
}
|
||||
Err(err) => details.push(format!("version cache parse: {err}")),
|
||||
},
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
|
||||
details.push("version cache: missing".to_string());
|
||||
}
|
||||
Err(err) => details.push(format!("version cache read: {err}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn update_action_label(context: &InstallContext) -> &'static str {
|
||||
match &context.method {
|
||||
InstallMethod::Npm => "npm install -g @openai/codex",
|
||||
InstallMethod::Bun => "bun install -g @openai/codex",
|
||||
InstallMethod::VitePlus => "vp install -g @openai/codex",
|
||||
InstallMethod::Pnpm => "pnpm add -g @openai/codex",
|
||||
InstallMethod::Brew => "brew upgrade --cask codex",
|
||||
InstallMethod::Standalone { .. } => "standalone installer",
|
||||
InstallMethod::Other => "manual or unknown",
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct VersionInfo {
|
||||
latest_version: String,
|
||||
#[serde(default)]
|
||||
last_checked_at: Option<String>,
|
||||
#[serde(default)]
|
||||
dismissed_version: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn update_action_labels_install_contexts() {
|
||||
assert_eq!(
|
||||
update_action_label(&InstallContext {
|
||||
method: InstallMethod::Npm,
|
||||
package_layout: None,
|
||||
}),
|
||||
"npm install -g @openai/codex"
|
||||
);
|
||||
assert_eq!(
|
||||
update_action_label(&InstallContext {
|
||||
method: InstallMethod::Pnpm,
|
||||
package_layout: None,
|
||||
}),
|
||||
"pnpm add -g @openai/codex"
|
||||
);
|
||||
assert_eq!(
|
||||
update_action_label(&InstallContext {
|
||||
method: InstallMethod::Other,
|
||||
package_layout: None,
|
||||
}),
|
||||
"manual or unknown"
|
||||
);
|
||||
}
|
||||
}
|
||||
160
akode-rs/cli/src/doctor/windows_dev_drive.rs
Normal file
160
akode-rs/cli/src/doctor/windows_dev_drive.rs
Normal file
@@ -0,0 +1,160 @@
|
||||
use std::ffi::OsString;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
|
||||
use akode_git_utils::get_git_repo_root;
|
||||
use os_info::Version;
|
||||
use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetVolumePathNameW;
|
||||
use windows_sys::Win32::System::IO::DeviceIoControl;
|
||||
use windows_sys::Win32::System::WindowsProgramming::DRIVE_FIXED;
|
||||
use windows_sys::Win32::System::WindowsProgramming::DRIVE_NO_ROOT_DIR;
|
||||
use windows_sys::Win32::System::WindowsProgramming::DRIVE_UNKNOWN;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
|
||||
const ID: &str = "git.worktree.dev_drive";
|
||||
const DEV_VOLUME: u32 = 0x0000_2000;
|
||||
const TRUSTED_VOLUME: u32 = 0x0000_4000;
|
||||
const QUERY_PERSISTENT_VOLUME_STATE: u32 = 0x0009_023c;
|
||||
|
||||
#[repr(C)]
|
||||
struct PersistentVolumeState {
|
||||
flags: u32,
|
||||
mask: u32,
|
||||
version: u32,
|
||||
reserved: u32,
|
||||
}
|
||||
|
||||
pub(super) fn check(cwd: &Path) -> DoctorCheck {
|
||||
let Some(worktree) = get_git_repo_root(cwd) else {
|
||||
return DoctorCheck::new(ID, "git", CheckStatus::Ok, "no Git worktree is active");
|
||||
};
|
||||
if matches!(
|
||||
os_info::get().version(),
|
||||
Version::Semantic(_, _, build) if *build < 22_621
|
||||
) {
|
||||
return DoctorCheck::new(
|
||||
ID,
|
||||
"git",
|
||||
CheckStatus::Ok,
|
||||
"Windows Dev Drives are unavailable on this Windows version",
|
||||
);
|
||||
}
|
||||
|
||||
match volume_flags(&worktree) {
|
||||
Ok(flags) if flags & DEV_VOLUME == 0 => DoctorCheck::new(
|
||||
ID,
|
||||
"git",
|
||||
CheckStatus::Warning,
|
||||
"this worktree is not on a Windows Dev Drive; moving it to a trusted Dev Drive can significantly improve repository and filesystem performance",
|
||||
)
|
||||
.remediation(
|
||||
"create a trusted Windows Dev Drive for source repositories: https://learn.microsoft.com/en-us/windows/dev-drive/",
|
||||
),
|
||||
Ok(flags) if flags & TRUSTED_VOLUME == 0 => DoctorCheck::new(
|
||||
ID,
|
||||
"git",
|
||||
CheckStatus::Warning,
|
||||
"the active Git worktree is on an untrusted Windows Dev Drive",
|
||||
)
|
||||
.remediation(
|
||||
"ask your administrator to trust the Windows Dev Drive: https://learn.microsoft.com/en-us/windows/dev-drive/#how-do-i-designate-a-dev-drive-as-trusted",
|
||||
),
|
||||
Ok(_) => DoctorCheck::new(
|
||||
ID,
|
||||
"git",
|
||||
CheckStatus::Ok,
|
||||
"the active Git worktree is on a trusted Windows Dev Drive",
|
||||
),
|
||||
Err(error) => DoctorCheck::new(
|
||||
ID,
|
||||
"git",
|
||||
CheckStatus::Warning,
|
||||
"the active Git worktree's Windows Dev Drive state could not be inspected",
|
||||
)
|
||||
.detail(format!("filesystem error: {:?}", error.kind()))
|
||||
.remediation("check access to the Git worktree and its Windows storage volume"),
|
||||
}
|
||||
}
|
||||
|
||||
fn volume_flags(path: &Path) -> io::Result<u32> {
|
||||
let path = path
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
let mut volume = vec![0_u16; path.len().max(261)];
|
||||
if unsafe { GetVolumePathNameW(path.as_ptr(), volume.as_mut_ptr(), volume.len() as u32) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
match unsafe { GetDriveTypeW(volume.as_ptr()) } {
|
||||
DRIVE_UNKNOWN | DRIVE_NO_ROOT_DIR => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"the Windows storage volume could not be determined",
|
||||
));
|
||||
}
|
||||
DRIVE_FIXED => {}
|
||||
_ => return Ok(0),
|
||||
}
|
||||
|
||||
let length = volume
|
||||
.iter()
|
||||
.position(|character| *character == 0)
|
||||
.unwrap_or(volume.len());
|
||||
let root = PathBuf::from(OsString::from_wide(&volume[..length]));
|
||||
let handle = OpenOptions::new()
|
||||
.access_mode(FILE_READ_ATTRIBUTES)
|
||||
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
|
||||
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
|
||||
.open(root)?;
|
||||
let mut state = PersistentVolumeState {
|
||||
flags: 0,
|
||||
mask: DEV_VOLUME | TRUSTED_VOLUME,
|
||||
version: 1,
|
||||
reserved: 0,
|
||||
};
|
||||
let state_size = std::mem::size_of::<PersistentVolumeState>() as u32;
|
||||
let state_ptr = ptr::from_mut(&mut state);
|
||||
let mut bytes_returned = 0;
|
||||
if unsafe {
|
||||
DeviceIoControl(
|
||||
handle.as_raw_handle(),
|
||||
QUERY_PERSISTENT_VOLUME_STATE,
|
||||
state_ptr.cast_const().cast(),
|
||||
state_size,
|
||||
state_ptr.cast(),
|
||||
state_size,
|
||||
&mut bytes_returned,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
let error = io::Error::last_os_error();
|
||||
return if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
|
||||
Ok(0)
|
||||
} else {
|
||||
Err(error)
|
||||
};
|
||||
}
|
||||
|
||||
Ok(state.flags)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "windows_dev_drive_tests.rs"]
|
||||
mod tests;
|
||||
16
akode-rs/cli/src/doctor/windows_dev_drive_tests.rs
Normal file
16
akode-rs/cli/src/doctor/windows_dev_drive_tests.rs
Normal file
@@ -0,0 +1,16 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::DEV_VOLUME;
|
||||
use super::volume_flags;
|
||||
|
||||
#[test]
|
||||
fn the_windows_system_volume_is_not_a_dev_drive() {
|
||||
let system_root = std::env::var_os("SystemRoot")
|
||||
.map(PathBuf::from)
|
||||
.expect("Windows exposes its system directory");
|
||||
let flags = volume_flags(&system_root).expect("the system volume can be inspected");
|
||||
|
||||
assert_eq!(flags & DEV_VOLUME, 0);
|
||||
}
|
||||
29
akode-rs/cli/src/exec_server_args_tests.rs
Normal file
29
akode-rs/cli/src/exec_server_args_tests.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use clap::error::ErrorKind;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn exec_server_help_documents_remote_options() {
|
||||
let command = MultitoolCli::command()
|
||||
.term_width(80)
|
||||
.mut_subcommand("exec-server", |command| {
|
||||
command
|
||||
.mut_arg("exit_on_stdin_close", |arg| arg.hide_env_values(true))
|
||||
.mut_arg("proxy_private_ips_via_upstream", |arg| {
|
||||
arg.hide_env_values(true)
|
||||
})
|
||||
});
|
||||
let help = command
|
||||
.try_get_matches_from(["codex", "exec-server", "--help"])
|
||||
.expect_err("help should exit before running the executor");
|
||||
assert_eq!(help.kind(), ErrorKind::DisplayHelp);
|
||||
let help_text = help
|
||||
.to_string()
|
||||
.lines()
|
||||
.map(str::trim_end)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!(help_text);
|
||||
}
|
||||
23
akode-rs/cli/src/exit_status.rs
Normal file
23
akode-rs/cli/src/exit_status.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn handle_exit_status(status: std::process::ExitStatus) -> ! {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
|
||||
// Use ExitStatus to derive the exit code.
|
||||
if let Some(code) = status.code() {
|
||||
std::process::exit(code);
|
||||
} else if let Some(signal) = status.signal() {
|
||||
std::process::exit(128 + signal);
|
||||
} else {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn handle_exit_status(status: std::process::ExitStatus) -> ! {
|
||||
if let Some(code) = status.code() {
|
||||
std::process::exit(code);
|
||||
} else {
|
||||
// Rare on Windows, but if it happens: use fallback code.
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
188
akode-rs/cli/src/lib.rs
Normal file
188
akode-rs/cli/src/lib.rs
Normal file
@@ -0,0 +1,188 @@
|
||||
pub(crate) mod debug_sandbox;
|
||||
mod exit_status;
|
||||
pub mod local_config;
|
||||
pub(crate) mod login;
|
||||
|
||||
use clap::Args;
|
||||
use clap::Parser;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_cli::CliConfigOverrides;
|
||||
use akode_utils_cli::ProfileV2Name;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub use debug_sandbox::run_command_under_landlock;
|
||||
pub use debug_sandbox::run_command_under_seatbelt;
|
||||
pub use debug_sandbox::run_command_under_windows_sandbox;
|
||||
pub use login::read_api_key_from_stdin;
|
||||
pub use login::run_login_provider_api_key;
|
||||
pub use login::run_login_status;
|
||||
pub use login::run_login_with_api_key;
|
||||
pub use login::run_logout;
|
||||
pub use login::run_logout_provider;
|
||||
|
||||
#[derive(Debug, Default, Args)]
|
||||
pub struct SandboxStateArgs {
|
||||
/// Opaque JSON value from `codex/sandbox-state` to apply directly.
|
||||
#[arg(
|
||||
long = "sandbox-state-json",
|
||||
value_name = "JSON",
|
||||
conflicts_with_all = ["permissions_profile", "cwd", "include_managed_config"]
|
||||
)]
|
||||
pub sandbox_state_json: Option<String>,
|
||||
|
||||
/// Add a readable root to the supplied sandbox state. Repeat for multiple roots.
|
||||
#[arg(
|
||||
long,
|
||||
requires = "sandbox_state_json",
|
||||
value_parser = parse_absolute_path
|
||||
)]
|
||||
pub sandbox_state_readable_root: Vec<AbsolutePathBuf>,
|
||||
|
||||
/// Disable direct network access in the supplied sandbox state.
|
||||
#[arg(long, requires = "sandbox_state_json", default_value_t = false)]
|
||||
pub sandbox_state_disable_network: bool,
|
||||
}
|
||||
|
||||
// These command structs share common sandbox options, but remain separate
|
||||
// because each host backend has a slightly different option surface.
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct SeatbeltCommand {
|
||||
#[command(flatten)]
|
||||
pub sandbox_state: SandboxStateArgs,
|
||||
|
||||
/// Named permissions profile to apply from the active configuration stack.
|
||||
#[arg(
|
||||
long = "permission-profile",
|
||||
alias = "permissions-profile",
|
||||
short = 'P',
|
||||
value_name = "NAME"
|
||||
)]
|
||||
pub permissions_profile: Option<String>,
|
||||
|
||||
/// Layer $AKODE_HOME/<name>.config.toml on top of the base user config.
|
||||
#[arg(long = "profile", short = 'p')]
|
||||
pub config_profile: Option<ProfileV2Name>,
|
||||
|
||||
/// Working directory used for profile resolution and command execution.
|
||||
#[arg(
|
||||
short = 'C',
|
||||
long = "cd",
|
||||
value_name = "DIR",
|
||||
requires = "permissions_profile"
|
||||
)]
|
||||
pub cwd: Option<PathBuf>,
|
||||
|
||||
/// Include managed requirements while resolving an explicit permissions profile.
|
||||
#[arg(
|
||||
long = "include-managed-config",
|
||||
default_value_t = false,
|
||||
requires = "permissions_profile"
|
||||
)]
|
||||
pub include_managed_config: bool,
|
||||
|
||||
/// Allow the sandboxed command to bind/connect AF_UNIX sockets rooted at this path. Relative paths are resolved against the current directory. Repeat to allow multiple paths.
|
||||
#[arg(long = "allow-unix-socket", value_parser = parse_absolute_path)]
|
||||
pub allow_unix_sockets: Vec<AbsolutePathBuf>,
|
||||
|
||||
/// While the command runs, capture macOS sandbox denials via `log stream` and print them after exit
|
||||
#[arg(long = "log-denials", default_value_t = false)]
|
||||
pub log_denials: bool,
|
||||
|
||||
#[clap(skip)]
|
||||
pub config_overrides: CliConfigOverrides,
|
||||
|
||||
/// Full command args to run under seatbelt.
|
||||
#[arg(trailing_var_arg = true)]
|
||||
pub command: Vec<String>,
|
||||
}
|
||||
|
||||
fn parse_absolute_path(raw: &str) -> Result<AbsolutePathBuf, String> {
|
||||
AbsolutePathBuf::relative_to_current_dir(raw)
|
||||
.map_err(|err| format!("invalid path {raw}: {err}"))
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct LandlockCommand {
|
||||
#[command(flatten)]
|
||||
pub sandbox_state: SandboxStateArgs,
|
||||
|
||||
/// Named permissions profile to apply from the active configuration stack.
|
||||
#[arg(
|
||||
long = "permission-profile",
|
||||
alias = "permissions-profile",
|
||||
short = 'P',
|
||||
value_name = "NAME"
|
||||
)]
|
||||
pub permissions_profile: Option<String>,
|
||||
|
||||
/// Layer $AKODE_HOME/<name>.config.toml on top of the base user config.
|
||||
#[arg(long = "profile", short = 'p')]
|
||||
pub config_profile: Option<ProfileV2Name>,
|
||||
|
||||
/// Working directory used for profile resolution and command execution.
|
||||
#[arg(
|
||||
short = 'C',
|
||||
long = "cd",
|
||||
value_name = "DIR",
|
||||
requires = "permissions_profile"
|
||||
)]
|
||||
pub cwd: Option<PathBuf>,
|
||||
|
||||
/// Include managed requirements while resolving an explicit permissions profile.
|
||||
#[arg(
|
||||
long = "include-managed-config",
|
||||
default_value_t = false,
|
||||
requires = "permissions_profile"
|
||||
)]
|
||||
pub include_managed_config: bool,
|
||||
|
||||
#[clap(skip)]
|
||||
pub config_overrides: CliConfigOverrides,
|
||||
|
||||
/// Full command args to run under the Linux sandbox.
|
||||
#[arg(trailing_var_arg = true)]
|
||||
pub command: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct WindowsCommand {
|
||||
#[command(flatten)]
|
||||
pub sandbox_state: SandboxStateArgs,
|
||||
|
||||
/// Named permissions profile to apply from the active configuration stack.
|
||||
#[arg(
|
||||
long = "permission-profile",
|
||||
alias = "permissions-profile",
|
||||
short = 'P',
|
||||
value_name = "NAME"
|
||||
)]
|
||||
pub permissions_profile: Option<String>,
|
||||
|
||||
/// Layer $AKODE_HOME/<name>.config.toml on top of the base user config.
|
||||
#[arg(long = "profile", short = 'p')]
|
||||
pub config_profile: Option<ProfileV2Name>,
|
||||
|
||||
/// Working directory used for profile resolution and command execution.
|
||||
#[arg(
|
||||
short = 'C',
|
||||
long = "cd",
|
||||
value_name = "DIR",
|
||||
requires = "permissions_profile"
|
||||
)]
|
||||
pub cwd: Option<PathBuf>,
|
||||
|
||||
/// Include managed requirements while resolving an explicit permissions profile.
|
||||
#[arg(
|
||||
long = "include-managed-config",
|
||||
default_value_t = false,
|
||||
requires = "permissions_profile"
|
||||
)]
|
||||
pub include_managed_config: bool,
|
||||
|
||||
#[clap(skip)]
|
||||
pub config_overrides: CliConfigOverrides,
|
||||
|
||||
/// Full command args to run under Windows restricted token sandbox.
|
||||
#[arg(trailing_var_arg = true)]
|
||||
pub command: Vec<String>,
|
||||
}
|
||||
53
akode-rs/cli/src/local_config.rs
Normal file
53
akode-rs/cli/src/local_config.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use akode_app_server::in_process::EmbeddedNetworkPolicy;
|
||||
use akode_core::config::Config;
|
||||
use akode_core::config::ConfigBuilder;
|
||||
use akode_core::config::ConfigOverrides;
|
||||
use akode_core::config::LoaderOverrides;
|
||||
use akode_core::config::find_codex_home;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_cli::CliConfigOverrides;
|
||||
|
||||
pub async fn load_config(
|
||||
config_overrides: &CliConfigOverrides,
|
||||
loader_overrides: LoaderOverrides,
|
||||
) -> Result<Config> {
|
||||
let mut config = config_builder(
|
||||
config_overrides,
|
||||
loader_overrides,
|
||||
ConfigOverrides::default(),
|
||||
)
|
||||
.await?
|
||||
.build()
|
||||
.await
|
||||
.context("failed to load configuration")?;
|
||||
config.config_layer_stack.ensure_config_server_applied()?;
|
||||
EmbeddedNetworkPolicy::default().activate(&mut config);
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Builds a config from local files only; aKode never fetches managed config
|
||||
/// bundles from a remote service.
|
||||
pub async fn config_builder(
|
||||
config_overrides: &CliConfigOverrides,
|
||||
loader_overrides: LoaderOverrides,
|
||||
harness_overrides: ConfigOverrides,
|
||||
) -> Result<ConfigBuilder> {
|
||||
let cli_overrides = config_overrides
|
||||
.parse_overrides()
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let codex_home = find_codex_home().context("failed to resolve AKODE_HOME")?;
|
||||
let cwd = match harness_overrides.cwd.as_deref() {
|
||||
Some(cwd) => AbsolutePathBuf::relative_to_current_dir(cwd),
|
||||
None => AbsolutePathBuf::current_dir(),
|
||||
}
|
||||
.context("failed to resolve current directory")?;
|
||||
|
||||
Ok(ConfigBuilder::default()
|
||||
.codex_home(codex_home.to_path_buf())
|
||||
.cli_overrides(cli_overrides)
|
||||
.loader_overrides(loader_overrides)
|
||||
.harness_overrides(harness_overrides)
|
||||
.fallback_cwd(Some(cwd.to_path_buf())))
|
||||
}
|
||||
400
akode-rs/cli/src/login.rs
Normal file
400
akode-rs/cli/src/login.rs
Normal file
@@ -0,0 +1,400 @@
|
||||
//! CLI login commands and their direct-user observability surfaces.
|
||||
//!
|
||||
//! The TUI path already installs a broader tracing stack with feedback, OpenTelemetry, and other
|
||||
//! interactive-session layers. Direct `akode login` intentionally does less: it preserves the
|
||||
//! existing stderr/browser UX and adds only a small file-backed tracing layer for login-specific
|
||||
//! targets. Keeping that setup local avoids pulling the TUI's session-oriented logging machinery
|
||||
//! into a one-shot CLI command while still producing a durable `akode-login.log` artifact that
|
||||
//! support can request from users.
|
||||
|
||||
use akode_core::config::Config;
|
||||
use akode_login::login_with_api_key;
|
||||
use akode_protocol::auth::AuthMode;
|
||||
use akode_protocol::config_types::ForcedLoginMethod;
|
||||
use akode_utils_cli::CliConfigOverrides;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::IsTerminal;
|
||||
use std::io::Read;
|
||||
use tracing_appender::non_blocking;
|
||||
use tracing_appender::non_blocking::WorkerGuard;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use tracing_subscriber::Layer;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
|
||||
const API_KEY_LOGIN_DISABLED_MESSAGE: &str =
|
||||
"API key login is disabled by the configured login restrictions.";
|
||||
const API_KEY_AUTHENTICATION_NOTICE: &str = "Authentication is checked when you send a request.";
|
||||
const DEFAULT_LOGIN_LOG_FILTER: &str =
|
||||
"akode_cli=info,akode_core=info,akode_login=info,akode_otel::auth_storage=warn";
|
||||
|
||||
/// Installs a small file-backed tracing layer for direct `akode login` flows.
|
||||
///
|
||||
/// This deliberately duplicates a narrow slice of the TUI logging setup instead of reusing it
|
||||
/// wholesale. The TUI stack includes session-oriented layers that are valuable for interactive
|
||||
/// runs but unnecessary for a one-shot login command. Keeping the direct CLI path local lets this
|
||||
/// command produce a durable `akode-login.log` artifact without coupling it to the TUI's broader
|
||||
/// telemetry and feedback initialization.
|
||||
fn init_login_file_logging(config: &Config) -> Option<WorkerGuard> {
|
||||
let log_dir = match akode_core::config::log_dir(config) {
|
||||
Ok(log_dir) => log_dir,
|
||||
Err(err) => {
|
||||
eprintln!("Warning: failed to resolve login log directory: {err}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(err) = std::fs::create_dir_all(&log_dir) {
|
||||
eprintln!(
|
||||
"Warning: failed to create login log directory {}: {err}",
|
||||
log_dir.display()
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut log_file_opts = OpenOptions::new();
|
||||
log_file_opts.create(true).append(true);
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
log_file_opts.mode(0o600);
|
||||
}
|
||||
|
||||
let log_path = log_dir.join("akode-login.log");
|
||||
let log_file = match log_file_opts.open(&log_path) {
|
||||
Ok(log_file) => log_file,
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"Warning: failed to open login log file {}: {err}",
|
||||
log_path.display()
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let (non_blocking, guard) = non_blocking(log_file);
|
||||
let env_filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new(DEFAULT_LOGIN_LOG_FILTER));
|
||||
let file_layer = tracing_subscriber::fmt::layer()
|
||||
.with_writer(non_blocking)
|
||||
.with_target(true)
|
||||
.with_ansi(false)
|
||||
.with_filter(env_filter);
|
||||
|
||||
// Direct `akode login` otherwise relies on ephemeral stderr and browser output.
|
||||
// Persist the same login targets to a file so support can inspect auth failures
|
||||
// without reproducing them through TUI or app-server.
|
||||
if let Err(err) = tracing_subscriber::registry().with(file_layer).try_init() {
|
||||
eprintln!(
|
||||
"Warning: failed to initialize login log file {}: {err}",
|
||||
log_path.display()
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(guard)
|
||||
}
|
||||
|
||||
/// Remote managed configuration (config server / cloud bundles) is not
|
||||
/// supported in aKode: requirements that demand it cannot be satisfied.
|
||||
async fn sign_in_to_config_server_and_reload_config(
|
||||
_config: &mut Config,
|
||||
_cli_config_overrides: &CliConfigOverrides,
|
||||
) -> std::io::Result<()> {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Unsupported,
|
||||
"remote managed configuration is not supported in aKode",
|
||||
))
|
||||
}
|
||||
|
||||
fn finish_login(result: std::io::Result<()>) -> ! {
|
||||
match result {
|
||||
Ok(_) => std::process::exit(0),
|
||||
Err(e) => {
|
||||
eprintln!("Error logging in: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_login_with_api_key(
|
||||
cli_config_overrides: CliConfigOverrides,
|
||||
api_key: String,
|
||||
) -> ! {
|
||||
let config = load_managed_login_config_or_exit(cli_config_overrides).await;
|
||||
let _login_log_guard = init_login_file_logging(&config);
|
||||
tracing::info!("starting api key login flow");
|
||||
|
||||
if !config
|
||||
.auth_config()
|
||||
.is_login_method_allowed(ForcedLoginMethod::Api)
|
||||
{
|
||||
eprintln!("{API_KEY_LOGIN_DISABLED_MESSAGE}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
match login_with_api_key(
|
||||
&config.codex_home,
|
||||
&api_key,
|
||||
config.cli_auth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind(),
|
||||
) {
|
||||
Ok(_) => {
|
||||
eprintln!("API key saved. {API_KEY_AUTHENTICATION_NOTICE}");
|
||||
std::process::exit(0);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Error logging in: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_api_key_from_stdin() -> String {
|
||||
read_stdin_secret(
|
||||
"--with-api-key expects the API key on stdin. Try piping it, e.g. `printenv OPENAI_API_KEY | akode login --with-api-key`.",
|
||||
"Reading API key from stdin...",
|
||||
"No API key provided via stdin.",
|
||||
)
|
||||
}
|
||||
|
||||
fn read_stdin_secret(terminal_message: &str, reading_message: &str, empty_message: &str) -> String {
|
||||
let mut stdin = std::io::stdin();
|
||||
|
||||
if stdin.is_terminal() {
|
||||
eprintln!("{terminal_message}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
eprintln!("{reading_message}");
|
||||
|
||||
let mut buffer = String::new();
|
||||
if let Err(err) = stdin.read_to_string(&mut buffer) {
|
||||
eprintln!("Failed to read stdin: {err}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
let secret = buffer.trim().to_string();
|
||||
if secret.is_empty() {
|
||||
eprintln!("{empty_message}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
secret
|
||||
}
|
||||
|
||||
/// Stores the API key of one model provider (`api_key = "keyring"`) in the configured
|
||||
/// provider key store (system keyring, or the private fallback file).
|
||||
pub async fn run_login_provider_api_key(
|
||||
cli_config_overrides: CliConfigOverrides,
|
||||
provider_id: String,
|
||||
api_key: String,
|
||||
) -> ! {
|
||||
let config = load_config_or_exit(cli_config_overrides).await;
|
||||
let _login_log_guard = init_login_file_logging(&config);
|
||||
tracing::info!("storing a provider API key");
|
||||
match config.model_providers.get(&provider_id) {
|
||||
Some(provider)
|
||||
if provider.api_key
|
||||
== Some(akode_model_provider_info::ProviderApiKeySource::Keyring) => {}
|
||||
Some(_) => eprintln!(
|
||||
"Warning: model_providers.{provider_id} does not set api_key = \"keyring\"; the stored key is used only after you add it."
|
||||
),
|
||||
None => eprintln!(
|
||||
"Warning: model provider `{provider_id}` is not defined in config.toml yet; add [model_providers.{provider_id}] with api_key = \"keyring\"."
|
||||
),
|
||||
}
|
||||
match akode_model_provider_info::save_provider_api_key(&provider_id, &api_key) {
|
||||
Ok(location) => {
|
||||
eprintln!(
|
||||
"API key for `{provider_id}` saved in {location}. {API_KEY_AUTHENTICATION_NOTICE}"
|
||||
);
|
||||
std::process::exit(0);
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("Error saving the API key: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the stored API key of one model provider.
|
||||
pub async fn run_logout_provider(
|
||||
cli_config_overrides: CliConfigOverrides,
|
||||
provider_id: String,
|
||||
) -> ! {
|
||||
let _config = load_config_or_exit(cli_config_overrides).await;
|
||||
match akode_model_provider_info::delete_provider_api_key(&provider_id) {
|
||||
Ok(true) => eprintln!("Removed the stored API key for `{provider_id}`"),
|
||||
Ok(false) => eprintln!("No API key is stored for `{provider_id}`"),
|
||||
Err(error) => {
|
||||
eprintln!("Error removing the API key: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
/// Prints where each `api_key = "keyring"` provider key is stored (never the key itself).
|
||||
/// Returns whether any provider key is available.
|
||||
fn print_provider_key_status(config: &Config) -> bool {
|
||||
let mut any = false;
|
||||
let mut ids = config.model_providers.keys().collect::<Vec<_>>();
|
||||
ids.sort();
|
||||
for id in ids {
|
||||
let provider = &config.model_providers[id];
|
||||
if provider.api_key == Some(akode_model_provider_info::ProviderApiKeySource::Keyring) {
|
||||
match akode_model_provider_info::locate_provider_api_key(id) {
|
||||
Ok(Some(location)) => {
|
||||
any = true;
|
||||
eprintln!("Provider `{id}`: API key stored in {location}");
|
||||
}
|
||||
Ok(None) => eprintln!(
|
||||
"Provider `{id}`: no API key stored (akode login --provider {id} --with-api-key)"
|
||||
),
|
||||
Err(error) => eprintln!("Provider `{id}`: cannot read the key store: {error}"),
|
||||
}
|
||||
} else if let Some(env_key) = &provider.env_key {
|
||||
let present = std::env::var(env_key).is_ok_and(|value| !value.trim().is_empty());
|
||||
any |= present;
|
||||
eprintln!(
|
||||
"Provider `{id}`: API key from ${env_key} ({})",
|
||||
if present { "set" } else { "not set" }
|
||||
);
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
/// Login using the OAuth device code flow.
|
||||
pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
|
||||
let config = load_config_or_exit(cli_config_overrides).await;
|
||||
|
||||
let auth_config = config.auth_config();
|
||||
match auth_config
|
||||
.load_auth(/*enable_codex_api_key_env*/ false)
|
||||
.await
|
||||
{
|
||||
Ok(Some(auth)) => match auth.auth_mode() {
|
||||
AuthMode::ApiKey => match auth.get_token() {
|
||||
Ok(api_key) => {
|
||||
eprintln!("API key configured - {}", safe_format_key(&api_key));
|
||||
print_provider_key_status(&config);
|
||||
eprintln!("{API_KEY_AUTHENTICATION_NOTICE}");
|
||||
std::process::exit(0);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Unexpected error retrieving API key: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
},
|
||||
AuthMode::Headers => {
|
||||
unreachable!("header auth cannot be loaded from auth storage")
|
||||
}
|
||||
},
|
||||
Ok(None) => {
|
||||
if print_provider_key_status(&config) {
|
||||
std::process::exit(0);
|
||||
}
|
||||
eprintln!("Not logged in");
|
||||
std::process::exit(1);
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Error checking login status: {err}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_logout(cli_config_overrides: CliConfigOverrides) -> ! {
|
||||
let config = load_config_or_exit(cli_config_overrides).await;
|
||||
let logged_out = match akode_login::logout(
|
||||
&config.codex_home,
|
||||
config.cli_auth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind(),
|
||||
) {
|
||||
Ok(logged_out) => logged_out,
|
||||
Err(err) => {
|
||||
eprintln!("Error logging out: {err}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
if logged_out {
|
||||
eprintln!("Successfully logged out");
|
||||
} else {
|
||||
eprintln!("Not logged in");
|
||||
}
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
async fn load_managed_login_config_or_exit(cli_config_overrides: CliConfigOverrides) -> Config {
|
||||
let mut config = load_config_or_exit(cli_config_overrides.clone()).await;
|
||||
if config
|
||||
.config_layer_stack
|
||||
.requirements_toml()
|
||||
.requires_remote_config()
|
||||
&& let Err(error) =
|
||||
sign_in_to_config_server_and_reload_config(&mut config, &cli_config_overrides).await
|
||||
{
|
||||
finish_login(Err(error));
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
async fn load_config_or_exit(cli_config_overrides: CliConfigOverrides) -> Config {
|
||||
let cli_overrides = match cli_config_overrides.parse_overrides() {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
eprintln!("Error parsing -c overrides: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
match Config::load_with_cli_overrides(cli_overrides).await {
|
||||
Ok(config) => match config.auth_config().validate() {
|
||||
Ok(()) => config,
|
||||
Err(e) => {
|
||||
eprintln!("Error loading configuration: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
eprintln!("Error loading configuration: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn safe_format_key(key: &str) -> String {
|
||||
if key.len() <= 13 {
|
||||
return "***".to_string();
|
||||
}
|
||||
let prefix = &key[..8];
|
||||
let suffix = &key[key.len() - 5..];
|
||||
format!("{prefix}***{suffix}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "login_storage_tests.rs"]
|
||||
mod storage_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::safe_format_key;
|
||||
|
||||
#[test]
|
||||
fn formats_long_key() {
|
||||
let key = "sk-proj-1234567890ABCDE";
|
||||
assert_eq!(safe_format_key(key), "sk-proj-***ABCDE");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_key_returns_stars() {
|
||||
let key = "sk-proj-12345";
|
||||
assert_eq!(safe_format_key(key), "***");
|
||||
}
|
||||
}
|
||||
87
akode-rs/cli/src/login_storage_tests.rs
Normal file
87
akode-rs/cli/src/login_storage_tests.rs
Normal file
@@ -0,0 +1,87 @@
|
||||
//! Verifies storage failures remain visible in direct login diagnostics.
|
||||
|
||||
use super::DEFAULT_LOGIN_LOG_FILTER;
|
||||
use akode_config::types::AuthCredentialsStoreMode;
|
||||
use akode_login::AuthKeyringBackendKind;
|
||||
use akode_login::login_with_api_key;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[test]
|
||||
fn login_default_filter_records_sanitized_storage_fallback() -> anyhow::Result<()> {
|
||||
let home = tempdir()?;
|
||||
// Fail before accessing the real keyring, then allow the plaintext fallback to succeed.
|
||||
std::fs::write(home.path().join("secrets"), "not a directory")?;
|
||||
let log_path = home.path().join("login.log");
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.without_time()
|
||||
.with_ansi(false)
|
||||
.with_env_filter(EnvFilter::new(DEFAULT_LOGIN_LOG_FILTER))
|
||||
.with_writer(std::fs::File::create(&log_path)?)
|
||||
.finish();
|
||||
tracing::subscriber::with_default(subscriber, || {
|
||||
login_with_api_key(
|
||||
home.path(),
|
||||
"private-api-key",
|
||||
AuthCredentialsStoreMode::Auto,
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
)
|
||||
})?;
|
||||
|
||||
let logs = std::fs::read_to_string(log_path)?;
|
||||
assert_eq!(logs.lines().count(), 2);
|
||||
let failure = logs.lines().next().unwrap();
|
||||
assert!(
|
||||
failure.contains("failed to save auth to keyring, falling back to file storage"),
|
||||
"{logs}"
|
||||
);
|
||||
assert!(failure.contains("failed to create secrets dir"), "{logs}");
|
||||
assert!(
|
||||
logs.contains("credential storage file fallback completed"),
|
||||
"{logs}"
|
||||
);
|
||||
assert!(logs.contains("fallback_reason=\"secure_error\""), "{logs}");
|
||||
assert!(logs.contains("outcome=\"success\""), "{logs}");
|
||||
assert!(!logs.contains("private-api-key"));
|
||||
let completion = logs.lines().last().unwrap();
|
||||
assert!(!completion.contains(home.path().to_str().unwrap()));
|
||||
let cause = std::fs::create_dir_all(home.path().join("secrets"))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
insta::assert_snapshot!(
|
||||
logs.replace(
|
||||
home.path().join("secrets").to_str().unwrap(),
|
||||
"[SECRETS_PATH]"
|
||||
)
|
||||
.replace(&cause, "[OS_ERROR]")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_storage_error_displays_context_and_cause() -> anyhow::Result<()> {
|
||||
let home = tempdir()?;
|
||||
let secrets_path = home.path().join("secrets");
|
||||
std::fs::write(&secrets_path, "not a directory")?;
|
||||
let cause = std::fs::create_dir_all(&secrets_path)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
let error = login_with_api_key(
|
||||
home.path(),
|
||||
"private-api-key",
|
||||
AuthCredentialsStoreMode::Keyring,
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
)
|
||||
.unwrap_err();
|
||||
let message = error.to_string();
|
||||
assert!(message.contains(&cause), "{message}");
|
||||
assert!(!message.contains("private-api-key"));
|
||||
// The temporary path and native filesystem error differ across platforms.
|
||||
insta::assert_snapshot!(
|
||||
message
|
||||
.replace(secrets_path.to_str().unwrap(), "[SECRETS_PATH]")
|
||||
.replace(&cause, "[OS_ERROR]")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
4771
akode-rs/cli/src/main.rs
Normal file
4771
akode-rs/cli/src/main.rs
Normal file
File diff suppressed because it is too large
Load Diff
587
akode-rs/cli/src/marketplace_cmd.rs
Normal file
587
akode-rs/cli/src/marketplace_cmd.rs
Normal file
@@ -0,0 +1,587 @@
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use clap::Parser;
|
||||
use akode_core::config::Config;
|
||||
use akode_core::config::ConfigOverrides;
|
||||
use akode_core::config::LoaderOverrides;
|
||||
use akode_core::plugins_manager_for_config;
|
||||
use akode_core_plugins::PluginMarketplaceUpgradeOutcome;
|
||||
use akode_core_plugins::PluginsConfigInput;
|
||||
use akode_core_plugins::installed_marketplaces::marketplace_install_root;
|
||||
use akode_core_plugins::installed_marketplaces::resolve_configured_marketplace_root;
|
||||
use akode_core_plugins::marketplace::marketplace_root_dir;
|
||||
use akode_core_plugins::marketplace_add::MarketplaceAddOutcome;
|
||||
use akode_core_plugins::marketplace_add::MarketplaceAddRequest;
|
||||
use akode_core_plugins::marketplace_add::add_marketplace;
|
||||
use akode_core_plugins::marketplace_remove::MarketplaceRemoveOutcome;
|
||||
use akode_core_plugins::marketplace_remove::MarketplaceRemoveRequest;
|
||||
use akode_core_plugins::marketplace_remove::remove_marketplace;
|
||||
use akode_utils_cli::CliConfigOverrides;
|
||||
use serde::Serialize;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::local_config;
|
||||
use crate::plugin_cmd::JsonMarketplaceSource;
|
||||
use crate::plugin_cmd::configured_marketplace_snapshot_issues;
|
||||
use crate::plugin_cmd::configured_marketplace_sources;
|
||||
use crate::plugin_cmd::load_cli_auth_manager;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(bin_name = "akode plugin marketplace")]
|
||||
pub struct MarketplaceCli {
|
||||
#[clap(flatten)]
|
||||
pub config_overrides: CliConfigOverrides,
|
||||
|
||||
#[command(subcommand)]
|
||||
subcommand: MarketplaceSubcommand,
|
||||
}
|
||||
|
||||
#[derive(Debug, clap::Subcommand)]
|
||||
enum MarketplaceSubcommand {
|
||||
/// Add a local or Git marketplace to the configured marketplace sources.
|
||||
Add(AddMarketplaceArgs),
|
||||
|
||||
/// List plugin marketplaces aKode is currently considering and their roots.
|
||||
List(ListMarketplaceArgs),
|
||||
|
||||
/// Refresh configured Git marketplace snapshots.
|
||||
///
|
||||
/// Omit MARKETPLACE_NAME to upgrade all configured Git marketplaces.
|
||||
Upgrade(UpgradeMarketplaceArgs),
|
||||
|
||||
/// Remove a configured marketplace source by name.
|
||||
Remove(RemoveMarketplaceArgs),
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
bin_name = "akode plugin marketplace add",
|
||||
after_help = "Examples:\n akode plugin marketplace add ./path/to/marketplace\n akode plugin marketplace add owner/repo --ref main\n akode plugin marketplace add https://github.com/owner/repo --sparse plugins/foo"
|
||||
)]
|
||||
struct AddMarketplaceArgs {
|
||||
/// Marketplace source: a local path, owner/repo[@ref], HTTPS Git URL, or SSH Git URL.
|
||||
#[arg(value_name = "SOURCE")]
|
||||
source: String,
|
||||
|
||||
/// Git ref to fetch for Git marketplace sources.
|
||||
#[arg(long = "ref", value_name = "REF")]
|
||||
ref_name: Option<String>,
|
||||
|
||||
/// Sparse checkout path for Git marketplace sources. Can be repeated.
|
||||
#[arg(
|
||||
long = "sparse",
|
||||
value_name = "PATH",
|
||||
action = clap::ArgAction::Append
|
||||
)]
|
||||
sparse_paths: Vec<String>,
|
||||
|
||||
/// Output add result as JSON.
|
||||
#[arg(long = "json")]
|
||||
json: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(bin_name = "akode plugin marketplace list")]
|
||||
struct ListMarketplaceArgs {
|
||||
/// Output marketplace list as JSON.
|
||||
#[arg(long = "json")]
|
||||
json: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
bin_name = "akode plugin marketplace upgrade",
|
||||
after_help = "Examples:\n akode plugin marketplace upgrade\n akode plugin marketplace upgrade debug"
|
||||
)]
|
||||
struct UpgradeMarketplaceArgs {
|
||||
/// Optional configured marketplace name to upgrade. Omit to upgrade all Git marketplaces.
|
||||
#[arg(value_name = "MARKETPLACE_NAME")]
|
||||
marketplace_name: Option<String>,
|
||||
|
||||
/// Output upgrade result as JSON.
|
||||
#[arg(long = "json")]
|
||||
json: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
bin_name = "akode plugin marketplace remove",
|
||||
after_help = "Example:\n akode plugin marketplace remove debug"
|
||||
)]
|
||||
struct RemoveMarketplaceArgs {
|
||||
/// Configured marketplace name to remove.
|
||||
#[arg(value_name = "MARKETPLACE_NAME")]
|
||||
marketplace_name: String,
|
||||
|
||||
/// Output remove result as JSON.
|
||||
#[arg(long = "json")]
|
||||
json: bool,
|
||||
}
|
||||
|
||||
impl MarketplaceCli {
|
||||
pub async fn run(self) -> Result<()> {
|
||||
let MarketplaceCli {
|
||||
config_overrides,
|
||||
subcommand,
|
||||
} = self;
|
||||
|
||||
let builder = local_config::config_builder(
|
||||
&config_overrides,
|
||||
LoaderOverrides::default(),
|
||||
ConfigOverrides::default(),
|
||||
)
|
||||
.await?;
|
||||
let config = builder.clone().build().await?;
|
||||
|
||||
match subcommand {
|
||||
MarketplaceSubcommand::Add(args) => run_add(config, args).await?,
|
||||
MarketplaceSubcommand::List(args) => run_list(config, args).await?,
|
||||
MarketplaceSubcommand::Upgrade(args) => run_upgrade(config, args, builder).await?,
|
||||
MarketplaceSubcommand::Remove(args) => run_remove(config, args).await?,
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_add(config: Config, args: AddMarketplaceArgs) -> Result<()> {
|
||||
let AddMarketplaceArgs {
|
||||
source,
|
||||
ref_name,
|
||||
sparse_paths,
|
||||
json,
|
||||
} = args;
|
||||
|
||||
let outcome = add_marketplace(
|
||||
config.codex_home.to_path_buf(),
|
||||
config.config_layer_stack.requirements().clone(),
|
||||
MarketplaceAddRequest {
|
||||
source,
|
||||
ref_name,
|
||||
sparse_paths,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
if json {
|
||||
let output = JsonMarketplaceAddOutput::from_outcome(outcome);
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if outcome.already_added {
|
||||
println!(
|
||||
"Marketplace `{}` is already added from {}.",
|
||||
outcome.marketplace_name, outcome.source_display
|
||||
);
|
||||
} else {
|
||||
println!(
|
||||
"Added marketplace `{}` from {}.",
|
||||
outcome.marketplace_name, outcome.source_display
|
||||
);
|
||||
}
|
||||
println!(
|
||||
"Installed marketplace root: {}",
|
||||
outcome.installed_root.as_path().display()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct JsonMarketplaceAddOutput {
|
||||
marketplace_name: String,
|
||||
installed_root: String,
|
||||
already_added: bool,
|
||||
}
|
||||
|
||||
impl JsonMarketplaceAddOutput {
|
||||
fn from_outcome(outcome: MarketplaceAddOutcome) -> Self {
|
||||
Self {
|
||||
marketplace_name: outcome.marketplace_name,
|
||||
installed_root: outcome.installed_root.as_path().display().to_string(),
|
||||
already_added: outcome.already_added,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_list(config: Config, args: ListMarketplaceArgs) -> Result<()> {
|
||||
let manager = plugins_manager_for_config(&config, load_cli_auth_manager(&config).await?);
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let marketplace_listing = manager
|
||||
.discover_marketplaces_for_config(&plugins_input, &[])
|
||||
.context("failed to list plugin marketplaces")?;
|
||||
let mut load_issues = configured_marketplace_snapshot_issues(
|
||||
config.codex_home.as_path(),
|
||||
&plugins_input,
|
||||
&marketplace_listing.errors,
|
||||
/*marketplace_name*/ None,
|
||||
);
|
||||
let mut issue_paths = load_issues
|
||||
.iter()
|
||||
.map(|issue| issue.path.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
for error in &marketplace_listing.errors {
|
||||
if issue_paths.insert(error.path.to_path_buf()) {
|
||||
load_issues.push(crate::plugin_cmd::ConfiguredMarketplaceSnapshotIssue {
|
||||
marketplace_name: error.path.display().to_string(),
|
||||
path: error.path.to_path_buf(),
|
||||
message: error.message.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if !load_issues.is_empty() {
|
||||
let issue_lines = load_issues
|
||||
.iter()
|
||||
.map(|issue| {
|
||||
format!(
|
||||
"- `{}` at {}: {}",
|
||||
issue.marketplace_name,
|
||||
issue.path.display(),
|
||||
issue.message
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
bail!("failed to load marketplace(s):\n{issue_lines}");
|
||||
}
|
||||
let marketplaces = marketplace_listing.marketplaces;
|
||||
if args.json {
|
||||
let marketplace_sources =
|
||||
configured_marketplace_sources_by_root(config.codex_home.as_path(), &plugins_input);
|
||||
let output =
|
||||
JsonMarketplaceListOutput::from_marketplaces(marketplaces, &marketplace_sources);
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if marketplaces.is_empty() {
|
||||
println!("No plugin marketplaces in scope.");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut seen_roots = HashSet::new();
|
||||
let mut rows = Vec::new();
|
||||
for marketplace in marketplaces {
|
||||
let Ok(root) = marketplace_root_dir(&marketplace.path) else {
|
||||
continue;
|
||||
};
|
||||
if !seen_roots.insert(root.clone()) {
|
||||
continue;
|
||||
}
|
||||
rows.push((marketplace.name, root));
|
||||
}
|
||||
|
||||
let marketplace_width = rows
|
||||
.iter()
|
||||
.map(|(name, _)| name.len())
|
||||
.max()
|
||||
.unwrap_or("MARKETPLACE".len())
|
||||
.max("MARKETPLACE".len());
|
||||
|
||||
println!("{:<marketplace_width$} ROOT", "MARKETPLACE");
|
||||
for (marketplace_name, root) in rows {
|
||||
println!(
|
||||
"{:<marketplace_width$} {}",
|
||||
marketplace_name,
|
||||
root.display()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct JsonMarketplaceListOutput {
|
||||
marketplaces: Vec<JsonMarketplaceListEntry>,
|
||||
}
|
||||
|
||||
impl JsonMarketplaceListOutput {
|
||||
fn from_marketplaces(
|
||||
marketplaces: Vec<akode_core_plugins::marketplace::Marketplace>,
|
||||
marketplace_sources: &HashMap<PathBuf, JsonMarketplaceSource>,
|
||||
) -> Self {
|
||||
let mut seen_roots = HashSet::new();
|
||||
let marketplaces = marketplaces
|
||||
.into_iter()
|
||||
.filter_map(|marketplace| {
|
||||
let root = marketplace_root_dir(&marketplace.path).ok()?;
|
||||
if !seen_roots.insert(root.clone()) {
|
||||
return None;
|
||||
}
|
||||
Some(JsonMarketplaceListEntry {
|
||||
marketplace_source: marketplace_sources.get(root.as_path()).cloned(),
|
||||
name: marketplace.name,
|
||||
root: root.display().to_string(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
Self { marketplaces }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct JsonMarketplaceListEntry {
|
||||
name: String,
|
||||
root: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
marketplace_source: Option<JsonMarketplaceSource>,
|
||||
}
|
||||
|
||||
fn configured_marketplace_sources_by_root(
|
||||
codex_home: &Path,
|
||||
plugins_input: &PluginsConfigInput,
|
||||
) -> HashMap<PathBuf, JsonMarketplaceSource> {
|
||||
let marketplace_sources = configured_marketplace_sources(plugins_input, codex_home);
|
||||
let effective_config = plugins_input.config_layer_stack.effective_config();
|
||||
let Some(marketplaces) = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
else {
|
||||
return HashMap::new();
|
||||
};
|
||||
|
||||
let default_install_root = marketplace_install_root(codex_home);
|
||||
marketplaces
|
||||
.iter()
|
||||
.filter_map(|(marketplace_name, marketplace)| {
|
||||
let marketplace_source = marketplace_sources.get(marketplace_name)?;
|
||||
let root = resolve_configured_marketplace_root(
|
||||
marketplace_name,
|
||||
marketplace,
|
||||
&default_install_root,
|
||||
)?;
|
||||
Some((root, marketplace_source.clone()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn run_upgrade(
|
||||
config: Config,
|
||||
args: UpgradeMarketplaceArgs,
|
||||
builder: akode_core::config::ConfigBuilder,
|
||||
) -> Result<()> {
|
||||
let UpgradeMarketplaceArgs {
|
||||
marketplace_name,
|
||||
json,
|
||||
} = args;
|
||||
let manager = plugins_manager_for_config(&config, load_cli_auth_manager(&config).await?);
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
let reload_config: akode_core_plugins::ConfigLayerReload = std::sync::Arc::new(move || {
|
||||
runtime
|
||||
.block_on(builder.clone().build())
|
||||
.map(|config| config.config_layer_stack)
|
||||
});
|
||||
let requested_name = marketplace_name.clone();
|
||||
let outcome = tokio::task::spawn_blocking(move || {
|
||||
manager.upgrade_configured_marketplaces_for_config(
|
||||
&plugins_input,
|
||||
requested_name.as_deref(),
|
||||
&reload_config,
|
||||
)
|
||||
})
|
||||
.await?
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
if json {
|
||||
print_upgrade_outcome_json(&outcome)
|
||||
} else {
|
||||
print_upgrade_outcome(&outcome, marketplace_name.as_deref())
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_remove(config: Config, args: RemoveMarketplaceArgs) -> Result<()> {
|
||||
let RemoveMarketplaceArgs {
|
||||
marketplace_name,
|
||||
json,
|
||||
} = args;
|
||||
let outcome = remove_marketplace(
|
||||
config.codex_home.to_path_buf(),
|
||||
config.config_layer_stack,
|
||||
MarketplaceRemoveRequest { marketplace_name },
|
||||
)
|
||||
.await?;
|
||||
|
||||
if json {
|
||||
let output = JsonMarketplaceRemoveOutput::from_outcome(outcome);
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!("Removed marketplace `{}`.", outcome.marketplace_name);
|
||||
if let Some(installed_root) = outcome.removed_installed_root {
|
||||
println!(
|
||||
"Removed installed marketplace root: {}",
|
||||
installed_root.as_path().display()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct JsonMarketplaceRemoveOutput {
|
||||
marketplace_name: String,
|
||||
installed_root: Option<String>,
|
||||
}
|
||||
|
||||
impl JsonMarketplaceRemoveOutput {
|
||||
fn from_outcome(outcome: MarketplaceRemoveOutcome) -> Self {
|
||||
Self {
|
||||
marketplace_name: outcome.marketplace_name,
|
||||
installed_root: outcome
|
||||
.removed_installed_root
|
||||
.map(|root| root.as_path().display().to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn print_upgrade_outcome_json(outcome: &PluginMarketplaceUpgradeOutcome) -> Result<()> {
|
||||
for error in &outcome.errors {
|
||||
eprintln!(
|
||||
"Failed to upgrade marketplace `{}`: {}",
|
||||
error.marketplace_name, error.message
|
||||
);
|
||||
}
|
||||
if !outcome.all_succeeded() {
|
||||
bail!("{} upgrade failure(s) occurred.", outcome.errors.len());
|
||||
}
|
||||
|
||||
let output = JsonMarketplaceUpgradeOutput::from_outcome(outcome);
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct JsonMarketplaceUpgradeOutput {
|
||||
selected_marketplaces: Vec<String>,
|
||||
upgraded_roots: Vec<String>,
|
||||
errors: Vec<JsonMarketplaceUpgradeError>,
|
||||
}
|
||||
|
||||
impl JsonMarketplaceUpgradeOutput {
|
||||
fn from_outcome(outcome: &PluginMarketplaceUpgradeOutcome) -> Self {
|
||||
Self {
|
||||
selected_marketplaces: outcome.selected_marketplaces.clone(),
|
||||
upgraded_roots: outcome
|
||||
.upgraded_roots
|
||||
.iter()
|
||||
.map(|root| root.display().to_string())
|
||||
.collect(),
|
||||
errors: outcome
|
||||
.errors
|
||||
.iter()
|
||||
.map(|error| JsonMarketplaceUpgradeError {
|
||||
marketplace_name: error.marketplace_name.clone(),
|
||||
message: error.message.clone(),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct JsonMarketplaceUpgradeError {
|
||||
marketplace_name: String,
|
||||
message: String,
|
||||
}
|
||||
|
||||
fn print_upgrade_outcome(
|
||||
outcome: &PluginMarketplaceUpgradeOutcome,
|
||||
marketplace_name: Option<&str>,
|
||||
) -> Result<()> {
|
||||
for error in &outcome.errors {
|
||||
eprintln!(
|
||||
"Failed to upgrade marketplace `{}`: {}",
|
||||
error.marketplace_name, error.message
|
||||
);
|
||||
}
|
||||
if !outcome.all_succeeded() {
|
||||
bail!("{} upgrade failure(s) occurred.", outcome.errors.len());
|
||||
}
|
||||
|
||||
let selection_label = marketplace_name.unwrap_or("all configured Git marketplaces");
|
||||
if outcome.selected_marketplaces.is_empty() {
|
||||
println!("No configured Git marketplaces to upgrade.");
|
||||
} else if outcome.upgraded_roots.is_empty() {
|
||||
if marketplace_name.is_some() {
|
||||
println!("Marketplace `{selection_label}` is already up to date.");
|
||||
} else {
|
||||
println!("All configured Git marketplaces are already up to date.");
|
||||
}
|
||||
} else if marketplace_name.is_some() {
|
||||
println!("Upgraded marketplace `{selection_label}` to the latest configured revision.");
|
||||
for root in &outcome.upgraded_roots {
|
||||
println!("Installed marketplace root: {}", root.display());
|
||||
}
|
||||
} else {
|
||||
println!("Upgraded {} marketplace(s).", outcome.upgraded_roots.len());
|
||||
for root in &outcome.upgraded_roots {
|
||||
println!("Installed marketplace root: {}", root.display());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn sparse_paths_parse_before_or_after_source() {
|
||||
let sparse_before_source =
|
||||
AddMarketplaceArgs::try_parse_from(["add", "--sparse", "plugins/foo", "owner/repo"])
|
||||
.unwrap();
|
||||
assert_eq!(sparse_before_source.source, "owner/repo");
|
||||
assert_eq!(sparse_before_source.sparse_paths, vec!["plugins/foo"]);
|
||||
|
||||
let sparse_after_source =
|
||||
AddMarketplaceArgs::try_parse_from(["add", "owner/repo", "--sparse", "plugins/foo"])
|
||||
.unwrap();
|
||||
assert_eq!(sparse_after_source.source, "owner/repo");
|
||||
assert_eq!(sparse_after_source.sparse_paths, vec!["plugins/foo"]);
|
||||
|
||||
let repeated_sparse = AddMarketplaceArgs::try_parse_from([
|
||||
"add",
|
||||
"--sparse",
|
||||
"plugins/foo",
|
||||
"--sparse",
|
||||
"skills/bar",
|
||||
"owner/repo",
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(repeated_sparse.source, "owner/repo");
|
||||
assert_eq!(
|
||||
repeated_sparse.sparse_paths,
|
||||
vec!["plugins/foo", "skills/bar"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upgrade_subcommand_parses_optional_marketplace_name() {
|
||||
let upgrade_all = UpgradeMarketplaceArgs::try_parse_from(["upgrade"]).unwrap();
|
||||
assert_eq!(upgrade_all.marketplace_name, None);
|
||||
|
||||
let upgrade_one = UpgradeMarketplaceArgs::try_parse_from(["upgrade", "debug"]).unwrap();
|
||||
assert_eq!(upgrade_one.marketplace_name.as_deref(), Some("debug"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_subcommand_parses_marketplace_name() {
|
||||
let remove = RemoveMarketplaceArgs::try_parse_from(["remove", "debug"]).unwrap();
|
||||
assert_eq!(remove.marketplace_name, "debug");
|
||||
}
|
||||
}
|
||||
1132
akode-rs/cli/src/mcp_cmd.rs
Normal file
1132
akode-rs/cli/src/mcp_cmd.rs
Normal file
File diff suppressed because it is too large
Load Diff
346
akode-rs/cli/src/mcp_cmd_tests.rs
Normal file
346
akode-rs/cli/src/mcp_cmd_tests.rs
Normal file
@@ -0,0 +1,346 @@
|
||||
//! Verifies MCP argument handling and managed networking in standalone commands.
|
||||
|
||||
use clap::Parser;
|
||||
use akode_http_client::ClientRouteClass;
|
||||
use akode_http_client::HttpError;
|
||||
use akode_http_client::NetworkPolicyDenied;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::McpCli;
|
||||
use super::McpSubcommand;
|
||||
|
||||
#[test]
|
||||
fn oauth_client_secret_is_redacted_in_parsed_command_debug() {
|
||||
let cli = McpCli::try_parse_from([
|
||||
"mcp",
|
||||
"add",
|
||||
"private",
|
||||
"--url",
|
||||
"https://example.com/mcp",
|
||||
"--oauth-client-id",
|
||||
"registered-client",
|
||||
"--oauth-client-secret",
|
||||
"cli-secret-marker",
|
||||
])
|
||||
.expect("parse confidential client arguments");
|
||||
let debug = format!("{cli:?}");
|
||||
assert!(!debug.contains("cli-secret-marker"));
|
||||
assert!(debug.contains("oauth_client_secret: Some(<redacted>)"));
|
||||
let McpSubcommand::Add(add) = cli.subcommand else {
|
||||
panic!("expected MCP add");
|
||||
};
|
||||
let http = add.transport_args.streamable_http.expect("HTTP arguments");
|
||||
assert_eq!(
|
||||
http.oauth_client_secret
|
||||
.as_ref()
|
||||
.map(|secret| secret.as_str()),
|
||||
Some("cli-secret-marker")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_client_secret_requires_url_and_client_id_without_disclosure() {
|
||||
for args in [
|
||||
vec!["--url", "https://example.com/mcp"],
|
||||
vec!["--oauth-client-id", "registered-client"],
|
||||
] {
|
||||
let error = McpCli::try_parse_from(
|
||||
[
|
||||
"mcp",
|
||||
"add",
|
||||
"private",
|
||||
"--oauth-client-secret",
|
||||
"cli-secret-marker",
|
||||
]
|
||||
.into_iter()
|
||||
.chain(args),
|
||||
)
|
||||
.expect_err("client secret requires both HTTP URL and client ID");
|
||||
assert_eq!(
|
||||
error.kind(),
|
||||
clap::error::ErrorKind::MissingRequiredArgument
|
||||
);
|
||||
assert!(!error.to_string().contains("cli-secret-marker"));
|
||||
}
|
||||
}
|
||||
|
||||
async fn isolated_test_home(test_name: &str) -> anyhow::Result<Option<PathBuf>> {
|
||||
const CHILD: &str = "AKODE_MCP_NETWORK_TEST_CHILD";
|
||||
let test_name = format!("mcp_cmd::tests::{test_name}");
|
||||
if std::env::var(CHILD).as_deref() == Ok(test_name.as_str()) {
|
||||
return Ok(Some(akode_core::config::find_codex_home()?.to_path_buf()));
|
||||
}
|
||||
|
||||
// Only the child receives the temporary home; the production loader resolves
|
||||
// AKODE_HOME normally and the parent test process keeps its environment.
|
||||
let home = tempfile::tempdir()?;
|
||||
let output = timeout(
|
||||
Duration::from_secs(45),
|
||||
Command::new(std::env::current_exe()?)
|
||||
.args(["--exact", &test_name, "--nocapture"])
|
||||
.kill_on_drop(true)
|
||||
.env(CHILD, &test_name)
|
||||
.env("AKODE_HOME", home.path())
|
||||
.env("NO_PROXY", "127.0.0.1,localhost")
|
||||
.env("no_proxy", "127.0.0.1,localhost")
|
||||
.env_remove("OPENAI_API_KEY")
|
||||
.env_remove("AKODE_API_KEY")
|
||||
.env_remove("AKODE_ACCESS_TOKEN")
|
||||
.current_dir(home.path())
|
||||
.output(),
|
||||
)
|
||||
.await??;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("1 passed; 0 failed"),
|
||||
"{test_name}: {stdout}\n{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn config_with_application_network(
|
||||
home: &std::path::Path,
|
||||
requirements: &str,
|
||||
extra_config: &str,
|
||||
) -> anyhow::Result<akode_core::config::Config> {
|
||||
std::fs::write(
|
||||
home.join("config.toml"),
|
||||
format!(
|
||||
"forced_login_method = 'api'\n\
|
||||
cli_auth_credentials_store = 'file'\n\
|
||||
mcp_oauth_credentials_store = 'file'\n\
|
||||
[features]\nplugins = false\nrecommended_plugins = false\n\
|
||||
{extra_config}"
|
||||
),
|
||||
)?;
|
||||
let requirements_path = home.join("requirements.toml");
|
||||
std::fs::write(&requirements_path, requirements)?;
|
||||
crate::local_config::load_config(
|
||||
&akode_utils_cli::CliConfigOverrides::default(),
|
||||
akode_core::config::LoaderOverrides {
|
||||
system_config_path: Some(home.join("absent-system-config.toml")),
|
||||
system_requirements_path: Some(requirements_path),
|
||||
ignore_project_config: true,
|
||||
..codex_core::config::LoaderOverrides::without_managed_config_for_tests()
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn http_add_args(url: &str) -> super::AddArgs {
|
||||
let cli = McpCli::try_parse_from(["mcp", "add", "policy-probe", "--url", url])
|
||||
.expect("parse HTTP add arguments");
|
||||
let McpSubcommand::Add(args) = cli.subcommand else {
|
||||
panic!("expected MCP add");
|
||||
};
|
||||
args
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn application_network_mcp_add_denies_initial_oauth_discovery_before_connect()
|
||||
-> anyhow::Result<()> {
|
||||
let Some(home) = isolated_test_home(
|
||||
"application_network_mcp_add_denies_initial_oauth_discovery_before_connect",
|
||||
)
|
||||
.await?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
|
||||
listener.set_nonblocking(true)?;
|
||||
let url = format!("https://{}/mcp", listener.local_addr()?);
|
||||
let config = config_with_application_network(&home, "[application.network]\n", "").await?;
|
||||
|
||||
// Add deliberately saves the server when discovery is unknown. A successful
|
||||
// command is therefore not evidence that its network request was permitted.
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
super::run_add(&config, http_add_args(&url)),
|
||||
)
|
||||
.await??;
|
||||
let saved: toml::Value = toml::from_str(&std::fs::read_to_string(home.join("config.toml"))?)?;
|
||||
assert_eq!(
|
||||
saved["mcp_servers"]["policy-probe"]["url"].as_str(),
|
||||
Some(url.as_str())
|
||||
);
|
||||
// No accepted TCP connection also proves no HTTP discovery request arrived.
|
||||
assert_eq!(
|
||||
listener.accept().unwrap_err().kind(),
|
||||
std::io::ErrorKind::WouldBlock
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn application_network_mcp_add_discovers_when_policy_is_disabled() -> anyhow::Result<()> {
|
||||
let Some(home) =
|
||||
isolated_test_home("application_network_mcp_add_discovers_when_policy_is_disabled").await?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let server = wiremock::MockServer::start().await;
|
||||
wiremock::Mock::given(wiremock::matchers::any())
|
||||
.respond_with(wiremock::ResponseTemplate::new(404))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let url = format!("{}/mcp", server.uri());
|
||||
let config =
|
||||
config_with_application_network(&home, "[application.network]\nenabled = false\n", "")
|
||||
.await?;
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
super::run_add(&config, http_add_args(&url)),
|
||||
)
|
||||
.await??;
|
||||
let requests = server.received_requests().await.expect("recorded requests");
|
||||
assert!(
|
||||
requests.iter().any(|request| request.url.path() == "/mcp"),
|
||||
"the positive control must perform real OAuth discovery"
|
||||
);
|
||||
// The 404 response has no OAuth support, so this cannot open a browser.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn application_network_mcp_login_denies_even_an_allowed_mcp_server() -> anyhow::Result<()> {
|
||||
let Some(home) =
|
||||
isolated_test_home("application_network_mcp_login_denies_even_an_allowed_mcp_server")
|
||||
.await?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
|
||||
listener.set_nonblocking(true)?;
|
||||
let url = format!("https://{}/mcp", listener.local_addr()?);
|
||||
let requirements =
|
||||
format!("[application.network]\n[mcp_servers.policy-probe.identity]\nurl = {url:?}\n");
|
||||
let extra_config = format!("[mcp_servers.policy-probe]\nurl = {url:?}\n");
|
||||
let config = config_with_application_network(&home, &requirements, &extra_config).await?;
|
||||
let server = &config.mcp_servers.get()["policy-probe"];
|
||||
assert!(
|
||||
server.enabled,
|
||||
"MCP identity allowlist must permit this server"
|
||||
);
|
||||
assert!(server.disabled_reason.is_none());
|
||||
let error = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
super::run_login(
|
||||
&config,
|
||||
super::LoginArgs {
|
||||
name: "policy-probe".to_string(),
|
||||
no_browser: true,
|
||||
scopes: Vec::new(),
|
||||
oauth_client_registration: None,
|
||||
},
|
||||
),
|
||||
)
|
||||
.await?
|
||||
.expect_err("MCP permission must not override application network restrictions");
|
||||
let message = format!("{error:#}");
|
||||
assert!(
|
||||
message.contains("destination denied by application network policy"),
|
||||
"{message}"
|
||||
);
|
||||
assert_eq!(
|
||||
listener.accept().unwrap_err().kind(),
|
||||
std::io::ErrorKind::WouldBlock
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn application_network_loader_denies_unlisted_destination_before_connect()
|
||||
-> anyhow::Result<()> {
|
||||
let Some(home) =
|
||||
isolated_test_home("application_network_loader_denies_unlisted_destination_before_connect")
|
||||
.await?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
|
||||
listener.set_nonblocking(true)?;
|
||||
let url = format!("https://{}/must-not-connect", listener.local_addr()?);
|
||||
let config = config_with_application_network(
|
||||
&home,
|
||||
"[application.network.domains]\n'allowed.example' = 'allow'\n",
|
||||
"",
|
||||
)
|
||||
.await?;
|
||||
let factory = config.http_client_factory();
|
||||
factory
|
||||
.network_policy()
|
||||
.acquire(&"https://allowed.example/v1".parse()?)?;
|
||||
let client = factory.build_client(&url, ClientRouteClass::Other)?;
|
||||
assert!(matches!(
|
||||
timeout(Duration::from_secs(2), client.get(&url).send()).await?,
|
||||
Err(HttpError::Policy(NetworkPolicyDenied::Destination))
|
||||
));
|
||||
assert_eq!(
|
||||
listener.accept().unwrap_err().kind(),
|
||||
std::io::ErrorKind::WouldBlock
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn application_network_loader_allows_listed_https_destination_to_connect()
|
||||
-> anyhow::Result<()> {
|
||||
let Some(home) =
|
||||
isolated_test_home("application_network_loader_allows_listed_https_destination_to_connect")
|
||||
.await?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let url = format!("https://{}/allowed", listener.local_addr()?);
|
||||
let config = config_with_application_network(
|
||||
&home,
|
||||
"[application.network.domains]\n'127.0.0.1' = 'allow'\n",
|
||||
"",
|
||||
)
|
||||
.await?;
|
||||
let client = config
|
||||
.http_client_factory()
|
||||
.build_client(&url, ClientRouteClass::Other)?;
|
||||
let (response, connection) = timeout(Duration::from_secs(2), async {
|
||||
tokio::join!(client.get(&url).send(), async {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
// This listener proves TCP permission; it deliberately does not provide TLS.
|
||||
drop(stream);
|
||||
Ok::<_, std::io::Error>(())
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
connection?;
|
||||
assert!(response.is_err(), "the raw listener cannot complete TLS");
|
||||
assert!(!matches!(response, Err(HttpError::Policy(_))));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn application_network_loader_rejects_malformed_managed_policy() -> anyhow::Result<()> {
|
||||
let Some(home) =
|
||||
isolated_test_home("application_network_loader_rejects_malformed_managed_policy").await?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let error = config_with_application_network(
|
||||
&home,
|
||||
"[application.network.domains]\n'*.example.com' = 'allow'\n",
|
||||
"",
|
||||
)
|
||||
.await
|
||||
.expect_err("invalid application policy must not load as unrestricted");
|
||||
let message = format!("{error:#}");
|
||||
assert!(message.contains("requirements.toml"), "{message}");
|
||||
assert!(
|
||||
message.contains("application.network.domains requires exact ASCII domain names"),
|
||||
"{message}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
266
akode-rs/cli/src/mcp_login.rs
Normal file
266
akode-rs/cli/src/mcp_login.rs
Normal file
@@ -0,0 +1,266 @@
|
||||
//! CLI MCP OAuth login modes and bounded, hidden callback input.
|
||||
//!
|
||||
//! Manual input remains cancellable while the OAuth flow waits for its HTTP
|
||||
//! callback, and dropping terminal input restores the terminal immediately.
|
||||
//! Ctrl-C also cancels token exchange and scope retries in manual login mode.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::io::BufRead;
|
||||
use std::io::IsTerminal;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use akode_config::McpServerOAuthConfig;
|
||||
use akode_config::types::AuthKeyringBackendKind;
|
||||
use akode_config::types::OAuthCredentialsStoreMode;
|
||||
use akode_exec_server::HttpClient;
|
||||
use akode_mcp::ResolvedMcpOAuthScopes;
|
||||
use akode_mcp::should_retry_without_scopes;
|
||||
use akode_rmcp_client::McpOAuthClientRegistration;
|
||||
use akode_rmcp_client::perform_oauth_login;
|
||||
use akode_rmcp_client::perform_oauth_login_with_callback_input;
|
||||
use crossterm::event::Event;
|
||||
use crossterm::event::EventStream;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEventKind;
|
||||
use crossterm::event::KeyModifiers;
|
||||
use crossterm::terminal;
|
||||
use futures::StreamExt;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
const MAX_CALLBACK_BYTES: usize = 64 * 1024;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum McpLoginMode {
|
||||
Browser,
|
||||
PasteCallback,
|
||||
}
|
||||
|
||||
/// Retry provider-rejected discovered scopes once, retaining the selected input mode.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn perform_oauth_login_retry_without_scopes(
|
||||
name: &str,
|
||||
url: &str,
|
||||
store_mode: OAuthCredentialsStoreMode,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
http_headers: Option<HashMap<String, String>>,
|
||||
env_http_headers: Option<HashMap<String, String>>,
|
||||
resolved_scopes: &ResolvedMcpOAuthScopes,
|
||||
oauth_config: Option<&McpServerOAuthConfig>,
|
||||
client_registration: McpOAuthClientRegistration,
|
||||
oauth_resource: Option<&str>,
|
||||
callback_port: Option<u16>,
|
||||
callback_url: Option<&str>,
|
||||
global_callback_url: Option<&str>,
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
mode: McpLoginMode,
|
||||
) -> Result<()> {
|
||||
let mut pending_input = None;
|
||||
// Tokio retains its process-wide signal handler, so keep listening throughout
|
||||
// token exchange and scope retries after the callback input reader is dropped.
|
||||
let ctrl_c = tokio::signal::ctrl_c();
|
||||
tokio::pin!(ctrl_c);
|
||||
for (attempt, scopes) in [resolved_scopes.scopes.as_slice(), &[]]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let login = async {
|
||||
match mode {
|
||||
McpLoginMode::Browser => {
|
||||
perform_oauth_login(
|
||||
name,
|
||||
url,
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
http_headers.clone(),
|
||||
env_http_headers.clone(),
|
||||
scopes,
|
||||
oauth_config,
|
||||
client_registration,
|
||||
oauth_resource,
|
||||
callback_port,
|
||||
callback_url,
|
||||
global_callback_url,
|
||||
Arc::clone(&http_client),
|
||||
)
|
||||
.await
|
||||
}
|
||||
McpLoginMode::PasteCallback => {
|
||||
let input = &mut pending_input;
|
||||
perform_oauth_login_with_callback_input(
|
||||
name,
|
||||
url,
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
http_headers.clone(),
|
||||
env_http_headers.clone(),
|
||||
scopes,
|
||||
oauth_config,
|
||||
client_registration,
|
||||
oauth_resource,
|
||||
callback_port,
|
||||
callback_url,
|
||||
global_callback_url,
|
||||
Arc::clone(&http_client),
|
||||
move |authorization_url| read_callback(authorization_url, input),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
};
|
||||
let result = tokio::select! {
|
||||
result = login => result,
|
||||
result = &mut ctrl_c, if matches!(mode, McpLoginMode::PasteCallback) => {
|
||||
result.context("failed to listen for Ctrl-C")?;
|
||||
bail!("OAuth login cancelled");
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Err(error) if attempt == 0 && should_retry_without_scopes(resolved_scopes, &error) => {
|
||||
println!("OAuth provider rejected discovered scopes. Retrying without scopes…");
|
||||
}
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
unreachable!("the empty-scope attempt always returns")
|
||||
}
|
||||
|
||||
async fn read_callback(
|
||||
authorization_url: String,
|
||||
pending_input: &mut Option<oneshot::Receiver<Result<String>>>,
|
||||
) -> Result<String> {
|
||||
println!(
|
||||
"Authorize the MCP server by opening this URL in your browser:\n{authorization_url}\n"
|
||||
);
|
||||
println!(
|
||||
"After signing in, copy the full URL from your browser's address bar.\n\
|
||||
If the callback page cannot load, paste that URL here anyway."
|
||||
);
|
||||
if io::stdin().is_terminal() {
|
||||
return read_terminal_callback().await;
|
||||
}
|
||||
print_callback_prompt()?;
|
||||
|
||||
// A pipe may stay open after the HTTP callback wins. A detached thread avoids
|
||||
// making runtime shutdown wait for an uncancellable blocking stdin read.
|
||||
// Retain an unfinished read if an HTTP provider error triggers a scope retry.
|
||||
// Otherwise its detached reader could consume the next attempt's pasted URL.
|
||||
if pending_input.is_none() {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("mcp-oauth-callback-input".to_string())
|
||||
.spawn(move || {
|
||||
let result = read_callback_line(io::stdin().lock());
|
||||
let _ = tx.send(result);
|
||||
})
|
||||
.context("failed to start callback input reader")?;
|
||||
*pending_input = Some(rx);
|
||||
}
|
||||
let reader = pending_input
|
||||
.as_mut()
|
||||
.context("callback input reader was unavailable")?;
|
||||
let result = reader.await;
|
||||
*pending_input = None;
|
||||
result.context("callback input reader stopped")?
|
||||
}
|
||||
|
||||
fn read_callback_line(reader: impl BufRead) -> Result<String> {
|
||||
let mut bytes = Vec::new();
|
||||
reader
|
||||
.take((MAX_CALLBACK_BYTES + 3) as u64)
|
||||
.read_until(b'\n', &mut bytes)
|
||||
.context("failed to read callback URL")?;
|
||||
if bytes.ends_with(b"\n") {
|
||||
bytes.pop();
|
||||
}
|
||||
if bytes.ends_with(b"\r") {
|
||||
bytes.pop();
|
||||
}
|
||||
if bytes.len() > MAX_CALLBACK_BYTES {
|
||||
bail!("OAuth callback URL exceeds 64 KiB");
|
||||
}
|
||||
if bytes.is_empty() {
|
||||
bail!("No OAuth callback URL received before input closed");
|
||||
}
|
||||
String::from_utf8(bytes).map_err(|_| anyhow::anyhow!("OAuth callback URL must be valid UTF-8"))
|
||||
}
|
||||
|
||||
struct TerminalInputGuard;
|
||||
|
||||
impl Drop for TerminalInputGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = terminal::disable_raw_mode();
|
||||
eprintln!();
|
||||
}
|
||||
}
|
||||
|
||||
fn print_callback_prompt() -> Result<()> {
|
||||
eprint!("Callback URL (input hidden): ");
|
||||
io::stderr()
|
||||
.flush()
|
||||
.context("failed to display callback prompt")
|
||||
}
|
||||
|
||||
async fn read_terminal_callback() -> Result<String> {
|
||||
terminal::enable_raw_mode().context("failed to hide callback input")?;
|
||||
let _guard = TerminalInputGuard;
|
||||
print_callback_prompt()?;
|
||||
let mut events = EventStream::new();
|
||||
let mut input = String::new();
|
||||
loop {
|
||||
let event = events
|
||||
.next()
|
||||
.await
|
||||
.context("callback input stream closed")?
|
||||
.context("failed to read callback input")?;
|
||||
match event {
|
||||
Event::Key(key) if key.kind != KeyEventKind::Release => match key.code {
|
||||
KeyCode::Enter => {
|
||||
if input.is_empty() {
|
||||
bail!("No OAuth callback URL entered");
|
||||
}
|
||||
return Ok(input);
|
||||
}
|
||||
KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
bail!("OAuth login cancelled");
|
||||
}
|
||||
KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
bail!("No OAuth callback URL received before input closed");
|
||||
}
|
||||
KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
input.clear()
|
||||
}
|
||||
KeyCode::Backspace => {
|
||||
input.pop();
|
||||
}
|
||||
KeyCode::Char(character)
|
||||
if !character.is_control()
|
||||
&& !key.modifiers.contains(KeyModifiers::CONTROL) =>
|
||||
{
|
||||
if input.len() + character.len_utf8() > MAX_CALLBACK_BYTES {
|
||||
bail!("OAuth callback URL exceeds 64 KiB");
|
||||
}
|
||||
input.push(character);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Event::Paste(paste) => {
|
||||
if input.len() + paste.len() > MAX_CALLBACK_BYTES {
|
||||
bail!("OAuth callback URL exceeds 64 KiB");
|
||||
}
|
||||
input.push_str(&paste);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// Yield even with queued input so callback completion and timeout stay responsive.
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mcp_login_tests.rs"]
|
||||
mod tests;
|
||||
46
akode-rs/cli/src/mcp_login_tests.rs
Normal file
46
akode-rs/cli/src/mcp_login_tests.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
//! Checks bounded callback input independently of terminal state.
|
||||
|
||||
use super::MAX_CALLBACK_BYTES;
|
||||
use super::read_callback_line;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io::Cursor;
|
||||
|
||||
#[test]
|
||||
fn callback_line_accepts_crlf_and_eof_after_input() {
|
||||
for input in [
|
||||
"https://example.test/callback?code=abc\r\n",
|
||||
"https://example.test/callback?code=abc",
|
||||
] {
|
||||
assert_eq!(
|
||||
read_callback_line(Cursor::new(input)).expect("read callback URL"),
|
||||
"https://example.test/callback?code=abc"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_line_is_bounded_and_does_not_expose_input_in_errors() {
|
||||
let maximum_input = "s".repeat(MAX_CALLBACK_BYTES);
|
||||
assert_eq!(
|
||||
read_callback_line(Cursor::new(format!("{maximum_input}\r\n"))).expect("bounded input"),
|
||||
maximum_input
|
||||
);
|
||||
let input = "s".repeat(MAX_CALLBACK_BYTES + 1);
|
||||
assert_eq!(
|
||||
read_callback_line(Cursor::new(input))
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"OAuth callback URL exceeds 64 KiB"
|
||||
);
|
||||
assert_eq!(
|
||||
read_callback_line(Cursor::new("")).unwrap_err().to_string(),
|
||||
"No OAuth callback URL received before input closed"
|
||||
);
|
||||
assert_eq!(
|
||||
format!(
|
||||
"{:?}",
|
||||
read_callback_line(Cursor::new(b"sensitive\xff")).unwrap_err()
|
||||
),
|
||||
"OAuth callback URL must be valid UTF-8"
|
||||
);
|
||||
}
|
||||
117
akode-rs/cli/src/migrate_nfs_db.rs
Normal file
117
akode-rs/cli/src/migrate_nfs_db.rs
Normal file
@@ -0,0 +1,117 @@
|
||||
//! Confirms explicit database migration and reports the shared migrator's results.
|
||||
//! Other SQLite clients must remain stopped during replacement, and NFS must enforce
|
||||
//! cross-client POSIX locks.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::ensure;
|
||||
use clap::Parser;
|
||||
use akode_config::LoaderOverrides;
|
||||
use akode_core::config::ConfigBuilder;
|
||||
use akode_state::NfsDbMigration;
|
||||
use akode_state::NfsDbMigrationOutcome;
|
||||
use akode_utils_cli::CliConfigOverrides;
|
||||
use owo_colors::OwoColorize;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
after_help = "Stop SQLite clients on every host and keep them stopped through cutover.\nThe NFS mount must support cross-client POSIX locks (no nolock/local_lock=all).\nThis command replaces configured databases in place and retains their WAL backups."
|
||||
)]
|
||||
pub(crate) struct MigrateNfsDbCommand {
|
||||
/// Use a local directory with space for the database and WAL files.
|
||||
/// The default is the system temporary directory.
|
||||
#[arg(long, default_value_os_t = std::env::temp_dir())]
|
||||
staging_dir: PathBuf,
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
command: MigrateNfsDbCommand,
|
||||
config_overrides: CliConfigOverrides,
|
||||
loader_overrides: LoaderOverrides,
|
||||
) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
cfg!(unix),
|
||||
"migrate-nfs-db currently requires Unix filesystem locking and directory fsync"
|
||||
);
|
||||
let warning = "WARNING: This operation is unsafe under concurrency.";
|
||||
if supports_color::on(supports_color::Stream::Stderr).is_some() {
|
||||
eprintln!("{}", warning.red().bold());
|
||||
} else {
|
||||
eprintln!("{warning}");
|
||||
}
|
||||
eprintln!(
|
||||
"Stop all aKode instances on every host that uses these databases.\nKeep them stopped until the migration completes successfully."
|
||||
);
|
||||
let config = ConfigBuilder::default()
|
||||
.cli_overrides(
|
||||
config_overrides
|
||||
.parse_overrides()
|
||||
.map_err(anyhow::Error::msg)?,
|
||||
)
|
||||
.loader_overrides(loader_overrides)
|
||||
.build()
|
||||
.await?;
|
||||
// Check the merged config for an explicit log directory.
|
||||
let effective_config = config.config_layer_stack.effective_config();
|
||||
let skip_logs = effective_config.get("log_dir").is_some();
|
||||
let sqlite = config.sqlite_config();
|
||||
if !sqlite.home().try_exists()? {
|
||||
println!("No databases found.");
|
||||
return Ok(());
|
||||
}
|
||||
let mut needs_permission_confirmation = false;
|
||||
for database in sqlite.runtime_db_paths() {
|
||||
if skip_logs && database.path == sqlite.logs_db_path() {
|
||||
continue;
|
||||
}
|
||||
needs_permission_confirmation |=
|
||||
NfsDbMigration::needs_permission_confirmation(&database.path)?;
|
||||
}
|
||||
if needs_permission_confirmation {
|
||||
eprintln!(
|
||||
"Some database files have permissions other than 0600.\nMigration preserves file mode bits, including group and other access."
|
||||
);
|
||||
}
|
||||
eprintln!(
|
||||
"Replacement files belong to you; the original owner, group, and extended ACLs are not copied.\nThis can remove another user's access even when file permissions are 0600.\nOriginal files remain in a private backup directory.\nYou need write access to the database directory and its migration lock."
|
||||
);
|
||||
let prompt = if needs_permission_confirmation {
|
||||
"Migrate databases, including files with permissions other than 0600? [y/N]:"
|
||||
} else {
|
||||
"Continue? [y/N]:"
|
||||
};
|
||||
ensure!(
|
||||
crate::confirm(prompt)?,
|
||||
"Migration cancelled. No databases were changed."
|
||||
);
|
||||
let mut migration = NfsDbMigration::lock(sqlite.home())?;
|
||||
let mut databases_found = 0;
|
||||
for database in sqlite.runtime_db_paths() {
|
||||
if skip_logs && database.path == sqlite.logs_db_path() {
|
||||
println!("Skipped logs database: log_dir is configured.");
|
||||
continue;
|
||||
}
|
||||
let outcome = migration.migrate(&database.path, &command.staging_dir).await.with_context(|| format!(
|
||||
"migration failed for {}. Keep all aKode instances stopped. Correct the error and rerun codex migrate-nfs-db",
|
||||
database.path.display()
|
||||
))?;
|
||||
match outcome {
|
||||
NfsDbMigrationOutcome::Missing => continue,
|
||||
NfsDbMigrationOutcome::AlreadyDelete => {
|
||||
println!("Already in DELETE mode: {}", database.path.display())
|
||||
}
|
||||
NfsDbMigrationOutcome::Migrated { backup_directory } => println!(
|
||||
"Migrated database: {}\nWAL backup: {}",
|
||||
database.path.display(),
|
||||
backup_directory.display()
|
||||
),
|
||||
}
|
||||
databases_found += 1;
|
||||
}
|
||||
if databases_found == 0 {
|
||||
println!("No databases found.");
|
||||
return Ok(());
|
||||
}
|
||||
println!("Migration completed successfully. You can restart aKode.");
|
||||
Ok(())
|
||||
}
|
||||
439
akode-rs/cli/src/migrate_rollouts.rs
Normal file
439
akode-rs/cli/src/migrate_rollouts.rs
Normal file
@@ -0,0 +1,439 @@
|
||||
use std::io;
|
||||
use std::io::IsTerminal;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use clap::Parser;
|
||||
use akode_core::config::ConfigBuilder;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_thread_store::LocalThreadStore;
|
||||
use akode_thread_store::LocalThreadStoreConfig;
|
||||
use akode_thread_store::RolloutMigrationMode;
|
||||
use akode_thread_store::RolloutMigrationOptions;
|
||||
use akode_thread_store::RolloutMigrationProgress;
|
||||
use akode_thread_store::RolloutMigrationReport;
|
||||
use akode_thread_store::RolloutMigrationStatus;
|
||||
use akode_utils_cli::CliConfigOverrides;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
pub(crate) struct MigrateRolloutsCommand {
|
||||
/// Publish the migration. Without this flag the command only reports eligible sessions.
|
||||
#[arg(long)]
|
||||
apply: bool,
|
||||
|
||||
/// Restrict inspection or migration to one or more thread IDs.
|
||||
#[arg(long, value_name = "THREAD_ID", value_parser = ThreadId::from_string)]
|
||||
thread: Vec<ThreadId>,
|
||||
|
||||
/// Limit aggregate rollout read and write throughput, in MiB per second.
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "MIB",
|
||||
value_parser = clap::value_parser!(u64).range(1..)
|
||||
)]
|
||||
max_mib_per_second: Option<u64>,
|
||||
|
||||
/// Emit the complete per-thread report as JSON.
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
|
||||
/// Print one line for every inspected rollout.
|
||||
#[arg(long)]
|
||||
verbose: bool,
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
command: MigrateRolloutsCommand,
|
||||
config_overrides: CliConfigOverrides,
|
||||
) -> anyhow::Result<()> {
|
||||
let overrides = config_overrides
|
||||
.parse_overrides()
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let config = ConfigBuilder::default()
|
||||
.cli_overrides(overrides)
|
||||
.build()
|
||||
.await?;
|
||||
let mode = if command.apply {
|
||||
RolloutMigrationMode::Apply
|
||||
} else {
|
||||
RolloutMigrationMode::DryRun
|
||||
};
|
||||
let json = command.json;
|
||||
let verbose = command.verbose;
|
||||
let thread_history_db_path = config.sqlite.thread_history_db_path();
|
||||
let thread_storage_before = if mode == RolloutMigrationMode::Apply && !json {
|
||||
thread_storage_bytes(
|
||||
config.codex_home.as_path(),
|
||||
thread_history_db_path.as_path(),
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let state_db = if mode == RolloutMigrationMode::Apply {
|
||||
Some(
|
||||
akode_rollout::state_db::try_init(&config)
|
||||
.await
|
||||
.context("failed to initialize local thread metadata")?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let store = LocalThreadStore::new(LocalThreadStoreConfig::from_config(&config), state_db);
|
||||
let mut progress = MigrationProgress::new(mode, json);
|
||||
progress.begin();
|
||||
let result = store
|
||||
.migrate_rollouts_with_progress(
|
||||
RolloutMigrationOptions {
|
||||
mode,
|
||||
thread_ids: command.thread,
|
||||
max_mib_per_second: command.max_mib_per_second,
|
||||
},
|
||||
|update| progress.update(update),
|
||||
)
|
||||
.await;
|
||||
progress.finish();
|
||||
let report = result?;
|
||||
let thread_storage = match thread_storage_before {
|
||||
Some(before) => thread_storage_bytes(
|
||||
config.codex_home.as_path(),
|
||||
thread_history_db_path.as_path(),
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.map(|after| (before, after)),
|
||||
None => None,
|
||||
};
|
||||
|
||||
if json {
|
||||
println!("{}", serde_json::to_string_pretty(&report)?);
|
||||
} else {
|
||||
print_human_report(&report, mode, verbose, progress.elapsed(), thread_storage);
|
||||
}
|
||||
|
||||
if report
|
||||
.outcomes
|
||||
.iter()
|
||||
.any(|outcome| outcome.status == RolloutMigrationStatus::Failed)
|
||||
{
|
||||
anyhow::bail!("one or more rollout migrations failed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const TTY_PROGRESS_INTERVAL: Duration = Duration::from_millis(250);
|
||||
const NON_TTY_PROGRESS_INTERVAL: usize = 1_000;
|
||||
const MAX_EXCEPTION_DETAILS: usize = 20;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum ProgressOutput {
|
||||
Quiet,
|
||||
Tty,
|
||||
Plain,
|
||||
}
|
||||
|
||||
struct MigrationProgress {
|
||||
mode: RolloutMigrationMode,
|
||||
output: ProgressOutput,
|
||||
started_at: Instant,
|
||||
last_rendered_at: Instant,
|
||||
last_plain_processed: usize,
|
||||
counts: MigrationCounts,
|
||||
wrote_tty_line: bool,
|
||||
}
|
||||
|
||||
impl MigrationProgress {
|
||||
fn new(mode: RolloutMigrationMode, json: bool) -> Self {
|
||||
let now = Instant::now();
|
||||
let output = if json {
|
||||
ProgressOutput::Quiet
|
||||
} else if io::stderr().is_terminal()
|
||||
&& std::env::var("TERM").ok().as_deref() != Some("dumb")
|
||||
{
|
||||
ProgressOutput::Tty
|
||||
} else {
|
||||
ProgressOutput::Plain
|
||||
};
|
||||
Self {
|
||||
mode,
|
||||
output,
|
||||
started_at: now,
|
||||
last_rendered_at: now,
|
||||
last_plain_processed: 0,
|
||||
counts: MigrationCounts::default(),
|
||||
wrote_tty_line: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn begin(&self) {
|
||||
if self.output != ProgressOutput::Quiet {
|
||||
eprintln!("Scanning local rollouts...");
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&mut self, update: RolloutMigrationProgress) {
|
||||
if let Some(status) = update.outcome_status {
|
||||
self.counts.observe(status);
|
||||
}
|
||||
match self.output {
|
||||
ProgressOutput::Quiet => {}
|
||||
ProgressOutput::Tty
|
||||
if update.processed_paths == update.total_paths
|
||||
|| self.last_rendered_at.elapsed() >= TTY_PROGRESS_INTERVAL =>
|
||||
{
|
||||
let line = self.line(update);
|
||||
let mut stderr = io::stderr().lock();
|
||||
let _ = write!(stderr, "\r\x1b[2K{line}");
|
||||
let _ = stderr.flush();
|
||||
self.last_rendered_at = Instant::now();
|
||||
self.wrote_tty_line = true;
|
||||
}
|
||||
ProgressOutput::Plain
|
||||
if update.processed_paths == update.total_paths
|
||||
|| update
|
||||
.processed_paths
|
||||
.saturating_sub(self.last_plain_processed)
|
||||
>= NON_TTY_PROGRESS_INTERVAL =>
|
||||
{
|
||||
eprintln!("{}", self.line(update));
|
||||
self.last_plain_processed = update.processed_paths;
|
||||
}
|
||||
ProgressOutput::Tty | ProgressOutput::Plain => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&mut self) {
|
||||
if self.output != ProgressOutput::Tty || !self.wrote_tty_line {
|
||||
return;
|
||||
}
|
||||
let mut stderr = io::stderr().lock();
|
||||
let _ = write!(stderr, "\r\x1b[2K");
|
||||
let _ = stderr.flush();
|
||||
self.wrote_tty_line = false;
|
||||
}
|
||||
|
||||
fn elapsed(&self) -> Duration {
|
||||
self.started_at.elapsed()
|
||||
}
|
||||
|
||||
fn line(&self, update: RolloutMigrationProgress) -> String {
|
||||
let percent = update
|
||||
.processed_paths
|
||||
.saturating_mul(100)
|
||||
.checked_div(update.total_paths)
|
||||
.unwrap_or(100);
|
||||
let action = match self.mode {
|
||||
RolloutMigrationMode::DryRun => "Checking",
|
||||
RolloutMigrationMode::Apply => "Migrating",
|
||||
};
|
||||
let status_counts = match self.mode {
|
||||
RolloutMigrationMode::DryRun => format!(
|
||||
"{} eligible • {} already paginated",
|
||||
self.counts.eligible, self.counts.already_paginated
|
||||
),
|
||||
RolloutMigrationMode::Apply => format!(
|
||||
"{} migrated • {} already paginated",
|
||||
self.counts.migrated, self.counts.already_paginated
|
||||
),
|
||||
};
|
||||
format!(
|
||||
"{action} rollouts {}/{} ({percent}%) • {status_counts} • {} skipped • {} failed • {}",
|
||||
update.processed_paths,
|
||||
update.total_paths,
|
||||
self.counts.skipped(),
|
||||
self.counts.failed,
|
||||
format_elapsed(self.elapsed()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MigrationCounts {
|
||||
eligible: usize,
|
||||
migrated: usize,
|
||||
already_paginated: usize,
|
||||
skipped_empty: usize,
|
||||
skipped_busy: usize,
|
||||
failed: usize,
|
||||
}
|
||||
|
||||
impl MigrationCounts {
|
||||
fn observe(&mut self, status: RolloutMigrationStatus) {
|
||||
match status {
|
||||
RolloutMigrationStatus::Eligible => self.eligible += 1,
|
||||
RolloutMigrationStatus::Migrated => self.migrated += 1,
|
||||
RolloutMigrationStatus::AlreadyPaginated => self.already_paginated += 1,
|
||||
RolloutMigrationStatus::SkippedEmpty => self.skipped_empty += 1,
|
||||
RolloutMigrationStatus::SkippedBusy => self.skipped_busy += 1,
|
||||
RolloutMigrationStatus::Failed => self.failed += 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn skipped(&self) -> usize {
|
||||
self.skipped_empty + self.skipped_busy
|
||||
}
|
||||
}
|
||||
|
||||
fn print_human_report(
|
||||
report: &RolloutMigrationReport,
|
||||
mode: RolloutMigrationMode,
|
||||
verbose: bool,
|
||||
elapsed: Duration,
|
||||
thread_storage: Option<(u64, u64)>,
|
||||
) {
|
||||
let mut counts = MigrationCounts::default();
|
||||
for outcome in &report.outcomes {
|
||||
counts.observe(outcome.status);
|
||||
}
|
||||
let completion = match mode {
|
||||
RolloutMigrationMode::DryRun => "Scan complete",
|
||||
RolloutMigrationMode::Apply => "Migration complete",
|
||||
};
|
||||
println!("{completion} in {}.", format_elapsed(elapsed));
|
||||
match mode {
|
||||
RolloutMigrationMode::DryRun => println!(
|
||||
"Scanned {} rollout(s): {} eligible, {} already paginated, {} skipped ({} empty, {} busy), {} failed.",
|
||||
report.outcomes.len(),
|
||||
counts.eligible,
|
||||
counts.already_paginated,
|
||||
counts.skipped(),
|
||||
counts.skipped_empty,
|
||||
counts.skipped_busy,
|
||||
counts.failed,
|
||||
),
|
||||
RolloutMigrationMode::Apply => println!(
|
||||
"Scanned {} rollout(s): {} migrated, {} already paginated, {} skipped ({} empty, {} busy), {} failed.",
|
||||
report.outcomes.len(),
|
||||
counts.migrated,
|
||||
counts.already_paginated,
|
||||
counts.skipped(),
|
||||
counts.skipped_empty,
|
||||
counts.skipped_busy,
|
||||
counts.failed,
|
||||
),
|
||||
}
|
||||
if let Some((before, after)) = thread_storage {
|
||||
println!(
|
||||
"Disk used for thread storage: {} -> {}",
|
||||
format_bytes(before),
|
||||
format_bytes(after)
|
||||
);
|
||||
}
|
||||
if mode == RolloutMigrationMode::DryRun && counts.eligible > 0 {
|
||||
println!("Run `akode migrate-rollouts --apply` to migrate eligible sessions.");
|
||||
}
|
||||
|
||||
if verbose {
|
||||
for outcome in &report.outcomes {
|
||||
print_outcome(outcome);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let exceptions = report.outcomes.iter().filter(|outcome| {
|
||||
matches!(
|
||||
outcome.status,
|
||||
RolloutMigrationStatus::SkippedBusy | RolloutMigrationStatus::Failed
|
||||
)
|
||||
});
|
||||
let exception_count = exceptions.clone().count();
|
||||
if exception_count == 0 {
|
||||
return;
|
||||
}
|
||||
println!();
|
||||
for outcome in exceptions.take(MAX_EXCEPTION_DETAILS) {
|
||||
print_outcome(outcome);
|
||||
}
|
||||
if exception_count > MAX_EXCEPTION_DETAILS {
|
||||
println!(
|
||||
"... and {} more; rerun with --json for the complete report.",
|
||||
exception_count - MAX_EXCEPTION_DETAILS
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn print_outcome(outcome: &akode_thread_store::RolloutMigrationOutcome) {
|
||||
let status = match outcome.status {
|
||||
RolloutMigrationStatus::Eligible => "eligible",
|
||||
RolloutMigrationStatus::Migrated => "migrated",
|
||||
RolloutMigrationStatus::AlreadyPaginated => "already paginated",
|
||||
RolloutMigrationStatus::SkippedEmpty => "skipped empty",
|
||||
RolloutMigrationStatus::SkippedBusy => "skipped busy",
|
||||
RolloutMigrationStatus::Failed => "failed",
|
||||
};
|
||||
let thread_id = outcome
|
||||
.thread_id
|
||||
.map_or_else(|| "unknown".to_string(), |thread_id| thread_id.to_string());
|
||||
match &outcome.message {
|
||||
Some(message) => println!("{status}\t{thread_id}\t{message}"),
|
||||
None => println!("{status}\t{thread_id}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_elapsed(elapsed: Duration) -> String {
|
||||
let seconds = elapsed.as_secs();
|
||||
let minutes = seconds / 60;
|
||||
if minutes == 0 {
|
||||
return format!("{seconds}s");
|
||||
}
|
||||
let hours = minutes / 60;
|
||||
if hours == 0 {
|
||||
return format!("{minutes}m{:02}s", seconds % 60);
|
||||
}
|
||||
format!("{hours}h{:02}m{:02}s", minutes % 60, seconds % 60)
|
||||
}
|
||||
|
||||
async fn thread_storage_bytes(codex_home: &Path, thread_history_db_path: &Path) -> io::Result<u64> {
|
||||
let mut bytes = 0_u64;
|
||||
let mut directories = vec![
|
||||
codex_home.join(akode_rollout::SESSIONS_SUBDIR),
|
||||
codex_home.join(akode_rollout::ARCHIVED_SESSIONS_SUBDIR),
|
||||
];
|
||||
while let Some(directory) = directories.pop() {
|
||||
let mut entries = match tokio::fs::read_dir(&directory).await {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
let file_type = entry.file_type().await?;
|
||||
if file_type.is_dir() {
|
||||
directories.push(entry.path());
|
||||
} else if file_type.is_file() {
|
||||
bytes = bytes.saturating_add(entry.metadata().await?.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for suffix in ["", "-wal", "-shm"] {
|
||||
let mut path = thread_history_db_path.as_os_str().to_owned();
|
||||
path.push(suffix);
|
||||
match tokio::fs::metadata(path).await {
|
||||
Ok(metadata) => bytes = bytes.saturating_add(metadata.len()),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn format_bytes(bytes: u64) -> String {
|
||||
const KIB: f64 = 1024.0;
|
||||
const MIB: f64 = KIB * 1024.0;
|
||||
const GIB: f64 = MIB * 1024.0;
|
||||
|
||||
let bytes = bytes as f64;
|
||||
if bytes >= GIB {
|
||||
format!("{:.1} GB", bytes / GIB)
|
||||
} else if bytes >= MIB {
|
||||
format!("{:.1} MB", bytes / MIB)
|
||||
} else if bytes >= KIB {
|
||||
format!("{:.1} KB", bytes / KIB)
|
||||
} else {
|
||||
format!("{} B", bytes as u64)
|
||||
}
|
||||
}
|
||||
894
akode-rs/cli/src/plugin_cmd.rs
Normal file
894
akode-rs/cli/src/plugin_cmd.rs
Normal file
@@ -0,0 +1,894 @@
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use clap::Parser;
|
||||
use akode_core::config::Config;
|
||||
use akode_core::config::find_codex_home;
|
||||
use akode_core::plugins_manager_for_config;
|
||||
use akode_core_plugins::ConfiguredMarketplace;
|
||||
use akode_core_plugins::OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
use akode_core_plugins::PluginInstallOutcome;
|
||||
use akode_core_plugins::PluginInstallRequest;
|
||||
use akode_core_plugins::PluginsConfigInput;
|
||||
use akode_core_plugins::PluginsManager;
|
||||
use akode_core_plugins::allowed_configured_marketplace_names;
|
||||
use akode_core_plugins::installed_marketplaces::marketplace_install_root;
|
||||
use akode_core_plugins::installed_marketplaces::resolve_configured_marketplace_root;
|
||||
use akode_core_plugins::marketplace::MarketplaceListError;
|
||||
use akode_core_plugins::marketplace::MarketplacePluginAuthPolicy;
|
||||
use akode_core_plugins::marketplace::MarketplacePluginInstallPolicy;
|
||||
use akode_core_plugins::marketplace::MarketplacePluginSource;
|
||||
use akode_core_plugins::marketplace::find_marketplace_manifest_path;
|
||||
use akode_login::AuthManager;
|
||||
use akode_plugin::PluginId;
|
||||
use akode_plugin::validate_plugin_segment;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_cli::CliConfigOverrides;
|
||||
use serde::Serialize;
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::marketplace_cmd::MarketplaceCli;
|
||||
|
||||
const OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME: &str = "openai-bundled-alpha";
|
||||
const OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME: &str = "openai-primary-runtime";
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(bin_name = "akode plugin")]
|
||||
pub struct PluginCli {
|
||||
#[clap(flatten)]
|
||||
pub config_overrides: CliConfigOverrides,
|
||||
|
||||
#[command(subcommand)]
|
||||
pub subcommand: PluginSubcommand,
|
||||
}
|
||||
|
||||
#[derive(Debug, clap::Subcommand)]
|
||||
pub enum PluginSubcommand {
|
||||
/// Install a plugin from a configured marketplace.
|
||||
///
|
||||
/// Pass either `PLUGIN@MARKETPLACE` or pass `PLUGIN` with
|
||||
/// `--marketplace MARKETPLACE`.
|
||||
Add(AddPluginArgs),
|
||||
|
||||
/// List plugins available from configured marketplaces.
|
||||
List(ListPluginsArgs),
|
||||
|
||||
/// Add, list, upgrade, or remove configured plugin marketplaces.
|
||||
Marketplace(MarketplaceCli),
|
||||
|
||||
/// Uninstall a plugin and remove its local cache.
|
||||
///
|
||||
/// Pass either `PLUGIN@MARKETPLACE` or pass `PLUGIN` with
|
||||
/// `--marketplace MARKETPLACE`.
|
||||
Remove(RemovePluginArgs),
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
bin_name = "akode plugin add",
|
||||
after_help = "Examples:\n akode plugin add sample@debug\n akode plugin add sample --marketplace debug"
|
||||
)]
|
||||
pub struct AddPluginArgs {
|
||||
/// Plugin selector to install: either PLUGIN@MARKETPLACE or PLUGIN with --marketplace.
|
||||
#[arg(value_name = "PLUGIN[@MARKETPLACE]")]
|
||||
plugin: String,
|
||||
|
||||
/// Marketplace name to use when PLUGIN does not include @MARKETPLACE.
|
||||
#[arg(long = "marketplace", short = 'm', value_name = "MARKETPLACE")]
|
||||
marketplace_name: Option<String>,
|
||||
|
||||
/// Output install result as JSON.
|
||||
#[arg(long = "json")]
|
||||
json: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
bin_name = "akode plugin list",
|
||||
after_help = "Examples:\n akode plugin list\n akode plugin list --marketplace debug\n akode plugin list --json\n akode plugin list --available --json"
|
||||
)]
|
||||
pub struct ListPluginsArgs {
|
||||
/// Only list plugins from this marketplace name.
|
||||
#[arg(long = "marketplace", short = 'm', value_name = "MARKETPLACE")]
|
||||
marketplace_name: Option<String>,
|
||||
|
||||
/// Output plugin list as JSON.
|
||||
#[arg(long = "json")]
|
||||
json: bool,
|
||||
|
||||
/// Include uninstalled marketplace plugins in the JSON output.
|
||||
#[arg(long = "available", requires = "json")]
|
||||
available: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(
|
||||
bin_name = "akode plugin remove",
|
||||
after_help = "Examples:\n akode plugin remove sample@debug\n akode plugin remove sample --marketplace debug"
|
||||
)]
|
||||
pub struct RemovePluginArgs {
|
||||
/// Plugin selector to remove: either PLUGIN@MARKETPLACE or PLUGIN with --marketplace.
|
||||
#[arg(value_name = "PLUGIN[@MARKETPLACE]")]
|
||||
plugin: String,
|
||||
|
||||
/// Marketplace name to use when PLUGIN does not include @MARKETPLACE.
|
||||
#[arg(long = "marketplace", short = 'm', value_name = "MARKETPLACE")]
|
||||
marketplace_name: Option<String>,
|
||||
|
||||
/// Output remove result as JSON.
|
||||
#[arg(long = "json")]
|
||||
json: bool,
|
||||
}
|
||||
|
||||
pub async fn run_plugin_add(
|
||||
overrides: Vec<(String, toml::Value)>,
|
||||
args: AddPluginArgs,
|
||||
) -> Result<()> {
|
||||
let AddPluginArgs {
|
||||
plugin,
|
||||
marketplace_name,
|
||||
json,
|
||||
} = args;
|
||||
let selection = parse_plugin_selection(plugin, marketplace_name)?;
|
||||
let context = load_plugin_command_context(overrides).await?;
|
||||
let marketplace = find_marketplace_for_plugin(
|
||||
&context.manager,
|
||||
context.codex_home.as_path(),
|
||||
&context.plugins_input,
|
||||
&selection.marketplace_name,
|
||||
&selection.plugin_name,
|
||||
)?;
|
||||
let outcome = context
|
||||
.manager
|
||||
.install_plugin(
|
||||
&context.plugins_input.config_layer_stack,
|
||||
PluginInstallRequest {
|
||||
plugin_name: selection.plugin_name,
|
||||
marketplace_path: marketplace.path,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let output = JsonPluginAddOutput::from_outcome(outcome);
|
||||
|
||||
if json {
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!(
|
||||
"Added plugin `{}` from marketplace `{}`.",
|
||||
output.name, output.marketplace_name
|
||||
);
|
||||
println!("Installed plugin root: {}", output.installed_path);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct JsonPluginAddOutput {
|
||||
plugin_id: String,
|
||||
name: String,
|
||||
marketplace_name: String,
|
||||
version: String,
|
||||
installed_path: String,
|
||||
auth_policy: &'static str,
|
||||
}
|
||||
|
||||
impl JsonPluginAddOutput {
|
||||
fn from_outcome(outcome: PluginInstallOutcome) -> Self {
|
||||
Self {
|
||||
plugin_id: outcome.plugin_id.as_key(),
|
||||
name: outcome.plugin_id.plugin_name,
|
||||
marketplace_name: outcome.plugin_id.marketplace_name,
|
||||
version: outcome.plugin_version,
|
||||
installed_path: outcome.installed_path.as_path().display().to_string(),
|
||||
auth_policy: auth_policy_label(outcome.auth_policy),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_plugin_list(
|
||||
overrides: Vec<(String, toml::Value)>,
|
||||
args: ListPluginsArgs,
|
||||
) -> Result<()> {
|
||||
let context = load_plugin_command_context(overrides).await?;
|
||||
let PluginCommandContext {
|
||||
codex_home,
|
||||
plugins_input,
|
||||
manager,
|
||||
..
|
||||
} = context;
|
||||
let outcome = manager
|
||||
.list_marketplaces_for_config(&plugins_input, &[], /*include_openai_curated*/ true)
|
||||
.context("failed to list marketplace plugins")?;
|
||||
ensure_configured_marketplace_snapshots_loaded(
|
||||
codex_home.as_path(),
|
||||
&plugins_input,
|
||||
&outcome.errors,
|
||||
args.marketplace_name.as_deref(),
|
||||
)?;
|
||||
|
||||
let marketplace_sources = configured_marketplace_sources(&plugins_input, codex_home.as_path());
|
||||
let marketplaces = outcome
|
||||
.marketplaces
|
||||
.into_iter()
|
||||
.map(|marketplace| {
|
||||
let source = marketplace_sources.get(&marketplace.name).cloned();
|
||||
PluginListMarketplace {
|
||||
plugins: marketplace
|
||||
.plugins
|
||||
.into_iter()
|
||||
.map(|plugin| {
|
||||
PluginListEntry::from_configured_plugin(
|
||||
&marketplace.name,
|
||||
source.clone(),
|
||||
plugin,
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
name: marketplace.name,
|
||||
path: marketplace.path,
|
||||
}
|
||||
})
|
||||
.filter(|marketplace| {
|
||||
args.marketplace_name
|
||||
.as_ref()
|
||||
.is_none_or(|name| marketplace.name == *name)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
write_plugin_list(&mut io::stdout().lock(), marketplaces, args)
|
||||
}
|
||||
|
||||
fn write_plugin_list(
|
||||
writer: &mut impl Write,
|
||||
marketplaces: Vec<PluginListMarketplace>,
|
||||
args: ListPluginsArgs,
|
||||
) -> Result<()> {
|
||||
let result = render_plugin_list(writer, marketplaces, args)
|
||||
.and_then(|()| writer.flush().map_err(Into::into));
|
||||
match result {
|
||||
// A consumer such as `head` may finish before the full catalog is written.
|
||||
Err(error)
|
||||
if error
|
||||
.downcast_ref::<io::Error>()
|
||||
.is_some_and(|error| error.kind() == io::ErrorKind::BrokenPipe) =>
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn render_plugin_list(
|
||||
writer: &mut impl Write,
|
||||
marketplaces: Vec<PluginListMarketplace>,
|
||||
args: ListPluginsArgs,
|
||||
) -> Result<()> {
|
||||
if args.json {
|
||||
let output = JsonPluginListOutput::from_marketplaces(marketplaces, args.available);
|
||||
writeln!(writer, "{}", serde_json::to_string_pretty(&output)?)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if marketplaces.is_empty() {
|
||||
if let Some(marketplace_name) = args.marketplace_name {
|
||||
writeln!(
|
||||
writer,
|
||||
"No plugins found in marketplace `{marketplace_name}`."
|
||||
)?;
|
||||
} else {
|
||||
writeln!(writer, "No marketplace plugins found.")?;
|
||||
}
|
||||
} else {
|
||||
for (index, marketplace) in marketplaces.into_iter().enumerate() {
|
||||
let mut rows = Vec::new();
|
||||
let mut plugin_width = "PLUGIN".len();
|
||||
let mut status_width = "STATUS".len();
|
||||
let mut installed_version_width = "VERSION".len();
|
||||
|
||||
for plugin in &marketplace.plugins {
|
||||
let state = if plugin.installed && plugin.enabled {
|
||||
"installed, enabled"
|
||||
} else if plugin.installed {
|
||||
"installed, disabled"
|
||||
} else {
|
||||
"not installed"
|
||||
};
|
||||
let installed_version = plugin.display_version.clone().unwrap_or_default();
|
||||
let path = match &plugin.source {
|
||||
JsonPluginSource::Local { path } => path.clone(),
|
||||
JsonPluginSource::Git { url, ref_name, sha }
|
||||
| JsonPluginSource::GitSubdir {
|
||||
url, ref_name, sha, ..
|
||||
} => {
|
||||
let mut parts = vec![url.clone()];
|
||||
if let JsonPluginSource::GitSubdir { path, .. } = &plugin.source {
|
||||
parts.push(format!("path `{path}`"));
|
||||
}
|
||||
if let Some(ref_name) = ref_name {
|
||||
parts.push(format!("ref `{ref_name}`"));
|
||||
}
|
||||
if let Some(sha) = sha {
|
||||
parts.push(format!("sha `{sha}`"));
|
||||
}
|
||||
parts.join(", ")
|
||||
}
|
||||
JsonPluginSource::Npm {
|
||||
package,
|
||||
version,
|
||||
registry,
|
||||
} => {
|
||||
let mut parts = vec![package.clone()];
|
||||
if let Some(version) = version {
|
||||
parts.push(format!("version `{version}`"));
|
||||
}
|
||||
if let Some(registry) = registry {
|
||||
parts.push(format!("registry `{registry}`"));
|
||||
}
|
||||
parts.join(", ")
|
||||
}
|
||||
};
|
||||
plugin_width = plugin_width.max(plugin.plugin_id.len());
|
||||
status_width = status_width.max(state.len());
|
||||
installed_version_width = installed_version_width.max(installed_version.len());
|
||||
rows.push((plugin.plugin_id.clone(), state, installed_version, path));
|
||||
}
|
||||
|
||||
if index > 0 {
|
||||
writeln!(writer)?;
|
||||
}
|
||||
writeln!(writer, "Marketplace `{}`", marketplace.name)?;
|
||||
writeln!(writer, "{}", marketplace.path.display())?;
|
||||
writeln!(writer)?;
|
||||
writeln!(
|
||||
writer,
|
||||
"{:<plugin_width$} {:<status_width$} {:<installed_version_width$} SOURCE",
|
||||
"PLUGIN", "STATUS", "VERSION"
|
||||
)?;
|
||||
for (plugin, status, installed_version, path) in rows {
|
||||
writeln!(
|
||||
writer,
|
||||
"{plugin:<plugin_width$} {status:<status_width$} {installed_version:<installed_version_width$} {path}"
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct PluginListMarketplace {
|
||||
name: String,
|
||||
path: AbsolutePathBuf,
|
||||
plugins: Vec<PluginListEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct JsonPluginListOutput {
|
||||
installed: Vec<PluginListEntry>,
|
||||
available: Vec<PluginListEntry>,
|
||||
}
|
||||
|
||||
impl JsonPluginListOutput {
|
||||
fn from_marketplaces(
|
||||
marketplaces: Vec<PluginListMarketplace>,
|
||||
include_available: bool,
|
||||
) -> Self {
|
||||
let mut installed = Vec::new();
|
||||
let mut available = Vec::new();
|
||||
|
||||
for marketplace in marketplaces {
|
||||
for entry in marketplace.plugins {
|
||||
if entry.installed {
|
||||
installed.push(entry);
|
||||
} else if include_available {
|
||||
available.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
installed,
|
||||
available,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct PluginListEntry {
|
||||
plugin_id: String,
|
||||
name: String,
|
||||
marketplace_name: String,
|
||||
version: Option<String>,
|
||||
#[serde(skip)]
|
||||
display_version: Option<String>,
|
||||
installed: bool,
|
||||
enabled: bool,
|
||||
source: JsonPluginSource,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
marketplace_source: Option<JsonMarketplaceSource>,
|
||||
install_policy: &'static str,
|
||||
auth_policy: &'static str,
|
||||
}
|
||||
|
||||
impl PluginListEntry {
|
||||
fn from_configured_plugin(
|
||||
marketplace_name: &str,
|
||||
marketplace_source: Option<JsonMarketplaceSource>,
|
||||
plugin: akode_core_plugins::ConfiguredMarketplacePlugin,
|
||||
) -> Self {
|
||||
let display_version = plugin.installed_version;
|
||||
let version = display_version.clone().or(plugin.local_version);
|
||||
Self {
|
||||
plugin_id: plugin.id,
|
||||
name: plugin.name,
|
||||
marketplace_name: marketplace_name.to_string(),
|
||||
version,
|
||||
display_version,
|
||||
installed: plugin.installed,
|
||||
enabled: plugin.enabled,
|
||||
source: JsonPluginSource::from_marketplace_source(plugin.source),
|
||||
marketplace_source,
|
||||
install_policy: install_policy_label(plugin.policy.installation),
|
||||
auth_policy: auth_policy_label(plugin.policy.authentication),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(tag = "source", rename_all = "kebab-case")]
|
||||
enum JsonPluginSource {
|
||||
Local {
|
||||
path: String,
|
||||
},
|
||||
Git {
|
||||
url: String,
|
||||
#[serde(rename = "ref", skip_serializing_if = "Option::is_none")]
|
||||
ref_name: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
sha: Option<String>,
|
||||
},
|
||||
GitSubdir {
|
||||
url: String,
|
||||
path: String,
|
||||
#[serde(rename = "ref", skip_serializing_if = "Option::is_none")]
|
||||
ref_name: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
sha: Option<String>,
|
||||
},
|
||||
Npm {
|
||||
package: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
version: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
registry: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl JsonPluginSource {
|
||||
fn from_marketplace_source(source: MarketplacePluginSource) -> Self {
|
||||
match source {
|
||||
MarketplacePluginSource::Local { path } => Self::Local {
|
||||
path: path.as_path().display().to_string(),
|
||||
},
|
||||
MarketplacePluginSource::Git {
|
||||
url,
|
||||
path: Some(path),
|
||||
ref_name,
|
||||
sha,
|
||||
} => Self::GitSubdir {
|
||||
url,
|
||||
path,
|
||||
ref_name,
|
||||
sha,
|
||||
},
|
||||
MarketplacePluginSource::Git {
|
||||
url,
|
||||
path: None,
|
||||
ref_name,
|
||||
sha,
|
||||
} => Self::Git { url, ref_name, sha },
|
||||
MarketplacePluginSource::Npm {
|
||||
package,
|
||||
version,
|
||||
registry,
|
||||
} => Self::Npm {
|
||||
package,
|
||||
version,
|
||||
registry,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct JsonMarketplaceSource {
|
||||
source_type: String,
|
||||
source: String,
|
||||
}
|
||||
|
||||
pub(crate) fn configured_marketplace_sources(
|
||||
plugins_input: &PluginsConfigInput,
|
||||
codex_home: &Path,
|
||||
) -> HashMap<String, JsonMarketplaceSource> {
|
||||
let effective_config = plugins_input.config_layer_stack.effective_config();
|
||||
let Some(marketplaces) = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
else {
|
||||
return HashMap::new();
|
||||
};
|
||||
let allowed_marketplace_names =
|
||||
allowed_configured_marketplace_names(&plugins_input.config_layer_stack, codex_home);
|
||||
|
||||
marketplaces
|
||||
.iter()
|
||||
.filter(|(marketplace_name, _)| allowed_marketplace_names.contains(*marketplace_name))
|
||||
.filter_map(|(marketplace_name, marketplace)| {
|
||||
let source_type = marketplace
|
||||
.get("source_type")
|
||||
.and_then(toml::Value::as_str)?;
|
||||
let source = marketplace.get("source").and_then(toml::Value::as_str)?;
|
||||
Some((
|
||||
marketplace_name.clone(),
|
||||
JsonMarketplaceSource {
|
||||
source_type: source_type.to_string(),
|
||||
source: source.to_string(),
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn install_policy_label(policy: MarketplacePluginInstallPolicy) -> &'static str {
|
||||
match policy {
|
||||
MarketplacePluginInstallPolicy::NotAvailable => "NOT_AVAILABLE",
|
||||
MarketplacePluginInstallPolicy::Available => "AVAILABLE",
|
||||
MarketplacePluginInstallPolicy::InstalledByDefault => "INSTALLED_BY_DEFAULT",
|
||||
}
|
||||
}
|
||||
|
||||
fn auth_policy_label(policy: MarketplacePluginAuthPolicy) -> &'static str {
|
||||
match policy {
|
||||
MarketplacePluginAuthPolicy::OnInstall => "ON_INSTALL",
|
||||
MarketplacePluginAuthPolicy::OnUse => "ON_USE",
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_plugin_remove(
|
||||
overrides: Vec<(String, toml::Value)>,
|
||||
args: RemovePluginArgs,
|
||||
) -> Result<()> {
|
||||
let RemovePluginArgs {
|
||||
plugin,
|
||||
marketplace_name,
|
||||
json,
|
||||
} = args;
|
||||
let selection = parse_plugin_selection(plugin, marketplace_name)?;
|
||||
let context = load_plugin_command_context(overrides).await?;
|
||||
|
||||
context
|
||||
.manager
|
||||
.uninstall_plugin(selection.plugin_key.clone())
|
||||
.await?;
|
||||
if json {
|
||||
let output = JsonPluginRemoveOutput::from_selection(selection);
|
||||
println!("{}", serde_json::to_string_pretty(&output)?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!(
|
||||
"Removed plugin `{}` from marketplace `{}`.",
|
||||
selection.plugin_name, selection.marketplace_name
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct JsonPluginRemoveOutput {
|
||||
plugin_id: String,
|
||||
name: String,
|
||||
marketplace_name: String,
|
||||
}
|
||||
|
||||
impl JsonPluginRemoveOutput {
|
||||
fn from_selection(selection: PluginSelection) -> Self {
|
||||
Self {
|
||||
plugin_id: selection.plugin_key,
|
||||
name: selection.plugin_name,
|
||||
marketplace_name: selection.marketplace_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PluginCommandContext {
|
||||
codex_home: PathBuf,
|
||||
plugins_input: PluginsConfigInput,
|
||||
manager: Arc<PluginsManager>,
|
||||
}
|
||||
|
||||
async fn load_plugin_command_context(
|
||||
overrides: Vec<(String, toml::Value)>,
|
||||
) -> Result<PluginCommandContext> {
|
||||
let codex_home = find_codex_home().context("failed to resolve AKODE_HOME")?;
|
||||
let config = Config::load_with_cli_overrides(overrides)
|
||||
.await
|
||||
.context("failed to load configuration")?;
|
||||
let plugins_input = config.plugins_config_input();
|
||||
let auth_manager = load_cli_auth_manager(&config).await?;
|
||||
let manager = Arc::new(plugins_manager_for_config(&config, auth_manager));
|
||||
Ok(PluginCommandContext {
|
||||
codex_home: codex_home.to_path_buf(),
|
||||
plugins_input,
|
||||
manager,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn load_cli_auth_manager(config: &Config) -> Result<Arc<AuthManager>> {
|
||||
Ok(AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ true).await?)
|
||||
}
|
||||
|
||||
struct PluginSelection {
|
||||
plugin_name: String,
|
||||
marketplace_name: String,
|
||||
plugin_key: String,
|
||||
}
|
||||
|
||||
impl PluginSelection {
|
||||
fn from_plugin_id(plugin_id: PluginId) -> Self {
|
||||
let plugin_key = plugin_id.as_key();
|
||||
Self {
|
||||
plugin_name: plugin_id.plugin_name,
|
||||
marketplace_name: plugin_id.marketplace_name,
|
||||
plugin_key,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_plugin_selection(
|
||||
plugin: String,
|
||||
marketplace_name: Option<String>,
|
||||
) -> Result<PluginSelection> {
|
||||
match (PluginId::parse(&plugin), marketplace_name) {
|
||||
(Ok(plugin_id), None) => Ok(PluginSelection::from_plugin_id(plugin_id)),
|
||||
(Ok(plugin_id), Some(marketplace_name)) => {
|
||||
if plugin_id.marketplace_name != marketplace_name {
|
||||
bail!(
|
||||
"plugin id `{}` belongs to marketplace `{}`, but --marketplace specified `{}`",
|
||||
plugin,
|
||||
plugin_id.marketplace_name,
|
||||
marketplace_name
|
||||
);
|
||||
}
|
||||
Ok(PluginSelection::from_plugin_id(plugin_id))
|
||||
}
|
||||
(Err(_), Some(marketplace_name)) => Ok(PluginSelection::from_plugin_id(PluginId::new(
|
||||
plugin,
|
||||
marketplace_name,
|
||||
)?)),
|
||||
(Err(_), None) => {
|
||||
bail!("plugin requires --marketplace unless passed as <plugin>@<marketplace>")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn find_marketplace_for_plugin(
|
||||
manager: &PluginsManager,
|
||||
codex_home: &std::path::Path,
|
||||
plugins_input: &PluginsConfigInput,
|
||||
marketplace_name: &str,
|
||||
plugin_name: &str,
|
||||
) -> Result<ConfiguredMarketplace> {
|
||||
let outcome = manager
|
||||
.list_marketplaces_for_config(plugins_input, &[], /*include_openai_curated*/ true)
|
||||
.context("failed to list marketplace plugins")?;
|
||||
ensure_configured_marketplace_snapshots_loaded(
|
||||
codex_home,
|
||||
plugins_input,
|
||||
&outcome.errors,
|
||||
Some(marketplace_name),
|
||||
)?;
|
||||
let matches = outcome
|
||||
.marketplaces
|
||||
.into_iter()
|
||||
.filter(|marketplace| marketplace.name == marketplace_name)
|
||||
.filter(|marketplace| {
|
||||
marketplace
|
||||
.plugins
|
||||
.iter()
|
||||
.any(|plugin| plugin.name == plugin_name)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
match matches.as_slice() {
|
||||
[] => bail!("plugin `{plugin_name}` was not found in marketplace `{marketplace_name}`"),
|
||||
[marketplace] => Ok(marketplace.clone()),
|
||||
_ => bail!(
|
||||
"plugin `{plugin_name}` in marketplace `{marketplace_name}` matched multiple marketplace roots"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ConfiguredMarketplaceSnapshotIssue {
|
||||
pub(crate) marketplace_name: String,
|
||||
pub(crate) path: PathBuf,
|
||||
pub(crate) message: String,
|
||||
}
|
||||
|
||||
fn ensure_configured_marketplace_snapshots_loaded(
|
||||
codex_home: &std::path::Path,
|
||||
plugins_input: &PluginsConfigInput,
|
||||
load_errors: &[MarketplaceListError],
|
||||
marketplace_name: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let issues = configured_marketplace_snapshot_issues(
|
||||
codex_home,
|
||||
plugins_input,
|
||||
load_errors,
|
||||
marketplace_name,
|
||||
);
|
||||
if issues.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let issue_lines = issues
|
||||
.iter()
|
||||
.map(|issue| {
|
||||
format!(
|
||||
"- `{}` at {}: {}",
|
||||
issue.marketplace_name,
|
||||
issue.path.display(),
|
||||
issue.message
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
bail!("failed to load configured marketplace snapshot(s):\n{issue_lines}");
|
||||
}
|
||||
|
||||
pub(crate) fn configured_marketplace_snapshot_issues(
|
||||
codex_home: &std::path::Path,
|
||||
plugins_input: &PluginsConfigInput,
|
||||
load_errors: &[MarketplaceListError],
|
||||
marketplace_name: Option<&str>,
|
||||
) -> Vec<ConfiguredMarketplaceSnapshotIssue> {
|
||||
let effective_config = plugins_input.config_layer_stack.effective_config();
|
||||
let Some(configured_marketplaces) = effective_config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let allowed_marketplace_names =
|
||||
allowed_configured_marketplace_names(&plugins_input.config_layer_stack, codex_home);
|
||||
|
||||
let default_install_root = marketplace_install_root(codex_home);
|
||||
let mut manifest_paths = Vec::new();
|
||||
let mut issues = Vec::new();
|
||||
for (configured_name, marketplace) in configured_marketplaces {
|
||||
if !allowed_marketplace_names.contains(configured_name) {
|
||||
continue;
|
||||
}
|
||||
if marketplace_name.is_some_and(|name| configured_name != name) {
|
||||
continue;
|
||||
}
|
||||
if !marketplace.is_table() {
|
||||
issues.push(ConfiguredMarketplaceSnapshotIssue {
|
||||
marketplace_name: configured_name.clone(),
|
||||
path: PathBuf::from("<invalid config>"),
|
||||
message: "configured marketplace entry must be a table".to_string(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if let Err(err) = validate_plugin_segment(configured_name, "marketplace name") {
|
||||
issues.push(ConfiguredMarketplaceSnapshotIssue {
|
||||
marketplace_name: configured_name.clone(),
|
||||
path: PathBuf::from("<invalid config>"),
|
||||
message: err.to_string(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if marketplace.get("source_type").and_then(toml::Value::as_str) == Some("local")
|
||||
&& marketplace
|
||||
.get("source")
|
||||
.and_then(toml::Value::as_str)
|
||||
.is_none_or(str::is_empty)
|
||||
{
|
||||
issues.push(ConfiguredMarketplaceSnapshotIssue {
|
||||
marketplace_name: configured_name.clone(),
|
||||
path: PathBuf::from("<invalid source>"),
|
||||
message: "configured local marketplace source is missing or empty".to_string(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let Some(root) = resolve_configured_marketplace_root(
|
||||
configured_name,
|
||||
marketplace,
|
||||
&default_install_root,
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
match find_marketplace_manifest_path(&root) {
|
||||
Some(path) => manifest_paths.push((configured_name.clone(), path)),
|
||||
None => {
|
||||
if is_implicit_system_marketplace_root(configured_name, codex_home, &root) {
|
||||
continue;
|
||||
}
|
||||
issues.push(ConfiguredMarketplaceSnapshotIssue {
|
||||
marketplace_name: configured_name.clone(),
|
||||
path: root,
|
||||
message: "marketplace root does not contain a supported manifest".to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for error in load_errors {
|
||||
if let Some((configured_name, _)) = manifest_paths
|
||||
.iter()
|
||||
.find(|(_, path)| path.as_path() == error.path.as_path())
|
||||
{
|
||||
issues.push(ConfiguredMarketplaceSnapshotIssue {
|
||||
marketplace_name: configured_name.clone(),
|
||||
path: error.path.to_path_buf(),
|
||||
message: error.message.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
issues
|
||||
}
|
||||
|
||||
fn is_implicit_system_marketplace_root(
|
||||
marketplace_name: &str,
|
||||
_codex_home: &Path,
|
||||
root: &Path,
|
||||
) -> bool {
|
||||
if matches!(
|
||||
marketplace_name,
|
||||
OPENAI_BUNDLED_MARKETPLACE_NAME | OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME
|
||||
) && path_ends_with(root, &[".tmp", "bundled-marketplaces", marketplace_name])
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
marketplace_name == OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME
|
||||
&& path_ends_with(
|
||||
root,
|
||||
&[
|
||||
"codex-runtimes",
|
||||
"codex-primary-runtime",
|
||||
"plugins",
|
||||
marketplace_name,
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn path_ends_with(path: &Path, suffix: &[&str]) -> bool {
|
||||
let path_components = path
|
||||
.components()
|
||||
.map(|component| component.as_os_str().to_string_lossy().into_owned())
|
||||
.collect::<Vec<_>>();
|
||||
path_components.as_slice().ends_with(
|
||||
&suffix
|
||||
.iter()
|
||||
.map(std::string::ToString::to_string)
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "plugin_cmd_tests.rs"]
|
||||
mod tests;
|
||||
76
akode-rs/cli/src/plugin_cmd_tests.rs
Normal file
76
akode-rs/cli/src/plugin_cmd_tests.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
//! Verify plugin-list output error handling at the writer boundary.
|
||||
|
||||
use super::ListPluginsArgs;
|
||||
use super::write_plugin_list;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Failure {
|
||||
Write,
|
||||
Flush,
|
||||
}
|
||||
|
||||
struct FailingWriter {
|
||||
failure: Failure,
|
||||
kind: io::ErrorKind,
|
||||
}
|
||||
|
||||
impl Write for FailingWriter {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
match self.failure {
|
||||
Failure::Write => Err(io::Error::new(self.kind, "output failed")),
|
||||
Failure::Flush => Ok(bytes.len()),
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
match self.failure {
|
||||
Failure::Write => Ok(()),
|
||||
Failure::Flush => Err(io::Error::new(self.kind, "output failed")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_list_treats_broken_pipe_as_success() {
|
||||
for json in [false, true] {
|
||||
for failure in [Failure::Write, Failure::Flush] {
|
||||
let mut writer = FailingWriter {
|
||||
failure,
|
||||
kind: io::ErrorKind::BrokenPipe,
|
||||
};
|
||||
let args = ListPluginsArgs {
|
||||
marketplace_name: None,
|
||||
json,
|
||||
available: true,
|
||||
};
|
||||
|
||||
write_plugin_list(&mut writer, Vec::new(), args).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_list_preserves_other_output_errors() {
|
||||
for json in [false, true] {
|
||||
for failure in [Failure::Write, Failure::Flush] {
|
||||
for kind in [io::ErrorKind::PermissionDenied, io::ErrorKind::WriteZero] {
|
||||
let mut writer = FailingWriter { failure, kind };
|
||||
let args = ListPluginsArgs {
|
||||
marketplace_name: None,
|
||||
json,
|
||||
available: true,
|
||||
};
|
||||
|
||||
let error = write_plugin_list(&mut writer, Vec::new(), args)
|
||||
.unwrap_err()
|
||||
.downcast::<io::Error>()
|
||||
.unwrap();
|
||||
assert_eq!(error.kind(), kind);
|
||||
assert_eq!(error.to_string(), "output failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
153
akode-rs/cli/src/queue_cmd.rs
Normal file
153
akode-rs/cli/src/queue_cmd.rs
Normal file
@@ -0,0 +1,153 @@
|
||||
use clap::Arg;
|
||||
use clap::ArgMatches;
|
||||
use clap::Command;
|
||||
use clap::CommandFactory;
|
||||
use clap::Parser;
|
||||
use clap::builder::NonEmptyStringValueParser;
|
||||
use clap::error::ErrorKind;
|
||||
use clap::parser::ValueSource;
|
||||
use akode_arg0::Arg0DispatchPaths;
|
||||
use akode_tui::Cli as TuiCli;
|
||||
use akode_utils_cli::CliConfigOverrides;
|
||||
|
||||
use crate::InteractiveRemoteOptions;
|
||||
use crate::SessionArchiveConfigOverrides;
|
||||
use crate::finalize_session_archive_interactive;
|
||||
use crate::resolve_remote_endpoint;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(defer(configure_help))]
|
||||
pub(crate) struct QueueCommand {
|
||||
/// Session UUID or exact session name.
|
||||
#[arg(long, value_name = "THREAD")]
|
||||
thread: String,
|
||||
|
||||
/// Message text to queue.
|
||||
#[arg(long, value_name = "TEXT", value_parser = NonEmptyStringValueParser::new())]
|
||||
message: String,
|
||||
|
||||
/// After queueing, try to resume the thread on the local daemon or selected --remote server.
|
||||
/// A failed resume produces a warning and the command still succeeds.
|
||||
#[arg(long)]
|
||||
resume: bool,
|
||||
|
||||
#[clap(flatten)]
|
||||
remote: InteractiveRemoteOptions,
|
||||
|
||||
#[clap(flatten)]
|
||||
pub(crate) config_overrides: SessionArchiveConfigOverrides,
|
||||
}
|
||||
|
||||
/// Only inherited options need restrictions; queue owns its other arguments.
|
||||
fn restricted_options(command: &Command) -> impl Iterator<Item = &Arg> {
|
||||
command.get_arguments().filter(|arg| {
|
||||
!matches!(
|
||||
arg.get_long(),
|
||||
Some(
|
||||
"remote"
|
||||
| "remote-auth-token-env"
|
||||
| "config"
|
||||
| "enable"
|
||||
| "disable"
|
||||
| "profile"
|
||||
| "strict-config"
|
||||
)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn configure_help(command: Command) -> Command {
|
||||
let interactive = TuiCli::command();
|
||||
command.mut_args(|arg| {
|
||||
if arg.get_long() == Some("config") {
|
||||
arg.long_help(None).help("Override a startup configuration value (key=value). Queued messages use the thread's model.")
|
||||
} else if !restricted_options(&interactive).any(|shared| shared.get_id() == arg.get_id()) {
|
||||
arg
|
||||
} else if arg.get_long() == Some("cd") {
|
||||
arg.help_heading("Local server options (without --remote)")
|
||||
} else {
|
||||
arg.hide(true)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Check both scopes before root flags such as `--approve-for-me` become config overrides.
|
||||
pub(super) fn validate_options(command: &Command, root: &ArgMatches) -> Result<(), clap::Error> {
|
||||
let Some(queue) = root.subcommand_matches("queue") else {
|
||||
return Ok(());
|
||||
};
|
||||
let remote = root
|
||||
.get_one::<String>("remote")
|
||||
.or_else(|| queue.get_one::<String>("remote"));
|
||||
let supplied = [root, queue].into_iter().flat_map(|scope| {
|
||||
scope
|
||||
.ids()
|
||||
.filter(|id| scope.value_source(id.as_str()) == Some(ValueSource::CommandLine))
|
||||
});
|
||||
for id in supplied {
|
||||
let Some(arg) = restricted_options(command).find(|arg| arg.get_id() == id) else {
|
||||
continue;
|
||||
};
|
||||
let message = match arg.get_long() {
|
||||
Some("cd") if remote.is_none() => continue,
|
||||
Some("cd") => "`akode queue` does not support `--cd` with `--remote`".to_string(),
|
||||
// These flags already have dedicated diagnostics in the CLI and session startup.
|
||||
Some("worktree" | "no-daemon") => continue,
|
||||
Some("model") => {
|
||||
"`akode queue` does not support `--model`; queued messages use the thread's model"
|
||||
.to_string()
|
||||
}
|
||||
Some("image") => "`akode queue` does not support image attachments".to_string(),
|
||||
Some(name) => format!("`akode queue` does not support `--{name}`"),
|
||||
None => {
|
||||
"`akode queue` does not accept a positional prompt; use `--message`".to_string()
|
||||
}
|
||||
};
|
||||
return Err(clap::Error::raw(ErrorKind::ArgumentConflict, message));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn run_queue_command(
|
||||
command: QueueCommand,
|
||||
interactive: TuiCli,
|
||||
root_config_overrides: CliConfigOverrides,
|
||||
root_remote: Option<String>,
|
||||
root_remote_auth_token_env: Option<String>,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
) -> anyhow::Result<String> {
|
||||
let QueueCommand {
|
||||
thread,
|
||||
message,
|
||||
resume,
|
||||
remote,
|
||||
config_overrides,
|
||||
} = command;
|
||||
let cli =
|
||||
finalize_session_archive_interactive(interactive, root_config_overrides, config_overrides);
|
||||
if cli.config_overrides.raw_overrides.iter().any(|entry| {
|
||||
entry
|
||||
.split_once('=')
|
||||
.is_some_and(|(key, _)| key.trim() == "model")
|
||||
}) {
|
||||
anyhow::bail!(
|
||||
"`akode queue` does not support a `model` config override; queued messages use the thread's model"
|
||||
);
|
||||
}
|
||||
let explicit_remote_endpoint = resolve_remote_endpoint(
|
||||
remote.remote.or(root_remote),
|
||||
remote.remote_auth_token_env.or(root_remote_auth_token_env),
|
||||
)?;
|
||||
akode_tui::run_session_queue_command(
|
||||
thread,
|
||||
message,
|
||||
resume,
|
||||
akode_tui::SessionArchiveCommandOptions {
|
||||
cli,
|
||||
arg0_paths,
|
||||
explicit_remote_endpoint,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!("{error:#}"))
|
||||
}
|
||||
230
akode-rs/cli/src/sandbox_setup.rs
Normal file
230
akode-rs/cli/src/sandbox_setup.rs
Normal file
@@ -0,0 +1,230 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Context;
|
||||
use clap::ArgAction;
|
||||
use clap::ArgGroup;
|
||||
use clap::Parser;
|
||||
use akode_core::config::ConfigBuilder;
|
||||
use akode_core::config::edit::ConfigEditsBuilder;
|
||||
use akode_core::config::find_codex_home;
|
||||
use akode_utils_cli::ProfileV2Name;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(group(
|
||||
ArgGroup::new("sandbox_user")
|
||||
.required(true)
|
||||
.args(["user", "current_user"])
|
||||
))]
|
||||
pub(crate) struct SandboxSetupCommand {
|
||||
/// Set up the elevated Windows sandbox.
|
||||
#[arg(long = "elevated", action = ArgAction::SetTrue)]
|
||||
elevated_sandbox_level: bool,
|
||||
|
||||
/// Windows user that will run aKode after managed deployment.
|
||||
#[arg(
|
||||
long = "user",
|
||||
value_name = "USER",
|
||||
conflicts_with = "current_user",
|
||||
requires = "codex_home"
|
||||
)]
|
||||
user: Option<String>,
|
||||
|
||||
/// Use the current Windows user as the aKode user.
|
||||
#[arg(
|
||||
long = "current-user",
|
||||
default_value_t = false,
|
||||
conflicts_with = "user"
|
||||
)]
|
||||
current_user: bool,
|
||||
|
||||
/// AKODE_HOME for the aKode user. Required with --user.
|
||||
#[arg(long = "akode-home", value_name = "DIR")]
|
||||
codex_home: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum SandboxSetupLevel {
|
||||
Elevated,
|
||||
}
|
||||
|
||||
impl SandboxSetupCommand {
|
||||
fn setup_level(&self) -> anyhow::Result<SandboxSetupLevel> {
|
||||
if self.elevated_sandbox_level {
|
||||
Ok(SandboxSetupLevel::Elevated)
|
||||
} else {
|
||||
anyhow::bail!("`akode sandbox setup` currently requires --elevated");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
cmd: SandboxSetupCommand,
|
||||
config_profile: Option<ProfileV2Name>,
|
||||
cli_overrides: Vec<(String, TomlValue)>,
|
||||
) -> anyhow::Result<()> {
|
||||
match cmd.setup_level()? {
|
||||
SandboxSetupLevel::Elevated => run_elevated(cmd, config_profile, cli_overrides).await,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_setup_command(
|
||||
sandbox_command: &[String],
|
||||
) -> anyhow::Result<Option<SandboxSetupCommand>> {
|
||||
if sandbox_command
|
||||
.first()
|
||||
.is_none_or(|command| command != "setup")
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
SandboxSetupCommand::try_parse_from(sandbox_command.iter().map(String::as_str))
|
||||
.map(Some)
|
||||
.map_err(anyhow::Error::from)
|
||||
}
|
||||
|
||||
async fn run_elevated(
|
||||
cmd: SandboxSetupCommand,
|
||||
config_profile: Option<ProfileV2Name>,
|
||||
cli_overrides: Vec<(String, TomlValue)>,
|
||||
) -> anyhow::Result<()> {
|
||||
let identity = resolve_sandbox_setup_identity(&cmd)?;
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(identity.codex_home.clone())
|
||||
.fallback_cwd(Some(identity.codex_home.clone()))
|
||||
.loader_overrides(super::loader_overrides_for_profile_at_codex_home(
|
||||
config_profile.as_ref(),
|
||||
&identity.codex_home,
|
||||
))
|
||||
.cli_overrides(cli_overrides)
|
||||
.build()
|
||||
.await
|
||||
.context("failed to load target user's aKode config for sandbox provisioning")?;
|
||||
|
||||
akode_core::windows_sandbox::run_elevated_provisioning_setup(
|
||||
identity.codex_home.as_path(),
|
||||
identity.real_user.as_str(),
|
||||
config.permissions.network.as_ref(),
|
||||
)?;
|
||||
ConfigEditsBuilder::new(identity.codex_home.as_path())
|
||||
.set_windows_sandbox_mode("elevated")
|
||||
.apply()
|
||||
.await
|
||||
.map_err(|err| {
|
||||
anyhow::anyhow!(
|
||||
"sandbox provisioning succeeded, but failed to persist elevated sandbox config: {err}"
|
||||
)
|
||||
})?;
|
||||
|
||||
println!(
|
||||
"Windows elevated sandbox setup completed for {} at {}.",
|
||||
identity.real_user,
|
||||
identity.codex_home.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct SandboxSetupIdentity {
|
||||
real_user: String,
|
||||
codex_home: PathBuf,
|
||||
}
|
||||
|
||||
fn resolve_sandbox_setup_identity(
|
||||
cmd: &SandboxSetupCommand,
|
||||
) -> anyhow::Result<SandboxSetupIdentity> {
|
||||
if cmd.current_user {
|
||||
let real_user = std::env::var("USERNAME")
|
||||
.or_else(|_| std::env::var("USER"))
|
||||
.map_err(|err| {
|
||||
anyhow::anyhow!("failed to determine current user from environment: {err}")
|
||||
})?;
|
||||
let codex_home = match cmd.codex_home.clone() {
|
||||
Some(codex_home) => codex_home,
|
||||
None => find_codex_home()?.to_path_buf(),
|
||||
};
|
||||
return Ok(SandboxSetupIdentity {
|
||||
real_user,
|
||||
codex_home,
|
||||
});
|
||||
}
|
||||
|
||||
let real_user = cmd
|
||||
.user
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("--user or --current-user is required"))?;
|
||||
let codex_home = cmd
|
||||
.codex_home
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("--codex-home is required with --user"))?;
|
||||
Ok(SandboxSetupIdentity {
|
||||
real_user,
|
||||
codex_home,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_managed_user_identity() {
|
||||
let command = SandboxSetupCommand::try_parse_from([
|
||||
"setup",
|
||||
"--elevated",
|
||||
"--user",
|
||||
"DOMAIN\\alice",
|
||||
"--codex-home",
|
||||
r"C:\Users\alice\.akode",
|
||||
])
|
||||
.expect("parse");
|
||||
|
||||
assert!(command.elevated_sandbox_level);
|
||||
assert_eq!(command.user.as_deref(), Some(r"DOMAIN\alice"));
|
||||
assert!(!command.current_user);
|
||||
assert_eq!(
|
||||
command.codex_home.as_deref(),
|
||||
Some(std::path::Path::new(r"C:\Users\alice\.akode"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requires_explicit_user_identity() {
|
||||
let err = SandboxSetupCommand::try_parse_from(["setup", "--elevated"])
|
||||
.expect_err("parse should fail");
|
||||
|
||||
assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requires_codex_home_for_managed_user() {
|
||||
let err =
|
||||
SandboxSetupCommand::try_parse_from(["setup", "--elevated", "--user", "DOMAIN\\alice"])
|
||||
.expect_err("parse should fail");
|
||||
|
||||
assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_setup_from_sandbox_command_args() {
|
||||
let command = parse_setup_command(&[
|
||||
"setup".to_string(),
|
||||
"--elevated".to_string(),
|
||||
"--user".to_string(),
|
||||
r"DOMAIN\alice".to_string(),
|
||||
"--codex-home".to_string(),
|
||||
r"C:\Users\alice\.akode".to_string(),
|
||||
])
|
||||
.expect("parse")
|
||||
.expect("setup command");
|
||||
|
||||
assert_eq!(command.user.as_deref(), Some(r"DOMAIN\alice"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_setup_sandbox_command_args() {
|
||||
let command =
|
||||
parse_setup_command(&["echo".to_string(), "hello".to_string()]).expect("parse");
|
||||
|
||||
assert!(command.is_none());
|
||||
}
|
||||
}
|
||||
21
akode-rs/cli/src/sandbox_uninstall.rs
Normal file
21
akode-rs/cli/src/sandbox_uninstall.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
//! Uninstalls the legacy Windows sandbox without loading config or removing user data.
|
||||
|
||||
use clap::Args;
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
#[command(
|
||||
about = "Remove the legacy Windows sandbox's machine-wide accounts and network rules",
|
||||
after_help = "Run as administrator after stopping apps using the legacy sandbox and its provisioning service, if installed.\nPreserves aKode home, including sandbox directories and filesystem permissions."
|
||||
)]
|
||||
pub(crate) struct SandboxUninstallCommand {}
|
||||
|
||||
impl SandboxUninstallCommand {
|
||||
pub(crate) fn run(self) -> anyhow::Result<()> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
akode_windows_sandbox::clean_up_legacy_windows_sandbox()
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
anyhow::bail!("`akode sandbox uninstall` is only supported on Windows")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
source: cli/src/doctor.rs
|
||||
expression: "render_human_report(&report, HumanOutputOptions\n{ show_details: true, show_all: true, ascii: true, color_enabled: false, })"
|
||||
---
|
||||
aKode Doctor v0.0.0
|
||||
|
||||
Notes
|
||||
[!!] terminal TERM=dumb - colors and cursor control are disabled in this non-interactive run
|
||||
-------------------------------------------------------------
|
||||
|
||||
Environment
|
||||
[!!] terminal TERM=dumb - colors and cursor control are disabled in this non-interactive run
|
||||
terminal dumb
|
||||
TERM dumb
|
||||
stdin is terminal false
|
||||
stdout is terminal false
|
||||
stderr is terminal false
|
||||
terminal size 120x40
|
||||
color output disabled (TERM=dumb)
|
||||
|
||||
-------------------------------------------------------------
|
||||
0 ok | 1 notes | 1 warn | 0 fail degraded
|
||||
|
||||
--summary compact output --all expand truncated lists
|
||||
--json redacted report
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
source: cli/src/doctor.rs
|
||||
expression: "render_human_report(&DoctorReport\n{\n schema_version: 1, generated_at: \"0s since unix epoch\".to_string(),\n overall_status: check.status, codex_version: \"0.0.0\".to_string(), checks:\n vec![check],\n}, HumanOutputOptions\n{ show_details: false, show_all: false, ascii: true, color_enabled: false, })"
|
||||
---
|
||||
aKode Doctor v0.0.0
|
||||
|
||||
Notes
|
||||
[XX] terminal 3 issues - TERMINFO unreadable - terminal capabilities are unknown; TERM=dumb - colors and cursor control are disabled in this non-interactive run
|
||||
-------------------------------------------------------------
|
||||
|
||||
Environment
|
||||
[XX] terminal 3 issues - TERMINFO unreadable - terminal capabilities are unknown; TERM=dumb - colors and cursor control are disabled in this non-interactive run
|
||||
|
||||
-------------------------------------------------------------
|
||||
0 ok | 1 notes | 0 warn | 1 fail failed
|
||||
|
||||
Run akode doctor without --summary for detailed diagnostics.
|
||||
--all expand truncated lists --json redacted report
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
source: cli/src/doctor.rs
|
||||
expression: rendered
|
||||
---
|
||||
successful handshake
|
||||
aKode Doctor v0.0.0
|
||||
|
||||
Connectivity
|
||||
[ok] network network environment is readable
|
||||
HTTPS proxy not set
|
||||
[ok] websocket Responses WebSocket handshake succeeded
|
||||
handshake result HTTP 101
|
||||
reasoning header true
|
||||
server model present true
|
||||
[ok] reachability active provider endpoints are reachable over HTTP
|
||||
OpenAI endpoint HTTP 200
|
||||
|
||||
-------------------------------------------------------------
|
||||
3 ok | 0 warn | 0 fail ok
|
||||
|
||||
--summary compact output --all expand truncated lists
|
||||
--json redacted report
|
||||
|
||||
immediate close
|
||||
aKode Doctor v0.0.0
|
||||
|
||||
Notes
|
||||
[!!] websocket Responses WebSocket closed immediately after handshake - Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.
|
||||
-------------------------------------------------------------
|
||||
|
||||
Connectivity
|
||||
[ok] network network environment is readable
|
||||
HTTPS proxy not set
|
||||
[!!] websocket Responses WebSocket closed immediately after handshake - Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.
|
||||
handshake result HTTP 101
|
||||
immediate close code 1008
|
||||
immediate close reason present (redacted)
|
||||
[ok] reachability active provider endpoints are reachable over HTTP
|
||||
OpenAI endpoint HTTP 200
|
||||
|
||||
-------------------------------------------------------------
|
||||
2 ok | 1 notes | 1 warn | 0 fail degraded
|
||||
|
||||
--summary compact output --all expand truncated lists
|
||||
--json redacted report
|
||||
|
||||
stream failure
|
||||
aKode Doctor v0.0.0
|
||||
|
||||
Notes
|
||||
[!!] websocket Responses WebSocket failed; HTTPS fallback may still work - Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.
|
||||
-------------------------------------------------------------
|
||||
|
||||
Connectivity
|
||||
[ok] network network environment is readable
|
||||
HTTPS proxy not set
|
||||
[!!] websocket Responses WebSocket failed; HTTPS fallback may still work - Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.
|
||||
endpoint wss://example.com/responses
|
||||
handshake stream error [redacted]
|
||||
[ok] reachability active provider endpoints are reachable over HTTP
|
||||
OpenAI endpoint HTTP 200
|
||||
|
||||
-------------------------------------------------------------
|
||||
2 ok | 1 notes | 1 warn | 0 fail degraded
|
||||
|
||||
--summary compact output --all expand truncated lists
|
||||
--json redacted report
|
||||
@@ -0,0 +1,126 @@
|
||||
---
|
||||
source: cli/src/exec_server_args_tests.rs
|
||||
expression: help_text
|
||||
---
|
||||
[EXPERIMENTAL] Run the standalone exec-server service
|
||||
|
||||
Usage: akode exec-server [OPTIONS] [COMMAND]
|
||||
|
||||
Commands:
|
||||
forward Register an existing WebSocket exec-server as a remote environment
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
|
||||
Options:
|
||||
-c, --config <key=value>
|
||||
Override a configuration value that would otherwise be loaded from
|
||||
`~/.akode/config.toml`. Use a dotted path (`foo.bar.baz`) to override
|
||||
nested values. The `value` portion is parsed as TOML. If it fails to
|
||||
parse as TOML, the raw string is used as a literal.
|
||||
|
||||
Examples: - `-c model="o3"` - `-c
|
||||
'sandbox_permissions=["disk-full-read-access"]'` - `-c
|
||||
shell_environment_policy.inherit=all`
|
||||
|
||||
--enable <FEATURE>
|
||||
Enable a feature (repeatable). Equivalent to `-c features.<name>=true`
|
||||
|
||||
--strict-config
|
||||
Error out when config.toml contains fields that are not recognized by
|
||||
this version of Codex
|
||||
|
||||
--disable <FEATURE>
|
||||
Disable a feature (repeatable). Equivalent to `-c
|
||||
features.<name>=false`
|
||||
|
||||
--linux-sandbox-pid-namespace <MODE>
|
||||
Linux PID namespace: isolate (default) or inherit. Inherit allows
|
||||
signals to other same-UID processes; enable only when provisioning a
|
||||
dedicated environment
|
||||
|
||||
[default: isolate]
|
||||
|
||||
--proxy-private-ips-via-upstream
|
||||
Allow permitted private IP destinations to use the configured upstream
|
||||
proxy. If no valid upstream proxy applies to the request protocol,
|
||||
connect directly. Loopback stays local. This flag does not require
|
||||
upstream routing
|
||||
|
||||
[env: AKODE_EXEC_SERVER_PROXY_PRIVATE_IPS_VIA_UPSTREAM]
|
||||
|
||||
--concurrent-requests <COUNT>
|
||||
Maximum number of requests to process concurrently on each connection
|
||||
|
||||
[default: 1]
|
||||
|
||||
--listen <URL>
|
||||
Transport endpoint URL. Supported values: `ws://IP:PORT` (default),
|
||||
`stdio`, `stdio://`
|
||||
|
||||
--ws-auth <MODE>
|
||||
Authentication mode for incoming WebSocket connections
|
||||
|
||||
[possible values: capability-token, signed-bearer-token]
|
||||
|
||||
--ws-token-file <PATH>
|
||||
Absolute path to the capability-token file
|
||||
|
||||
--ws-token-sha256 <HEX>
|
||||
Hex-encoded SHA-256 digest of the capability token
|
||||
|
||||
--ws-shared-secret-file <PATH>
|
||||
Absolute path to the shared secret file for signed JWT bearer tokens
|
||||
|
||||
--ws-issuer <ISSUER>
|
||||
Expected issuer for signed JWT bearer tokens
|
||||
|
||||
--ws-audience <AUDIENCE>
|
||||
Expected audience for signed JWT bearer tokens
|
||||
|
||||
--ws-max-clock-skew-seconds <SECONDS>
|
||||
Maximum clock skew when validating signed JWT bearer tokens
|
||||
|
||||
--remote <URL>
|
||||
Register this exec-server as a remote environment using the given base
|
||||
URL
|
||||
|
||||
--remote-transport <REMOTE_TRANSPORT>
|
||||
Transport used for the remote executor connection
|
||||
|
||||
[default: noise]
|
||||
[possible values: noise, direct]
|
||||
|
||||
--environment-id <ID>
|
||||
Environment id to attach to when registering remotely
|
||||
|
||||
--name <NAME>
|
||||
Human-readable environment name
|
||||
|
||||
--registration-bearer-stdin
|
||||
Read one registration bearer from stdin
|
||||
|
||||
--executor-credential-stdin
|
||||
Read rotating executor credentials from stdin; exit when the pipe
|
||||
closes
|
||||
|
||||
--aws-sigv4
|
||||
Sign Direct registration and WebSocket handshake requests with AWS
|
||||
SigV4
|
||||
|
||||
--aws-profile <PROFILE>
|
||||
AWS profile used for SigV4 authentication
|
||||
|
||||
--aws-region <REGION>
|
||||
AWS signing region. Uses the SDK region chain when omitted
|
||||
|
||||
--aws-service <SERVICE>
|
||||
AWS signing service
|
||||
|
||||
[default: execute-api]
|
||||
|
||||
--exit-on-stdin-close
|
||||
Exit when the parent-owned standard-input pipe closes
|
||||
|
||||
[env: AKODE_EXEC_SERVER_EXIT_ON_STDIN_CLOSE]
|
||||
|
||||
-h, --help
|
||||
Print help (see a summary with '-h')
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
source: cli/src/main.rs
|
||||
assertion_line: 3324
|
||||
expression: "errors.join(\"\\n\")"
|
||||
---
|
||||
akode --worktree login: `--worktree` supports new interactive sessions, `akode fork`, `akode exec`, and `akode exec fork`
|
||||
akode fork --worktree: `akode fork --worktree` requires an explicit session ID
|
||||
akode fork --worktree --last: `akode fork --worktree` requires an explicit session ID
|
||||
akode exec resume --worktree session: `--worktree` cannot resume an existing session; use `akode exec fork --worktree`
|
||||
akode exec review --worktree: `--worktree` is not supported for code review
|
||||
akode resume --worktree session: `--worktree` supports new interactive sessions, `akode fork`, `akode exec`, and `akode exec fork`
|
||||
codex archive session --worktree: `--worktree` supports new interactive sessions, `akode fork`, `akode exec`, and `akode exec fork`
|
||||
codex queue --thread session --message hi --worktree: `--worktree` supports new interactive sessions, `akode fork`, `akode exec`, and `akode exec fork`
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: cli/src/login_storage_tests.rs
|
||||
assertion_line: 52
|
||||
expression: "logs.replace(home.path().join(\"secrets\").to_str().unwrap(),\n\"[SECRETS_PATH]\").replace(&cause, \"[OS_ERROR]\")"
|
||||
---
|
||||
WARN akode_login::auth::storage: failed to save auth to keyring, falling back to file storage: failed to write CLI auth to encrypted auth storage: failed to create secrets dir [SECRETS_PATH]: [OS_ERROR]
|
||||
WARN akode_otel::auth_storage: credential storage file fallback completed credential_kind="codex" store_mode="auto" selected_store="secrets" actual_store="file" operation="save" secure_outcome="error" outcome="success" fallback_reason="secure_error" secure_error="other" storage_phase="policy" originator="none"
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
source: cli/src/login_storage_tests.rs
|
||||
assertion_line: 81
|
||||
expression: "message.replace(secrets_path.to_str().unwrap(),\n\"[SECRETS_PATH]\").replace(&cause, \"[OS_ERROR]\")"
|
||||
---
|
||||
failed to write CLI auth to encrypted auth storage: failed to create secrets dir [SECRETS_PATH]: [OS_ERROR]
|
||||
156
akode-rs/cli/src/state_db_recovery.rs
Normal file
156
akode-rs/cli/src/state_db_recovery.rs
Normal file
@@ -0,0 +1,156 @@
|
||||
//! CLI handling for local state database startup failures.
|
||||
//!
|
||||
//! This keeps user-facing backup and lock-contention handling out of the main
|
||||
//! CLI dispatch path while preserving the TUI startup error as the boundary type.
|
||||
|
||||
use akode_state::RuntimeDbBackup;
|
||||
use akode_tui::LocalStateDbStartupError;
|
||||
use std::io::IsTerminal;
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) fn startup_error(err: &std::io::Error) -> Option<&LocalStateDbStartupError> {
|
||||
err.get_ref()
|
||||
.and_then(|err| err.downcast_ref::<LocalStateDbStartupError>())
|
||||
}
|
||||
|
||||
pub(crate) fn is_locked(detail: &str) -> bool {
|
||||
akode_state::sqlite_error_detail_is_lock(detail)
|
||||
}
|
||||
|
||||
pub(crate) fn is_auto_backup_recoverable(startup_error: &LocalStateDbStartupError) -> bool {
|
||||
startup_error.is_corruption() || sqlite_home_is_blocking_file(startup_error)
|
||||
}
|
||||
|
||||
fn sqlite_home_is_blocking_file(startup_error: &LocalStateDbStartupError) -> bool {
|
||||
startup_error
|
||||
.database_path()
|
||||
.parent()
|
||||
.and_then(|path| std::fs::metadata(path).ok())
|
||||
.is_some_and(|metadata| metadata.is_file())
|
||||
}
|
||||
|
||||
pub(crate) fn print_auto_backup_start(startup_error: &LocalStateDbStartupError) {
|
||||
eprintln!("aKode couldn't start because its local database appears to be damaged.");
|
||||
eprintln!("Moving the damaged local database aside so aKode can rebuild it from saved data.");
|
||||
print_technical_details(startup_error);
|
||||
}
|
||||
|
||||
pub(crate) async fn backup_files_for_fresh_start(
|
||||
startup_error: &LocalStateDbStartupError,
|
||||
) -> std::io::Result<Vec<RuntimeDbBackup>> {
|
||||
akode_state::backup_runtime_db_for_fresh_start(startup_error.database_path()).await
|
||||
}
|
||||
|
||||
pub(crate) fn confirm_fresh_start_rebuild(
|
||||
startup_error: &LocalStateDbStartupError,
|
||||
backups: &[RuntimeDbBackup],
|
||||
) -> std::io::Result<()> {
|
||||
eprintln!("aKode rebuilt its local database.");
|
||||
eprintln!(
|
||||
"aKode detected a damaged local database, moved it into a backup folder, and will continue startup with a fresh database."
|
||||
);
|
||||
eprintln!("Database path: {}", startup_error.database_path().display());
|
||||
if let Some(backup_folder) = backup_folder(backups) {
|
||||
eprintln!("Backup folder: {}", backup_folder.display());
|
||||
} else {
|
||||
eprintln!("Backup folder: unavailable");
|
||||
}
|
||||
|
||||
if std::io::stdin().is_terminal() && std::io::stderr().is_terminal() {
|
||||
eprintln!("Press Enter to continue.");
|
||||
let mut input = String::new();
|
||||
std::io::stdin().read_line(&mut input)?;
|
||||
} else {
|
||||
eprintln!("Continuing startup with a fresh local database...");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn print_diagnostic_guidance(startup_error: &LocalStateDbStartupError) {
|
||||
eprintln!("aKode couldn't start because its local database appears to be damaged.");
|
||||
eprintln!("Run `akode doctor` to check your setup and get next-step guidance.");
|
||||
eprintln!("If this keeps happening, share the technical details below when asking for help.");
|
||||
print_technical_details(startup_error);
|
||||
}
|
||||
|
||||
pub(crate) fn print_locked_guidance(startup_error: &LocalStateDbStartupError) {
|
||||
eprintln!("aKode couldn't start because another aKode process is using its local data.");
|
||||
eprintln!("Quit any other copies of aKode that may still be running, then try again.");
|
||||
print_technical_details(startup_error);
|
||||
}
|
||||
|
||||
fn print_technical_details(startup_error: &LocalStateDbStartupError) {
|
||||
eprintln!("Technical details:");
|
||||
eprintln!(" Location: {}", startup_error.database_path().display());
|
||||
eprintln!(" Cause: {}", startup_error.detail());
|
||||
}
|
||||
|
||||
fn backup_folder(backups: &[RuntimeDbBackup]) -> Option<&Path> {
|
||||
backups.first()?.backup_path.parent()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use akode_utils_absolute_path::test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn backup_backs_up_only_failed_database_file() -> std::io::Result<()> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let sqlite = akode_state::SqliteConfig::new_for_testing(temp_dir.path().abs());
|
||||
let state_path = sqlite.state_db_path();
|
||||
let failed_db_path = sqlite.logs_db_path();
|
||||
tokio::fs::write(state_path.as_path(), b"state").await?;
|
||||
tokio::fs::write(failed_db_path.as_path(), b"logs").await?;
|
||||
|
||||
let startup_error =
|
||||
LocalStateDbStartupError::new(failed_db_path.clone(), anyhow::anyhow!("corrupt"));
|
||||
let backups = backup_files_for_fresh_start(&startup_error).await?;
|
||||
|
||||
assert_eq!(
|
||||
backups
|
||||
.iter()
|
||||
.map(|backup| &backup.original_path)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![&failed_db_path]
|
||||
);
|
||||
assert!(!tokio::fs::try_exists(failed_db_path.as_path()).await?);
|
||||
assert!(tokio::fs::try_exists(state_path.as_path()).await?);
|
||||
assert!(tokio::fs::try_exists(backups[0].backup_path.as_path()).await?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn backup_replaces_blocking_sqlite_home_file() -> std::io::Result<()> {
|
||||
let temp_dir = TempDir::new()?;
|
||||
let sqlite_home = temp_dir.path().join("sqlite-home");
|
||||
tokio::fs::write(sqlite_home.as_path(), b"not-a-directory").await?;
|
||||
let sqlite = akode_state::SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
|
||||
let startup_error =
|
||||
LocalStateDbStartupError::new(sqlite.state_db_path(), anyhow::anyhow!("File exists"));
|
||||
|
||||
assert!(is_auto_backup_recoverable(&startup_error));
|
||||
let backups = backup_files_for_fresh_start(&startup_error).await?;
|
||||
|
||||
assert_eq!(backups.len(), 1);
|
||||
assert!(tokio::fs::metadata(sqlite_home.as_path()).await?.is_dir());
|
||||
assert!(tokio::fs::try_exists(backups[0].backup_path.as_path()).await?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backup_folder_uses_parent_of_first_backup_path() {
|
||||
let backups = vec![RuntimeDbBackup {
|
||||
original_path: PathBuf::from("/tmp/state_5.sqlite"),
|
||||
backup_path: PathBuf::from("/tmp/db-backups/sqlite-1-0/state_5.sqlite"),
|
||||
}];
|
||||
|
||||
assert_eq!(
|
||||
backup_folder(&backups),
|
||||
Some(Path::new("/tmp/db-backups/sqlite-1-0"))
|
||||
);
|
||||
}
|
||||
}
|
||||
59
akode-rs/cli/src/wsl_paths.rs
Normal file
59
akode-rs/cli/src/wsl_paths.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
use std::ffi::OsStr;
|
||||
|
||||
/// Returns true if the current process is running under WSL.
|
||||
pub use akode_utils_path::is_wsl;
|
||||
|
||||
/// Convert a Windows absolute path (`C:\foo\bar` or `C:/foo/bar`) to a WSL mount path (`/mnt/c/foo/bar`).
|
||||
/// Returns `None` if the input does not look like a Windows drive path.
|
||||
pub fn win_path_to_wsl(path: &str) -> Option<String> {
|
||||
let bytes = path.as_bytes();
|
||||
if bytes.len() < 3
|
||||
|| bytes[1] != b':'
|
||||
|| !(bytes[2] == b'\\' || bytes[2] == b'/')
|
||||
|| !bytes[0].is_ascii_alphabetic()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let drive = (bytes[0] as char).to_ascii_lowercase();
|
||||
let tail = path[3..].replace('\\', "/");
|
||||
if tail.is_empty() {
|
||||
return Some(format!("/mnt/{drive}"));
|
||||
}
|
||||
Some(format!("/mnt/{drive}/{tail}"))
|
||||
}
|
||||
|
||||
/// If under WSL and given a Windows-style path, return the equivalent `/mnt/<drive>/…` path.
|
||||
/// Otherwise returns the input unchanged.
|
||||
pub fn normalize_for_wsl<P: AsRef<OsStr>>(path: P) -> String {
|
||||
let value = path.as_ref().to_string_lossy().to_string();
|
||||
if !is_wsl() {
|
||||
return value;
|
||||
}
|
||||
if let Some(mapped) = win_path_to_wsl(&value) {
|
||||
return mapped;
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn win_to_wsl_basic() {
|
||||
assert_eq!(
|
||||
win_path_to_wsl(r"C:\Temp\codex.zip").as_deref(),
|
||||
Some("/mnt/c/Temp/codex.zip")
|
||||
);
|
||||
assert_eq!(
|
||||
win_path_to_wsl("D:/Work/codex.tgz").as_deref(),
|
||||
Some("/mnt/d/Work/codex.tgz")
|
||||
);
|
||||
assert!(win_path_to_wsl("/home/user/codex").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_is_noop_on_unix_paths() {
|
||||
assert_eq!(normalize_for_wsl("/home/u/x"), "/home/u/x");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user