Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
mod pid;
pub(crate) mod stderr_log;
#[cfg(windows)]
pub(crate) mod windows;
use std::collections::BTreeMap;
use std::path::Path;
use std::path::PathBuf;
use serde::Serialize;
pub(crate) use pid::PidBackend;
pub(crate) use pid::wait_for_process_exit;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum BackendKind {
Pid,
}
#[derive(Debug, Clone)]
pub(crate) struct BackendPaths {
pub(crate) codex_bin: PathBuf,
pub(crate) pid_file: PathBuf,
pub(crate) update_pid_file: PathBuf,
pub(crate) remote_control_enabled: bool,
pub(crate) feature_overrides: BTreeMap<String, bool>,
}
pub(crate) fn pid_backend(paths: BackendPaths) -> PidBackend {
let mut backend = PidBackend::new(
paths.codex_bin,
paths.pid_file,
paths.remote_control_enabled,
);
backend.feature_overrides = paths.feature_overrides;
backend
}
pub(crate) fn pid_update_loop_backend(paths: BackendPaths) -> PidBackend {
PidBackend::new_update_loop(
paths.codex_bin,
paths.update_pid_file,
/*restore_release*/ None,
)
}
pub(crate) async fn append_stderr_log_tail_context(pid_file: &Path, context: &mut String) {
match pid::read_stderr_log_tail(pid_file).await {
Ok(Some(tail)) => tail.append_to_context(context),
Ok(None) => {}
Err(err) => {
context.push_str(&format!(
"\n\nFailed to read managed app-server stderr log: {err:#}"
));
}
}
}

View File

@@ -0,0 +1,880 @@
//! PID reservations serialize detached launches; process identities protect stale-record cleanup.
//! PID probes explicitly unlock so concurrent forks cannot retain their transient reservations.
#[path = "pid_identity.rs"]
mod identity;
#[cfg(any(unix, windows))]
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::io::SeekFrom;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use crate::managed_install::ExecutableIdentity;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
#[cfg(any(unix, windows))]
use codex_app_server_transport::REMOTE_CONTROL_DISABLED_ENV_VAR;
use serde::Deserialize;
use serde::Serialize;
use tokio::fs;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncSeekExt;
#[cfg(unix)]
use tokio::process::Command;
use tokio::time::sleep;
use crate::settings::DEFAULT_SHUTDOWN_GRACE_SECONDS;
const STOP_POLL_INTERVAL: Duration = Duration::from_millis(50);
const STOP_FORCE_TIMEOUT: Duration = Duration::from_secs(10);
const START_TIMEOUT: Duration = Duration::from_secs(10);
const STDERR_LOG_TAIL_BYTES: u64 = 4096;
#[derive(Debug)]
#[cfg_attr(not(any(unix, windows)), allow(dead_code))]
pub(crate) struct PidBackend {
pub(super) feature_overrides: BTreeMap<String, bool>,
codex_bin: PathBuf,
pid_file: PathBuf,
lock_file: PathBuf,
command_kind: PidCommandKind,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PidRecord {
pid: u32,
// Keep the legacy timestamp for older CLI/updater versions reading this record.
process_start_time: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[serde(alias = "linuxProcessIdentity")]
process_identity: Option<identity::ProcessIdentity>,
#[serde(default, skip_serializing_if = "Option::is_none")]
executable_identity: Option<ExecutableIdentity>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PidLogTail {
pub(crate) path: PathBuf,
pub(crate) contents: String,
}
impl PidLogTail {
pub(crate) fn append_to_context(&self, context: &mut String) {
context.push_str(&format!(
"\n\nManaged app-server stderr ({}):",
self.path.display()
));
for line in self.contents.lines() {
context.push_str("\n ");
context.push_str(line);
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum PidFileState {
Missing,
Starting,
Running(PidRecord),
}
#[derive(Debug, Clone)]
#[cfg_attr(not(any(unix, windows)), allow(dead_code))]
enum PidCommandKind {
AppServer { remote_control_enabled: bool },
UpdateLoop { restore_release: Option<String> },
}
impl PidBackend {
pub(crate) async fn running_executable_identity(&self) -> Result<Option<ExecutableIdentity>> {
match self.read_pid_file_state().await? {
PidFileState::Running(record) if self.record_is_active(&record).await? => {
// Updaters can exec a different release without changing PID. Only the
// updater itself can reliably identify its executable after a handoff.
if matches!(self.command_kind, PidCommandKind::UpdateLoop { .. })
&& record.pid == std::process::id()
{
return crate::managed_install::executable_identity(&std::env::current_exe()?)
.await
.map(Some);
}
Ok(record.executable_identity)
}
_ => Ok(None),
}
}
pub(crate) fn new(codex_bin: PathBuf, pid_file: PathBuf, remote_control_enabled: bool) -> Self {
let lock_file = pid_file.with_extension("pid.lock");
Self {
feature_overrides: BTreeMap::new(),
codex_bin,
pid_file,
lock_file,
command_kind: PidCommandKind::AppServer {
remote_control_enabled,
},
}
}
pub(crate) fn new_update_loop(
codex_bin: PathBuf,
pid_file: PathBuf,
restore_release: Option<String>,
) -> Self {
let lock_file = pid_file.with_extension("pid.lock");
Self {
feature_overrides: BTreeMap::new(),
codex_bin,
pid_file,
lock_file,
command_kind: PidCommandKind::UpdateLoop { restore_release },
}
}
pub(crate) async fn is_starting_or_running(&self) -> Result<bool> {
loop {
match self.read_pid_file_state().await? {
PidFileState::Missing => return Ok(false),
PidFileState::Starting => return Ok(true),
PidFileState::Running(record) => {
if self.record_is_active(&record).await? {
return Ok(true);
}
match self.refresh_after_stale_record(&record).await? {
PidFileState::Missing => return Ok(false),
PidFileState::Starting | PidFileState::Running(_) => continue,
}
}
}
}
}
#[cfg(any(unix, windows))]
pub(crate) async fn start(&self) -> Result<Option<u32>> {
self.start_inner(/*replacement*/ None).await
}
#[cfg(not(any(unix, windows)))]
pub(crate) async fn start(&self) -> Result<Option<u32>> {
bail!("pid-managed app-server startup is unsupported on this platform")
}
pub(crate) async fn stop(&self) -> Result<()> {
self.stop_with_grace(DEFAULT_SHUTDOWN_GRACE_SECONDS).await
}
pub(crate) async fn stop_with_grace(&self, grace_seconds: u32) -> Result<()> {
loop {
let Some(record) = self.wait_for_pid_start().await? else {
return Ok(());
};
if !self.record_is_active(&record).await? {
match self.refresh_after_stale_record(&record).await? {
PidFileState::Missing => return Ok(()),
PidFileState::Starting | PidFileState::Running(_) => continue,
}
}
let pid = record.pid;
crate::diagnostics::event("shutdown_requested", serde_json::json!({ "pid": pid }));
let started_at = tokio::time::Instant::now();
let force_after = Duration::from_secs(grace_seconds.into());
let deadline = started_at + force_after + STOP_FORCE_TIMEOUT;
#[cfg(unix)]
self.terminate_process(pid)?;
#[cfg(windows)]
let process = {
let Some(process) = super::windows::Process::open(pid)? else {
continue;
};
if process.start_time()? != record.process_start_time {
continue;
}
match self.command_kind {
PidCommandKind::AppServer { .. } => {
let codex_home = self
.pid_file
.parent()
.and_then(Path::parent)
.context("daemon pid path has no Codex home")?;
let socket_path =
codex_app_server_transport::app_server_control_socket_path(codex_home)?;
if let Err(err) =
crate::client::request_shutdown(socket_path.as_path(), pid).await
{
tracing::warn!(%pid, %err, "managed app-server shutdown request failed; waiting for force deadline");
}
}
PidCommandKind::UpdateLoop { .. } => {
fs::write(self.pid_file.with_extension("shutdown"), pid.to_string())
.await
.context("failed to request updater shutdown")?;
}
}
process
};
let mut forced = false;
loop {
#[cfg(unix)]
if let Ok(raw_pid) = libc::pid_t::try_from(pid)
&& raw_pid > 0
{
// A previous updater may have started this child; reap it if it has exited.
unsafe { libc::waitpid(raw_pid, std::ptr::null_mut(), libc::WNOHANG) };
}
if !self.record_is_active(&record).await? {
match self.refresh_after_stale_record(&record).await? {
PidFileState::Missing => return Ok(()),
PidFileState::Starting | PidFileState::Running(_) => break,
}
}
if tokio::time::Instant::now() >= deadline {
break;
}
if !forced && started_at.elapsed() >= force_after {
crate::diagnostics::event("shutdown_forced", serde_json::json!({ "pid": pid }));
#[cfg(unix)]
self.force_terminate_process(pid)?;
#[cfg(windows)]
process.terminate()?;
forced = true;
}
sleep(STOP_POLL_INTERVAL).await;
}
if self.record_is_active(&record).await? {
bail!("timed out waiting for pid-managed app server {pid} to stop");
}
}
}
async fn wait_for_pid_start(&self) -> Result<Option<PidRecord>> {
let deadline = tokio::time::Instant::now() + START_TIMEOUT;
loop {
match self.read_pid_file_state().await? {
PidFileState::Missing => return Ok(None),
PidFileState::Running(record) => return Ok(Some(record)),
PidFileState::Starting if tokio::time::Instant::now() < deadline => {
sleep(STOP_POLL_INTERVAL).await;
}
PidFileState::Starting => {
bail!(
"timed out waiting for pid reservation in {} to finish initializing",
self.pid_file.display()
);
}
}
}
}
async fn read_pid_file_state(&self) -> Result<PidFileState> {
let contents = match fs::read_to_string(&self.pid_file).await {
Ok(contents) => contents,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return if reservation_lock_is_active(&self.lock_file).await? {
Ok(PidFileState::Starting)
} else {
Ok(PidFileState::Missing)
};
}
Err(err) => {
return Err(err).with_context(|| {
format!("failed to read pid file {}", self.pid_file.display())
});
}
};
if contents.trim().is_empty() {
match inspect_empty_pid_reservation(&self.pid_file, &self.lock_file).await? {
EmptyPidReservation::Active => {
return Ok(PidFileState::Starting);
}
EmptyPidReservation::Stale => {
return Ok(PidFileState::Missing);
}
EmptyPidReservation::Record(record) => return Ok(PidFileState::Running(record)),
}
}
let record = serde_json::from_str(&contents)
.with_context(|| format!("invalid pid file contents in {}", self.pid_file.display()))?;
Ok(PidFileState::Running(record))
}
async fn read_pid_file_state_with_lock_held(&self) -> Result<PidFileState> {
let contents = match fs::read_to_string(&self.pid_file).await {
Ok(contents) => contents,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return Ok(PidFileState::Missing);
}
Err(err) => {
return Err(err).with_context(|| {
format!("failed to read pid file {}", self.pid_file.display())
});
}
};
if contents.trim().is_empty() {
let _ = fs::remove_file(&self.pid_file).await;
return Ok(PidFileState::Missing);
}
let record = serde_json::from_str(&contents)
.with_context(|| format!("invalid pid file contents in {}", self.pid_file.display()))?;
Ok(PidFileState::Running(record))
}
async fn refresh_after_stale_record(&self, expected: &PidRecord) -> Result<PidFileState> {
let reservation_lock = self.acquire_reservation_lock().await?;
let state = match self.read_pid_file_state_with_lock_held().await? {
PidFileState::Running(record) if record == *expected => {
let _ = fs::remove_file(&self.pid_file).await;
PidFileState::Missing
}
state => state,
};
drop(reservation_lock);
Ok(state)
}
async fn acquire_reservation_lock(&self) -> Result<fs::File> {
let reservation_lock = fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&self.lock_file)
.await
.with_context(|| {
format!("failed to open pid lock file {}", self.lock_file.display())
})?;
let lock_deadline = tokio::time::Instant::now() + START_TIMEOUT;
while !try_lock_file(&reservation_lock)? {
if tokio::time::Instant::now() >= lock_deadline {
bail!(
"timed out waiting for pid lock {}",
self.lock_file.display()
);
}
sleep(STOP_POLL_INTERVAL).await;
}
Ok(reservation_lock)
}
#[cfg(any(unix, windows))]
async fn open_stderr_log(&self) -> Result<fs::File> {
let stderr_log_file = stderr_log_file_for_pid_file(&self.pid_file);
super::stderr_log::preserve(&stderr_log_file).await;
let result = async {
fs::OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(&stderr_log_file)
.await?;
// The updater predecessor can still write after a Windows handoff
// truncates this file. Append handles prevent stale offsets and gaps.
fs::OpenOptions::new()
.append(true)
.open(&stderr_log_file)
.await
}
.await;
result.with_context(|| {
format!(
"failed to open stderr log for pid-managed app server {}",
stderr_log_file.display()
)
})
}
#[cfg(any(unix, windows))]
fn command_args(&self) -> Vec<Cow<'_, str>> {
let mut args = match &self.command_kind {
PidCommandKind::AppServer {
remote_control_enabled: true,
} => vec![
"app-server".into(),
"--remote-control".into(),
"--listen".into(),
"unix://".into(),
],
PidCommandKind::AppServer {
remote_control_enabled: false,
} => vec!["app-server".into(), "--listen".into(), "unix://".into()],
PidCommandKind::UpdateLoop { restore_release } => {
let mut args = vec![
"app-server".into(),
"daemon".into(),
"pid-update-loop".into(),
];
if let Some(release) = restore_release {
args.extend(["--restore-release".into(), release.as_str().into()]);
}
args
}
};
if matches!(self.command_kind, PidCommandKind::AppServer { .. }) {
// Match first-party clients' default while preserving explicit analytics opt-outs.
args.push("--analytics-default-enabled".into());
for (name, enabled) in &self.feature_overrides {
args.extend(["-c".into(), format!("features.{name}={enabled}").into()]);
}
}
args
}
#[cfg(any(unix, windows))]
fn command_env(&self) -> Option<(&'static str, &'static str)> {
match self.command_kind {
PidCommandKind::AppServer {
remote_control_enabled: false,
} => Some((REMOTE_CONTROL_DISABLED_ENV_VAR, "1")),
PidCommandKind::AppServer {
remote_control_enabled: true,
}
| PidCommandKind::UpdateLoop { .. } => None,
}
}
fn terminate_process(&self, pid: u32) -> Result<()> {
match self.command_kind {
PidCommandKind::AppServer { .. } => terminate_process(pid),
#[cfg(unix)]
PidCommandKind::UpdateLoop { .. } => terminate_process_group(pid),
#[cfg(not(unix))]
PidCommandKind::UpdateLoop { .. } => terminate_process(pid),
}
}
#[cfg(not(windows))]
fn force_terminate_process(&self, pid: u32) -> Result<()> {
match self.command_kind {
PidCommandKind::AppServer { .. } => force_terminate_process(pid),
PidCommandKind::UpdateLoop { .. } => force_terminate_process_group(pid),
}
}
async fn record_is_active(&self, record: &PidRecord) -> Result<bool> {
process_matches_record(record).await
}
}
/// Wait for a published process to exit without modifying its PID reservation.
pub(crate) async fn wait_for_process_exit(pid_file: &Path) {
loop {
// A missing or empty record can belong to a launch still publishing its PID.
if let Ok(contents) = fs::read(pid_file).await
&& let Ok(record) = serde_json::from_slice::<PidRecord>(&contents)
&& matches!(process_matches_record(&record).await, Ok(false))
{
return;
}
sleep(crate::START_POLL_INTERVAL).await;
}
}
pub(crate) async fn read_stderr_log_tail(pid_file: &Path) -> Result<Option<PidLogTail>> {
let path = stderr_log_file_for_pid_file(pid_file);
let Some(contents) = read_log_tail(&path, STDERR_LOG_TAIL_BYTES).await? else {
return Ok(None);
};
Ok(Some(PidLogTail { path, contents }))
}
fn stderr_log_file_for_pid_file(pid_file: &Path) -> PathBuf {
pid_file.with_extension("stderr.log")
}
async fn read_log_tail(path: &Path, byte_limit: u64) -> Result<Option<String>> {
let mut file = match fs::File::open(path).await {
Ok(file) => file,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => {
return Err(err)
.with_context(|| format!("failed to open stderr log {}", path.display()));
}
};
let len = file
.metadata()
.await
.with_context(|| format!("failed to inspect stderr log {}", path.display()))?
.len();
if len == 0 {
return Ok(None);
}
let start = len.saturating_sub(byte_limit);
file.seek(SeekFrom::Start(start))
.await
.with_context(|| format!("failed to seek stderr log {}", path.display()))?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)
.await
.with_context(|| format!("failed to read stderr log {}", path.display()))?;
if start > 0
&& let Some(newline_index) = bytes.iter().position(|byte| *byte == b'\n')
{
bytes.drain(..=newline_index);
}
let contents = String::from_utf8_lossy(&bytes).trim_end().to_string();
if contents.is_empty() {
return Ok(None);
}
Ok(Some(contents))
}
#[cfg(unix)]
fn process_exists(pid: u32) -> bool {
let Ok(pid) = libc::pid_t::try_from(pid) else {
return false;
};
let result = unsafe { libc::kill(pid, 0) };
result == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
#[cfg(unix)]
fn terminate_process(pid: u32) -> Result<()> {
let raw_pid = libc::pid_t::try_from(pid)
.with_context(|| format!("pid-managed app server pid {pid} is out of range"))?;
let result = unsafe { libc::kill(raw_pid, libc::SIGTERM) };
if result == 0 {
return Ok(());
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) {
return Ok(());
}
Err(err).with_context(|| format!("failed to terminate pid-managed app server {pid}"))
}
#[cfg(unix)]
fn force_terminate_process(pid: u32) -> Result<()> {
let raw_pid = libc::pid_t::try_from(pid)
.with_context(|| format!("pid-managed app server pid {pid} is out of range"))?;
let result = unsafe { libc::kill(raw_pid, libc::SIGKILL) };
if result == 0 {
return Ok(());
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) {
return Ok(());
}
Err(err).with_context(|| format!("failed to force terminate pid-managed app server {pid}"))
}
#[cfg(unix)]
fn terminate_process_group(pid: u32) -> Result<()> {
let raw_pid = libc::pid_t::try_from(pid)
.with_context(|| format!("pid-managed updater pid {pid} is out of range"))?;
let result = unsafe { libc::kill(-raw_pid, libc::SIGTERM) };
if result == 0 {
return Ok(());
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) {
return Ok(());
}
Err(err).with_context(|| format!("failed to terminate pid-managed updater group {pid}"))
}
#[cfg(unix)]
fn force_terminate_process_group(pid: u32) -> Result<()> {
let raw_pid = libc::pid_t::try_from(pid)
.with_context(|| format!("pid-managed updater pid {pid} is out of range"))?;
let result = unsafe { libc::kill(-raw_pid, libc::SIGKILL) };
if result == 0 {
return Ok(());
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ESRCH) {
return Ok(());
}
Err(err).with_context(|| format!("failed to force terminate pid-managed updater group {pid}"))
}
#[cfg(not(any(unix, windows)))]
fn terminate_process(_pid: u32) -> Result<()> {
bail!("pid-managed app-server shutdown is unsupported on this platform")
}
#[cfg(not(any(unix, windows)))]
fn force_terminate_process(_pid: u32) -> Result<()> {
bail!("pid-managed app-server shutdown is unsupported on this platform")
}
#[cfg(not(any(unix, windows)))]
fn force_terminate_process_group(_pid: u32) -> Result<()> {
bail!("pid-managed updater shutdown is unsupported on this platform")
}
#[cfg(unix)]
async fn process_matches_record(record: &PidRecord) -> Result<bool> {
if !process_exists(record.pid) {
return Ok(false);
}
let details = async {
#[cfg(any(target_os = "linux", target_os = "macos"))]
if let Some(expected) = &record.process_identity {
return expected.matches_process(record.pid).await;
}
let (state, start_time) = read_process_details(record.pid).await?;
let matches = start_time == record.process_start_time;
let is_zombie = state.starts_with('Z');
if !matches && !is_zombie {
bail!(
"cannot verify pid-managed process {}: legacy start time changed; PID record retained. \
Retry with the locale and timezone used to start the daemon. If the system clock \
changed, stop the original process before restarting the daemon",
record.pid
);
}
Ok((is_zombie, matches))
}
.await;
match details {
Ok((is_zombie, matches)) => {
// An unreaped zombie still passes kill(pid, 0) and retains its start
// time, but it can no longer run the app-server or updater.
if is_zombie {
if matches && let Ok(raw_pid) = libc::pid_t::try_from(record.pid) {
// Re-exec can lose the Child handle without changing parenthood.
unsafe { libc::waitpid(raw_pid, std::ptr::null_mut(), libc::WNOHANG) };
}
return Ok(false);
}
Ok(matches)
}
Err(_err) if !process_exists(record.pid) => Ok(false),
Err(err) => Err(err),
}
}
#[cfg(not(any(unix, windows)))]
async fn process_matches_record(_record: &PidRecord) -> Result<bool> {
Ok(false)
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(not(any(unix, windows)), allow(dead_code))]
enum EmptyPidReservation {
Active,
Stale,
Record(PidRecord),
}
#[cfg(unix)]
fn try_lock_file(file: &fs::File) -> Result<bool> {
use std::os::fd::AsRawFd;
let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if result == 0 {
return Ok(true);
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::EWOULDBLOCK) {
return Ok(false);
}
Err(err).context("failed to lock pid reservation")
}
#[cfg(not(any(unix, windows)))]
fn try_lock_file(_file: &fs::File) -> Result<bool> {
bail!("pid-managed app-server startup is unsupported on this platform")
}
#[cfg(any(unix, windows))]
async fn reservation_lock_is_active(path: &Path) -> Result<bool> {
let file = match fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(path)
.await
{
Ok(file) => file,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return Ok(false);
}
Err(err) => {
return Err(err)
.with_context(|| format!("failed to inspect pid lock file {}", path.display()));
}
};
probe_reservation_lock(file)
}
#[cfg(any(unix, windows))]
fn probe_reservation_lock(file: fs::File) -> Result<bool> {
if !try_lock_file(&file)? {
return Ok(true);
}
#[cfg(unix)]
{
use std::os::fd::AsRawFd;
// A concurrent fork can inherit this descriptor before it closes. Release the
// probe's lock explicitly so the child cannot look like a live reservation.
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_UN) } != 0 {
return Err(std::io::Error::last_os_error())
.context("failed to unlock pid reservation probe");
}
}
Ok(false)
}
#[cfg(not(any(unix, windows)))]
async fn reservation_lock_is_active(_path: &Path) -> Result<bool> {
Ok(false)
}
#[cfg(any(unix, windows))]
async fn inspect_empty_pid_reservation(
pid_path: &Path,
lock_path: &Path,
) -> Result<EmptyPidReservation> {
let file = match fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(lock_path)
.await
{
Ok(file) => file,
Err(err) => {
return Err(err).with_context(|| {
format!("failed to inspect pid lock file {}", lock_path.display())
});
}
};
inspect_empty_pid_reservation_with_file(pid_path, file).await
}
#[cfg(unix)]
struct EmptyPidProbeLock(fs::File);
#[cfg(unix)]
impl Drop for EmptyPidProbeLock {
fn drop(&mut self) {
use std::os::fd::AsRawFd;
// Closing alone leaves the lock held by any concurrent fork. Release it
// on every exit, including errors and cancellation while inspecting the PID.
if unsafe { libc::flock(self.0.as_raw_fd(), libc::LOCK_UN) } != 0 {
let error = std::io::Error::last_os_error();
tracing::warn!(%error, "failed to unlock empty pid reservation probe");
}
}
}
#[cfg(any(unix, windows))]
async fn inspect_empty_pid_reservation_with_file(
pid_path: &Path,
file: fs::File,
) -> Result<EmptyPidReservation> {
if !try_lock_file(&file)? {
return Ok(EmptyPidReservation::Active);
}
#[cfg(unix)]
let _probe_lock = EmptyPidProbeLock(file);
let contents = match fs::read_to_string(pid_path).await {
Ok(contents) => contents,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return Ok(EmptyPidReservation::Stale);
}
Err(err) => {
return Err(err)
.with_context(|| format!("failed to reread pid file {}", pid_path.display()));
}
};
if contents.trim().is_empty() {
let _ = fs::remove_file(pid_path).await;
return Ok(EmptyPidReservation::Stale);
}
let record = serde_json::from_str(&contents)
.with_context(|| format!("invalid pid file contents in {}", pid_path.display()))?;
Ok(EmptyPidReservation::Record(record))
}
#[cfg(not(any(unix, windows)))]
async fn inspect_empty_pid_reservation(
_pid_path: &Path,
_lock_path: &Path,
) -> Result<EmptyPidReservation> {
Ok(EmptyPidReservation::Stale)
}
#[cfg(unix)]
async fn read_process_start_time(pid: u32) -> Result<String> {
Ok(read_process_details(pid).await?.1)
}
#[cfg(unix)]
async fn read_process_details(pid: u32) -> Result<(String, String)> {
let output = Command::new("ps")
.args(["-p", &pid.to_string(), "-o", "stat=", "-o", "lstart="])
.kill_on_drop(true)
.output()
.await
.context("failed to invoke ps for pid-managed app server")?;
if !output.status.success() {
bail!("failed to read start time for pid-managed app server {pid}");
}
let details = String::from_utf8(output.stdout)
.context("pid-managed app server process details were not utf-8")?;
let Some((state, start_time)) = details.trim().split_once(char::is_whitespace) else {
bail!("pid-managed app server {pid} has no recorded start time");
};
let start_time = start_time.trim();
if start_time.is_empty() {
bail!("pid-managed app server {pid} has no recorded start time");
}
Ok((state.to_string(), start_time.to_string()))
}
#[cfg(all(test, any(unix, windows)))]
#[path = "pid_tests.rs"]
mod tests;
#[cfg(windows)]
use super::windows::try_lock_file;
#[cfg(windows)]
async fn read_process_start_time(pid: u32) -> Result<String> {
super::windows::Process::open(pid)?
.context("daemon process exited during startup")?
.start_time()
}
#[cfg(windows)]
async fn process_matches_record(record: &PidRecord) -> Result<bool> {
let Some(process) = super::windows::Process::open(record.pid)? else {
return Ok(false);
};
Ok(process.is_running()? && process.start_time()? == record.process_start_time)
}
#[cfg(windows)]
fn force_terminate_process(pid: u32) -> Result<()> {
if let Some(process) = super::windows::Process::open(pid)? {
process.terminate()?;
}
Ok(())
}
#[cfg(windows)]
use force_terminate_process as terminate_process;
#[cfg(windows)]
#[path = "pid_windows.rs"]
mod windows;
#[cfg(any(unix, windows))]
#[path = "pid_start.rs"]
mod start;

View File

@@ -0,0 +1,242 @@
//! Native process identities and zombie state, independent of locale and timezone.
//! Boot IDs prevent records surviving reboot from matching reused process identifiers.
#[cfg(any(target_os = "linux", target_os = "macos", test))]
use anyhow::Context;
#[cfg(any(target_os = "linux", target_os = "macos", test))]
use anyhow::Result;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged, rename_all_fields = "camelCase")]
pub(super) enum ProcessIdentity {
Linux {
boot_id: String,
start_ticks: u64,
},
// Untagged decoding must try this before the timestamp-only MacOs variant.
MacOsUnique {
boot_id: String,
unique_id: u64,
start_seconds: u64,
start_microseconds: u64,
},
MacOs {
start_seconds: u64,
start_microseconds: u64,
},
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
impl ProcessIdentity {
pub(super) async fn matches_process(&self, pid: u32) -> Result<(bool, bool)> {
// A different boot proves staleness even when the reused PID is inaccessible.
if let Self::Linux { boot_id, .. } | Self::MacOsUnique { boot_id, .. } = self
&& *boot_id != read_boot_id().await?
{
return Ok((false, false));
}
#[cfg(target_os = "macos")]
if let Self::MacOsUnique { unique_id, .. } = self
&& *unique_id != read_unique_id(pid)?
{
return Ok((false, false));
}
let (is_zombie, actual) = read_process_details(pid).await?;
let matches = if let (
// Timestamp-only native records predate the cross-user identity check.
Self::MacOs {
start_seconds,
start_microseconds,
},
Self::MacOsUnique {
start_seconds: actual_seconds,
start_microseconds: actual_microseconds,
..
},
) = (self, &actual)
{
start_seconds == actual_seconds && start_microseconds == actual_microseconds
} else {
*self == actual
};
Ok((is_zombie, matches))
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
impl super::PidBackend {
pub(crate) async fn promote_legacy_identity(&self) -> Result<()> {
let _reservation = self.acquire_reservation_lock().await?;
let super::PidFileState::Running(mut record) =
self.read_pid_file_state_with_lock_held().await?
else {
return Ok(());
};
if matches!(
record.process_identity,
Some(ProcessIdentity::Linux { .. } | ProcessIdentity::MacOsUnique { .. })
) {
return Ok(());
}
// An updater keeps its PID across exec during upgrades. Only promote a
// legacy record while its original check still identifies the process,
// with the native identity unchanged on both sides of that check.
let before = read_process_details(record.pid).await?;
if before.0 || !super::process_matches_record(&record).await? {
return Ok(());
}
if read_process_details(record.pid).await? != before {
return Ok(());
}
record.process_identity = Some(before.1);
let temporary = self.pid_file.with_extension("pid.tmp");
tokio::fs::write(&temporary, serde_json::to_vec(&record)?).await?;
tokio::fs::rename(&temporary, &self.pid_file).await?;
Ok(())
}
}
#[cfg(target_os = "macos")]
pub(super) async fn read_process_details(pid: u32) -> Result<(bool, ProcessIdentity)> {
let boot_id = read_boot_id().await?;
let unique_id = read_unique_id(pid)?;
let pid = libc::pid_t::try_from(pid).context("daemon pid is out of range")?;
let mut info = std::mem::MaybeUninit::<libc::proc_bsdinfo>::uninit();
let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
// SAFETY: the buffer has the exact size and alignment required by this flavor.
// arg=1 includes zombies so callers can reap children that have exited.
let read = unsafe {
libc::proc_pidinfo(
pid,
libc::PROC_PIDTBSDINFO,
/*arg*/ 1,
info.as_mut_ptr().cast(),
size,
)
};
if read <= 0 {
return Err(std::io::Error::last_os_error())
.context("failed to read daemon process identity");
}
anyhow::ensure!(read == size, "incomplete daemon process identity");
// SAFETY: proc_pidinfo initialized the entire structure on success.
let info = unsafe { info.assume_init() };
anyhow::ensure!(
unique_id == read_unique_id(info.pbi_pid)?,
"daemon process changed while reading its identity"
);
Ok((
info.pbi_status == libc::SZOMB,
ProcessIdentity::MacOsUnique {
boot_id,
unique_id,
start_seconds: info.pbi_start_tvsec,
start_microseconds: info.pbi_start_tvusec,
},
))
}
#[cfg(target_os = "macos")]
fn read_unique_id(pid: u32) -> Result<u64> {
// XNU's proc_uniqidentifierinfo ABI (flavor 17), unchanged in size since 2013.
// Unlike PROC_PIDTBSDINFO, this query does not require matching process ownership.
#[repr(C)]
struct UniqueInfo {
executable_uuid: [u8; 16],
unique_id: u64,
parent_unique_id: u64,
reserved: [u64; 3],
}
let pid = libc::pid_t::try_from(pid).context("daemon pid is out of range")?;
let mut info = std::mem::MaybeUninit::<UniqueInfo>::uninit();
let size = std::mem::size_of::<UniqueInfo>() as libc::c_int;
// SAFETY: the buffer matches proc_uniqidentifierinfo's size and alignment.
let read = unsafe {
libc::proc_pidinfo(
pid,
/*flavor*/ 17,
/*arg*/ 1,
info.as_mut_ptr().cast(),
size,
)
};
if read <= 0 {
return Err(std::io::Error::last_os_error()).context("failed to read daemon unique ID");
}
anyhow::ensure!(read == size, "incomplete daemon unique ID");
// SAFETY: proc_pidinfo initialized the entire structure on success.
Ok(unsafe { info.assume_init() }.unique_id)
}
#[cfg(target_os = "macos")]
async fn read_boot_id() -> Result<String> {
let mut buffer = [0u8; 37];
let mut size = buffer.len();
// SAFETY: the writable buffer has size bytes; the new-value pointer is null.
let result = unsafe {
libc::sysctlbyname(
c"kern.bootsessionuuid".as_ptr(),
buffer.as_mut_ptr().cast(),
&mut size,
std::ptr::null_mut(),
/*newlen*/ 0,
)
};
if result != 0 {
return Err(std::io::Error::last_os_error()).context("failed to read macOS boot ID");
}
anyhow::ensure!(size == buffer.len(), "incomplete macOS boot ID");
Ok(std::ffi::CStr::from_bytes_with_nul(&buffer)?
.to_str()?
.to_owned())
}
#[cfg(target_os = "linux")]
pub(super) async fn read_process_details(pid: u32) -> Result<(bool, ProcessIdentity)> {
let stat = tokio::fs::read(format!("/proc/{pid}/stat"))
.await
.with_context(|| format!("failed to read process stat for pid-managed process {pid}"))?;
let (state, start_ticks) = parse_stat(&stat)?;
Ok((
state == "Z",
ProcessIdentity::Linux {
boot_id: read_boot_id().await?,
start_ticks,
},
))
}
#[cfg(target_os = "linux")]
async fn read_boot_id() -> Result<String> {
let boot_id = tokio::fs::read_to_string("/proc/sys/kernel/random/boot_id")
.await
.context("failed to read Linux boot ID")?;
let boot_id = boot_id.trim();
anyhow::ensure!(!boot_id.is_empty(), "Linux boot ID is empty");
Ok(boot_id.to_owned())
}
#[cfg(any(target_os = "linux", test))]
fn parse_stat(stat: &[u8]) -> Result<(String, u64)> {
// comm (field 2) can contain spaces and closing parentheses. The final ')'
// terminates it; splitting the whole line on whitespace miscounts fields.
let end = stat
.iter()
.rposition(|byte| *byte == b')')
.context("process stat has no comm")?;
let fields = std::str::from_utf8(&stat[end + 1..]).context("invalid process stat fields")?;
let mut fields = fields.split_whitespace();
let state = fields.next().context("process stat has no state")?;
let start_ticks = fields
.nth(/*n*/ 18)
.context("process stat has no start time")?
.parse()
.context("process stat start time is invalid")?;
Ok((state.to_string(), start_ticks))
}
#[cfg(test)]
#[path = "pid_identity_tests.rs"]
mod tests;

View File

@@ -0,0 +1,89 @@
use super::parse_stat;
use pretty_assertions::assert_eq;
#[test]
fn parses_start_ticks_after_comm_with_spaces_and_parentheses() {
let stat =
b"123 (codex \xff) worker) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 987654321 20";
assert_eq!(parse_stat(stat).unwrap(), ("S".to_string(), 987654321));
}
#[test]
fn reads_earlier_linux_identity_field() {
use crate::backend::pid::PidRecord;
let mut expected = serde_json::json!({
"pid": 42,
"processStartTime": "legacy timestamp",
"linuxProcessIdentity": {"bootId": "boot", "startTicks": 123},
});
let record: PidRecord = serde_json::from_value(expected.clone()).unwrap();
expected["processIdentity"] = expected
.as_object_mut()
.unwrap()
.remove("linuxProcessIdentity")
.unwrap();
assert_eq!(serde_json::to_value(record).unwrap(), expected);
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
async fn previous_boot_does_not_require_process_inspection() {
let (_, identity) = super::read_process_details(std::process::id())
.await
.unwrap();
let mut record = serde_json::to_value(identity).unwrap();
record["bootId"] = "previous boot".into();
let identity: super::ProcessIdentity = serde_json::from_value(record).unwrap();
// An invalid PID would make process inspection fail if it preceded the boot check.
assert_eq!(
identity.matches_process(u32::MAX).await.unwrap(),
(false, false)
);
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn reused_pid_can_belong_to_root() {
let (_, identity) = super::read_process_details(std::process::id())
.await
.unwrap();
// launchd is root-owned: PROC_PIDTBSDINFO returns EPERM for an ordinary caller.
assert_eq!(
identity.matches_process(/*pid*/ 1).await.unwrap(),
(false, false)
);
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn promotes_timestamp_only_macos_record() {
use crate::backend::pid::PidBackend;
use crate::backend::pid::PidRecord;
let temp = tempfile::TempDir::new().unwrap();
let path = temp.path().join("server.pid");
let (_, identity) = super::read_process_details(std::process::id())
.await
.unwrap();
let mut legacy = serde_json::to_value(&identity).unwrap();
legacy.as_object_mut().unwrap().remove("bootId");
legacy.as_object_mut().unwrap().remove("uniqueId");
let mut record = PidRecord {
pid: std::process::id(),
process_start_time: "unused legacy text".into(),
process_identity: Some(serde_json::from_value(legacy).unwrap()),
executable_identity: None,
};
std::fs::write(&path, serde_json::to_vec(&record).unwrap()).unwrap();
let backend = PidBackend::new(
temp.path().join("codex"),
path.clone(),
/*remote_control_enabled*/ false,
);
backend.promote_legacy_identity().await.unwrap();
record.process_identity = Some(identity);
assert_eq!(
serde_json::from_slice::<PidRecord>(&std::fs::read(path).unwrap()).unwrap(),
record,
);
}

View File

@@ -0,0 +1,323 @@
//! Detached process launch and PID publication. Hold the reservation lock until
//! the record is published, and on Windows until an updater acknowledges startup.
//! Windows children use a separate working directory to preserve the state directory ACL.
//! Recover a deleted Unix cwd without changing workspace defaults for usable directories.
use super::PidBackend;
#[cfg(windows)]
use super::PidCommandKind;
use super::PidFileState;
use super::PidRecord;
use super::read_process_start_time;
use crate::managed_install::executable_identity;
use crate::telemetry::StartFailure;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use std::process::Stdio;
use tokio::fs;
use tokio::process::Command;
impl PidBackend {
pub(super) async fn start_inner(&self, replacement: Option<PidRecord>) -> Result<Option<u32>> {
#[cfg(windows)]
crate::backend::windows::ensure_not_elevated()?;
if let Some(parent) = self.pid_file.parent() {
codex_uds::prepare_private_socket_directory(parent)
.await
.with_context(|| format!("failed to create pid directory {}", parent.display()))?;
}
#[cfg(windows)]
let workdir = {
let workdir = self
.pid_file
.parent()
.context("daemon pid path has no parent")?
.join("workdir");
fs::create_dir_all(&workdir).await.with_context(|| {
format!(
"failed to create daemon working directory {}",
workdir.display()
)
})?;
workdir
};
let reservation_lock = self.acquire_reservation_lock().await?;
loop {
match fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(&self.pid_file)
.await
{
Ok(pid_file) => {
drop(pid_file);
break;
}
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
match self.read_pid_file_state_with_lock_held().await? {
PidFileState::Missing => continue,
PidFileState::Running(record) => {
if replacement.as_ref() == Some(&record) {
break;
}
if replacement.is_some() {
if self.record_is_active(&record).await? {
bail!("updater ownership changed before handoff");
}
// A failed rollback may leave the dead successor's record.
break;
}
if self.record_is_active(&record).await? {
return Ok(None);
}
let _ = fs::remove_file(&self.pid_file).await;
continue;
}
PidFileState::Starting => {
unreachable!("lock holder cannot observe starting")
}
}
}
Err(err) => {
return Err(err).with_context(|| {
format!("failed to reserve pid file {}", self.pid_file.display())
});
}
}
}
// Pin the selected release across installer symlink/junction retargeting.
let codex_bin = fs::canonicalize(&self.codex_bin)
.await
.unwrap_or_else(|_| self.codex_bin.clone());
let launched_identity =
if matches!(self.command_kind, super::PidCommandKind::AppServer { .. }) {
executable_identity(&codex_bin).await.ok()
} else {
None
};
let mut command = Command::from(codex_utils_process::background_command(&codex_bin));
let stderr_log = match self.open_stderr_log().await {
Ok(stderr_log) => stderr_log,
Err(err) => {
if replacement.is_none() {
let _ = fs::remove_file(&self.pid_file).await;
}
return Err(err);
}
};
command
// Handoff suppression belongs to the foreground CLI, not its long-lived children.
.env_remove(crate::telemetry::HANDOFF_ENV)
.args(self.command_args().iter().map(std::borrow::Cow::as_ref))
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(stderr_log.into_std().await));
// Older or pinned managed binaries may predate this optional startup flag.
let managed_app_server =
matches!(self.command_kind, super::PidCommandKind::AppServer { .. });
if managed_app_server
&& matches!(
tokio::time::timeout(
std::time::Duration::from_secs(5),
Command::new(&codex_bin)
.args(["app-server", "--managed-daemon", "--help"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true)
.status(),
).await,
Ok(Ok(status)) if status.success()
)
{
command.arg("--managed-daemon");
} else if managed_app_server {
let codex_home = self
.pid_file
.parent()
.and_then(std::path::Path::parent)
.context("daemon pid path has no Codex home")?;
let recovery_file = codex_app_server_transport::daemon_recovery_file_path(codex_home);
match fs::remove_file(&recovery_file).await {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => {
tracing::warn!(path = %recovery_file.display(), %err, "failed to clear daemon recovery state before legacy launch");
}
}
}
if let Some((key, value)) = self.command_env() {
command.env(key, value);
}
crate::background_command::set_working_directory(
command.as_std_mut(),
self.pid_file
.parent()
.context("daemon pid path has no parent")?,
)?;
#[cfg(unix)]
{
unsafe {
command.pre_exec(|| {
if libc::setsid() == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
}
#[cfg(windows)]
{
use windows_sys::Win32::System::Threading::CREATE_BREAKAWAY_FROM_JOB;
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
use windows_sys::Win32::System::Threading::DETACHED_PROCESS;
// A Windows process pins its working directory for its lifetime.
// Keep both managed children out of the launching project's directory.
// Sandbox setup may broaden the cwd ACL, so do not use the private state directory.
command.current_dir(&workdir);
// Never retry inside the parent's Job Object: that would report a
// successful launch that dies when the terminal/SSH session closes.
command.creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS | CREATE_BREAKAWAY_FROM_JOB);
if matches!(self.command_kind, PidCommandKind::UpdateLoop { .. }) {
match fs::remove_file(self.pid_file.with_extension("ready")).await {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => return Err(err).context("failed to clear updater readiness"),
}
}
match self.command_kind {
PidCommandKind::AppServer { .. } => {
command.env(codex_app_server_transport::DAEMON_SHUTDOWN_SOCKET_ENV, "1");
}
PidCommandKind::UpdateLoop { .. } => {
let shutdown_file = self.pid_file.with_extension("shutdown");
match fs::remove_file(&shutdown_file).await {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => {
return Err(err).context("failed to clear updater shutdown request");
}
}
command.env(
codex_app_server_transport::DAEMON_SHUTDOWN_FILE_ENV,
shutdown_file,
);
}
}
}
let started = std::time::Instant::now();
#[cfg(windows)]
let child = super::super::windows::spawn_without_inheriting_stdio(&mut command);
#[cfg(not(windows))]
let child = command.spawn().map_err(anyhow::Error::from);
let child = crate::diagnostics::result("process_spawn", started, child);
let mut child = match child {
Ok(child) => child,
Err(err) => {
if replacement.is_none() {
let _ = fs::remove_file(&self.pid_file).await;
}
return Err(err).with_context(|| {
let job_hint = if cfg!(windows) {
" (the Windows host job must allow breakaway)"
} else {
""
};
StartFailure::Spawn(format!(
"failed to spawn detached app-server process using {}{job_hint}",
self.codex_bin.display()
))
});
}
};
let pid = child
.id()
.context("spawned app-server process has no pid")?;
crate::diagnostics::event("process_spawned", serde_json::json!({ "pid": pid }));
let started = std::time::Instant::now();
let record = async {
let process_start_time = read_process_start_time(pid).await?;
#[cfg(any(target_os = "linux", target_os = "macos"))]
let process_identity = super::identity::read_process_details(pid)
.await
.ok()
.map(|(_, identity)| identity);
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
let process_identity = None;
anyhow::Ok(PidRecord {
pid,
process_start_time,
process_identity,
executable_identity: launched_identity,
})
}
.await;
let record = match crate::diagnostics::result("process_identity", started, record) {
Ok(record) => record,
Err(err) => {
let exited = managed_app_server && matches!(child.try_wait(), Ok(Some(_)));
if !exited {
let _ = self.terminate_process(pid);
}
let mut context =
format!("failed to record pid-managed app-server process {pid} startup");
super::super::append_stderr_log_tail_context(&self.pid_file, &mut context).await;
if replacement.is_none() {
let _ = fs::remove_file(&self.pid_file).await;
}
return if exited {
Err(err).context(StartFailure::EarlyChildExit(context))
} else {
Err(err).context(context)
};
}
};
let contents = serde_json::to_vec(&record).context("failed to serialize pid record")?;
let temp_pid_file = self.pid_file.with_extension("pid.tmp");
let started = std::time::Instant::now();
if let Err(err) = crate::diagnostics::result(
"pid_write",
started,
fs::write(&temp_pid_file, &contents)
.await
.map_err(anyhow::Error::from),
) {
let _ = self.terminate_process(pid);
if replacement.is_none() {
let _ = fs::remove_file(&self.pid_file).await;
}
return Err(err).with_context(|| {
format!("failed to write pid temp file {}", temp_pid_file.display())
});
}
let started = std::time::Instant::now();
if let Err(err) = crate::diagnostics::result(
"pid_publish",
started,
fs::rename(&temp_pid_file, &self.pid_file)
.await
.map_err(anyhow::Error::from),
) {
let _ = self.terminate_process(pid);
let _ = fs::remove_file(&temp_pid_file).await;
if replacement.is_none() {
let _ = fs::remove_file(&self.pid_file).await;
}
return Err(err).with_context(|| {
format!("failed to publish pid file {}", self.pid_file.display())
});
}
#[cfg(windows)]
if matches!(self.command_kind, PidCommandKind::UpdateLoop { .. }) {
self.finish_updater_start(&record, replacement.as_ref())
.await?;
}
drop(reservation_lock);
Ok(Some(pid))
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,119 @@
//! Windows updater publication handshake. The predecessor holds the operation
//! and reservation locks until its successor initializes and acknowledges readiness.
use super::super::windows::Process;
use super::PidBackend;
use super::PidFileState;
use super::PidRecord;
use super::START_TIMEOUT;
use super::STOP_POLL_INTERVAL;
use super::process_matches_record;
use super::read_process_start_time;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use tokio::fs;
use tokio::time::sleep;
impl PidBackend {
pub(crate) async fn wait_for_ownership(&self) -> Result<()> {
let deadline = tokio::time::Instant::now() + START_TIMEOUT;
loop {
if let PidFileState::Running(record) = self.read_pid_file_state().await?
&& record.pid == std::process::id()
&& self.record_is_active(&record).await?
{
return Ok(());
}
if tokio::time::Instant::now() >= deadline {
bail!("updater was not published by its launcher");
}
sleep(STOP_POLL_INTERVAL).await;
}
}
pub(crate) async fn mark_ready(&self) -> Result<()> {
fs::write(self.pid_file.with_extension("ready"), b"")
.await
.context("failed to acknowledge updater startup")
}
// Keep pruning excluded until successor startup and any ownership rollback finish.
#[allow(clippy::await_holding_invalid_type)]
pub(crate) async fn replace_current_updater(&self) -> Result<()> {
// Retry busy pruning instead of waiting on the logging worker. Keep it paused
// before open_stderr_log() truncates the shared log and throughout startup.
let mut pruning_enabled = super::super::stderr_log::PRUNING_ENABLED
.try_lock()
.context("stderr pruning is busy; retry updater handoff")?;
let record = PidRecord {
pid: std::process::id(),
process_start_time: read_process_start_time(std::process::id()).await?,
process_identity: None,
executable_identity: None,
};
*pruning_enabled = false;
let result = self.start_inner(Some(record.clone())).await;
// Resume only after ownership is restored. Failed cleanup may leave the
// successor alive, and successful handoff leaves it in charge of retention.
if result.is_err()
&& matches!(
self.read_pid_file_state().await,
Ok(PidFileState::Running(previous)) if previous == record
)
{
*pruning_enabled = true;
}
result?;
Ok(())
}
pub(super) async fn finish_updater_start(
&self,
record: &PidRecord,
replacement: Option<&PidRecord>,
) -> Result<()> {
let temp_pid_file = self.pid_file.with_extension("pid.tmp");
let ready = self.pid_file.with_extension("ready");
let deadline = tokio::time::Instant::now() + START_TIMEOUT;
let startup = async {
loop {
if !process_matches_record(record).await? {
bail!("updater exited before becoming ready");
}
match fs::remove_file(&ready).await {
Ok(()) => return Ok(()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => return Err(err.into()),
}
if tokio::time::Instant::now() >= deadline {
bail!("updater did not become ready");
}
sleep(STOP_POLL_INTERVAL).await;
}
}
.await;
if let Err(err) = startup {
if let Some(process) = Process::open(record.pid)?
&& process.start_time()? == record.process_start_time
{
process.terminate()?;
let deadline = tokio::time::Instant::now() + START_TIMEOUT;
while process.is_running()? {
if tokio::time::Instant::now() >= deadline {
bail!("failed updater did not exit; ownership was not restored");
}
sleep(STOP_POLL_INTERVAL).await;
}
}
if let Some(previous) = replacement {
fs::write(&temp_pid_file, serde_json::to_vec(previous)?).await?;
fs::rename(&temp_pid_file, &self.pid_file).await?;
} else {
let _ = fs::remove_file(&self.pid_file).await;
}
return Err(err);
}
Ok(())
}
}

View File

@@ -0,0 +1,231 @@
//! Bounds managed stderr with the shared nonblocking logging worker and tail retention.
//! The worker serializes writes with pruning and pauses pruning during Windows handoff.
//! Native writers remain best effort.
use std::io;
use std::io::Read;
use std::io::Seek;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::sync::OnceLock;
use std::time::Instant;
use tokio::sync::Mutex;
use tracing_appender::non_blocking::NonBlocking;
use tracing_appender::non_blocking::NonBlockingBuilder;
use tracing_appender::non_blocking::WorkerGuard;
const MAX_PREVIOUS_LOG_BYTES: u64 = 256 * 1024;
const MAX_CURRENT_LOG_BYTES: u64 = 1024 * 1024;
const QUEUED_RECORDS: usize = 64;
const MAX_RECORD_BYTES: usize = 16 * 1024;
// Process lifetime: dropping WorkerGuard would wait for a potentially stalled disk.
static LOGGER: OnceLock<(NonBlocking, WorkerGuard)> = OnceLock::new();
// Handoff holds this lock through startup and leaves predecessor pruning disabled on success.
// Both callers use try_lock so a stalled worker cannot make handoff wait on disk.
pub(super) static PRUNING_ENABLED: Mutex<bool> = Mutex::const_new(true);
pub(crate) fn start(path: PathBuf) {
LOGGER.get_or_init(|| {
nonblocking(LogFile {
path,
file: None,
can_prune: None,
})
});
}
fn nonblocking(writer: impl Write + Send + 'static) -> (NonBlocking, WorkerGuard) {
NonBlockingBuilder::default()
.buffered_lines_limit(QUEUED_RECORDS)
.lossy(/* is_lossy */ true)
.finish(writer)
}
/// Writes complete records through the bounded managed queue, or ordinary stderr otherwise.
/// Each write must contain one complete record; oversized records are discarded before copying.
pub fn stderr_writer() -> impl Write {
StderrWriter
}
struct StderrWriter;
impl Write for StderrWriter {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
if let Some((writer, _guard)) = LOGGER.get() {
if bytes.len() <= MAX_RECORD_BYTES {
writer.clone().write_all(bytes)?;
}
Ok(bytes.len())
} else {
io::stderr().write(bytes)
}
}
fn flush(&mut self) -> io::Result<()> {
if LOGGER.get().is_none() {
io::stderr().flush()?;
}
Ok(())
}
}
struct LogFile {
path: PathBuf,
file: Option<std::fs::File>,
can_prune: Option<bool>,
}
impl Write for LogFile {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
// All filesystem work, including first open and legacy handle setup, stays on the worker.
if *self
.can_prune
.get_or_insert_with(|| enable_append().is_ok())
{
let _ = prune(&self.path, &PRUNING_ENABLED);
}
let file = match self.file {
Some(ref mut file) => file,
None => self.file.insert(
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&self.path)?,
),
};
file.write_all(bytes)?;
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[cfg(unix)]
fn enable_append() -> io::Result<()> {
use std::os::fd::AsRawFd;
let fd = std::io::stderr().as_raw_fd();
// SAFETY: F_GETFL reads flags from the borrowed descriptor and takes no pointers.
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
if flags == -1 {
return Err(io::Error::last_os_error());
}
// SAFETY: F_SETFL changes status flags on the same descriptor without taking ownership.
if unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_APPEND) } == -1 {
return Err(io::Error::last_os_error());
}
Ok(())
}
#[cfg(windows)]
fn enable_append() -> io::Result<()> {
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::IntoRawHandle;
use std::os::windows::io::OwnedHandle;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_WRITE;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_DATA;
use windows_sys::Win32::Storage::FileSystem::ReOpenFile;
use windows_sys::Win32::System::Console::STD_ERROR_HANDLE;
use windows_sys::Win32::System::Console::SetStdHandle;
let stderr = std::io::stderr();
// SAFETY: stderr is borrowed and remains open; reopening does not truncate it.
let handle = unsafe {
ReOpenFile(
stderr.as_raw_handle(),
// Append-only access makes writes follow EOF after truncation.
FILE_GENERIC_WRITE & !FILE_WRITE_DATA,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
/*dwflagsandattributes*/ 0,
)
};
if handle == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
// SAFETY: ReOpenFile returned a new, valid handle owned by this function.
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
// SAFETY: the append handle is valid and retained for the process lifetime on success.
if unsafe { SetStdHandle(STD_ERROR_HANDLE, handle.as_raw_handle()) } == 0 {
return Err(io::Error::last_os_error());
}
// The process owns its new stderr. Keep the borrowed original valid for cached users.
let _ = handle.into_raw_handle();
Ok(())
}
fn prune(path: &Path, pruning_enabled: &Mutex<bool>) -> io::Result<()> {
let Ok(enabled) = pruning_enabled.try_lock() else {
return Ok(());
};
if !*enabled {
return Ok(());
}
let metadata = std::fs::symlink_metadata(path)?;
if !metadata.is_file() || metadata.len() <= MAX_CURRENT_LOG_BYTES {
return Ok(());
}
preserve_tail(path)?;
// Keep inherited handles connected, holding the pruning lock through truncation.
std::fs::OpenOptions::new()
.write(true)
.open(path)?
.set_len(0)
}
pub(super) async fn preserve(path: &Path) {
let started = Instant::now();
let path = path.to_path_buf();
let result = async {
tokio::task::spawn_blocking(move || preserve_tail(&path)).await??;
anyhow::Ok(())
}
.await;
if let Err(error) = result {
let _ = crate::diagnostics::result::<()>("stderr_preservation", started, Err(error));
}
}
fn preserve_tail(path: &Path) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if !metadata.is_file() => return Ok(()),
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error),
}
let mut file = match std::fs::File::open(path) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error),
};
let metadata = file.metadata()?;
let len = metadata.len();
if !metadata.is_file() || len == 0 {
return Ok(());
}
file.seek(io::SeekFrom::Start(
len.saturating_sub(MAX_PREVIOUS_LOG_BYTES),
))?;
let mut bytes = Vec::new();
file.take(MAX_PREVIOUS_LOG_BYTES).read_to_end(&mut bytes)?;
let previous = path.with_extension("log.previous");
let temporary = path.with_extension("log.previous.tmp");
let result =
std::fs::write(&temporary, bytes).and_then(|()| std::fs::rename(&temporary, previous));
if result.is_err() {
let _ = std::fs::remove_file(&temporary);
}
result
}
#[cfg(test)]
#[path = "stderr_log_tests.rs"]
mod tests;

View File

@@ -0,0 +1,217 @@
use super::MAX_CURRENT_LOG_BYTES;
use super::MAX_PREVIOUS_LOG_BYTES;
use super::preserve;
use super::prune;
use pretty_assertions::assert_eq;
#[cfg(any(unix, windows))]
#[tokio::test]
async fn pruning_resets_the_write_position_of_a_legacy_nonappend_writer() -> anyhow::Result<()> {
use std::io::Write;
const CHILD_LOG: &str = "CODEX_TEST_LEGACY_STDERR_LOG";
if let Some(path) = std::env::var_os(CHILD_LOG) {
std::io::stderr().write_all(b"before pruning\n")?;
let mut writer = super::LogFile {
path: path.into(),
file: None,
can_prune: None,
};
writer.write_all(b"queued logging\n")?;
std::io::stderr().write_all(b"still logging\n")?;
return Ok(());
}
let home = tempfile::tempdir()?;
let path = home.path().join("daemon.stderr.log");
let mut writer = std::fs::File::create(&path)?;
writer.write_all(&vec![b'x'; MAX_CURRENT_LOG_BYTES as usize + 1])?;
// Isolate the process-wide stderr replacement and inherit the legacy writer's offset.
let status = tokio::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"backend::stderr_log::tests::pruning_resets_the_write_position_of_a_legacy_nonappend_writer",
"--nocapture",
])
.env(CHILD_LOG, &path)
.stderr(writer)
.kill_on_drop(true)
.status()
.await?;
assert!(status.success(), "legacy stderr child failed: {status}");
assert_eq!(
tokio::fs::read(&path).await?,
b"queued logging\nstill logging\n"
);
Ok(())
}
#[tokio::test]
async fn preserves_bounded_tail_and_keeps_it_after_empty_launch() -> anyhow::Result<()> {
let home = tempfile::tempdir()?;
let path = home.path().join("daemon.stderr.log");
let previous = path.with_extension("log.previous");
preserve(&path).await;
assert!(!previous.exists());
let mut bytes = vec![b'x'; MAX_PREVIOUS_LOG_BYTES as usize + 100];
bytes.extend_from_slice(b"latest failure");
tokio::fs::write(&path, &bytes).await?;
preserve(&path).await;
assert_eq!(
tokio::fs::read(&previous).await?,
bytes[bytes.len() - MAX_PREVIOUS_LOG_BYTES as usize..]
);
tokio::fs::write(&path, b"").await?;
preserve(&path).await;
assert_eq!(
tokio::fs::read(&previous).await?,
bytes[bytes.len() - MAX_PREVIOUS_LOG_BYTES as usize..]
);
tokio::fs::write(&path, b"next launch").await?;
preserve(&path).await;
assert_eq!(tokio::fs::read(&previous).await?, b"next launch");
Ok(())
}
#[tokio::test]
#[allow(clippy::await_holding_invalid_type)] // Exercise pruning exclusion during handoff I/O.
async fn prunes_live_log_without_disconnecting_inherited_append_handles() -> anyhow::Result<()> {
use tokio::io::AsyncWriteExt;
let pruning_enabled = tokio::sync::Mutex::new(true);
let home = tempfile::tempdir()?;
let path = home.path().join("daemon.stderr.log");
let mut writer = tokio::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.await?;
writer.write_all(b"startup\n").await?;
writer.flush().await?;
prune(&path, &pruning_enabled)?;
assert_eq!(tokio::fs::read(&path).await?, b"startup\n");
let mut bytes = vec![b'x'; MAX_CURRENT_LOG_BYTES as usize];
bytes.extend_from_slice(b"latest failure\n");
writer.write_all(&bytes).await?;
writer.flush().await?;
// A failed tail publication must leave the live log untouched.
let previous = path.with_extension("log.previous");
tokio::fs::create_dir(&previous).await?;
assert!(prune(&path, &pruning_enabled).is_err());
assert_eq!(
tokio::fs::read(&path).await?,
[b"startup\n".as_slice(), bytes.as_slice()].concat()
);
tokio::fs::remove_dir(&previous).await?;
// Handoff excludes pruning even while the shared log exceeds the limit.
let mut handoff = pruning_enabled.try_lock()?;
*handoff = false;
prune(&path, &pruning_enabled)?;
assert_eq!(
tokio::fs::read(&path).await?,
[b"startup\n".as_slice(), bytes.as_slice()].concat()
);
// Failed handoff restores ownership, so retention resumes after unlocking.
*handoff = true;
drop(handoff);
prune(&path, &pruning_enabled)?;
assert_eq!(
tokio::fs::read(previous).await?,
bytes[bytes.len() - MAX_PREVIOUS_LOG_BYTES as usize..]
);
writer.write_all(b"still logging\n").await?;
writer.flush().await?;
assert_eq!(tokio::fs::read(&path).await?, b"still logging\n");
// Successful handoff keeps predecessor pruning disabled after unlocking.
let mut handoff = pruning_enabled.try_lock()?;
*handoff = false;
writer.write_all(&bytes).await?;
writer.write_all(b"successor startup\n").await?;
writer.flush().await?;
drop(handoff);
prune(&path, &pruning_enabled)?;
assert_eq!(
tokio::fs::read(&path).await?,
[
b"still logging\n".as_slice(),
bytes.as_slice(),
b"successor startup\n",
]
.concat()
);
Ok(())
}
#[test]
fn logging_does_not_wait_for_a_stalled_worker() -> anyhow::Result<()> {
use std::io::Write;
use std::sync::Barrier;
use std::sync::mpsc;
const CHILD: &str = "CODEX_TEST_STALLED_LOG_WORKER";
if std::env::var_os(CHILD).is_none() {
let output = std::process::Command::new(std::env::current_exe()?)
.args([
"--exact",
"backend::stderr_log::tests::logging_does_not_wait_for_a_stalled_worker",
])
.env(CHILD, "1")
.output()?;
assert!(
output.status.success(),
"logging child failed: {}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(output.stderr, Vec::<u8>::new());
return Ok(());
}
struct StalledWriter(mpsc::Sender<()>);
impl Write for StalledWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.send(()).unwrap();
// No second participant: the worker stays stalled until process exit.
Barrier::new(/* n */ 2).wait();
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let (entered_tx, entered_rx) = mpsc::channel();
assert!(
super::LOGGER
.set(super::nonblocking(StalledWriter(entered_tx)))
.is_ok()
);
// The updater's diagnostic starts the stalled write.
crate::diagnostics::event("stalled-worker", serde_json::json!({}));
entered_rx.recv()?;
// Exercise the same tracing formatter/writer combination used by app-server.
let subscriber = tracing_subscriber::fmt()
.with_writer(super::stderr_writer)
.finish();
tracing::subscriber::with_default(subscriber, || tracing::warn!("app-server event"));
super::stderr_writer().write_all(&vec![b'x'; super::MAX_RECORD_BYTES + 1])?;
for _ in 1..super::QUEUED_RECORDS {
super::stderr_writer().write_all(&vec![b'x'; super::MAX_RECORD_BYTES])?;
}
super::stderr_writer().write_all(b"queue is full\n")?;
super::stderr_writer().flush()?;
assert_eq!(
super::LOGGER
.get()
.unwrap()
.0
.error_counter()
.dropped_lines(),
1
);
// Returning also proves process shutdown does not wait for the stalled worker.
Ok(())
}

View File

@@ -0,0 +1,327 @@
//! Windows process identity and file locks. Keep a process handle across shutdown
//! so PID reuse can never redirect forced termination to a different process.
//! Managed servers must not elevate ordinary clients sharing the account's socket.
//! Installer jobs contain extraction processes when an update is cancelled.
//! Detached launches stop the launcher's original stdio handles from propagating.
//! Launch probes distinguish job restrictions from other failures without running the binary.
use std::fmt;
use std::io;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::os::windows::process::CommandExt;
use std::path::Path;
use std::process::Command;
use std::process::Stdio;
use anyhow::Context;
use anyhow::Result;
use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;
use windows_sys::Win32::Foundation::ERROR_INVALID_HANDLE;
use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER;
use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION;
use windows_sys::Win32::Foundation::FILETIME;
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Foundation::HANDLE_FLAG_INHERIT;
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
use windows_sys::Win32::Foundation::SetHandleInformation;
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
use windows_sys::Win32::Security::GetTokenInformation;
use windows_sys::Win32::Security::TOKEN_ELEVATION;
use windows_sys::Win32::Security::TOKEN_QUERY;
use windows_sys::Win32::Security::TokenElevation;
use windows_sys::Win32::Storage::FileSystem::LOCKFILE_EXCLUSIVE_LOCK;
use windows_sys::Win32::Storage::FileSystem::LOCKFILE_FAIL_IMMEDIATELY;
use windows_sys::Win32::Storage::FileSystem::LockFileEx;
use windows_sys::Win32::System::JobObjects::AssignProcessToJobObject;
use windows_sys::Win32::System::JobObjects::CreateJobObjectW;
use windows_sys::Win32::System::JobObjects::JOB_OBJECT_LIMIT_BREAKAWAY_OK;
use windows_sys::Win32::System::JobObjects::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
use windows_sys::Win32::System::JobObjects::JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
use windows_sys::Win32::System::JobObjects::JobObjectExtendedLimitInformation;
use windows_sys::Win32::System::JobObjects::SetInformationJobObject;
use windows_sys::Win32::System::Threading::CREATE_BREAKAWAY_FROM_JOB;
use windows_sys::Win32::System::Threading::CREATE_SUSPENDED;
use windows_sys::Win32::System::Threading::DETACHED_PROCESS;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
use windows_sys::Win32::System::Threading::GetProcessId;
use windows_sys::Win32::System::Threading::GetProcessTimes;
use windows_sys::Win32::System::Threading::OpenProcess;
use windows_sys::Win32::System::Threading::OpenProcessToken;
use windows_sys::Win32::System::Threading::PROCESS_ACCESS_RIGHTS;
use windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
use windows_sys::Win32::System::Threading::PROCESS_SYNCHRONIZE;
use windows_sys::Win32::System::Threading::PROCESS_TERMINATE;
use windows_sys::Win32::System::Threading::TerminateProcess;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
pub(super) fn spawn_without_inheriting_stdio(
command: &mut tokio::process::Command,
) -> Result<tokio::process::Child> {
// The daemon must not inherit the launcher's output pipes: callers wait for
// them to close after the launcher exits. Leave the flags cleared so concurrent
// launches cannot inherit them either; Rust duplicates the child's chosen stdio.
for (name, handle) in [
("stdin", io::stdin().as_raw_handle()),
("stdout", io::stdout().as_raw_handle()),
("stderr", io::stderr().as_raw_handle()),
] {
if handle.is_null() || handle == INVALID_HANDLE_VALUE {
continue;
}
// SAFETY: these are borrowed standard handles; changing the inherit
// flag neither closes them nor changes their read/write access.
if unsafe {
SetHandleInformation(handle, HANDLE_FLAG_INHERIT, /*dwflags*/ 0)
} == 0
{
let error = io::Error::last_os_error();
// An already-closed handle cannot be inherited.
if error.raw_os_error() == Some(ERROR_INVALID_HANDLE as i32) {
continue;
}
return Err(error)
.with_context(|| format!("failed to clear launcher {name} inheritance"));
}
}
Ok(command.spawn()?)
}
/// Reports whether this process has administrator privileges, rather than
/// merely belonging to an administrator account.
pub fn is_elevated() -> Result<bool> {
let mut token = std::ptr::null_mut();
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
return Err(io::Error::last_os_error()).context("failed to query daemon launcher token");
}
let token = unsafe { OwnedHandle::from_raw_handle(token) };
let mut elevation: TOKEN_ELEVATION = unsafe { std::mem::zeroed() };
let mut returned = 0;
if unsafe {
GetTokenInformation(
token.as_raw_handle(),
TokenElevation,
(&mut elevation as *mut TOKEN_ELEVATION).cast(),
std::mem::size_of::<TOKEN_ELEVATION>() as u32,
&mut returned,
)
} == 0
{
return Err(io::Error::last_os_error())
.context("failed to query daemon launcher elevation");
}
Ok(elevation.TokenIsElevated != 0)
}
pub(crate) fn ensure_not_elevated() -> Result<()> {
anyhow::ensure!(
!is_elevated()?,
"start the Windows daemon from a non-elevated terminal; shared clients must not inherit administrator privileges"
);
Ok(())
}
/// A launch that only fails when asked to leave the launcher's Windows job.
/// Automatic CLI startup may use its embedded server; lifecycle operations
/// must still return this error before stopping an existing daemon.
#[derive(Debug)]
pub struct DetachedLaunchRestricted;
impl fmt::Display for DetachedLaunchRestricted {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(
"this Windows launcher prevents background processes from outliving it (for example, cargo run); build and run codex.exe directly to use the background server",
)
}
}
// Check that breakaway launch is permitted before stopping an existing daemon.
// An outer system job may remain attached; membership alone does not establish
// whether it will terminate the daemon. Suspend the probe before cleanup.
pub(crate) fn ensure_detached_launch(executable: &Path) -> Result<()> {
let mut command = Command::new(executable);
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.creation_flags(CREATE_SUSPENDED | DETACHED_PROCESS | CREATE_BREAKAWAY_FROM_JOB);
let (mut child, launch_result) = match command.spawn() {
Ok(child) => (child, Ok(())),
Err(err) if err.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) => {
// Access denied can also mean the file cannot be executed. Only
// classify a job restriction if removing breakaway makes it work.
// This diagnostic child stays suspended and is always reaped.
command.creation_flags(CREATE_SUSPENDED | DETACHED_PROCESS);
let child = match command.spawn() {
Ok(child) => child,
Err(_) => {
return Err(err).context(crate::telemetry::StartFailure::Spawn(
"cannot launch detached daemon".into(),
));
}
};
(child, Err(err).context(DetachedLaunchRestricted))
}
Err(err) => {
return Err(err).context(crate::telemetry::StartFailure::Spawn(
"cannot launch detached daemon".into(),
));
}
};
child
.kill()
.context("failed to terminate suspended launch probe")?;
child
.wait()
.context("failed to reap suspended launch probe")?;
launch_result
}
pub(super) struct Process(OwnedHandle);
impl Process {
pub(super) fn open(pid: u32) -> Result<Option<Self>> {
Self::open_with_access(pid, PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE)
}
fn open_with_access(pid: u32, access: PROCESS_ACCESS_RIGHTS) -> Result<Option<Self>> {
let handle = unsafe {
OpenProcess(access, /*binherithandle*/ 0, pid)
};
if handle.is_null() {
let err = io::Error::last_os_error();
return if err.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
Ok(None)
} else {
Err(err).context("failed to open daemon process")
};
}
Ok(Some(Self(unsafe { OwnedHandle::from_raw_handle(handle) })))
}
pub(super) fn start_time(&self) -> Result<String> {
let mut created: FILETIME = unsafe { std::mem::zeroed() };
let mut exited = created;
let mut kernel = created;
let mut user = created;
if unsafe {
GetProcessTimes(
self.0.as_raw_handle(),
&mut created,
&mut exited,
&mut kernel,
&mut user,
)
} == 0
{
return Err(io::Error::last_os_error()).context("failed to query daemon creation time");
}
Ok(
((u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime))
.to_string(),
)
}
pub(super) fn is_running(&self) -> Result<bool> {
match unsafe {
WaitForSingleObject(self.0.as_raw_handle(), /*dwmilliseconds*/ 0)
} {
WAIT_TIMEOUT => Ok(true),
WAIT_OBJECT_0 => Ok(false),
_ => Err(io::Error::last_os_error()).context("failed to wait for daemon process"),
}
}
pub(super) fn terminate(&self) -> Result<()> {
if !self.is_running()? {
return Ok(());
}
let pid = unsafe { GetProcessId(self.0.as_raw_handle()) };
let Some(target) = Self::open_with_access(
pid,
PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE | PROCESS_TERMINATE,
)?
else {
return Ok(());
};
// Keep the original identity handle alive and validate the handle that
// will actually be terminated, rather than trusting a second PID lookup.
if target.start_time()? != self.start_time()? || !target.is_running()? {
return Ok(());
}
if unsafe {
TerminateProcess(target.0.as_raw_handle(), /*uexitcode*/ 1)
} == 0
{
return Err(io::Error::last_os_error()).context("failed to terminate daemon process");
}
Ok(())
}
}
pub(crate) fn try_lock_file(file: &tokio::fs::File) -> Result<bool> {
let mut overlapped = unsafe { std::mem::zeroed() };
if unsafe {
LockFileEx(
file.as_raw_handle(),
LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
/*dwreserved*/ 0,
/*nnumberofbytestolocklow*/ 1,
/*nnumberofbytestolockhigh*/ 0,
&mut overlapped,
)
} != 0
{
return Ok(true);
}
let err = io::Error::last_os_error();
if err.raw_os_error() == Some(ERROR_LOCK_VIOLATION as i32) {
return Ok(false);
}
Err(err).context("failed to lock daemon state")
}
// Keep installer descendants bounded by the updater's lifetime, while allowing
// app-server launches and successor updaters to break away from this job.
pub(crate) fn updater_job() -> Result<OwnedHandle> {
process_job(unsafe { GetCurrentProcess() })
}
/// Called before writing the installer script, while PowerShell is waiting on stdin.
pub(crate) fn installer_job(child: &tokio::process::Child) -> Result<OwnedHandle> {
let process = child
.raw_handle()
.context("installer process handle is unavailable")?;
process_job(process)
}
fn process_job(process: HANDLE) -> Result<OwnedHandle> {
let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
if job.is_null() {
return Err(io::Error::last_os_error()).context("failed to create updater job");
}
let owned = unsafe { OwnedHandle::from_raw_handle(job) };
let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
limits.BasicLimitInformation.LimitFlags =
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_BREAKAWAY_OK;
if unsafe {
SetInformationJobObject(
job,
JobObjectExtendedLimitInformation,
(&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
std::mem::size_of_val(&limits) as u32,
)
} == 0
|| unsafe { AssignProcessToJobObject(job, process) } == 0
{
return Err(io::Error::last_os_error())
.context("failed to contain updater installer processes");
}
Ok(owned)
}
#[cfg(test)]
#[path = "windows_tests.rs"]
mod tests;

View File

@@ -0,0 +1,365 @@
use super::Process;
use pretty_assertions::assert_eq;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::OwnedHandle;
use std::os::windows::process::CommandExt;
use std::process::Stdio;
use std::time::Duration;
use tokio::io::AsyncReadExt;
use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;
use windows_sys::Win32::Foundation::HANDLE_FLAG_INHERIT;
use windows_sys::Win32::Foundation::SetHandleInformation;
use windows_sys::Win32::System::JobObjects::IsProcessInJob;
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
use windows_sys::Win32::System::Threading::DETACHED_PROCESS;
use windows_sys::Win32::System::Threading::TerminateProcess;
#[tokio::test]
async fn captured_stdio_closes_while_child_is_alive() {
const TEST: &str = "backend::windows::tests::captured_stdio_closes_while_child_is_alive";
const ROLE: &str = "CODEX_TEST_STDIO_ROLE";
const HOME: &str = "CODEX_TEST_STDIO_HOME";
let executable = std::env::current_exe().expect("test executable");
if let Ok(role) = std::env::var(ROLE) {
let home = std::path::PathBuf::from(std::env::var_os(HOME).expect("test home"));
if role == "child" {
eprintln!("child stderr");
std::fs::write(home.join("ready"), []).unwrap();
tokio::time::sleep(Duration::from_secs(30)).await;
return;
}
let handles = [
std::io::stdout().as_raw_handle(),
std::io::stderr().as_raw_handle(),
];
for handle in handles {
assert_ne!(
unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) },
0
);
}
let mut command = tokio::process::Command::new(executable);
command
.args(["--exact", TEST, "--nocapture"])
.env(ROLE, "child")
// The CI job may forbid breakaway; it does not affect stdio inheritance.
.creation_flags(DETACHED_PROCESS)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(std::fs::File::create(home.join("child.log")).unwrap());
let child = super::spawn_without_inheriting_stdio(&mut command).unwrap();
let pid = child.id().unwrap();
let started = Process::open(pid).unwrap().unwrap().start_time().unwrap();
std::fs::write(
home.join("pid"),
serde_json::to_vec(&(pid, started)).unwrap(),
)
.unwrap();
println!("launcher stdout");
eprintln!("launcher stderr");
return;
}
let home = tempfile::tempdir().unwrap();
let mut launcher = tokio::process::Command::new(executable)
.args(["--exact", TEST, "--nocapture"])
.env(ROLE, "launcher")
.env(HOME, home.path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.unwrap();
let status = tokio::time::timeout(Duration::from_secs(10), launcher.wait())
.await
.expect("launcher exit")
.unwrap();
let (pid, started): (u32, String) =
serde_json::from_slice(&std::fs::read(home.path().join("pid")).unwrap()).unwrap();
let child = Process::open(pid).unwrap().expect("live child");
assert_eq!(
child.start_time().unwrap(),
started,
"fixture PID was reused"
);
let mut stdout = String::new();
let mut stderr = String::new();
let captured = tokio::time::timeout(Duration::from_secs(5), async {
let ready = home.path().join("ready");
while !ready.exists() {
tokio::time::sleep(Duration::from_millis(25)).await;
}
tokio::try_join!(
launcher
.stdout
.as_mut()
.unwrap()
.read_to_string(&mut stdout),
launcher
.stderr
.as_mut()
.unwrap()
.read_to_string(&mut stderr),
)
})
.await;
let still_running = child.is_running();
child.terminate().expect("cleanup child");
tokio::time::timeout(Duration::from_secs(5), async {
while child.is_running().unwrap() {
tokio::time::sleep(Duration::from_millis(25)).await;
}
})
.await
.expect("child exit after cleanup");
captured.expect("launcher output must close").unwrap();
assert!(status.success(), "{stderr}");
assert!(
still_running.unwrap(),
"child exited before its launcher output closed"
);
assert!(stdout.contains("launcher stdout"));
assert!(stderr.contains("launcher stderr"));
assert!(
std::fs::read_to_string(home.path().join("child.log"))
.unwrap()
.contains("child stderr")
);
}
#[test]
fn detached_launch_preflight_rejects_restrictive_job() {
const CHILD: &str = "CODEX_TEST_RESTRICTIVE_LAUNCH_JOB";
let executable = std::env::current_exe().expect("test executable");
if std::env::var_os(CHILD).is_some() {
let job = unsafe { super::CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
assert!(!job.is_null());
let job = unsafe {
<std::os::windows::io::OwnedHandle as std::os::windows::io::FromRawHandle>::from_raw_handle(job)
};
assert_ne!(
unsafe {
super::AssignProcessToJobObject(job.as_raw_handle(), super::GetCurrentProcess())
},
0
);
// A new job does not permit breakaway. Reject before any lifecycle mutation.
let err = super::ensure_detached_launch(&executable).expect_err("breakaway forbidden");
assert!(
err.is::<super::DetachedLaunchRestricted>(),
"expected a classified job restriction: {err:#}"
);
// File access failures must still fail normally, even in a restricted
// job: a CLI must not hide corrupt or inaccessible installations.
let temp = tempfile::tempdir().expect("test directory");
let err =
super::ensure_detached_launch(temp.path()).expect_err("directory is not an executable");
assert!(!err.is::<super::DetachedLaunchRestricted>(), "{err:#}");
return;
}
let output = std::process::Command::new(executable)
.args([
"--exact",
"backend::windows::tests::detached_launch_preflight_rejects_restrictive_job",
"--nocapture",
])
.env(CHILD, "1")
.output()
.expect("isolated job test");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
}
#[test]
fn detached_launch_preflight_allows_residual_job() {
const CHILD: &str = "CODEX_TEST_RESIDUAL_LAUNCH_JOB";
let executable = std::env::current_exe().expect("test executable");
if std::env::var_os(CHILD).is_some() {
let mut jobs = Vec::new();
for inner in [false, true] {
let job = unsafe { super::CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
assert!(!job.is_null());
let job = unsafe { OwnedHandle::from_raw_handle(job) };
if inner {
let mut limits: super::JOBOBJECT_EXTENDED_LIMIT_INFORMATION =
unsafe { std::mem::zeroed() };
limits.BasicLimitInformation.LimitFlags = super::JOB_OBJECT_LIMIT_BREAKAWAY_OK;
assert_ne!(
unsafe {
super::SetInformationJobObject(
job.as_raw_handle(),
super::JobObjectExtendedLimitInformation,
(&limits as *const super::JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
std::mem::size_of_val(&limits) as u32,
)
},
0
);
}
assert_ne!(
unsafe {
super::AssignProcessToJobObject(job.as_raw_handle(), super::GetCurrentProcess())
},
0
);
jobs.push(job);
}
let mut probe = std::process::Command::new(&executable)
.creation_flags(
super::CREATE_SUSPENDED
| super::DETACHED_PROCESS
| super::CREATE_BREAKAWAY_FROM_JOB,
)
.spawn()
.expect("breakaway probe");
let mut in_outer = 0;
let mut in_inner = 0;
let outer_checked = unsafe {
IsProcessInJob(
probe.as_raw_handle(),
jobs[0].as_raw_handle(),
&mut in_outer,
)
};
let inner_checked = unsafe {
IsProcessInJob(
probe.as_raw_handle(),
jobs[1].as_raw_handle(),
&mut in_inner,
)
};
probe.kill().expect("terminate probe");
probe.wait().expect("reap probe");
assert_ne!(outer_checked, 0);
assert_ne!(inner_checked, 0);
assert_ne!(in_outer, 0, "probe must retain its outer job");
assert_eq!(in_inner, 0, "probe must leave its inner job");
super::ensure_detached_launch(&executable).expect("residual job must be accepted");
if let Err(err) = super::ensure_not_elevated() {
assert!(err.to_string().contains("non-elevated terminal"));
return;
}
let temp = tempfile::tempdir().expect("temp dir");
let script = temp.path().join("codex.cmd");
std::fs::write(
&script,
"@echo off\r\nif \"%3\"==\"--help\" exit /b 1\r\necho ready > \"%~dp0ready\"\r\nfor /l %%i in (1,1,10000000) do @rem\r\n",
)
.expect("write daemon fixture");
let backend = crate::backend::pid::PidBackend::new(
script,
temp.path().join("state").join("daemon.pid"),
/*remote_control_enabled*/ false,
);
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("runtime");
let pid = runtime
.block_on(backend.start())
.expect("daemon launch")
.expect("new daemon pid");
let process = Process::open(pid)
.expect("open daemon")
.expect("live daemon");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while !temp.path().join("ready").exists() && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(50));
}
let ready = temp.path().join("ready").exists();
let outer_checked = unsafe {
IsProcessInJob(
process.0.as_raw_handle(),
jobs[0].as_raw_handle(),
&mut in_outer,
)
};
let inner_checked = unsafe {
IsProcessInJob(
process.0.as_raw_handle(),
jobs[1].as_raw_handle(),
&mut in_inner,
)
};
process.terminate().expect("terminate daemon fixture");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while process.is_running().expect("daemon liveness") && std::time::Instant::now() < deadline
{
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(!process.is_running().expect("daemon liveness"));
assert!(ready, "daemon fixture did not start");
assert_ne!(outer_checked, 0);
assert_ne!(inner_checked, 0);
assert_ne!(in_outer, 0, "daemon must retain its outer job");
assert_eq!(in_inner, 0, "daemon must leave its inner job");
return;
}
let output = std::process::Command::new(executable)
.args([
"--exact",
"backend::windows::tests::detached_launch_preflight_allows_residual_job",
"--nocapture",
])
.env(CHILD, "1")
.output()
.expect("isolated job test");
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
}
#[tokio::test]
async fn identity_queries_do_not_require_termination_access() {
let mut child = tokio::process::Command::new("powershell.exe")
.args([
"-NoProfile",
"-NonInteractive",
"-Command",
"Start-Sleep 60",
])
.creation_flags(CREATE_NO_WINDOW)
.kill_on_drop(true)
.spawn()
.expect("child");
let process = Process::open(child.id().expect("pid"))
.expect("query handle")
.expect("live process");
assert!(!process.start_time().expect("creation time").is_empty());
assert!(process.is_running().expect("liveness"));
// Check the rights on the actual query handle, independent of privileges
// that could let the caller reopen the process with termination access.
assert_eq!(
unsafe {
TerminateProcess(process.0.as_raw_handle(), /*uexitcode*/ 1)
},
0
);
assert_eq!(
std::io::Error::last_os_error().raw_os_error(),
Some(ERROR_ACCESS_DENIED as i32)
);
assert!(
process
.is_running()
.expect("query must not terminate child")
);
child
.kill()
.await
.expect("cleanup through original spawn handle");
}

View File

@@ -0,0 +1,92 @@
//! Recovers background startup after the launching directory is removed.
//! Preserve process-scoped paths; retain usable Unix cwd defaults for clients.
use std::path::Path;
use std::process::Command;
use anyhow::Result;
pub(crate) fn set_working_directory(command: &mut Command, state_dir: &Path) -> Result<()> {
#[cfg(unix)]
let cwd_missing = match std::env::current_dir() {
Ok(_) => false,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => true,
Err(err) => return Err(err.into()),
};
if let Ok(value) = std::env::var("CODEX_HOME")
&& !value.is_empty()
{
let home = codex_utils_home_dir::find_codex_home()?;
// Remove parent components without discarding a valid configured symlink alias.
let absolute = std::path::absolute(value)?;
let alias = home.join(&absolute);
let preserved = if alias.canonicalize().ok().as_ref() == Some(&home) {
alias.as_path()
} else if home.as_path().to_str().is_some() {
home.as_path()
} else {
// The home resolver ignores non-Unicode env values; keep the valid original alias.
absolute.as_path()
};
command.env("CODEX_HOME", preserved);
}
// Preserve process-scoped paths before changing cwd; CA names match CUSTOM_CA_ENV_KEYS.
for name in [
#[cfg(windows)]
"CODEX_SQLITE_HOME",
"CODEX_CA_CERTIFICATE",
"SSL_CERT_FILE",
"REQUESTS_CA_BUNDLE",
"CURL_CA_BUNDLE",
"NODE_EXTRA_CA_CERTS",
"GIT_SSL_CAINFO",
"CARGO_HTTP_CAINFO",
"PIP_CERT",
"BUNDLE_SSL_CA_CERT",
"npm_config_cafile",
"NPM_CONFIG_CAFILE",
"AWS_CONFIG_FILE",
"AWS_SHARED_CREDENTIALS_FILE",
"AWS_WEB_IDENTITY_TOKEN_FILE",
"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",
] {
let Some(mut value) = std::env::var_os(name) else {
continue;
};
if matches!(
name,
"CODEX_SQLITE_HOME" | "npm_config_cafile" | "NPM_CONFIG_CAFILE"
) {
value = value.to_str().unwrap_or_default().trim().into();
}
// These consumers expand `~` independently of the working directory.
let expands_home = if matches!(name, "npm_config_cafile" | "NPM_CONFIG_CAFILE") {
value
.to_str()
.is_some_and(|path| path.starts_with("~/") || path.starts_with("~\\"))
} else {
matches!(
name,
"CODEX_SQLITE_HOME" | "AWS_CONFIG_FILE" | "AWS_SHARED_CREDENTIALS_FILE"
) && std::path::Path::new(&value).starts_with("~")
};
if value.is_empty() || expands_home {
continue;
}
command.env(name, std::path::absolute(value)?);
}
if let Some(value) = std::env::var_os("SSL_CERT_DIR") {
let paths = std::env::split_paths(&value)
.filter(|path| !path.as_os_str().is_empty())
.map(std::path::absolute)
.collect::<std::io::Result<Vec<_>>>()?;
command.env("SSL_CERT_DIR", std::env::join_paths(paths)?);
}
#[cfg(unix)]
if cwd_missing {
command.current_dir(state_dir);
}
#[cfg(windows)]
command.current_dir(state_dir);
Ok(())
}

View File

@@ -0,0 +1,207 @@
use std::path::Path;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use codex_app_server_protocol::ClientInfo;
use codex_app_server_protocol::InitializeCapabilities;
use codex_app_server_protocol::InitializeParams;
use codex_app_server_protocol::InitializeResponse;
use codex_app_server_protocol::JSONRPCMessage;
use codex_app_server_protocol::JSONRPCNotification;
use codex_app_server_protocol::JSONRPCRequest;
use codex_app_server_protocol::RequestId;
use codex_uds::UnixStream;
use futures::SinkExt;
use futures::StreamExt;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use tokio::time::timeout;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::client_async;
use tokio_tungstenite::tungstenite::Message;
pub(crate) const CONTROL_SOCKET_RESPONSE_TIMEOUT: Duration = Duration::from_secs(2);
const CLIENT_NAME: &str = "codex_app_server_daemon";
const INITIALIZE_REQUEST_ID: RequestId = RequestId::Integer(1);
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProbeInfo {
pub(crate) app_server_version: String,
}
pub(crate) async fn probe(socket_path: &Path) -> Result<ProbeInfo> {
timeout(CONTROL_SOCKET_RESPONSE_TIMEOUT, probe_inner(socket_path))
.await
.with_context(|| {
format!(
"timed out probing app-server control socket {}",
socket_path.display()
)
})?
}
async fn probe_inner(socket_path: &Path) -> Result<ProbeInfo> {
let mut websocket = connect(socket_path).await?;
let initialize_response = initialize(&mut websocket, /*experimental_api*/ false).await?;
let initialized = JSONRPCMessage::Notification(JSONRPCNotification {
method: "initialized".to_string(),
params: None,
});
send_message(&mut websocket, &initialized)
.await
.context("failed to send initialized notification")?;
websocket.close(None).await.ok();
Ok(ProbeInfo {
app_server_version: parse_version_from_user_agent(&initialize_response.user_agent)?,
})
}
pub(crate) async fn connect(socket_path: &Path) -> Result<WebSocketStream<UnixStream>> {
connect_at(socket_path, "ws://localhost/").await
}
async fn connect_at(socket_path: &Path, url: &str) -> Result<WebSocketStream<UnixStream>> {
let stream = UnixStream::connect(socket_path)
.await
.with_context(|| format!("failed to connect to {}", socket_path.display()))?;
let (websocket, _response) = client_async(url, stream)
.await
.with_context(|| format!("failed to upgrade {}", socket_path.display()))?;
Ok(websocket)
}
#[cfg(windows)]
pub(crate) async fn request_shutdown(socket_path: &Path, pid: u32) -> Result<()> {
timeout(CONTROL_SOCKET_RESPONSE_TIMEOUT, async {
let mut websocket = connect_at(socket_path, "ws://localhost/daemon/shutdown").await?;
websocket
.send(Message::Text(pid.to_string().into()))
.await?;
let reply = websocket
.next()
.await
.context("shutdown socket closed without acknowledgment")??;
anyhow::ensure!(
matches!(reply, Message::Text(ack) if ack == pid.to_string()),
"shutdown acknowledgment did not match the managed process {pid}"
);
websocket.close(None).await?;
Ok(())
})
.await
.context("timed out waiting for managed app-server shutdown acknowledgment")?
}
pub(crate) async fn initialize<S>(
websocket: &mut WebSocketStream<S>,
experimental_api: bool,
) -> Result<InitializeResponse>
where
S: AsyncRead + AsyncWrite + Unpin,
{
let initialize = JSONRPCMessage::Request(JSONRPCRequest {
id: INITIALIZE_REQUEST_ID,
method: "initialize".to_string(),
params: Some(serde_json::to_value(InitializeParams {
client_info: ClientInfo {
name: CLIENT_NAME.to_string(),
title: Some("Codex App Server Daemon".to_string()),
version: env!("CARGO_PKG_VERSION").to_string(),
},
capabilities: if experimental_api {
Some(InitializeCapabilities {
experimental_api: true,
..Default::default()
})
} else {
None
},
})?),
trace: None,
});
send_message(websocket, &initialize)
.await
.context("failed to send initialize request")?;
let response = loop {
let message = timeout(CONTROL_SOCKET_RESPONSE_TIMEOUT, read_message(websocket))
.await
.context("timed out waiting for initialize response")??;
if let JSONRPCMessage::Response(response) = message
&& response.id == INITIALIZE_REQUEST_ID
{
break response;
}
};
serde_json::from_value::<InitializeResponse>(response.result)
.context("failed to parse initialize response")
}
pub(crate) async fn send_message<S>(
websocket: &mut WebSocketStream<S>,
message: &JSONRPCMessage,
) -> Result<()>
where
S: AsyncRead + AsyncWrite + Unpin,
{
websocket
.send(Message::Text(serde_json::to_string(message)?.into()))
.await?;
Ok(())
}
pub(crate) async fn read_message<S>(websocket: &mut WebSocketStream<S>) -> Result<JSONRPCMessage>
where
S: AsyncRead + AsyncWrite + Unpin,
{
loop {
let frame = websocket
.next()
.await
.ok_or_else(|| anyhow!("app-server closed the control socket"))??;
let Message::Text(payload) = frame else {
continue;
};
return serde_json::from_str::<JSONRPCMessage>(&payload)
.context("failed to parse app-server JSON-RPC message");
}
}
fn parse_version_from_user_agent(user_agent: &str) -> Result<String> {
let (_originator, rest) = user_agent
.split_once('/')
.ok_or_else(|| anyhow!("app-server user-agent omitted version separator"))?;
let version = rest
.split_whitespace()
.next()
.filter(|version| !version.is_empty())
.ok_or_else(|| anyhow!("app-server user-agent omitted version"))?;
Ok(version.to_string())
}
#[cfg(all(test, unix))]
mod tests {
use pretty_assertions::assert_eq;
use super::parse_version_from_user_agent;
#[test]
fn parses_version_from_codex_user_agent() {
assert_eq!(
parse_version_from_user_agent(
"codex_app_server_daemon/1.2.3 (Linux 6.8.0; x86_64) codex_cli_rs/1.2.3",
)
.expect("version"),
"1.2.3"
);
}
#[test]
fn rejects_user_agent_without_version() {
assert!(parse_version_from_user_agent("codex_app_server_daemon").is_err());
}
}

View File

@@ -0,0 +1,124 @@
//! Default-on local lifecycle records contain only fixed events and typed OS errors.
//! Error messages and chains can contain raw child stderr or protocol data; never print them.
use std::io::IsTerminal;
use std::io::Write;
use std::time::Instant;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use anyhow::Result;
use serde::Serialize;
#[derive(Debug, Serialize, PartialEq, Eq)]
struct Failure {
kind: String,
os_code: Option<i32>,
}
impl From<&anyhow::Error> for Failure {
fn from(error: &anyhow::Error) -> Self {
match error.downcast_ref::<std::io::Error>() {
Some(error) => Self {
kind: format!("{:?}", error.kind()),
os_code: error.raw_os_error(),
},
None => Self {
kind: "other".to_string(),
os_code: None,
},
}
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Record<D> {
timestamp_ms: u128,
process_pid: u32,
#[serde(flatten)]
payload: Payload<D>,
}
#[derive(Serialize)]
#[serde(untagged)]
enum Payload<D> {
Event {
event: &'static str,
details: D,
},
Result {
stage: &'static str,
outcome: Outcome,
#[serde(rename = "elapsedMs")]
elapsed_ms: u128,
failure: Option<Failure>,
},
}
#[derive(Serialize)]
#[serde(rename_all = "lowercase")]
enum Outcome {
Succeeded,
Failed,
}
pub(crate) fn event(name: &'static str, details: impl Serialize) {
emit(Payload::Event {
event: name,
details,
});
}
pub(crate) fn result<T>(stage: &'static str, started: Instant, result: Result<T>) -> Result<T> {
emit(Payload::<()>::Result {
stage,
outcome: if result.is_ok() {
Outcome::Succeeded
} else {
Outcome::Failed
},
elapsed_ms: started.elapsed().as_millis(),
failure: result.as_ref().err().map(Failure::from),
});
result
}
fn emit(payload: Payload<impl Serialize>) {
let failed = matches!(
&payload,
Payload::Result {
outcome: Outcome::Failed,
..
}
);
let record = Record {
timestamp_ms: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis(),
process_pid: std::process::id(),
payload,
};
let Ok(mut record) = serde_json::to_string(&record) else {
return;
};
if tracing::dispatcher::has_been_set() {
// Use the configured logger whenever one is available.
if failed {
tracing::warn!(target: "codex_app_server_daemon", "{record}");
} else {
tracing::info!(target: "codex_app_server_daemon", "{record}");
}
} else if !std::io::stderr().is_terminal() {
// The detached updater has redirected stderr and no tracing subscriber.
// A TUI can own a live terminal before installing its subscriber.
// Never let a log write failure interrupt the lifecycle operation.
record.push('\n');
let _ = crate::stderr_writer().write_all(record.as_bytes());
}
}
#[cfg(test)]
#[path = "diagnostics_tests.rs"]
mod tests;

View File

@@ -0,0 +1,55 @@
use super::Failure;
use pretty_assertions::assert_eq;
#[test]
fn failure_omits_error_messages_and_context() {
let error = anyhow::Error::new(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"secret child output",
))
.context("secret protocol data");
assert_eq!(
Failure::from(&error),
Failure {
kind: "PermissionDenied".to_string(),
os_code: None
},
);
let error = anyhow::anyhow!("secret child output");
assert_eq!(
Failure::from(&error),
Failure {
kind: "other".to_string(),
os_code: None
},
);
}
#[test]
fn result_record_preserves_json_shape_and_redacts_error_text() {
let error = anyhow::Error::new(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"secret child output",
));
let record = super::Record {
timestamp_ms: 123,
process_pid: 456,
payload: super::Payload::<()>::Result {
stage: "process_spawn",
outcome: super::Outcome::Failed,
elapsed_ms: 789,
failure: Some(Failure::from(&error)),
},
};
assert_eq!(
serde_json::to_value(record).unwrap(),
serde_json::json!({
"timestampMs": 123,
"processPid": 456,
"stage": "process_spawn",
"outcome": "failed",
"elapsedMs": 789,
"failure": { "kind": "PermissionDenied", "os_code": null },
}),
);
}

View File

@@ -0,0 +1,143 @@
//! Coordinates package selection with the shell and PowerShell installers.
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use std::fs::OpenOptions;
use std::path::Path;
use std::time::Duration;
use tokio::time::sleep;
pub(crate) struct InstallLock {
_file: Option<tokio::fs::File>,
directory: Option<std::path::PathBuf>,
_directory_owner: Option<tempfile::TempDir>,
}
impl Drop for InstallLock {
fn drop(&mut self) {
if let Some(directory) = &self.directory {
let _ = std::fs::remove_file(directory);
}
}
}
pub(crate) async fn acquire_install_lock(root: &Path) -> Result<InstallLock> {
let lock = root.join("install.lock");
let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
#[cfg(unix)]
let use_lockf = {
// Match the installer so both processes coordinate on the same lock.
let choice = tokio::process::Command::new("/bin/sh")
.args(["-c", if cfg!(target_os = "macos") {
"if command -v lockf >/dev/null 2>&1; then exit 0; elif command -v flock >/dev/null 2>&1; then exit 1; else exit 2; fi"
} else {
"if command -v flock >/dev/null 2>&1; then exit 1; else exit 2; fi"
}])
.status().await?;
match choice.code() {
Some(0) => true,
Some(1) => false,
Some(2) => {
let directory = root.join("install.lock.d");
// Publish complete metadata atomically. Older shell installers
// immediately remove an empty lock directory as stale.
let owner = tempfile::Builder::new()
.prefix("install-lock-")
.tempdir_in(root)?;
std::fs::write(owner.path().join("pid"), std::process::id().to_string())?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)?
.as_secs();
std::fs::write(owner.path().join("started_at"), now.to_string())?;
loop {
match std::os::unix::fs::symlink(owner.path(), &directory) {
Ok(()) => {
return Ok(InstallLock {
_file: None,
directory: Some(directory),
_directory_owner: Some(owner),
});
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(error) => {
return Err(error)
.context("failed to acquire daemon installer directory lock");
}
}
let pid = std::fs::read_to_string(directory.join("pid"))
.ok()
.and_then(|pid| pid.trim().parse::<i32>().ok())
.filter(|pid| *pid > 0);
let dead = pid.is_none_or(|pid| unsafe { libc::kill(pid, 0) } != 0
&& std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH));
let age = std::fs::metadata(&directory)
.and_then(|metadata| metadata.modified())
.ok()
.and_then(|modified| modified.elapsed().ok())
.unwrap_or_default();
// Allow the creator time to publish its PID; match the installer's
// ten-minute stale-lock grace instead of stealing an active lock.
if dead && age >= Duration::from_secs(600) {
std::fs::remove_dir_all(&directory)?;
continue;
}
anyhow::ensure!(
tokio::time::Instant::now() < deadline,
"timed out waiting for daemon installer lock {}",
directory.display()
);
sleep(Duration::from_millis(50)).await;
}
}
_ => return Err(anyhow!("failed to detect daemon installer lock tools")),
}
};
let mut options = OpenOptions::new();
options.create(true).truncate(false).write(true);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
options.share_mode(0);
}
loop {
let acquired = options.open(&lock);
#[cfg(unix)]
let acquired = acquired.and_then(|file| {
{
use std::os::fd::AsRawFd;
let result = if use_lockf {
unsafe { libc::lockf(file.as_raw_fd(), libc::F_TLOCK, 0) }
} else {
unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }
};
if result != 0 {
return Err(std::io::Error::last_os_error());
}
}
Ok(file)
});
match acquired {
Ok(file) => {
return Ok(InstallLock {
_file: Some(tokio::fs::File::from_std(file)),
directory: None,
_directory_owner: None,
});
}
Err(error)
if error.kind() == std::io::ErrorKind::WouldBlock
|| cfg!(windows)
&& (error.raw_os_error() == Some(32)
|| error.kind() == std::io::ErrorKind::PermissionDenied) => {}
Err(error) => return Err(error).context("failed to acquire daemon installer lock"),
}
if tokio::time::Instant::now() >= deadline {
return Err(anyhow!(
"timed out waiting for daemon installer lock {}",
lock.display()
));
}
sleep(Duration::from_millis(50)).await;
}
}

View File

@@ -0,0 +1,84 @@
//! Invocation overrides apply on fresh starts or explicitly confirmed managed restarts.
//! The lifecycle lock serializes persistence against other clients and updates.
use crate::Daemon;
use crate::LifecycleOutput;
use crate::ensure_supported_platform;
use crate::telemetry::StartError;
use anyhow::Result;
use anyhow::ensure;
use std::collections::BTreeMap;
/// Start a missing daemon with these features, preserving other saved overrides,
/// or leave a running daemon unchanged.
/// Callers must check the running server's configuration before using it.
/// Startup diagnostics go to tracing, so a caller with a live TUI can keep rendering.
pub async fn start_with_features(features: &BTreeMap<String, bool>) -> Result<LifecycleOutput> {
start_with_features_classified(features)
.await
.map_err(|err| err.error)
}
/// Starts the daemon and classifies failures for the TUI startup counter.
pub async fn start_with_features_classified(
features: &BTreeMap<String, bool>,
) -> Result<LifecycleOutput, StartError> {
ensure_supported_platform()?;
#[cfg(windows)]
crate::backend::windows::ensure_not_elevated()?;
let mut daemon = Daemon::from_environment()?;
daemon.log_diagnostics = true;
let _operation_lock = daemon.acquire_operation_lock().await?;
let selected = daemon.current_installation()?;
let mut overrides = selected.load_settings().await?.feature_overrides;
overrides.extend(features.clone());
Box::pin(selected.start(&overrides)).await
}
/// Apply confirmed feature settings to an existing managed daemon and restart it.
/// Callers must obtain consent for changes to shared services and interrupted work,
/// then verify effective server compatibility after this operation completes.
pub async fn restart_with_features(features: &BTreeMap<String, bool>) -> Result<LifecycleOutput> {
ensure_supported_platform()?;
#[cfg(windows)]
crate::backend::windows::ensure_not_elevated()?;
let daemon = Daemon::from_environment()?;
let _operation_lock = daemon.acquire_operation_lock().await?;
let selected = daemon.current_installation()?;
Box::pin(selected.restart_with_features_locked(features)).await
}
impl Daemon {
pub(super) async fn restart(
&self,
features: &BTreeMap<String, bool>,
) -> Result<LifecycleOutput> {
let mut settings = self.load_settings().await?;
// Explicit requests replace saved aliases as well as canonical keys.
settings.feature_overrides.retain(|name, _| {
let canonical = codex_features::feature_for_key(name)
.map(codex_features::Feature::key)
.unwrap_or(name);
!features.contains_key(canonical)
});
settings.feature_overrides.extend(features.clone());
self.restart_with_settings(settings).await
}
pub(super) async fn restart_with_features_locked(
&self,
features: &BTreeMap<String, bool>,
) -> Result<LifecycleOutput> {
let mut settings = self.load_settings().await?;
ensure!(
self.running_backend_instance(&settings).await?.is_some(),
"no running managed daemon; rerun the command to check the current server"
);
let previous = settings.feature_overrides.clone();
settings.feature_overrides.extend(features.clone());
if settings.feature_overrides == previous {
return self.start(&previous).await.map_err(|err| err.error);
}
self.restart_with_settings(settings).await
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,261 @@
//! Resolves both package and legacy standalone layouts and compares installed executables.
use std::path::Path;
use std::path::PathBuf;
use std::process::Stdio;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use serde::Deserialize;
use serde::Serialize;
use tokio::fs;
use tokio::process::Command;
use tokio::time::timeout;
/// New daemons own their packages, regardless of how the calling CLI was installed.
/// Preserve legacy launch state, including logs left after a daemon is stopped;
/// settings, installer selections, and lock files alone do not prove a prior launch.
pub(crate) fn package_root(codex_home: &Path) -> PathBuf {
let dedicated = codex_home.join("packages/app-server-daemon");
if !matches!(dedicated.join("current").symlink_metadata(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound)
{
return dedicated;
}
let state = codex_home.join("app-server-daemon");
for (package, artifacts) in [
(
"app-server-daemon",
[
crate::DAEMON_PID_FILE_NAME,
"daemon.stderr.log",
crate::DAEMON_UPDATE_PID_FILE_NAME,
"daemon-updater.stderr.log",
],
),
(
"standalone",
[
crate::LEGACY_PID_FILE_NAME,
"app-server.stderr.log",
crate::LEGACY_UPDATE_PID_FILE_NAME,
"app-server-updater.stderr.log",
],
),
] {
if artifacts.iter().any(|name| {
!matches!(state.join(name).symlink_metadata(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound)
}) {
return codex_home.join("packages").join(package);
}
}
dedicated
}
/// Resolve both packaged and legacy binaries without requiring a valid install.
pub(crate) fn managed_codex_bin(codex_home: &Path) -> PathBuf {
let root = package_root(codex_home);
let current = root.join("current");
let packaged = current.join("bin").join(managed_codex_file_name());
let legacy = current.join(managed_codex_file_name());
if packaged.is_file()
|| !legacy.is_file() && (cfg!(windows) || root.ends_with("app-server-daemon"))
{
packaged
} else {
legacy
}
}
/// Only latest-channel stable releases may run the public latest-version updater.
pub(crate) fn is_stable_standalone_release(codex_home: &Path, codex_bin: &Path) -> bool {
let standalone = package_root(codex_home);
let Ok(releases) = std::fs::canonicalize(standalone.join("releases")) else {
return false;
};
let Ok(release) = std::fs::canonicalize(standalone.join("current")) else {
return false;
};
if release.parent() != Some(releases.as_path()) {
return false;
}
let Some(release_name) = release.file_name().and_then(|name| name.to_str()) else {
return false;
};
// GNU packages can seed the new directory; retain legacy updater eligibility.
if standalone.ends_with("standalone") && release_name.ends_with("-gnu") {
return false;
}
let targets = [
"aarch64-apple-darwin",
"x86_64-apple-darwin",
"aarch64-unknown-linux-gnu",
"x86_64-unknown-linux-gnu",
"aarch64-unknown-linux-musl",
"x86_64-unknown-linux-musl",
"aarch64-pc-windows-msvc",
"x86_64-pc-windows-msvc",
];
let Some(version) = targets
.iter()
.find_map(|target| release_name.strip_suffix(&format!("-{target}")))
else {
return false;
};
let components: Vec<_> = version.split('.').collect();
components.len() == 3
&& components.iter().all(|component| {
!component.is_empty() && component.bytes().all(|byte| byte.is_ascii_digit())
})
&& std::fs::read_to_string(standalone.join("auto-update-version"))
.is_ok_and(|selected| selected == release_name)
&& std::fs::canonicalize(codex_bin).is_ok_and(|bin| bin.starts_with(&release))
}
/// Older managed binaries can serve app-server requests without owning an updater.
pub(crate) async fn supports_daemon_update_loop(codex_bin: &Path) -> bool {
supports_daemon_command(codex_bin, &["pid-update-loop", "--help"]).await
}
/// Probe an internal daemon command without running a long-lived process.
pub(crate) async fn supports_daemon_command(codex_bin: &Path, args: &[&str]) -> bool {
let mut command = Command::new(codex_bin);
#[cfg(windows)]
command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
timeout(
Duration::from_secs(5),
command
.args(["app-server", "daemon"])
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true)
.status(),
)
.await
.is_ok_and(|result| result.is_ok_and(|status| status.success()))
}
pub(crate) async fn resolved_managed_codex_bin(codex_bin: &Path) -> Result<PathBuf> {
fs::canonicalize(codex_bin).await.with_context(|| {
format!(
"failed to resolve managed Codex binary {}",
codex_bin.display()
)
})
}
pub(crate) async fn managed_codex_version(codex_bin: &Path) -> Result<String> {
let mut command = Command::new(codex_bin);
#[cfg(windows)]
command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
let output = command
.arg("--version")
.kill_on_drop(true)
.output()
.await
.with_context(|| {
format!(
"failed to invoke managed Codex binary {}",
codex_bin.display()
)
})?;
if !output.status.success() {
return Err(anyhow!(
"managed Codex binary {} exited with status {}",
codex_bin.display(),
output.status
));
}
let stdout = String::from_utf8(output.stdout).with_context(|| {
format!(
"managed Codex version was not utf-8: {}",
codex_bin.display()
)
})?;
parse_codex_version(&stdout)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct ExecutableIdentity {
pub(crate) digest: [u8; 32],
// Distinguish release generations whose executable bytes are identical.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) path_digest: Option<[u8; 32]>,
}
impl ExecutableIdentity {
pub(crate) fn same_contents(&self, other: &Self) -> bool {
self.digest == other.digest
}
}
pub(crate) async fn executable_identity(executable: &Path) -> Result<ExecutableIdentity> {
let executable = executable.to_path_buf();
// Debug executables can be hundreds of MB. Stream the digest off the async
// runtime instead of allocating the whole file and blocking a runtime thread.
tokio::task::spawn_blocking(move || {
let executable = std::fs::canonicalize(&executable).unwrap_or(executable);
let mut identity = std::fs::File::open(&executable)
.and_then(executable_identity_from_reader)
.with_context(|| format!("failed to read executable {}", executable.display()))?;
identity.path_digest = Some(path_digest(&executable));
Ok(identity)
})
.await
.context("executable identity task failed")?
}
pub(crate) fn executable_identity_from_reader(
reader: impl std::io::Read,
) -> std::io::Result<ExecutableIdentity> {
let mut hasher = blake3::Hasher::new();
hasher.update_reader(reader)?;
Ok(ExecutableIdentity {
digest: *hasher.finalize().as_bytes(),
path_digest: None,
})
}
pub(crate) fn path_digest(path: &Path) -> [u8; 32] {
let mut hasher = blake3::Hasher::new();
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
hasher.update(path.as_os_str().as_bytes());
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
for unit in path.as_os_str().encode_wide() {
hasher.update(&unit.to_le_bytes());
}
}
*hasher.finalize().as_bytes()
}
fn managed_codex_file_name() -> &'static str {
if cfg!(windows) { "codex.exe" } else { "codex" }
}
fn parse_codex_version(output: &str) -> Result<String> {
let version = output
.split_whitespace()
.nth(1)
.filter(|version| !version.is_empty())
.ok_or_else(|| anyhow!("managed Codex version output was malformed"))?;
Ok(version.to_string())
}
#[cfg(test)]
#[path = "managed_install_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "managed_install_path_tests.rs"]
mod path_tests;

View File

@@ -0,0 +1,123 @@
use pretty_assertions::assert_eq;
#[test]
fn discovers_package_and_legacy_installs() {
let home = tempfile::TempDir::new().expect("home");
let current = home.path().join("packages/standalone/current");
let legacy = current.join(super::managed_codex_file_name());
assert_eq!(
super::managed_codex_bin(home.path()),
home.path()
.join("packages/app-server-daemon/current/bin")
.join(super::managed_codex_file_name())
);
std::fs::create_dir_all(&current).expect("current directory");
std::fs::write(&legacy, b"legacy").expect("legacy executable");
let state = home.path().join("app-server-daemon");
std::fs::create_dir(&state).unwrap();
for name in ["settings.json", "daemon.lock", "app-server.pid.lock"] {
std::fs::write(state.join(name), b"").unwrap();
}
// A CLI install and a previous stop/status operation do not establish ownership.
assert_eq!(
super::package_root(home.path()),
home.path().join("packages/app-server-daemon")
);
std::fs::write(state.join("app-server.stderr.log"), b"").unwrap();
assert_eq!(super::managed_codex_bin(home.path()), legacy);
let packaged = current.join("bin").join(super::managed_codex_file_name());
std::fs::create_dir(current.join("bin")).expect("bin directory");
std::fs::write(&packaged, b"packaged").expect("packaged executable");
assert_eq!(super::managed_codex_bin(home.path()), packaged);
std::fs::remove_dir_all(home.path().join("packages/standalone")).unwrap();
assert_eq!(
super::package_root(home.path()),
home.path().join("packages/standalone")
);
std::fs::remove_file(state.join("app-server.stderr.log")).unwrap();
std::fs::write(state.join("app-server.pid"), b"running daemon").unwrap();
assert_eq!(
super::package_root(home.path()),
home.path().join("packages/standalone")
);
std::fs::write(state.join("daemon.pid"), b"running dedicated daemon").unwrap();
assert_eq!(
super::package_root(home.path()),
home.path().join("packages/app-server-daemon")
);
std::fs::remove_file(state.join("daemon.pid")).unwrap();
std::fs::write(state.join("daemon.stderr.log"), b"").unwrap();
assert_eq!(
super::package_root(home.path()),
home.path().join("packages/app-server-daemon")
);
#[cfg(unix)]
{
let dedicated = home.path().join("packages/app-server-daemon");
std::fs::write(&dedicated, b"not a directory").expect("unreadable selection");
assert_eq!(super::package_root(home.path()), dedicated);
}
}
#[cfg(unix)]
#[test]
fn updater_only_runs_for_stable_installer_owned_releases() {
let home = tempfile::TempDir::new().expect("home");
let state = home.path().join("app-server-daemon");
std::fs::create_dir(&state).unwrap();
std::fs::write(state.join("app-server.stderr.log"), b"").unwrap();
let standalone = home.path().join("packages/standalone");
let current = standalone.join("current");
let release = standalone.join("releases/0.150.0-aarch64-apple-darwin");
let managed = release.join("bin/codex");
std::fs::create_dir_all(managed.parent().expect("bin parent")).expect("release");
std::fs::write(&managed, b"stable").expect("managed bin");
std::os::unix::fs::symlink(&release, &current).expect("current release");
assert!(!super::is_stable_standalone_release(home.path(), &managed));
let marker = standalone.join("auto-update-version");
let release_name = release.file_name().expect("release name");
std::fs::write(&marker, release_name.as_encoded_bytes()).expect("latest selection");
assert!(super::is_stable_standalone_release(home.path(), &managed));
std::fs::write(&marker, b"0.149.0-aarch64-apple-darwin").expect("stale selection");
assert!(!super::is_stable_standalone_release(home.path(), &managed));
std::fs::remove_file(&marker).expect("pinned selection");
assert!(!super::is_stable_standalone_release(home.path(), &managed));
let alpha = standalone.join("releases/0.151.0-alpha.1-aarch64-apple-darwin");
let alpha_managed = alpha.join("bin/codex");
std::fs::create_dir_all(alpha_managed.parent().expect("alpha bin parent"))
.expect("alpha release");
std::fs::write(&alpha_managed, b"alpha").expect("alpha bin");
std::fs::remove_file(&current).expect("remove current");
std::os::unix::fs::symlink(alpha, &current).expect("current alpha");
assert!(!super::is_stable_standalone_release(
home.path(),
&alpha_managed
));
let local = standalone.join("local-main");
let local_managed = local.join("bin/codex");
std::fs::create_dir_all(local_managed.parent().expect("local bin parent"))
.expect("local build");
std::fs::write(&local_managed, b"local").expect("local bin");
std::fs::remove_file(&current).expect("remove current");
std::os::unix::fs::symlink(local, &current).expect("current local build");
assert!(!super::is_stable_standalone_release(
home.path(),
&local_managed
));
}
#[cfg(unix)]
#[tokio::test]
async fn older_managed_binary_does_not_claim_updater_support() {
let temp = tempfile::TempDir::new().expect("home");
let binary = temp.path().join("codex");
codex_utils_cargo_bin::write_executable(&binary, "#!/bin/sh\nexit 2\n").expect("older binary");
assert!(!super::supports_daemon_update_loop(&binary).await);
codex_utils_cargo_bin::write_executable(&binary, "#!/bin/sh\nexit 0\n").expect("newer binary");
assert!(super::supports_daemon_update_loop(&binary).await);
}

View File

@@ -0,0 +1,55 @@
use pretty_assertions::assert_eq;
use super::ExecutableIdentity;
use super::executable_identity;
use super::parse_codex_version;
#[test]
fn parses_codex_cli_version_output() {
assert_eq!(
parse_codex_version("codex 1.2.3\n").expect("version"),
"1.2.3"
);
}
#[test]
fn rejects_malformed_codex_cli_version_output() {
assert!(parse_codex_version("codex\n").is_err());
}
#[tokio::test]
async fn executable_identity_uses_path_and_binary_contents() {
let directory = tempfile::tempdir().expect("temporary directory");
let executable = directory.path().join("codex");
// Span multiple reads, including a partial final buffer, and preserve the
// digest stored by older clients that hashed the complete file in memory.
let mut bytes: Vec<u8> = (0..200_003).map(|index| (index % 251) as u8).collect();
for contents in [&bytes[..], &[][..]] {
std::fs::write(&executable, contents).expect("write executable");
assert_eq!(
executable_identity(&executable).await.expect("identity"),
ExecutableIdentity {
digest: *blake3::hash(contents).as_bytes(),
path_digest: Some(super::path_digest(
&std::fs::canonicalize(&executable).expect("canonical executable"),
)),
}
);
}
let copy = directory.path().join("codex-copy");
std::fs::copy(&executable, &copy).expect("copy executable");
let identity = executable_identity(&executable).await.expect("identity");
let copy_identity = executable_identity(&copy).await.expect("copy identity");
assert_ne!(identity, copy_identity);
assert!(identity.same_contents(&copy_identity));
std::fs::write(&executable, &bytes).expect("write executable");
let old = executable_identity(&executable).await.expect("identity");
bytes[100_000] ^= 1;
std::fs::write(&executable, bytes).expect("replace executable");
assert_ne!(
executable_identity(&executable)
.await
.expect("new identity"),
old
);
}

View File

@@ -0,0 +1,284 @@
//! Forwards manual requests to the updater and reports its install and restart result.
use anyhow::Context;
use anyhow::Result;
use codex_uds::UnixStream;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::time::Duration;
use tokio::time::sleep;
use tokio::time::timeout;
use super::InstallerHttp;
use super::Signal;
use super::UpdateLoopControl;
use super::UpdateTrigger;
use super::selected_release;
use super::update_once;
use crate::Daemon;
use crate::RestartIfRunningOutcome;
use crate::UpdateOutput;
use crate::UpdateStatus;
use crate::client;
use crate::managed_install::executable_identity;
use crate::managed_install::managed_codex_version;
pub(super) const MAX_RESPONSE_BYTES: u64 = 16 * 1024;
pub(crate) async fn request(daemon: &Daemon) -> Result<UpdateOutput> {
let socket_path = daemon.manual_update_socket_path();
let mut replacement_deadline = None;
'request: loop {
let mut connection = if let Some(deadline) = replacement_deadline {
loop {
if let Ok(connection) = UnixStream::connect(&socket_path).await {
break connection;
}
// A one-shot updater may exit after accepting the connection but
// before reading our request. Give a successor time to appear,
// then return to the normal startup path if none owns the PID.
if tokio::time::Instant::now() + Duration::from_secs(29) >= deadline {
let settings = daemon.load_settings().await?;
if !crate::backend::pid_update_loop_backend(daemon.backend_paths(&settings))
.is_starting_or_running()
.await?
{
replacement_deadline = None;
continue 'request;
}
}
anyhow::ensure!(
tokio::time::Instant::now() < deadline,
"timed out waiting for the replacement daemon updater"
);
sleep(Duration::from_millis(50)).await;
}
} else {
match UnixStream::connect(&socket_path).await {
Ok(connection) => connection,
Err(_) => {
let _operation_lock = daemon.acquire_operation_lock().await?;
if let Ok(connection) = UnixStream::connect(&socket_path).await {
connection
} else {
let settings = daemon.load_settings().await?;
if !supported(daemon)?
|| (daemon.running_backend_instance(&settings).await?.is_none()
&& client::probe(&daemon.socket_path).await.is_ok())
{
return unsupported(daemon).await;
}
crate::backend::pid_update_loop_backend(daemon.backend_paths(&settings))
.stop()
.await?;
let current_exe = std::env::current_exe()?;
let paths = daemon.backend_paths_with_bin(&settings, &current_exe);
let restore_release = if daemon.is_stable_standalone_release()? {
None
} else {
Some(selected_release(daemon)?.2)
};
let worker = crate::backend::PidBackend::new_update_loop(
paths.codex_bin,
paths.update_pid_file,
restore_release,
);
worker.start().await?;
let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
loop {
if let Ok(connection) = UnixStream::connect(&socket_path).await {
break connection;
}
anyhow::ensure!(
tokio::time::Instant::now() < deadline,
"timed out waiting for the daemon updater to accept a manual request"
);
sleep(Duration::from_millis(50)).await;
}
}
}
}
};
let mut response = Vec::new();
let transport = async {
#[cfg(windows)]
connection.ensure_non_elevated_peer()?;
connection.write_all(b"update\n").await?;
connection
.take(MAX_RESPONSE_BYTES)
.read_to_end(&mut response)
.await?;
Ok::<_, std::io::Error>(())
}
.await;
if response.is_empty() {
if transport
.as_ref()
.is_err_and(|err| err.kind() == std::io::ErrorKind::PermissionDenied)
{
transport?;
}
let deadline = replacement_deadline
.get_or_insert_with(|| tokio::time::Instant::now() + Duration::from_secs(30));
anyhow::ensure!(
tokio::time::Instant::now() < *deadline,
"daemon updater disconnected before responding"
);
sleep(Duration::from_millis(50)).await;
continue;
}
transport?;
let outcome: std::result::Result<UpdateOutput, String> =
serde_json::from_slice(&response).context("invalid response from daemon updater")?;
let outcome = outcome.map_err(anyhow::Error::msg)?;
if outcome.status == UpdateStatus::Unsupported && supported(daemon)? {
// A scheduled or older updater cannot authorize restoring a pin.
// Replace it under the writable operation lock, even with identical bytes.
let _operation_lock = daemon.acquire_operation_lock().await?;
let settings = daemon.load_settings().await?;
let worker = crate::backend::pid_update_loop_backend(daemon.backend_paths(&settings));
if !daemon.is_stable_standalone_release()? {
worker.stop().await?;
continue 'request;
}
}
return Ok(outcome);
}
}
pub(super) fn supported(daemon: &Daemon) -> Result<bool> {
if daemon.is_stable_standalone_release()? {
return Ok(true);
}
let Ok((root, release, _)) = selected_release(daemon) else {
return Ok(false);
};
let bin = daemon.current_managed_codex_bin()?;
Ok(std::fs::canonicalize(root.join("releases"))
.is_ok_and(|releases| release.parent() == Some(releases.as_path()))
&& bin.is_file()
&& std::fs::canonicalize(bin).is_ok_and(|bin| bin.starts_with(&release)))
}
const UNSUPPORTED_MESSAGE: &str =
"This command requires a daemon package selected from its managed releases directory.";
pub(super) async fn unsupported(daemon: &Daemon) -> Result<UpdateOutput> {
let managed_codex_path = daemon.current_managed_codex_bin()?;
Ok(UpdateOutput {
status: UpdateStatus::Unsupported,
installed_version: managed_codex_version(&managed_codex_path).await.ok(),
running_version: client::probe(&daemon.socket_path)
.await
.ok()
.map(|info| info.app_server_version),
managed_codex_path,
message: UNSUPPORTED_MESSAGE.to_string(),
})
}
pub(super) async fn handle_request(
mut connection: UnixStream,
http: &impl InstallerHttp,
daemon: &Daemon,
running_updater_identity: &crate::managed_install::ExecutableIdentity,
terminate: &mut Signal,
trigger: UpdateTrigger<'_>,
) -> Result<RequestDisposition> {
#[cfg(windows)]
if connection.ensure_non_elevated_peer().is_err() {
return Ok(RequestDisposition::Unchanged);
}
let mut request = [0; 7];
if !matches!(
timeout(Duration::from_secs(5), connection.read_exact(&mut request)).await,
Ok(Ok(_))
) || &request != b"update\n"
{
return Ok(RequestDisposition::Unchanged);
}
let result = run(http, daemon, running_updater_identity, terminate, trigger).await;
let interrupted = result.as_ref().err().is_some_and(|err| {
err.downcast_ref::<std::io::Error>()
.is_some_and(|err| err.kind() == std::io::ErrorKind::Interrupted)
});
let unsupported = result
.as_ref()
.is_ok_and(|output| output.status == UpdateStatus::Unsupported);
let outcome: std::result::Result<UpdateOutput, String> =
result.map_err(|err| format!("{err:#}"));
let sent = connection.write_all(&serde_json::to_vec(&outcome)?).await;
if interrupted {
return Ok(RequestDisposition::Stop);
}
sent?;
Ok(if unsupported {
RequestDisposition::Unchanged
} else {
RequestDisposition::Continue
})
}
pub(super) enum RequestDisposition {
Continue,
Unchanged,
Stop,
}
pub(super) async fn run(
http: &impl InstallerHttp,
daemon: &Daemon,
running_updater_identity: &crate::managed_install::ExecutableIdentity,
terminate: &mut Signal,
trigger: UpdateTrigger<'_>,
) -> Result<UpdateOutput> {
let settings = daemon.load_settings().await?;
let managed_running = daemon.running_backend_instance(&settings).await?.is_some();
if !(daemon.is_stable_standalone_release()?
|| matches!(trigger, UpdateTrigger::RestoreProduction(_)) && supported(daemon)?)
|| (!managed_running && client::probe(&daemon.socket_path).await.is_ok())
{
return unsupported(daemon).await;
}
let managed_codex_path = daemon.current_managed_codex_bin()?;
let (_, previous_release, _) = selected_release(daemon)?;
let previous_identity = executable_identity(&managed_codex_path).await?;
let (control, restart) =
update_once(http, daemon, running_updater_identity, terminate, trigger).await?;
if matches!(control, UpdateLoopControl::Stop) {
return Err(std::io::Error::from(std::io::ErrorKind::Interrupted).into());
}
let current_managed_codex_path = daemon.current_managed_codex_bin()?;
let installed_version = Some(managed_codex_version(&current_managed_codex_path).await?);
let updated = previous_release != selected_release(daemon)?.1
|| !previous_identity
.same_contents(&executable_identity(&current_managed_codex_path).await?);
let running_version = client::probe(&daemon.socket_path)
.await
.ok()
.map(|info| info.app_server_version);
let message = match restart {
Some(RestartIfRunningOutcome::Restarted) => {
"The managed installation is ready and the running daemon was restarted. Active or queued work may have been interrupted."
}
Some(RestartIfRunningOutcome::AlreadyCurrent) => {
"The managed installation and running daemon are already current; the daemon was left running."
}
Some(RestartIfRunningOutcome::NotRunning) => {
"The managed installation is ready; no daemon was running when the updater checked."
}
_ => unreachable!("successful manual update has a restart outcome"),
};
Ok(UpdateOutput {
status: if updated {
UpdateStatus::Updated
} else {
UpdateStatus::NoUpdate
},
managed_codex_path: current_managed_codex_path,
installed_version,
running_version,
message: message.to_string(),
})
}

View File

@@ -0,0 +1,193 @@
//! Moves a legacy daemon to its dedicated package only during an explicit update.
//! Preparation leaves the legacy selection intact; publishing current is the cutover.
use std::path::Path;
use anyhow::Context;
use anyhow::Result;
use futures::FutureExt;
use super::InstallerHttp;
use super::InstallerMode;
use super::fetch_installer_script;
use super::run_installer_script;
use super::selected_release;
use crate::Daemon;
use crate::UpdateOutput;
use crate::UpdateStatus;
use crate::backend;
use crate::client;
use crate::install_lock::acquire_install_lock;
use crate::managed_install;
pub(super) async fn run(http: &impl InstallerHttp, legacy: &Daemon) -> Result<UpdateOutput> {
let _operation_lock = legacy.acquire_operation_lock().await?;
let previous = selected_release(legacy)?;
anyhow::ensure!(
previous.0.ends_with("standalone") && super::manual_update::supported(legacy)?,
"daemon selection changed; retry the update"
);
let home = previous
.0
.parent()
.and_then(Path::parent)
.context("package root has no Codex home")?;
let root = home.join("packages/app-server-daemon");
let settings = legacy.load_settings().await?;
let running = legacy.running_backend_instance(&settings).await?;
if running.is_none() && client::probe(&legacy.socket_path).await.is_ok() {
return super::manual_update::unsupported(legacy).await;
}
#[cfg(unix)]
let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
let cancellation = async {
#[cfg(unix)]
tokio::select! {
_ = terminate.recv() => {},
_ = tokio::signal::ctrl_c() => {},
}
#[cfg(windows)]
let _ = tokio::signal::ctrl_c().await;
Some(())
};
let mut cancellation = std::pin::pin!(cancellation);
let script = fetch_installer_script(http).await?;
anyhow::ensure!(
script
.windows(b"CODEX_INSTALL_DEFER_SELECTION".len())
.any(|window| window == b"CODEX_INSTALL_DEFER_SELECTION"),
"the published installer does not support daemon migration yet; the legacy installation was left unchanged"
);
eprintln!("Preparing the daemon update in {}...", root.display());
#[cfg(unix)]
{
if matches!(
run_installer_script(
&script,
InstallerMode::Migration,
&root,
cancellation.as_mut()
)
.await?,
super::UpdateLoopControl::Stop
) {
return Err(std::io::Error::from(std::io::ErrorKind::Interrupted).into());
}
}
#[cfg(windows)]
tokio::select! {
result = run_installer_script(&script, InstallerMode::Migration, &root) => { result?; },
_ = &mut cancellation => return Err(std::io::Error::from(std::io::ErrorKind::Interrupted).into()),
}
let _install_lock = acquire_install_lock(&root).await?;
let pending = root.join(".migration-current");
let release = pending
.canonicalize()
.context("installer did not prepare a daemon package")?;
let name = release
.file_name()
.context("prepared release has no name")?;
anyhow::ensure!(
release.parent() == Some(root.join("releases").canonicalize()?.as_path())
&& std::fs::read_to_string(root.join("auto-update-version"))? == name.to_string_lossy(),
"installer did not prepare a latest-channel daemon package"
);
let entrypoint = if cfg!(windows) {
"bin/codex.exe"
} else {
"bin/codex"
};
let binary = release.join(entrypoint);
let version = managed_install::managed_codex_version(&binary).await?;
anyhow::ensure!(
name.to_string_lossy().starts_with(&format!("{version}-")),
"prepared daemon version does not match its release"
);
// An older production updater understands only the legacy package/PID paths.
anyhow::ensure!(
managed_install::supports_daemon_command(
&binary,
&["pid-update-loop", "--check-package-ownership"]
)
.await,
"the latest production release does not support daemon migration yet; the legacy daemon was left running"
);
#[cfg(windows)]
backend::windows::ensure_detached_launch(&binary)?;
anyhow::ensure!(
selected_release(legacy)? == previous,
"daemon selection changed; retry the update"
);
if cancellation.as_mut().now_or_never().is_some() {
return Err(std::io::Error::from(std::io::ErrorKind::Interrupted).into());
}
let cutover = async {
backend::pid_update_loop_backend(legacy.backend_paths(&settings))
.stop()
.await?;
anyhow::ensure!(
selected_release(legacy)? == previous,
"daemon selection changed; retry the update"
);
if let Some(running) = &running {
crate::thread_recovery::discard_pending(legacy)?;
running
.stop_with_grace(settings.shutdown_grace_seconds)
.await?;
}
std::fs::rename(&pending, root.join("current"))
.context("failed to select the new daemon package; retry the update")
}
.await;
if let Err(error) = cutover {
if let Err(restore_error) = async {
legacy
.current_installation()?
.ensure_managed_updater(&settings)
.await
}
.await
{
eprintln!(
"warning: failed to restore the legacy updater after migration failed: {restore_error:#}"
);
}
return Err(error);
}
let selected = Daemon {
pid_file: legacy.pid_file.with_file_name(crate::DAEMON_PID_FILE_NAME),
update_pid_file: legacy
.update_pid_file
.with_file_name(crate::DAEMON_UPDATE_PID_FILE_NAME),
managed_codex_bin: root.join("current").join(entrypoint),
..legacy.clone()
};
let running_version = if running.is_some() {
selected.start_managed_backend(&settings).await.context(
"daemon migrated but could not start; retry with `codex app-server daemon start`",
)?;
Some(
selected
.wait_until_ready()
.await
.context(
"daemon migrated but is not ready; retry with `codex app-server daemon start`",
)?
.app_server_version,
)
} else {
None
};
if let Err(error) = selected.ensure_managed_updater(&settings).await {
eprintln!("warning: daemon migrated but its updater could not start: {error:#}");
}
Ok(UpdateOutput {
status: UpdateStatus::Updated,
installed_version: Some(version),
running_version,
managed_codex_path: selected.managed_codex_bin,
message: "The daemon was updated and moved to its dedicated package. The legacy CLI package was left unchanged.".to_string(),
})
}

View File

@@ -0,0 +1,571 @@
//! Installs complete CLI packages after confirmation. Initial starts preserve
//! existing selections; explicit replacements migrate to dedicated packages and stay pinned.
//! WinGet sources are verified in their original layout before staging a canonical daemon package.
use std::collections::BTreeMap;
use std::path::Path;
use std::path::PathBuf;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use codex_install_context::CodexPackageManifest;
use codex_install_context::InstallContext;
use crate::Daemon;
use crate::install_lock::acquire_install_lock;
use crate::managed_install;
use crate::settings::DaemonSettings;
/// The complete CLI package offered for a daemon installation.
pub struct InstallRequest {
pub source: PathBuf,
pub version: String,
pub destination: PathBuf,
pub installed_version: Option<String>,
pub restart_required: bool,
}
/// Prepare a missing package while the caller holds the daemon operation lock.
pub(super) async fn prepare(daemon: &Daemon, settings: &DaemonSettings) -> Result<()> {
let source = InstallContext::current().package_layout.as_ref();
// Keep package replacement state out of the CLI dispatcher's async stack frame.
Box::pin(prepare_from_package(
daemon,
settings,
InstallMode::Missing,
source.map(|layout| layout.package_dir.as_path()),
&std::env::current_exe()?,
|_| Ok(true),
))
.await
.map(|_| ())
}
/// Select this CLI's complete package and pin it, restarting only a running daemon.
/// Returns None when the user cancels without changing the installation.
pub async fn update_from_cli(
confirm: impl FnOnce(&InstallRequest) -> Result<bool>,
) -> Result<Option<crate::UpdateOutput>> {
crate::ensure_supported_platform()?;
#[cfg(windows)]
crate::backend::windows::ensure_not_elevated()?;
let daemon = Daemon::from_environment()?;
let settings = daemon.load_settings().await?;
let source = InstallContext::current().package_layout.as_ref();
if !Box::pin(prepare_from_package(
&daemon,
&settings,
InstallMode::Replace,
source.map(|layout| layout.package_dir.as_path()),
&std::env::current_exe()?,
confirm,
))
.await?
{
return Ok(None);
}
let managed_codex_path = daemon.current_managed_codex_bin()?;
Ok(Some(crate::UpdateOutput {
status: crate::UpdateStatus::Updated,
installed_version: Some(managed_install::managed_codex_version(&managed_codex_path).await?),
running_version: crate::client::probe(&daemon.socket_path)
.await
.ok()
.map(|info| info.app_server_version),
managed_codex_path,
message: "The CLI package is selected and pinned. Run `codex app-server daemon update` to return to production updates.".to_string(),
}))
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum InstallMode {
Missing,
Replace,
}
async fn prepare_from_package(
daemon: &Daemon,
settings: &DaemonSettings,
mode: InstallMode,
source: Option<&Path>,
running_exe: &Path,
confirm: impl FnOnce(&InstallRequest) -> Result<bool>,
) -> Result<bool> {
let home = daemon
.settings_file
.parent()
.and_then(Path::parent)
.context("daemon settings path has no Codex home")?;
let previous_root = managed_install::package_root(home);
let root = home.join("packages/app-server-daemon");
anyhow::ensure!(
daemon.managed_codex_bin.starts_with(&previous_root),
"daemon package location changed; retry the command"
);
if mode == InstallMode::Missing {
if previous_root != root
|| daemon.running_backend_instance(settings).await?.is_some()
|| crate::client::probe(&daemon.socket_path).await.is_ok()
{
return Ok(true);
}
if !matches!(root.join("current").symlink_metadata(), Err(error) if error.kind() == std::io::ErrorKind::NotFound)
|| ["daemon.pid", "daemon.stderr.log", "daemon-updater.pid", "daemon-updater.stderr.log"]
.iter().any(|name| !matches!(home.join("app-server-daemon").join(name).symlink_metadata(), Err(error) if error.kind() == std::io::ErrorKind::NotFound))
{
daemon.ensure_managed_codex_bin()?;
return Ok(true);
}
} else {
anyhow::ensure!(
previous_root.join("current").symlink_metadata().is_ok(),
"no daemon package is selected; run `codex app-server daemon start` first"
);
}
std::fs::create_dir_all(&root)?;
anyhow::ensure!(
managed_install::package_root(home) == previous_root,
"daemon package location changed; retry the command"
);
let backend = daemon.running_backend_instance(settings).await?;
anyhow::ensure!(
backend.is_some() || crate::client::probe(&daemon.socket_path).await.is_err(),
"app server is running but is not managed by codex app-server daemon"
);
let selected = managed_install::managed_codex_bin(home);
let previous_release = previous_root.join("current").canonicalize().ok();
if mode == InstallMode::Missing {
if selected.is_file() {
return Ok(true);
}
anyhow::ensure!(
backend.is_none()
&& matches!(root.join("current").symlink_metadata(), Err(error) if error.kind() == std::io::ErrorKind::NotFound),
"the selected daemon package is incomplete; repair its installation before starting"
);
}
let source = source.context(
"this CLI has no complete local package; install a packaged Codex CLI or use the standalone installer",
)?;
anyhow::ensure!(
!root.canonicalize()?.starts_with(source.canonicalize()?),
"CODEX_HOME must be outside the source CLI package"
);
let manifest_bytes = std::fs::read(source.join("codex-package.json"))?;
let manifest: CodexPackageManifest = serde_json::from_slice(&manifest_bytes)?;
let version = manifest.version.to_string();
let target = platform_target()?;
let mut metadata: serde_json::Value = serde_json::from_slice(&manifest_bytes)?;
let entrypoint = if cfg!(windows) {
"bin/codex.exe"
} else {
"bin/codex"
};
let source_entrypoint = metadata["entrypoint"].as_str().unwrap_or_default();
let winget = cfg!(windows)
&& metadata["layoutVersion"] == 1
&& source_entrypoint == format!("codex-{target}.exe");
anyhow::ensure!(
metadata["target"] == target && (source_entrypoint == entrypoint || winget),
"the CLI package does not match this platform or executable"
);
validate_package(source, source_entrypoint)?;
// A local build may replace the executable while confirmation is pending.
let running_identity = managed_install::executable_identity(running_exe).await?;
if mode == InstallMode::Replace {
if !confirm(&InstallRequest {
source: source.to_path_buf(),
version: version.clone(),
destination: root.clone(),
installed_version: tokio::time::timeout(
std::time::Duration::from_secs(5),
managed_install::managed_codex_version(&selected),
)
.await
.ok()
.and_then(Result::ok),
restart_required: backend.is_some(),
})? {
return Ok(false);
}
} else {
daemon.diagnostic(format_args!(
"Installing daemon from CLI version {version} into {}...",
root.display()
));
}
// Confirmation must not block lifecycle commands. Recheck the approved
// selection and running state once this operation owns both locks.
let _operation_lock = if mode == InstallMode::Replace {
Some(daemon.acquire_operation_lock().await?)
} else {
None // Initial startup already holds the operation lock.
};
let current_settings = if mode == InstallMode::Replace {
Some(daemon.load_settings().await?)
} else {
None
};
let settings = current_settings.as_ref().unwrap_or(settings);
let _install_lock = acquire_install_lock(&root).await?;
anyhow::ensure!(
managed_install::package_root(home) == previous_root,
"daemon package location changed; retry the command"
);
if mode == InstallMode::Missing && managed_install::managed_codex_bin(home).is_file() {
return Ok(true);
}
anyhow::ensure!(
previous_root.join("current").canonicalize().ok() == previous_release,
"daemon selection changed while awaiting confirmation; retry the command"
);
let current_backend = daemon.running_backend_instance(settings).await?;
anyhow::ensure!(
current_backend.is_some() == backend.is_some(),
"daemon running state changed while awaiting confirmation; retry the command"
);
let backend = current_backend;
let stable = stable_version(&version).is_some();
let releases = root.join("releases");
std::fs::create_dir_all(&releases)?;
let stage = tempfile::Builder::new()
.prefix(".staging.")
.tempdir_in(&releases)?;
let mut staged_digests = BTreeMap::new();
let digest = package_tree(source, Some(stage.path()), &mut staged_digests)?;
let staged_exe = if cfg!(target_os = "macos") && stage.path().join("CodexCLI.app").is_dir() {
Path::new("CodexCLI.app/Contents/MacOS/codex")
} else {
Path::new(source_entrypoint)
};
anyhow::ensure!(
package_tree(source, /*destination*/ None, &mut BTreeMap::new())? == digest
&& std::fs::read(stage.path().join("codex-package.json"))? == manifest_bytes
&& staged_digests.get(staged_exe).map(blake3::Hash::as_bytes)
== Some(&running_identity.digest),
"the CLI package changed while preparing the daemon or differs from the running executable"
);
// Reverse the WinGet archive's root filenames only after verifying the copied
// source. Hash the final tree for reuse, since it now differs from the source.
let digest = if winget {
std::fs::create_dir_all(stage.path().join("bin"))?;
#[cfg(windows)]
for (from, to) in [
(staged_exe, Path::new(entrypoint)),
(
Path::new("codex-code-mode-host.exe"),
Path::new("bin/codex-code-mode-host.exe"),
),
] {
windows::publish_release(&stage.path().join(from), &stage.path().join(to)).await?;
if let Some(digest) = staged_digests.remove(from) {
staged_digests.insert(to.to_path_buf(), digest);
}
}
let voice_path = stage.path().join("codex-resources/voice/manifest.json");
if voice_path.try_exists()? {
let mut voice: serde_json::Value =
serde_json::from_slice(&std::fs::read(&voice_path)?)?;
let checksums = voice["sha256"]
.as_object_mut()
.context("invalid WinGet voice manifest checksums")?;
let checksum = checksums
.remove(source_entrypoint)
.context("WinGet voice manifest is missing the CLI checksum")?;
checksums.insert(entrypoint.to_string(), checksum);
let bytes = serde_json::to_vec_pretty(&voice)?;
std::fs::write(voice_path, &bytes)?;
staged_digests.insert(
PathBuf::from("codex-resources/voice/manifest.json"),
blake3::hash(&bytes),
);
}
metadata["entrypoint"] = entrypoint.into();
let bytes = serde_json::to_vec_pretty(&metadata)?;
std::fs::write(stage.path().join("codex-package.json"), &bytes)?;
staged_digests.insert(PathBuf::from("codex-package.json"), blake3::hash(&bytes));
package_tree(stage.path(), /*destination*/ None, &mut staged_digests)?
} else {
digest
};
validate_package(stage.path(), entrypoint)?;
let binary_version =
managed_install::managed_codex_version(&stage.path().join(entrypoint)).await?;
anyhow::ensure!(
!stable || version == binary_version,
"the CLI package version does not match its executable"
);
let name = if stable && mode == InstallMode::Missing {
format!("{version}-{target}")
} else {
format!("local-{digest}-{target}")
};
let release = releases.join(&name);
if release.try_exists()? {
anyhow::ensure!(
!release.symlink_metadata()?.file_type().is_symlink()
&& package_tree(&release, /*destination*/ None, &mut BTreeMap::new())? == digest,
"an existing daemon release has different contents; refusing to overwrite it"
);
} else {
#[cfg(unix)]
if !stage.path().join("codex").exists() {
std::os::unix::fs::symlink("bin/codex", stage.path().join("codex"))?;
}
#[cfg(windows)]
windows::publish_release(stage.path(), &release).await?;
#[cfg(not(windows))]
std::fs::rename(stage.path(), &release)?;
}
let release = release.canonicalize()?;
let standalone = home.join("packages/standalone");
let canonical_source = source.canonicalize()?;
let follows_latest = mode == InstallMode::Missing
&& stable
&& (standalone.join("current").canonicalize().ok().as_deref()
!= Some(canonical_source.as_path())
|| std::fs::read_to_string(standalone.join("auto-update-version"))
.ok()
.as_deref()
== canonical_source.file_name().and_then(|name| name.to_str()));
anyhow::ensure!(
managed_install::package_root(home) == previous_root
&& (backend.is_some() || crate::client::probe(&daemon.socket_path).await.is_err()),
"daemon package location or socket ownership changed while preparing its package; retry the command"
);
#[cfg(windows)]
if backend.is_some() {
crate::backend::windows::ensure_detached_launch(&release.join(entrypoint))?;
}
#[cfg(windows)]
windows::validate_selection(&root)?;
if mode == InstallMode::Replace {
let stopped = async {
crate::backend::pid_update_loop_backend(daemon.backend_paths(settings))
.stop()
.await?;
anyhow::ensure!(
managed_install::package_root(home) == previous_root
&& previous_root.join("current").canonicalize().ok() == previous_release,
"daemon selection changed while preparing its package; retry the command"
);
if let Some(backend) = &backend {
if let Err(error) = crate::thread_recovery::discard_pending(daemon) {
eprintln!(
"warning: failed to clear stale daemon recovery before replacement: {error}"
);
}
backend
.stop_with_grace(settings.shutdown_grace_seconds)
.await?;
}
Ok::<(), anyhow::Error>(())
}
.await;
if let Err(error) = stopped {
if let Err(restore_error) = async {
daemon
.current_installation()?
.ensure_managed_updater(settings)
.await
}
.await
{
eprintln!(
"warning: failed to restore the daemon updater after replacement failed: {restore_error:#}"
);
}
return Err(error);
}
}
let marker = root.join("auto-update-version");
if follows_latest {
let temporary = tempfile::NamedTempFile::new_in(&root)?;
std::fs::write(temporary.path(), &name)?;
temporary.persist(marker)?;
} else if marker.exists() {
std::fs::remove_file(marker)?;
}
if previous_release.as_deref() != Some(release.as_path()) {
#[cfg(unix)]
{
let temporary = tempfile::TempDir::new_in(&root)?;
let link = temporary.path().join("current");
std::os::unix::fs::symlink(&release, &link)?;
std::fs::rename(link, root.join("current"))?;
}
#[cfg(windows)]
windows::select_release(&root, &release)?;
if let Err(error) =
crate::release_pruning::record_selection(&root, previous_release.as_deref())
{
tracing::warn!(%error, "could not record daemon selection for pruning");
}
}
if backend.is_some() {
let selected = Daemon {
pid_file: daemon.pid_file.with_file_name(crate::DAEMON_PID_FILE_NAME),
update_pid_file: daemon
.update_pid_file
.with_file_name(crate::DAEMON_UPDATE_PID_FILE_NAME),
managed_codex_bin: root.join("current").join(entrypoint),
..daemon.clone()
};
selected.start_managed_backend(settings).await.context(
"daemon package selected but could not start; retry with `codex app-server daemon start`",
)?;
selected.wait_until_ready().await?;
}
if let Err(error) = crate::release_pruning::prune(daemon, &root, settings).await {
tracing::debug!(%error, "skipped daemon release pruning");
}
Ok(true)
}
/// Hash the complete tree and optionally copy those same bytes. Relative file
/// links are materialized; escaping links and directory links are rejected.
/// Only reuse digests for a private staging directory; source and release
/// validation must pass a fresh map.
fn package_tree(
root: &Path,
destination: Option<&Path>,
file_digests: &mut BTreeMap<PathBuf, blake3::Hash>,
) -> Result<String> {
let canonical_root = root.canonicalize()?;
let mut hasher = blake3::Hasher::new();
let mut paths = vec![root.to_path_buf()];
while let Some(path) = paths.pop() {
let relative = path.strip_prefix(root)?;
// The Unix installer adds this alias outside the package layout.
if cfg!(unix)
&& relative == Path::new("codex")
&& std::fs::read_link(&path).ok().as_deref() == Some(Path::new("bin/codex"))
{
continue;
}
anyhow::ensure!(
path.canonicalize()?.starts_with(&canonical_root),
"package link escapes its root"
);
let metadata = path.metadata()?;
hasher.update(relative.as_os_str().as_encoded_bytes());
hasher.update(&[0]);
if metadata.is_dir() {
anyhow::ensure!(
!path.symlink_metadata()?.file_type().is_symlink(),
"package contains a directory link"
);
hasher.update(b"directory");
if let Some(destination) = destination
&& !relative.as_os_str().is_empty()
{
std::fs::create_dir(destination.join(relative))?;
}
let mut entries = std::fs::read_dir(&path)?
.map(|entry| entry.map(|entry| entry.path()))
.collect::<std::io::Result<Vec<_>>>()?;
entries.sort();
paths.extend(entries);
} else {
anyhow::ensure!(metadata.is_file(), "package contains an unsupported file");
let digest = if let Some(digest) = file_digests.get(relative)
&& destination.is_none()
{
*digest
} else {
let bytes = std::fs::read(&path)?;
let digest = blake3::hash(&bytes);
if let Some(destination) = destination {
let target = destination.join(relative);
std::fs::write(&target, bytes)?;
std::fs::set_permissions(target, metadata.permissions())?;
}
file_digests.insert(relative.to_path_buf(), digest);
digest
};
hasher.update(b"file");
hasher.update(digest.as_bytes());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
hasher.update(&(metadata.permissions().mode() & 0o777).to_le_bytes());
}
}
}
Ok(hasher.finalize().to_hex().to_string())
}
fn stable_version(value: &str) -> Option<semver::Version> {
let version = semver::Version::parse(value).ok()?;
(version.pre.is_empty()
&& version.build.is_empty()
&& (version.major, version.minor, version.patch) != (0, 0, 0))
.then_some(version)
}
fn validate_package(root: &Path, entrypoint: &str) -> Result<()> {
let code_mode_host = Path::new(entrypoint).with_file_name(if cfg!(windows) {
"codex-code-mode-host.exe"
} else {
"codex-code-mode-host"
});
let code_mode_host = code_mode_host.to_string_lossy();
let mut names = vec![
"codex-package.json",
entrypoint,
code_mode_host.as_ref(),
if cfg!(windows) {
"codex-path/rg.exe"
} else {
"codex-path/rg"
},
];
if cfg!(windows) {
names.extend([
"codex-resources/codex-command-runner.exe",
"codex-resources/codex-windows-sandbox-setup.exe",
]);
} else if cfg!(target_os = "linux") {
names.push("codex-resources/bwrap");
}
for name in names {
if !root.join(name).is_file() {
return Err(anyhow!(
"local Codex package is missing {name}; reinstall the CLI or use the standalone installer"
));
}
#[cfg(unix)]
if name != "codex-package.json" {
use std::os::unix::fs::PermissionsExt;
if std::fs::metadata(root.join(name))?.permissions().mode() & 0o111 == 0 {
return Err(anyhow!(
"local Codex package file {name} is not executable; reinstall the CLI or use the standalone installer"
));
}
}
}
Ok(())
}
fn platform_target() -> Result<&'static str> {
match (std::env::consts::OS, std::env::consts::ARCH) {
("macos", "aarch64") => Ok("aarch64-apple-darwin"),
("macos", "x86_64") => Ok("x86_64-apple-darwin"),
("linux", "aarch64") if cfg!(target_env = "gnu") => Ok("aarch64-unknown-linux-gnu"),
("linux", "aarch64") => Ok("aarch64-unknown-linux-musl"),
("linux", "x86_64") if cfg!(target_env = "gnu") => Ok("x86_64-unknown-linux-gnu"),
("linux", "x86_64") => Ok("x86_64-unknown-linux-musl"),
("windows", "aarch64") => Ok("aarch64-pc-windows-msvc"),
("windows", "x86_64") => Ok("x86_64-pc-windows-msvc"),
(os, arch) => Err(anyhow!("unsupported packaged daemon platform {os}/{arch}")),
}
}
#[cfg(windows)]
#[path = "prepare_install_windows.rs"]
mod windows;
#[cfg(test)]
#[path = "prepare_install_tests.rs"]
mod tests;

View File

@@ -0,0 +1,477 @@
//! Covers complete-package staging, conservative selection, and legacy preservation.
#![cfg(unix)]
use std::collections::BTreeMap;
use super::InstallMode;
use super::prepare_from_package;
use super::validate_package;
use crate::release_pruning;
use crate::settings::DaemonSettings;
use pretty_assertions::assert_eq;
use std::path::Path;
use std::path::PathBuf;
fn daemon(home: &std::path::Path) -> crate::Daemon {
let state = home.join("app-server-daemon");
crate::Daemon {
log_diagnostics: false,
socket_path: state.join("app-server.sock"),
pid_file: state.join("app-server.pid"),
update_pid_file: state.join("app-server-updater.pid"),
operation_lock_file: state.join("daemon.lock"),
settings_file: state.join("settings.json"),
managed_codex_bin: crate::managed_install::managed_codex_bin(home),
}
}
fn package(root: &Path, version: &str) -> PathBuf {
let target = super::platform_target().expect("target");
for dir in ["bin", "codex-path", "codex-resources/nested"] {
std::fs::create_dir_all(root.join(dir)).expect("package directory");
}
let bin = root.join("bin/codex");
codex_utils_cargo_bin::write_executable(&bin, &format!("#!/bin/sh\necho 'codex {version}'\n"))
.expect("codex executable");
for file in ["bin/codex-code-mode-host", "codex-path/rg"] {
codex_utils_cargo_bin::write_executable(&root.join(file), "runtime")
.expect("executable helper");
}
std::fs::write(root.join("codex-resources/nested/runtime"), b"runtime").expect("package file");
if cfg!(target_os = "linux") {
codex_utils_cargo_bin::write_executable(&root.join("codex-resources/bwrap"), "runtime")
.expect("executable bwrap");
}
std::fs::write(
root.join("codex-package.json"),
serde_json::json!({
"version": version, "target": target, "entrypoint": "bin/codex"
})
.to_string(),
)
.expect("manifest");
bin
}
#[tokio::test]
async fn seeds_full_package() {
let temp = tempfile::TempDir::new().expect("temp");
let home = temp.path().join("home");
let daemon = daemon(&home);
let settings = DaemonSettings::default();
let old = temp.path().join("old");
let old_bin = package(&old, "0.152.0");
prepare_from_package(
&daemon,
&settings,
InstallMode::Missing,
Some(&old),
&old_bin,
|_| Ok(true),
)
.await
.expect("seed");
let standalone = home.join("packages/app-server-daemon");
let selected = std::fs::canonicalize(standalone.join("current")).expect("selected");
assert_eq!(
std::fs::read(selected.join("codex-resources/nested/runtime")).expect("runtime"),
b"runtime"
);
assert_eq!(
std::fs::read_to_string(standalone.join("auto-update-version")).expect("marker"),
selected.file_name().expect("name").to_string_lossy()
);
assert!(validate_package(&selected, "bin/codex").is_ok());
let root = standalone;
let releases = root.join("releases").canonicalize().unwrap();
let target = super::platform_target().unwrap();
// Reinstall the seed's exact package after partially deleting an older copy.
let original = old;
let digest =
super::package_tree(&original, /*destination*/ None, &mut BTreeMap::new()).unwrap();
let old = releases.join(format!("local-{digest}-{target}"));
let previous = releases.join(format!("0.151.0-{target}"));
package(&old, "0.152.0");
// Match the alias present in actual Unix downloads.
std::os::unix::fs::symlink("bin/codex", old.join("codex")).unwrap();
package(&previous, "0.151.0");
let outside = temp.path().join("outside");
package(&outside, "0.149.0");
let linked = releases.join(format!("0.148.0-{target}"));
package(&linked, "0.148.0");
std::os::unix::fs::symlink(&outside, linked.join("codex-resources/other")).unwrap();
let _operation_lock = daemon.acquire_operation_lock().await.unwrap();
let _install_lock = crate::install_lock::acquire_install_lock(&root)
.await
.unwrap();
// An older selector can move away and back without updating history.
// The name alone must not authorize deletion.
std::fs::remove_file(root.join("current")).unwrap();
std::os::unix::fs::symlink(&previous, root.join("current")).unwrap();
std::fs::remove_file(root.join("current")).unwrap();
std::os::unix::fs::symlink(&selected, root.join("current")).unwrap();
let _ = release_pruning::prune(&daemon, &root, &settings).await;
assert!(old.join("codex-resources/nested/runtime").is_file());
release_pruning::record_selection(&root, Some(&previous)).unwrap();
// Root can delete read-only files. Other users simulate a real partial failure.
use std::os::unix::fs::PermissionsExt;
let read_only = old.join("codex-resources/nested");
std::fs::set_permissions(&read_only, std::fs::Permissions::from_mode(0o555)).unwrap();
let result = release_pruning::prune(&daemon, &root, &settings).await;
assert!(!old.exists(), "release was not retired: {result:#?}");
for retained in [&selected, &previous, &outside, &linked] {
assert!(retained.join("codex-resources/nested/runtime").is_file());
}
// Reinstall after a partial deletion, and verify that leftovers are not retried.
drop(_install_lock);
drop(_operation_lock);
if unsafe { libc::geteuid() } != 0 {
let leftover = std::fs::read_dir(&releases)
.unwrap()
.map(Result::unwrap)
.find(|entry| entry.file_name().to_string_lossy().starts_with(".retired."))
.unwrap()
.path()
.join("release/codex-resources/nested");
std::fs::set_permissions(&leftover, std::fs::Permissions::from_mode(0o755)).unwrap();
prepare_from_package(
&daemon,
&settings,
InstallMode::Replace,
Some(&original),
&old_bin,
|_| Ok(true),
)
.await
.unwrap();
assert_eq!(root.join("current").canonicalize().unwrap(), old);
// Subsequent pruning does not retry a retirement, even when deletable now.
assert_eq!(std::fs::read(leftover.join("runtime")).unwrap(), b"runtime");
}
}
#[tokio::test]
async fn incomplete_source_fails_without_selecting_it() {
let temp = tempfile::TempDir::new().expect("temp");
let source = temp.path().join("package");
let bin = package(&source, "0.152.0");
std::fs::remove_file(source.join("bin/codex-code-mode-host")).expect("remove helper");
let home = temp.path().join("home");
let error = prepare_from_package(
&daemon(&home),
&DaemonSettings::default(),
InstallMode::Missing,
Some(&source),
&bin,
|_| Ok(true),
)
.await
.expect_err("incomplete package");
assert!(error.to_string().contains("bin/codex-code-mode-host"));
assert!(!home.join("packages/app-server-daemon/current").exists());
}
#[cfg(target_os = "macos")]
#[tokio::test]
async fn provisioned_macos_bundle_seeds_from_its_running_executable() {
let temp = tempfile::TempDir::new().expect("temp");
let source = temp.path().join("package");
let launcher = package(&source, "0.1.0-internal-test.202609091200.1");
codex_utils_cargo_bin::write_executable(&launcher, "#!/bin/sh\necho codex 0.0.0\n")
.expect("launcher");
let bundle = source.join("CodexCLI.app/Contents/MacOS/codex");
std::fs::create_dir_all(bundle.parent().expect("bundle parent")).expect("bundle dir");
std::fs::write(&bundle, b"provisioned executable").expect("bundle executable");
let home = temp.path().join("home");
prepare_from_package(
&daemon(&home),
&DaemonSettings::default(),
InstallMode::Missing,
Some(&source),
&bundle,
|_| Ok(true),
)
.await
.expect("seed provisioned bundle");
let selected = std::fs::canonicalize(home.join("packages/app-server-daemon/current"))
.expect("selected release");
assert_eq!(
std::fs::read(selected.join("CodexCLI.app/Contents/MacOS/codex"))
.expect("bundled executable"),
b"provisioned executable"
);
assert!(
!home
.join("packages/app-server-daemon/auto-update-version")
.exists()
);
}
#[tokio::test]
async fn legacy_selection_is_not_migrated_or_refreshed() {
let temp = tempfile::TempDir::new().unwrap();
let home = temp.path().join("home");
let legacy = home.join("packages/standalone");
let bin = package(&legacy.join("releases/old"), "0.150.0");
std::os::unix::fs::symlink("releases/old", legacy.join("current")).unwrap();
let state = home.join("app-server-daemon");
std::fs::create_dir(&state).unwrap();
std::fs::write(state.join("app-server.stderr.log"), b"").unwrap();
let source = temp.path().join("new");
let new_bin = package(&source, "0.160.0");
prepare_from_package(
&daemon(&home),
&DaemonSettings::default(),
InstallMode::Missing,
Some(&source),
&new_bin,
|_| Ok(true),
)
.await
.unwrap();
assert_eq!(
crate::managed_install::managed_codex_bin(&home)
.canonicalize()
.unwrap(),
bin.canonicalize().unwrap()
);
assert!(!home.join("packages/app-server-daemon").exists());
}
#[tokio::test]
async fn standalone_seed_preserves_explicit_pin_or_latest_channel() {
for follows_latest in [false, true] {
let temp = tempfile::TempDir::new().unwrap();
let home = temp.path().join("home");
let standalone = home.join("packages/standalone");
let source = standalone.join("releases/0.152.0-local-target");
let bin = package(&source, "0.152.0");
std::os::unix::fs::symlink(&source, standalone.join("current")).unwrap();
if follows_latest {
std::fs::write(
standalone.join("auto-update-version"),
"0.152.0-local-target",
)
.unwrap();
}
prepare_from_package(
&daemon(&home),
&DaemonSettings::default(),
InstallMode::Missing,
Some(&source),
&bin,
|_| Ok(true),
)
.await
.unwrap();
let root = home.join("packages/app-server-daemon");
let selected = root.join("current").canonicalize().unwrap();
assert_eq!(
std::fs::read_to_string(root.join("auto-update-version")).ok(),
follows_latest.then(|| selected.file_name().unwrap().to_string_lossy().into_owned())
);
}
}
#[tokio::test]
async fn explicit_selection_requires_unchanged_cli_and_pins_all_versions() {
for legacy in [false, true] {
let temp = tempfile::TempDir::new().unwrap();
let home = temp.path().join("home");
let source = temp.path().join("source");
let bin = package(&source, "0.152.0");
let settings = DaemonSettings::default();
let initial = daemon(&home);
prepare_from_package(
&initial,
&settings,
InstallMode::Missing,
Some(&source),
&bin,
|_| Ok(true),
)
.await
.unwrap();
if legacy {
std::fs::rename(
home.join("packages/app-server-daemon"),
home.join("packages/standalone"),
)
.unwrap();
let root = home.join("packages/standalone");
let name = std::fs::read_to_string(root.join("auto-update-version")).unwrap();
std::fs::remove_file(root.join("current")).unwrap();
std::os::unix::fs::symlink(root.join("releases").join(name), root.join("current"))
.unwrap();
let state = home.join("app-server-daemon");
std::fs::create_dir_all(&state).unwrap();
std::fs::write(state.join("app-server.stderr.log"), b"").unwrap();
}
let initial_root = crate::managed_install::package_root(&home);
let legacy_release = initial_root.join("current").canonicalize().unwrap();
let legacy_marker = std::fs::read(initial_root.join("auto-update-version")).unwrap();
let error = prepare_from_package(
&daemon(&home),
&settings,
InstallMode::Replace,
Some(&source),
&bin,
|_| {
let mut rebuilt = std::fs::read(&bin)?;
rebuilt.extend_from_slice(b"# rebuilt during confirmation\n");
std::fs::write(&bin, rebuilt)?;
Ok(true)
},
)
.await
.expect_err("reject a CLI rebuilt during confirmation");
assert!(
error
.to_string()
.contains("differs from the running executable")
);
assert_eq!(
initial_root.join("current").canonicalize().unwrap(),
legacy_release
);
assert_eq!(
std::fs::read(initial_root.join("auto-update-version")).unwrap(),
legacy_marker
);
let root = home.join("packages/app-server-daemon");
let mut previous = legacy_release.clone();
for version in [
"0.153.0",
"0.151.0",
"0.151.0",
"0.154.0-alpha.1",
"0.0.0",
"0.0.0",
] {
let daemon = daemon(&home);
let previous_root = crate::managed_install::package_root(&home);
package(&source, version);
std::fs::write(
source.join("codex-resources/nested/runtime"),
previous.to_string_lossy().as_bytes(),
)
.unwrap();
let before = std::fs::read(previous.join("bin/codex")).unwrap();
assert!(
!prepare_from_package(
&daemon,
&settings,
InstallMode::Replace,
Some(&source),
&bin,
|request| {
assert_eq!(request.destination, root);
Ok(false)
}
)
.await
.unwrap()
);
assert_eq!(crate::managed_install::package_root(&home), previous_root);
assert_eq!(
previous_root.join("current").canonicalize().unwrap(),
previous
);
prepare_from_package(
&daemon,
&settings,
InstallMode::Replace,
Some(&source),
&bin,
|_| Ok(true),
)
.await
.unwrap();
let selected = root.join("current").canonicalize().unwrap();
assert_eq!(crate::managed_install::package_root(&home), root);
if legacy {
assert_eq!(
initial_root.join("current").canonicalize().unwrap(),
legacy_release
);
assert_eq!(
std::fs::read(initial_root.join("auto-update-version")).unwrap(),
legacy_marker
);
}
assert_ne!(selected, previous);
assert_eq!(
std::fs::read(selected.join("bin/codex")).unwrap(),
std::fs::read(&bin).unwrap()
);
assert_eq!(std::fs::read(previous.join("bin/codex")).unwrap(), before);
// Different resources, even at the same version: retain last two selections.
for entry in std::fs::read_dir(root.join("releases")).unwrap() {
let path = entry.unwrap().path().canonicalize().unwrap();
assert!(
[&selected, &previous].contains(&&path),
"unexpected release: {path:?}"
);
}
assert!(!root.join("auto-update-version").exists());
assert!(daemon.running_backend(&settings).await.unwrap().is_none());
previous = selected;
}
// Reusing a release must still validate its current contents from disk.
std::fs::write(previous.join("codex-package.json"), b"corrupt manifest").unwrap();
let error = prepare_from_package(
&daemon(&home),
&settings,
InstallMode::Replace,
Some(&source),
&bin,
|_| Ok(true),
)
.await
.unwrap_err();
assert!(
error
.to_string()
.contains("existing daemon release has different contents")
);
assert_eq!(root.join("current").canonicalize().unwrap(), previous);
}
}
#[tokio::test]
async fn broken_selection_is_not_a_missing_installation() {
let temp = tempfile::TempDir::new().unwrap();
let home = temp.path().join("home");
let source = temp.path().join("source");
let bin = package(&source, "0.152.0");
let daemon = daemon(&home);
let current = home.join("packages/app-server-daemon/current");
std::fs::create_dir_all(current.parent().unwrap()).unwrap();
std::os::unix::fs::symlink("missing-release", &current).unwrap();
let error = prepare_from_package(
&daemon,
&DaemonSettings::default(),
InstallMode::Missing,
Some(&source),
&bin,
|_| panic!("broken installation must not request replacement"),
)
.await
.unwrap_err();
assert!(
error
.to_string()
.contains("repair the existing installation")
);
let start_error = daemon.start(&BTreeMap::new()).await.unwrap_err();
assert_eq!(start_error.failure_reason(), "install");
assert_eq!(
std::fs::read_link(current).unwrap(),
PathBuf::from("missing-release")
);
}

View File

@@ -0,0 +1,212 @@
//! Publishes and selects Windows managed releases despite transient filesystem contention.
use std::os::windows::ffi::OsStrExt;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use std::os::windows::process::CommandExt;
use std::path::Path;
use std::process::Command;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_DELETE;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
use windows_sys::Win32::System::IO::DeviceIoControl;
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
const PUBLISH_RELEASE_RETRY_INTERVAL: Duration = Duration::from_millis(50);
const PUBLISH_RELEASE_RETRY_LIMIT: usize = 100;
pub(super) async fn publish_release(stage: &Path, release: &Path) -> Result<()> {
let mut retries = 0;
loop {
match std::fs::rename(stage, release) {
Ok(()) => return Ok(()),
// Executable scanners can briefly hold newly staged files without delete sharing.
Err(error)
if retries < PUBLISH_RELEASE_RETRY_LIMIT
&& (error.kind() == std::io::ErrorKind::PermissionDenied
|| error.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32)) =>
{
retries += 1;
tokio::time::sleep(PUBLISH_RELEASE_RETRY_INTERVAL).await;
}
Err(error) => {
return Err(error).with_context(|| {
format!(
"failed to publish managed daemon release from {} to {}",
stage.display(),
release.display()
)
});
}
}
}
}
pub(super) fn select_release(root: &Path, release: &Path) -> Result<()> {
select_release_with(root, release, retarget_junction)
}
fn select_release_with(
root: &Path,
release: &Path,
retarget: impl FnOnce(&Path, &Path) -> Result<()>,
) -> Result<()> {
let release = release.canonicalize()?;
let current = root.join("current");
if current.symlink_metadata().is_err() {
let temporary = tempfile::TempDir::new_in(root)?;
let junction = temporary.path().join("current");
std::fs::create_dir(&junction)?;
return match retarget(&junction, &release) {
Ok(()) => Ok(std::fs::rename(junction, current)?),
Err(error) if is_permission_denied(&error) => install_junction(root, &release)
.with_context(|| format!("failed to create managed daemon junction after native creation was denied: {error:#}")),
Err(error) => Err(error),
};
}
validate_selection(root)?;
match retarget(&current, &release) {
Ok(()) => Ok(()),
Err(error) if is_permission_denied(&error) => {
install_junction(root, &release).with_context(|| format!("failed to replace managed daemon junction after retargeting was denied: {error:#}"))
}
Err(error) => Err(error),
}
}
fn is_permission_denied(error: &anyhow::Error) -> bool {
error
.downcast_ref::<std::io::Error>()
.is_some_and(|error| error.kind() == std::io::ErrorKind::PermissionDenied)
}
fn install_junction(root: &Path, release: &Path) -> Result<()> {
let temporary = tempfile::TempDir::new_in(root)?;
let junction = temporary.path().join("current");
let current = root.join("current");
let replacing = current.symlink_metadata().is_ok();
if replacing {
validate_selection(root)?;
}
// Some Windows policies deny in-process reparse-point mutation while allowing the system
// junction creator. Pass paths through the environment so cmd metacharacters stay quoted.
let system_root = std::env::var_os("SystemRoot").context("SystemRoot is not set")?;
let command_shell = Path::new(&system_root).join("System32").join("cmd.exe");
anyhow::ensure!(
command_shell.is_absolute(),
"SystemRoot must be an absolute path"
);
let output = Command::new(command_shell)
.env("CODEX_DAEMON_JUNCTION_LINK", &junction)
.env("CODEX_DAEMON_JUNCTION_TARGET", release)
.args(["/d", "/s", "/e:on", "/v:off", "/c"])
.raw_arg(r#""mklink /J "%CODEX_DAEMON_JUNCTION_LINK%" "%CODEX_DAEMON_JUNCTION_TARGET%"""#)
.creation_flags(CREATE_NO_WINDOW)
.output()
.context("failed to run cmd.exe to create managed daemon junction")?;
anyhow::ensure!(
output.status.success(),
"cmd.exe could not create managed daemon junction (status {}): stdout: {}; stderr: {}",
output.status,
String::from_utf8_lossy(&output.stdout).trim(),
String::from_utf8_lossy(&output.stderr).trim()
);
if !replacing {
std::fs::rename(junction, current)?;
return Ok(());
}
let previous = temporary.path().join("previous");
std::fs::rename(&current, &previous)?;
if let Err(error) = std::fs::rename(&junction, &current) {
if let Err(restore_error) = std::fs::rename(&previous, &current) {
let preserved = temporary.keep();
anyhow::bail!(
"failed to replace managed daemon junction: {error}; also failed to restore the previous junction from {}: {restore_error}",
preserved.display()
);
}
return Err(error).context("failed to replace managed daemon junction");
}
if let Err(error) = std::fs::remove_dir(previous) {
tracing::warn!(
%error,
"failed to remove previous managed daemon junction"
);
}
Ok(())
}
fn retarget_junction(current: &Path, release: &Path) -> Result<()> {
// Use the same mount-point reparse operation as the standalone installer.
// Retargeting in place keeps current available to concurrent readers.
const FSCTL_SET_REPARSE_POINT: u32 = 0x0009_00a4;
const IO_REPARSE_TAG_MOUNT_POINT: u32 = 0xa000_0003;
const GENERIC_WRITE: u32 = 0x4000_0000;
let release: Vec<u16> = release.as_os_str().encode_wide().collect();
let prefix: Vec<u16> = r"\\?\".encode_utf16().collect();
let release = release.strip_prefix(prefix.as_slice()).unwrap_or(&release);
let substitute: Vec<u8> = r"\??\"
.encode_utf16()
.chain(release.iter().copied())
.flat_map(u16::to_le_bytes)
.collect();
u16::try_from(substitute.len() + 20).context("managed release path is too long")?;
let length = substitute.len() as u16;
// REPARSE_DATA_BUFFER: an 8-byte header, then four u16 byte offsets/lengths
// for substitute and print names. The UTF-16 path buffer starts at byte 16;
// both names have a trailing NUL, and the print name is empty.
let mut data = vec![0; substitute.len() + 20];
data[0..4].copy_from_slice(&IO_REPARSE_TAG_MOUNT_POINT.to_le_bytes());
data[4..6].copy_from_slice(&(length + 12).to_le_bytes());
data[10..12].copy_from_slice(&length.to_le_bytes());
data[12..14].copy_from_slice(&(length + 2).to_le_bytes());
data[16..16 + substitute.len()].copy_from_slice(&substitute);
let handle = std::fs::OpenOptions::new()
.access_mode(GENERIC_WRITE)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(current)?;
let mut returned = 0;
if unsafe {
DeviceIoControl(
handle.as_raw_handle(),
FSCTL_SET_REPARSE_POINT,
data.as_ptr().cast(),
data.len() as u32,
std::ptr::null_mut(),
0,
&mut returned,
std::ptr::null_mut(),
)
} == 0
{
return Err(std::io::Error::last_os_error())
.context("failed to retarget managed daemon junction");
}
Ok(())
}
pub(super) fn validate_selection(root: &Path) -> Result<()> {
let current = root.join("current");
if matches!(current.symlink_metadata(), Err(error) if error.kind() == std::io::ErrorKind::NotFound)
{
return Ok(());
}
anyhow::ensure!(
current.canonicalize()?.parent() == Some(root.join("releases").canonicalize()?.as_path()),
"refusing to replace a daemon selection outside its releases directory"
);
Ok(())
}
#[cfg(test)]
#[path = "prepare_install_windows_tests.rs"]
mod tests;

View File

@@ -0,0 +1,60 @@
//! Verifies Windows package publication and selection without requiring an elevated daemon.
use anyhow::Context;
use pretty_assertions::assert_eq;
use std::os::windows::fs::OpenOptionsExt;
use std::time::Duration;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
#[tokio::test]
async fn publishing_release_retries_transient_access_denied() {
let home = tempfile::TempDir::new().unwrap();
let stage = home.path().join(".staging");
let release = home.path().join("release");
std::fs::create_dir(&stage).unwrap();
std::fs::write(stage.join("payload"), b"complete").unwrap();
let directory = std::fs::OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(&stage)
.unwrap();
let holder = tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(150)).await;
drop(directory);
});
super::publish_release(&stage, &release).await.unwrap();
holder.await.unwrap();
assert_eq!(std::fs::read(release.join("payload")).unwrap(), b"complete");
}
#[cfg(windows)]
#[test]
fn daemon_junction_can_be_created_retargeted_and_replaced_without_cli_links() {
let home = tempfile::TempDir::new().unwrap();
let root = home
.path()
.join("home & 100% ready!/packages/app-server-daemon");
for (version, native_denied) in [("first", true), ("second", false), ("third", true)] {
let release = root.join("releases").join(version);
std::fs::create_dir_all(&release).unwrap();
if native_denied {
super::select_release_with(&root, &release, |_, _| {
Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
.context("failed to retarget managed daemon junction")
})
.unwrap();
} else {
super::select_release(&root, &release).unwrap();
}
assert_eq!(
root.join("current").canonicalize().unwrap(),
release.canonicalize().unwrap()
);
}
assert!(!root.with_file_name("standalone").exists());
}

View File

@@ -0,0 +1,251 @@
//! Tracks dedicated selections under the installer lock. Pruning requires both lifecycle and
//! installer locks and valid history; inspect idle packages before a single best-effort retirement.
use std::io::Write;
use std::path::Path;
use anyhow::Context;
use anyhow::Result;
#[cfg(windows)]
use windows_sys::Win32::Storage::FileSystem as winfs;
use crate::Daemon;
use crate::backend;
use crate::managed_install;
use crate::settings::DaemonSettings;
#[derive(serde::Deserialize)]
struct Manifest {
version: semver::Version,
target: String,
entrypoint: String,
}
#[cfg(unix)]
fn selection_identity(current: &Path) -> Result<String> {
use std::os::unix::fs::MetadataExt;
let meta = current.symlink_metadata()?;
Ok(format!(
"{} {} {}.{:09}",
meta.dev(),
meta.ino(),
meta.ctime(),
meta.ctime_nsec()
))
}
#[cfg(windows)]
fn selection_identity(current: &Path) -> Result<String> {
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::System::IO::DeviceIoControl;
let file = std::fs::OpenOptions::new()
.access_mode(winfs::FILE_READ_ATTRIBUTES)
.share_mode(winfs::FILE_SHARE_READ | winfs::FILE_SHARE_WRITE | winfs::FILE_SHARE_DELETE)
.custom_flags(winfs::FILE_FLAG_BACKUP_SEMANTICS | winfs::FILE_FLAG_OPEN_REPARSE_POINT)
.open(current)?;
// FSCTL_READ_FILE_USN_DATA, with default V2 record version. The input is always
// "current", so 1024 bytes accommodates its journal record including the file name.
let mut record = [0u8; 1024];
let mut returned = 0;
if unsafe {
DeviceIoControl(
file.as_raw_handle(),
0x0009_00eb,
std::ptr::null(),
0,
record.as_mut_ptr().cast(),
record.len() as u32,
&raw mut returned,
std::ptr::null_mut(),
)
} == 0
{
return Err(std::io::Error::last_os_error().into());
}
let usn = i64::from_le_bytes(record[24..32].try_into()?);
anyhow::ensure!(
returned >= 32 && u16::from_le_bytes(record[4..6].try_into()?) == 2 && usn > 0,
"no reliable daemon selection journal record"
);
let file_id = u64::from_le_bytes(record[8..16].try_into()?);
Ok(format!("{file_id:x} {usn:x}"))
}
/// Call after changing the selection, while holding the installer lock.
pub(crate) fn record_selection(root: &Path, previous: Option<&Path>) -> Result<()> {
let current = root.join("current");
let selected = current.canonicalize()?;
let previous = previous
.and_then(Path::file_name)
.unwrap_or_default()
.to_string_lossy();
// If previous came from a shared install, conservatively retain its name here too.
let name = selected.file_name().unwrap_or_default().to_string_lossy();
let identity = selection_identity(&current)?;
let mut file = tempfile::NamedTempFile::new_in(root)?;
write!(file, "{name}\n{previous}\n{identity}\n")?;
file.persist(root.join("selection-history"))?;
Ok(())
}
/// Only ordinary files/directories can belong to a release. Linux device IDs alone
/// cannot distinguish same-device bind mounts; missing procfs disables pruning.
fn owned_mount(path: &Path) -> Result<u64> {
let meta = path.symlink_metadata()?;
anyhow::ensure!(
meta.is_dir() || meta.is_file(),
"not an ordinary package entry"
);
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
anyhow::ensure!(
meta.file_attributes() & winfs::FILE_ATTRIBUTE_REPARSE_POINT == 0,
"package entry is a reparse point"
);
// Volume mount points on Windows are reparse points.
Ok(0)
}
#[cfg(target_os = "linux")]
{
use std::os::fd::AsRawFd;
use std::os::unix::fs::OpenOptionsExt;
let file = std::fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(path)?;
let info = std::fs::read_to_string(format!("/proc/self/fdinfo/{}", file.as_raw_fd()))?;
info.lines()
.find_map(|line| line.strip_prefix("mnt_id:"))
.context("unknown package mount")?
.trim()
.parse()
.context("invalid package mount")
}
#[cfg(all(unix, not(target_os = "linux")))]
{
use std::os::unix::fs::MetadataExt;
Ok(meta.dev())
}
}
pub(crate) async fn prune(daemon: &Daemon, root: &Path, settings: &DaemonSettings) -> Result<()> {
let home = daemon
.settings_file
.parent()
.and_then(Path::parent)
.context("missing Codex home")?;
// Require a real dedicated root, never a shared alias or an in-progress migration.
let releases = root.join("releases");
let mount = owned_mount(&home.join("packages"))?;
anyhow::ensure!(
root == home.join("packages/app-server-daemon")
&& owned_mount(root)? == mount
&& owned_mount(&releases)? == mount
&& root.join(".migration-current").symlink_metadata().is_err(),
"invalid daemon package directory"
);
let releases = releases.canonicalize()?;
let current = root.join("current");
let selected = current.canonicalize()?;
let history = std::fs::read_to_string(root.join("selection-history"))?;
let previous = history
.lines()
.nth(1)
.context("missing previous selection")?;
let name = selected
.file_name()
.context("missing selection")?
.to_string_lossy();
anyhow::ensure!(
selected.parent() == Some(releases.as_path())
&& history == format!("{name}\n{previous}\n{}\n", selection_identity(&current)?)
&& (previous.is_empty()
|| Path::new(previous).file_name().and_then(|n| n.to_str()) == Some(previous)),
"invalid or stale daemon selection"
);
let paths = daemon.current_installation()?.backend_paths(settings);
let server = backend::pid_backend(paths.clone());
let updater = backend::pid_update_loop_backend(paths);
anyhow::ensure!(
server.is_starting_or_running().await?
|| crate::client::probe(&daemon.socket_path).await.is_err(),
"unmanaged daemon"
);
let mut identities = Vec::new();
for worker in [server, updater] {
if worker.is_starting_or_running().await? {
identities.push(
worker
.running_executable_identity()
.await?
.and_then(|identity| identity.path_digest)
.context("unknown running package")?,
);
}
}
let caller = std::env::current_exe()?.canonicalize()?;
'releases: for entry in std::fs::read_dir(&releases)? {
let entry = entry?;
let path = entry.path();
if path == selected
|| entry.file_name() == previous
|| caller.starts_with(&path)
|| !owned_mount(&path).is_ok_and(|id| id == mount)
{
continue;
}
let Some(manifest) = std::fs::File::open(path.join("codex-package.json"))
.ok()
.and_then(|file| serde_json::from_reader::<_, Manifest>(file).ok())
else {
continue;
};
// Accept only managed release names, never arbitrary or legacy folders.
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
let local = name
.strip_prefix("local-")
.and_then(|s| s.strip_suffix(&format!("-{}", manifest.target)));
if !(name == format!("{}-{}", manifest.version, manifest.target)
|| local.is_some_and(|digest| blake3::Hash::from_hex(digest).is_ok()))
|| !matches!(manifest.entrypoint.as_str(), "bin/codex" | "bin/codex.exe")
{
continue;
}
let Ok(executable) = path.join(manifest.entrypoint).canonicalize() else {
continue;
};
if identities.contains(&managed_install::path_digest(&executable)) {
continue;
}
let mut pending = vec![path.clone()];
while let Some(child) = pending.pop() {
// The Unix installer adds this alias; it never traverses outside the release.
#[cfg(unix)]
if child == path.join("codex")
&& std::fs::read_link(&child).ok().as_deref() == Some(Path::new("bin/codex"))
{
continue;
}
if !owned_mount(&child).is_ok_and(|id| id == mount) {
continue 'releases;
}
if child.is_dir() {
for entry in std::fs::read_dir(child)? {
pending.push(entry?.path());
}
}
}
// Clean up a failed rename, but never retry deletion after retirement.
let retired = tempfile::Builder::new()
.prefix(".retired.")
.tempdir_in(&releases)?;
std::fs::rename(&path, retired.path().join("release"))?;
std::fs::remove_dir_all(retired.keep())?;
}
Ok(())
}

View File

@@ -0,0 +1,835 @@
use std::path::Path;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use codex_app_server_protocol::JSONRPCMessage;
use codex_app_server_protocol::JSONRPCNotification;
use codex_app_server_protocol::JSONRPCRequest;
use codex_app_server_protocol::RemoteControlConnectionStatus;
use codex_app_server_protocol::RemoteControlDisableParams;
use codex_app_server_protocol::RemoteControlDisableResponse;
use codex_app_server_protocol::RemoteControlEnableParams;
use codex_app_server_protocol::RemoteControlEnableResponse;
use codex_app_server_protocol::RemoteControlPairingStartParams;
use codex_app_server_protocol::RemoteControlPairingStartResponse;
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
use codex_app_server_protocol::RequestId;
use serde::de::DeserializeOwned;
use tokio::io::AsyncRead;
use tokio::io::AsyncWrite;
use tokio::time::Instant;
use tokio::time::sleep;
use tokio::time::timeout;
use tokio_tungstenite::WebSocketStream;
use crate::RemoteControlReadyStatus;
use crate::client;
const REMOTE_CONTROL_READY_TIMEOUT: Duration = Duration::from_secs(10);
// Allow the daemon's 30-second pairing request to finish and return its response.
const PAIRING_TIMEOUT: Duration = Duration::from_secs(35);
const REMOTE_CONTROL_REQUEST_ID: RequestId = RequestId::Integer(2);
const INVALID_PARAMS_ERROR_CODE: i64 = -32602;
enum RemoteControlRpcResponse<T> {
Success(T),
InvalidParams,
}
pub(crate) async fn enable_remote_control(socket_path: &Path) -> Result<RemoteControlReadyStatus> {
let mut websocket = client::connect(socket_path).await?;
enable_remote_control_with_timeout(&mut websocket, REMOTE_CONTROL_READY_TIMEOUT).await
}
pub(crate) async fn disable_remote_control(socket_path: &Path) -> Result<RemoteControlReadyStatus> {
let mut websocket = client::connect(socket_path).await?;
initialize_client(&mut websocket).await?;
let params = serde_json::to_value(RemoteControlDisableParams { ephemeral: true })?;
let response: RemoteControlDisableResponse = request_remote_control_with_legacy_fallback(
&mut websocket,
"remoteControl/disable",
params,
)
.await?;
websocket.close(None).await.ok();
Ok(RemoteControlReadyStatus::from(response))
}
pub(crate) async fn start_pairing(socket_path: &Path) -> Result<RemoteControlPairingStartResponse> {
timeout(PAIRING_TIMEOUT, start_pairing_inner(socket_path))
.await
.context("timed out waiting for remoteControl/pairing/start response")?
}
async fn start_pairing_inner(socket_path: &Path) -> Result<RemoteControlPairingStartResponse> {
let mut websocket = client::connect(socket_path).await?;
initialize_client(&mut websocket).await?;
let params = serde_json::to_value(RemoteControlPairingStartParams { manual_code: true })?;
send_remote_control_request(
&mut websocket,
REMOTE_CONTROL_REQUEST_ID.clone(),
"remoteControl/pairing/start",
Some(params),
)
.await?;
let response = match read_remote_control_response(
&mut websocket,
&REMOTE_CONTROL_REQUEST_ID,
"remoteControl/pairing/start",
/*message_timeout*/ None,
)
.await?
{
RemoteControlRpcResponse::Success(response) => response,
RemoteControlRpcResponse::InvalidParams => {
return Err(anyhow!(
"remoteControl/pairing/start rejected manual pairing parameters"
));
}
};
websocket.close(None).await.ok();
Ok(response)
}
pub(crate) async fn enable_remote_control_with_connect_retry(
socket_path: &Path,
connect_timeout: Duration,
connect_retry_delay: Duration,
) -> Result<RemoteControlReadyStatus> {
let mut websocket =
connect_with_retry(socket_path, connect_timeout, connect_retry_delay).await?;
enable_remote_control_with_timeout(&mut websocket, REMOTE_CONTROL_READY_TIMEOUT).await
}
async fn enable_remote_control_with_timeout<S>(
websocket: &mut WebSocketStream<S>,
ready_timeout: Duration,
) -> Result<RemoteControlReadyStatus>
where
S: AsyncRead + AsyncWrite + Unpin,
{
initialize_client(websocket).await?;
let response: RemoteControlEnableResponse = request_remote_control_with_legacy_fallback(
websocket,
"remoteControl/enable",
serde_json::to_value(RemoteControlEnableParams { ephemeral: true })?,
)
.await?;
let mut latest = RemoteControlReadyStatus::from(response);
if latest.status == RemoteControlConnectionStatus::Connecting {
latest = wait_for_remote_control_status(websocket, latest, ready_timeout).await?;
}
websocket.close(None).await.ok();
Ok(latest)
}
async fn initialize_client<S>(websocket: &mut WebSocketStream<S>) -> Result<()>
where
S: AsyncRead + AsyncWrite + Unpin,
{
client::initialize(websocket, /*experimental_api*/ true).await?;
let initialized = JSONRPCMessage::Notification(JSONRPCNotification {
method: "initialized".to_string(),
params: None,
});
client::send_message(websocket, &initialized)
.await
.context("failed to send initialized notification")
}
async fn send_remote_control_request<S>(
websocket: &mut WebSocketStream<S>,
request_id: RequestId,
method: &str,
params: Option<serde_json::Value>,
) -> Result<()>
where
S: AsyncRead + AsyncWrite + Unpin,
{
let request = JSONRPCMessage::Request(JSONRPCRequest {
id: request_id,
method: method.to_string(),
params,
trace: None,
});
client::send_message(websocket, &request)
.await
.with_context(|| format!("failed to send {method} request"))
}
async fn request_remote_control_with_legacy_fallback<S, T>(
websocket: &mut WebSocketStream<S>,
method: &str,
params: serde_json::Value,
) -> Result<T>
where
S: AsyncRead + AsyncWrite + Unpin,
T: DeserializeOwned,
{
send_remote_control_request(
websocket,
REMOTE_CONTROL_REQUEST_ID.clone(),
method,
Some(params),
)
.await?;
let message_timeout = Some(client::CONTROL_SOCKET_RESPONSE_TIMEOUT);
match read_remote_control_response(
websocket,
&REMOTE_CONTROL_REQUEST_ID,
method,
message_timeout,
)
.await?
{
RemoteControlRpcResponse::Success(response) => Ok(response),
RemoteControlRpcResponse::InvalidParams => {
send_remote_control_request(
websocket,
REMOTE_CONTROL_REQUEST_ID.clone(),
method,
/*params*/ None,
)
.await?;
match read_remote_control_response(
websocket,
&REMOTE_CONTROL_REQUEST_ID,
method,
message_timeout,
)
.await?
{
RemoteControlRpcResponse::Success(response) => Ok(response),
RemoteControlRpcResponse::InvalidParams => {
Err(anyhow!("{method} rejected legacy params"))
}
}
}
}
}
async fn connect_with_retry(
socket_path: &Path,
connect_timeout: Duration,
connect_retry_delay: Duration,
) -> Result<WebSocketStream<codex_uds::UnixStream>> {
let deadline = Instant::now() + connect_timeout;
loop {
match client::connect(socket_path).await {
Ok(websocket) => return Ok(websocket),
Err(_) if Instant::now() < deadline => {
sleep(connect_retry_delay).await;
}
Err(error) => {
return Err(error).with_context(|| {
format!(
"app server did not become ready on {}",
socket_path.display()
)
});
}
}
}
}
async fn read_remote_control_response<S, T>(
websocket: &mut WebSocketStream<S>,
request_id: &RequestId,
method: &str,
message_timeout: Option<Duration>,
) -> Result<RemoteControlRpcResponse<T>>
where
S: AsyncRead + AsyncWrite + Unpin,
T: DeserializeOwned,
{
loop {
let read = client::read_message(websocket);
let message = if let Some(duration) = message_timeout {
timeout(duration, read)
.await
.with_context(|| format!("timed out waiting for {method} response"))??
} else {
read.await?
};
match message {
JSONRPCMessage::Response(response) if response.id == *request_id => {
let response = serde_json::from_value::<T>(response.result)
.with_context(|| format!("failed to parse {method} response"))?;
return Ok(RemoteControlRpcResponse::Success(response));
}
JSONRPCMessage::Error(err)
if err.id == *request_id && err.error.code == INVALID_PARAMS_ERROR_CODE =>
{
return Ok(RemoteControlRpcResponse::InvalidParams);
}
JSONRPCMessage::Error(err) if err.id == *request_id => {
return Err(anyhow!("{method} failed: {}", err.error.message));
}
JSONRPCMessage::Notification(notification)
if remote_control_status_notification(&notification).is_some() =>
{
continue;
}
_ => {}
}
}
}
async fn wait_for_remote_control_status<S>(
websocket: &mut WebSocketStream<S>,
mut latest: RemoteControlReadyStatus,
ready_timeout: Duration,
) -> Result<RemoteControlReadyStatus>
where
S: AsyncRead + AsyncWrite + Unpin,
{
let deadline = tokio::time::Instant::now() + ready_timeout;
while tokio::time::Instant::now() < deadline {
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
let message = match timeout(remaining, client::read_message(websocket)).await {
Ok(Ok(message)) => message,
Ok(Err(err)) => return Err(err),
Err(_) => {
latest.timed_out = true;
return Ok(latest);
}
};
let JSONRPCMessage::Notification(notification) = message else {
continue;
};
let Some(status) = remote_control_status_notification(&notification) else {
continue;
};
latest = RemoteControlReadyStatus::from(status);
if latest.status != RemoteControlConnectionStatus::Connecting {
return Ok(latest);
}
}
latest.timed_out = true;
Ok(latest)
}
fn remote_control_status_notification(
notification: &JSONRPCNotification,
) -> Option<RemoteControlStatusChangedNotification> {
if notification.method != "remoteControl/status/changed" {
return None;
}
let params = notification.params.clone()?;
serde_json::from_value(params).ok()
}
impl From<RemoteControlEnableResponse> for RemoteControlReadyStatus {
fn from(response: RemoteControlEnableResponse) -> Self {
let RemoteControlEnableResponse {
status,
server_name,
installation_id: _,
environment_id,
} = response;
Self {
status,
server_name,
environment_id,
timed_out: false,
}
}
}
impl From<RemoteControlDisableResponse> for RemoteControlReadyStatus {
fn from(response: RemoteControlDisableResponse) -> Self {
let RemoteControlDisableResponse {
status,
server_name,
installation_id: _,
environment_id,
} = response;
Self {
status,
server_name,
environment_id,
timed_out: false,
}
}
}
impl From<RemoteControlStatusChangedNotification> for RemoteControlReadyStatus {
fn from(notification: RemoteControlStatusChangedNotification) -> Self {
let RemoteControlStatusChangedNotification {
status,
server_name,
installation_id: _,
environment_id,
} = notification;
Self {
status,
server_name,
environment_id,
timed_out: false,
}
}
}
#[cfg(all(test, unix))]
mod tests {
use anyhow::Result;
use codex_app_server_protocol::JSONRPCError;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::JSONRPCResponse;
use codex_uds::UnixListener;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use tokio_tungstenite::accept_async;
use super::*;
const INITIALIZE_REQUEST_ID: RequestId = RequestId::Integer(1);
const TEST_INSTALLATION_ID: &str = "11111111-1111-4111-8111-111111111111";
const TEST_SERVER_NAME: &str = "owen-mbp";
const TEST_CODEX_HOME: &str = "/tmp/codex-home";
#[tokio::test]
async fn enable_remote_control_uses_connected_enable_response_without_later_notification()
-> Result<()> {
let status = run_enable_remote_control_scenario(EnableScenario {
initial_notification: Some(remote_control_status(
RemoteControlConnectionStatus::Connected,
Some("env_test"),
)),
enable_response: remote_control_status(
RemoteControlConnectionStatus::Connected,
Some("env_test"),
),
after_enable_notification: None,
ready_timeout: Duration::from_millis(20),
reject_ephemeral_params: false,
})
.await?;
assert_eq!(
status,
RemoteControlReadyStatus {
status: RemoteControlConnectionStatus::Connected,
server_name: TEST_SERVER_NAME.to_string(),
environment_id: Some("env_test".to_string()),
timed_out: false,
}
);
Ok(())
}
#[tokio::test]
async fn enable_remote_control_waits_for_connected_notification() -> Result<()> {
let status = run_enable_remote_control_scenario(EnableScenario {
initial_notification: None,
enable_response: remote_control_status(
RemoteControlConnectionStatus::Connecting,
/*environment_id*/ None,
),
after_enable_notification: Some(remote_control_status(
RemoteControlConnectionStatus::Connected,
Some("env_test"),
)),
ready_timeout: Duration::from_secs(1),
reject_ephemeral_params: false,
})
.await?;
assert_eq!(
status,
RemoteControlReadyStatus {
status: RemoteControlConnectionStatus::Connected,
server_name: TEST_SERVER_NAME.to_string(),
environment_id: Some("env_test".to_string()),
timed_out: false,
}
);
Ok(())
}
#[tokio::test]
async fn enable_remote_control_reports_connecting_after_timeout() -> Result<()> {
let status = run_enable_remote_control_scenario(EnableScenario {
initial_notification: None,
enable_response: remote_control_status(
RemoteControlConnectionStatus::Connecting,
/*environment_id*/ None,
),
after_enable_notification: None,
ready_timeout: Duration::from_millis(20),
reject_ephemeral_params: false,
})
.await?;
assert_eq!(
status,
RemoteControlReadyStatus {
status: RemoteControlConnectionStatus::Connecting,
server_name: TEST_SERVER_NAME.to_string(),
environment_id: None,
timed_out: true,
}
);
Ok(())
}
#[tokio::test]
async fn enable_remote_control_returns_errored_enable_response() -> Result<()> {
let status = run_enable_remote_control_scenario(EnableScenario {
initial_notification: None,
enable_response: remote_control_status(
RemoteControlConnectionStatus::Errored,
/*environment_id*/ None,
),
after_enable_notification: None,
ready_timeout: Duration::from_millis(20),
reject_ephemeral_params: false,
})
.await?;
assert_eq!(
status,
RemoteControlReadyStatus {
status: RemoteControlConnectionStatus::Errored,
server_name: TEST_SERVER_NAME.to_string(),
environment_id: None,
timed_out: false,
}
);
Ok(())
}
#[tokio::test]
async fn enable_remote_control_retries_without_params_for_older_servers() -> Result<()> {
let status = run_enable_remote_control_scenario(EnableScenario {
initial_notification: None,
enable_response: remote_control_status(
RemoteControlConnectionStatus::Connected,
Some("env_test"),
),
after_enable_notification: None,
ready_timeout: Duration::from_millis(20),
reject_ephemeral_params: true,
})
.await?;
assert_eq!(
status,
RemoteControlReadyStatus {
status: RemoteControlConnectionStatus::Connected,
server_name: TEST_SERVER_NAME.to_string(),
environment_id: Some("env_test".to_string()),
timed_out: false,
}
);
Ok(())
}
#[tokio::test]
async fn disable_remote_control_retries_without_params_for_older_servers() -> Result<()> {
let dir = TempDir::new()?;
let socket_path = dir.path().join("app-server.sock");
let listener = UnixListener::bind(&socket_path).await?;
let server_task = tokio::spawn(async move {
let mut websocket = accept_initialized_client(listener).await?;
let disable = client::read_message(&mut websocket).await?;
let JSONRPCMessage::Request(disable) = disable else {
panic!("expected remoteControl/disable request");
};
assert_eq!(disable.id, REMOTE_CONTROL_REQUEST_ID);
assert_eq!(disable.method, "remoteControl/disable");
assert_eq!(
disable.params,
Some(serde_json::json!({ "ephemeral": true }))
);
client::send_message(
&mut websocket,
&JSONRPCMessage::Error(JSONRPCError {
id: REMOTE_CONTROL_REQUEST_ID,
error: JSONRPCErrorError {
code: INVALID_PARAMS_ERROR_CODE,
message: "Invalid params".to_string(),
data: None,
},
}),
)
.await?;
let fallback = client::read_message(&mut websocket).await?;
let JSONRPCMessage::Request(fallback) = fallback else {
panic!("expected fallback remoteControl/disable request");
};
assert_eq!(fallback.id, REMOTE_CONTROL_REQUEST_ID);
assert_eq!(fallback.method, "remoteControl/disable");
assert_eq!(fallback.params, None);
client::send_message(
&mut websocket,
&JSONRPCMessage::Response(JSONRPCResponse {
id: REMOTE_CONTROL_REQUEST_ID,
result: serde_json::to_value(RemoteControlDisableResponse::from(
remote_control_status(
RemoteControlConnectionStatus::Disabled,
/*environment_id*/ None,
),
))?,
}),
)
.await?;
Ok::<_, anyhow::Error>(())
});
let status = disable_remote_control(&socket_path).await?;
server_task.await??;
assert_eq!(
status,
RemoteControlReadyStatus {
status: RemoteControlConnectionStatus::Disabled,
server_name: TEST_SERVER_NAME.to_string(),
environment_id: None,
timed_out: false,
}
);
Ok(())
}
#[tokio::test]
async fn start_pairing_requests_manual_code() -> Result<()> {
let dir = TempDir::new()?;
let socket_path = dir.path().join("app-server.sock");
let listener = UnixListener::bind(&socket_path).await?;
let server_task = tokio::spawn(async move {
let mut websocket = accept_initialized_client(listener).await?;
let pairing = client::read_message(&mut websocket).await?;
let JSONRPCMessage::Request(pairing) = pairing else {
panic!("expected remoteControl/pairing/start request");
};
assert_eq!(pairing.id, REMOTE_CONTROL_REQUEST_ID);
assert_eq!(pairing.method, "remoteControl/pairing/start");
assert_eq!(
pairing.params,
Some(serde_json::json!({ "manualCode": true }))
);
// Use virtual time only for the reply delay, after the socket handshake.
tokio::time::pause();
sleep(Duration::from_secs(3)).await;
tokio::time::resume();
client::send_message(
&mut websocket,
&JSONRPCMessage::Response(JSONRPCResponse {
id: REMOTE_CONTROL_REQUEST_ID,
result: serde_json::to_value(RemoteControlPairingStartResponse {
pairing_code: "pairing-code".to_string(),
manual_pairing_code: Some("ABCD-EFGH".to_string()),
environment_id: "env_test".to_string(),
expires_at: 1_700_000_000,
})?,
}),
)
.await?;
Ok::<_, anyhow::Error>(())
});
let response = start_pairing(&socket_path).await?;
server_task.await??;
assert_eq!(
response,
RemoteControlPairingStartResponse {
pairing_code: "pairing-code".to_string(),
manual_pairing_code: Some("ABCD-EFGH".to_string()),
environment_id: "env_test".to_string(),
expires_at: 1_700_000_000,
}
);
Ok(())
}
#[tokio::test]
async fn pairing_notification_does_not_extend_the_response_deadline() -> Result<()> {
let dir = TempDir::new()?;
let socket_path = dir.path().join("app-server.sock");
let listener = UnixListener::bind(&socket_path).await?;
let server_task = tokio::spawn(async move {
let mut websocket = accept_initialized_client(listener).await?;
client::read_message(&mut websocket).await?;
tokio::time::pause();
sleep(Duration::from_secs(20)).await;
send_remote_control_status(
&mut websocket,
remote_control_status(
RemoteControlConnectionStatus::Connecting,
/*environment_id*/ None,
),
)
.await?;
// With a fresh timeout after the notification, the client would see EOF at 40s.
sleep(Duration::from_secs(20)).await;
Ok::<_, anyhow::Error>(())
});
let start = Instant::now();
let error = start_pairing(&socket_path).await.unwrap_err();
let elapsed = start.elapsed();
server_task.await??;
assert!(error.is::<tokio::time::error::Elapsed>(), "{error:#}");
assert!(
(Duration::from_secs(30)..Duration::from_secs(40)).contains(&elapsed),
"pairing timed out after {elapsed:?}"
);
Ok(())
}
struct EnableScenario {
initial_notification: Option<RemoteControlStatusChangedNotification>,
enable_response: RemoteControlStatusChangedNotification,
after_enable_notification: Option<RemoteControlStatusChangedNotification>,
ready_timeout: Duration,
reject_ephemeral_params: bool,
}
async fn run_enable_remote_control_scenario(
scenario: EnableScenario,
) -> Result<RemoteControlReadyStatus> {
let dir = TempDir::new()?;
let socket_path = dir.path().join("app-server.sock");
let listener = UnixListener::bind(&socket_path).await?;
let ready_timeout = scenario.ready_timeout;
let server_task = tokio::spawn(serve_enable_remote_control_scenario(listener, scenario));
let mut websocket = client::connect(&socket_path).await?;
let status = enable_remote_control_with_timeout(&mut websocket, ready_timeout).await?;
server_task.await??;
Ok(status)
}
async fn serve_enable_remote_control_scenario(
listener: UnixListener,
scenario: EnableScenario,
) -> Result<()> {
let mut websocket = accept_initialized_client(listener).await?;
if let Some(status) = scenario.initial_notification {
send_remote_control_status(&mut websocket, status).await?;
}
let enable = client::read_message(&mut websocket).await?;
let JSONRPCMessage::Request(enable) = enable else {
panic!("expected remoteControl/enable request");
};
assert_eq!(enable.id, REMOTE_CONTROL_REQUEST_ID);
assert_eq!(enable.method, "remoteControl/enable");
assert_eq!(
enable.params,
Some(serde_json::json!({ "ephemeral": true }))
);
if scenario.reject_ephemeral_params {
client::send_message(
&mut websocket,
&JSONRPCMessage::Error(JSONRPCError {
id: REMOTE_CONTROL_REQUEST_ID,
error: JSONRPCErrorError {
code: INVALID_PARAMS_ERROR_CODE,
message: "Invalid params".to_string(),
data: None,
},
}),
)
.await?;
let fallback = client::read_message(&mut websocket).await?;
let JSONRPCMessage::Request(fallback) = fallback else {
panic!("expected fallback remoteControl/enable request");
};
assert_eq!(fallback.id, REMOTE_CONTROL_REQUEST_ID);
assert_eq!(fallback.method, "remoteControl/enable");
assert_eq!(fallback.params, None);
}
client::send_message(
&mut websocket,
&JSONRPCMessage::Response(JSONRPCResponse {
id: REMOTE_CONTROL_REQUEST_ID,
result: serde_json::to_value(RemoteControlEnableResponse::from(
scenario.enable_response,
))?,
}),
)
.await?;
if let Some(status) = scenario.after_enable_notification {
send_remote_control_status(&mut websocket, status).await?;
} else {
tokio::time::sleep(Duration::from_millis(50)).await;
}
Ok(())
}
async fn accept_initialized_client(
mut listener: UnixListener,
) -> Result<WebSocketStream<codex_uds::UnixStream>> {
let stream = listener.accept().await?;
let mut websocket = accept_async(stream).await?;
let initialize = client::read_message(&mut websocket).await?;
let JSONRPCMessage::Request(initialize) = initialize else {
panic!("expected initialize request");
};
assert_eq!(initialize.id, INITIALIZE_REQUEST_ID);
assert_eq!(initialize.method, "initialize");
let Some(initialize_params) = initialize.params else {
panic!("expected initialize params");
};
assert_eq!(
initialize_params["capabilities"]["experimentalApi"],
serde_json::Value::Bool(true)
);
client::send_message(
&mut websocket,
&JSONRPCMessage::Response(JSONRPCResponse {
id: INITIALIZE_REQUEST_ID,
result: serde_json::json!({
"userAgent": "codex_app_server/1.2.3",
"codexHome": TEST_CODEX_HOME,
"platformFamily": "unix",
"platformOs": "macos",
}),
}),
)
.await?;
let initialized = client::read_message(&mut websocket).await?;
let JSONRPCMessage::Notification(initialized) = initialized else {
panic!("expected initialized notification");
};
assert_eq!(initialized.method, "initialized");
Ok(websocket)
}
async fn send_remote_control_status<S>(
websocket: &mut WebSocketStream<S>,
status: RemoteControlStatusChangedNotification,
) -> Result<()>
where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
{
client::send_message(
websocket,
&JSONRPCMessage::Notification(JSONRPCNotification {
method: "remoteControl/status/changed".to_string(),
params: Some(serde_json::to_value(status)?),
}),
)
.await
}
fn remote_control_status(
status: RemoteControlConnectionStatus,
environment_id: Option<&str>,
) -> RemoteControlStatusChangedNotification {
RemoteControlStatusChangedNotification {
status,
server_name: TEST_SERVER_NAME.to_string(),
installation_id: TEST_INSTALLATION_ID.to_string(),
environment_id: environment_id.map(str::to_string),
}
}
}

View File

@@ -0,0 +1,242 @@
use std::collections::BTreeMap;
use std::path::Path;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::ensure;
use serde::Deserialize;
use serde::de::DeserializeOwned;
use serde_json::Map;
use serde_json::Value;
use tokio::fs;
pub(crate) const DEFAULT_UPDATE_INTERVAL_MINUTES: u32 = 60;
pub(crate) const DEFAULT_SHUTDOWN_GRACE_SECONDS: u32 = 60;
pub(crate) const MAX_SHUTDOWN_GRACE_SECONDS: u32 = 5 * 60;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DaemonSettings {
pub(crate) remote_control_enabled: bool,
pub(crate) feature_overrides: BTreeMap<String, bool>,
pub(crate) auto_update_enabled: bool,
pub(crate) update_interval_minutes: u32,
pub(crate) shutdown_grace_seconds: u32,
}
impl Default for DaemonSettings {
fn default() -> Self {
Self {
remote_control_enabled: false,
feature_overrides: BTreeMap::new(),
auto_update_enabled: true,
update_interval_minutes: DEFAULT_UPDATE_INTERVAL_MINUTES,
shutdown_grace_seconds: DEFAULT_SHUTDOWN_GRACE_SECONDS,
}
}
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct StopSettings {
shutdown_grace_seconds: Option<u32>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct StoredSettings {
#[serde(default)]
remote_control_enabled: bool,
#[serde(default)]
feature_overrides: BTreeMap<String, bool>,
#[serde(default = "default_shutdown_grace_seconds")]
shutdown_grace_seconds: u32,
#[serde(default)]
updater: UpdaterSettings,
}
impl Default for StoredSettings {
fn default() -> Self {
Self {
remote_control_enabled: false,
feature_overrides: BTreeMap::new(),
shutdown_grace_seconds: DEFAULT_SHUTDOWN_GRACE_SECONDS,
updater: UpdaterSettings::default(),
}
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct UpdaterSettings {
#[serde(default = "default_auto_update_enabled")]
pub(crate) auto_update_enabled: bool,
#[serde(default = "default_update_interval_minutes")]
pub(crate) update_interval_minutes: u32,
}
impl Default for UpdaterSettings {
fn default() -> Self {
Self {
auto_update_enabled: default_auto_update_enabled(),
update_interval_minutes: default_update_interval_minutes(),
}
}
}
fn default_auto_update_enabled() -> bool {
true
}
fn default_update_interval_minutes() -> u32 {
DEFAULT_UPDATE_INTERVAL_MINUTES
}
fn default_shutdown_grace_seconds() -> u32 {
DEFAULT_SHUTDOWN_GRACE_SECONDS
}
fn validate_shutdown_grace(seconds: u32) -> Result<()> {
ensure!(
seconds <= MAX_SHUTDOWN_GRACE_SECONDS,
"shutdown grace must be between 0 and {MAX_SHUTDOWN_GRACE_SECONDS} seconds"
);
Ok(())
}
impl UpdaterSettings {
pub(crate) async fn load(settings_file: &Path) -> Result<Self> {
let settings: StoredSettings = read_settings(settings_file).await?;
validate_shutdown_grace(settings.shutdown_grace_seconds)?;
let settings = settings.updater;
settings.validate()?;
Ok(settings)
}
pub(crate) fn validate(&self) -> Result<()> {
ensure!(
self.update_interval_minutes > 0,
"update interval must be positive"
);
Ok(())
}
pub(crate) fn update_interval(&self, minute: Duration) -> Duration {
minute * self.update_interval_minutes
}
}
impl DaemonSettings {
pub(crate) async fn load(path: &Path) -> Result<Self> {
let settings: StoredSettings = read_settings(path).await?;
settings.updater.validate()?;
validate_shutdown_grace(settings.shutdown_grace_seconds)?;
Ok(Self {
remote_control_enabled: settings.remote_control_enabled,
feature_overrides: settings.feature_overrides,
auto_update_enabled: settings.updater.auto_update_enabled,
update_interval_minutes: settings.updater.update_interval_minutes,
shutdown_grace_seconds: settings.shutdown_grace_seconds,
})
}
pub(crate) async fn load_for_stop(path: &Path) -> Self {
// Stop must work even when settings are unreadable or partially edited.
let shutdown_grace_seconds = read_settings::<StopSettings>(path)
.await
.ok()
.and_then(|settings| settings.shutdown_grace_seconds)
.filter(|&seconds| seconds <= MAX_SHUTDOWN_GRACE_SECONDS)
.unwrap_or(DEFAULT_SHUTDOWN_GRACE_SECONDS);
Self {
shutdown_grace_seconds,
..Self::default()
}
}
pub(crate) async fn save(&self, path: &Path) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).await.with_context(|| {
format!(
"failed to create daemon settings directory {}",
parent.display()
)
})?;
}
let mut settings: Map<String, Value> = read_settings(path).await?;
settings.insert(
"remoteControlEnabled".to_string(),
Value::Bool(self.remote_control_enabled),
);
if self.feature_overrides.is_empty() {
settings.remove("featureOverrides");
} else {
settings.insert(
"featureOverrides".to_string(),
serde_json::to_value(&self.feature_overrides)?,
);
}
let contents =
serde_json::to_vec_pretty(&settings).context("failed to serialize settings")?;
let temporary_path = path.with_extension("tmp");
fs::write(&temporary_path, contents)
.await
.with_context(|| {
format!(
"failed to write daemon settings {}",
temporary_path.display()
)
})?;
fs::rename(&temporary_path, path)
.await
.with_context(|| format!("failed to replace daemon settings {}", path.display()))
}
}
pub(crate) async fn telemetry_tags(path: &Path) -> Result<[(&'static str, &'static str); 4]> {
let raw: Map<String, Value> = read_settings(path).await?;
// Validate the same snapshot used for presence checks, using the existing settings parser.
let settings: StoredSettings = serde_json::from_value(Value::Object(raw.clone()))?;
settings.updater.validate()?;
validate_shutdown_grace(settings.shutdown_grace_seconds)?;
let updater = raw.get("updater");
let presence = |configured| if configured { "configured" } else { "default" };
Ok([
(
"auto_update",
if settings.updater.auto_update_enabled {
"enabled"
} else {
"disabled"
},
),
(
"auto_update_setting",
presence(updater.is_some_and(|value| value.get("autoUpdateEnabled").is_some())),
),
(
"update_interval_setting",
presence(updater.is_some_and(|value| value.get("updateIntervalMinutes").is_some())),
),
(
"shutdown_grace_setting",
presence(raw.contains_key("shutdownGraceSeconds")),
),
])
}
async fn read_settings<T: DeserializeOwned + Default>(path: &Path) -> Result<T> {
let contents = match fs::read_to_string(path).await {
Ok(contents) => contents,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(T::default()),
Err(err) => {
return Err(err).with_context(|| format!("failed to read settings {}", path.display()));
}
};
serde_json::from_str(&contents)
.with_context(|| format!("failed to parse settings {}", path.display()))
}
#[cfg(test)]
#[path = "settings_tests.rs"]
mod tests;

View File

@@ -0,0 +1,155 @@
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use super::DaemonSettings;
use super::MAX_SHUTDOWN_GRACE_SECONDS;
#[tokio::test]
async fn remote_control_save_preserves_updater_settings() {
let temp = TempDir::new().expect("temp dir");
let path = temp.path().join("settings.json");
tokio::fs::write(&path, r#"{"remoteControlEnabled":true}"#)
.await
.expect("write legacy settings");
let settings = DaemonSettings::load(&path).await.expect("load settings");
assert_eq!(
settings,
DaemonSettings {
remote_control_enabled: true,
..DaemonSettings::default()
}
);
tokio::fs::write(
&path,
r#"{"remoteControlEnabled":true,"shutdownGraceSeconds":25,"updater":{"autoUpdateEnabled":false,"updateIntervalMinutes":17},"featureOverrides":{"api_key_model_discovery":true,"code_mode_host":false},"futureSetting":42}"#,
)
.await
.expect("write settings");
let updated = DaemonSettings {
remote_control_enabled: false,
..DaemonSettings::load(&path)
.await
.expect("load updater settings")
};
updated.save(&path).await.expect("save remote control");
assert_eq!(
serde_json::from_slice::<serde_json::Value>(
&tokio::fs::read(&path).await.expect("read settings")
)
.expect("parse settings"),
serde_json::json!({
"remoteControlEnabled": false,
"shutdownGraceSeconds": 25,
"updater": {"autoUpdateEnabled": false, "updateIntervalMinutes": 17},
"featureOverrides": {"api_key_model_discovery": true, "code_mode_host": false},
"futureSetting": 42,
})
);
}
#[tokio::test]
async fn shutdown_grace_accepts_zero_through_five_minutes() {
let temp = TempDir::new().expect("temp dir");
let path = temp.path().join("settings.json");
assert_eq!(
DaemonSettings::load(&path).await.expect("missing settings"),
DaemonSettings::default()
);
assert_eq!(
DaemonSettings::load_for_stop(&path)
.await
.shutdown_grace_seconds,
60
);
for seconds in [
0,
MAX_SHUTDOWN_GRACE_SECONDS,
MAX_SHUTDOWN_GRACE_SECONDS + 1,
] {
tokio::fs::write(
&path,
serde_json::to_vec(&serde_json::json!({"shutdownGraceSeconds": seconds}))
.expect("serialize settings"),
)
.await
.expect("write settings");
let expected = (seconds <= MAX_SHUTDOWN_GRACE_SECONDS).then_some(seconds);
assert_eq!(
DaemonSettings::load(&path)
.await
.ok()
.map(|settings| settings.shutdown_grace_seconds),
expected
);
assert_eq!(
DaemonSettings::load_for_stop(&path)
.await
.shutdown_grace_seconds,
expected.unwrap_or(60)
);
}
tokio::fs::write(&path, r#"{"shutdownGraceSeconds":"unlimited"}"#)
.await
.expect("write invalid settings");
assert!(DaemonSettings::load(&path).await.is_err());
assert_eq!(
DaemonSettings::load_for_stop(&path)
.await
.shutdown_grace_seconds,
60
);
}
#[tokio::test]
async fn update_interval_accepts_long_values_and_rejects_zero() {
let temp = TempDir::new().expect("temp dir");
let path = temp.path().join("settings.json");
for minutes in [u32::MAX, 0] {
tokio::fs::write(
&path,
serde_json::to_vec(&serde_json::json!({
"updater": {"updateIntervalMinutes": minutes},
}))
.expect("serialize invalid settings"),
)
.await
.expect("write invalid settings");
let loaded = DaemonSettings::load(&path).await;
if minutes == 0 {
assert!(loaded.is_err());
} else {
assert_eq!(
loaded.expect("load long interval").update_interval_minutes,
minutes
);
}
}
}
#[tokio::test]
async fn telemetry_distinguishes_presence_from_default_values() -> anyhow::Result<()> {
let home = TempDir::new()?;
let dir = home.path().join("app-server-daemon");
tokio::fs::create_dir(&dir).await?;
let path = dir.join("settings.json");
for (contents, presence) in [
("{}", "default"),
(
r#"{"updater":{"autoUpdateEnabled":true,"updateIntervalMinutes":60},"shutdownGraceSeconds":60}"#,
"configured",
),
] {
tokio::fs::write(&path, contents).await?;
assert_eq!(
crate::telemetry::settings_tags(home.path())
.await
.map(|(_, value)| value),
["enabled", presence, presence, presence]
);
}
Ok(())
}

View File

@@ -0,0 +1,78 @@
//! Bounded observations for foreground callers. This module never exports telemetry;
//! in particular, the detached updater must not create a telemetry provider.
use std::path::Path;
/// Failure of a foreground auto-start, with the original diagnostic kept separate from the metric.
#[derive(Debug)]
pub struct StartError {
pub error: anyhow::Error,
during_install: bool,
}
impl StartError {
pub fn failure_reason(&self) -> &'static str {
#[cfg(windows)]
if self.error.is::<crate::DetachedLaunchRestricted>() {
return "spawn";
}
match self.error.downcast_ref::<StartFailure>() {
Some(StartFailure::Spawn(_)) => "spawn",
Some(StartFailure::EarlyChildExit(_)) => "early_child_exit",
Some(StartFailure::ReadinessTimeout(_)) => "readiness_timeout",
None if self.during_install => "install",
None => "other",
}
}
pub(crate) fn install(error: anyhow::Error) -> Self {
Self {
error,
during_install: true,
}
}
}
impl From<anyhow::Error> for StartError {
fn from(error: anyhow::Error) -> Self {
Self {
error,
during_install: false,
}
}
}
/// Typed anyhow context preserves both the original diagnostic and downcasts through it.
#[derive(Debug)]
pub(crate) enum StartFailure {
Spawn(String),
EarlyChildExit(String),
ReadinessTimeout(String),
}
impl std::fmt::Display for StartFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Spawn(message)
| Self::EarlyChildExit(message)
| Self::ReadinessTimeout(message) => f.write_str(message),
}
}
}
/// Suppress child reporting when the foreground TUI handoff owns the observation.
pub const HANDOFF_ENV: &str = "CODEX_DAEMON_TELEMETRY_HANDOFF";
/// Only presence and enabled state leave the settings reader, never values or contents.
/// Missing files mean defaults; unreadable or invalid settings remain unknown.
pub async fn settings_tags(codex_home: &Path) -> [(&'static str, &'static str); 4] {
let path = codex_home
.join(crate::STATE_DIR_NAME)
.join(crate::SETTINGS_FILE_NAME);
crate::settings::telemetry_tags(&path).await.unwrap_or([
("auto_update", "unknown"),
("auto_update_setting", "unknown"),
("update_interval_setting", "unknown"),
("shutdown_grace_setting", "unknown"),
])
}

View File

@@ -0,0 +1,16 @@
//! Removes stale snapshots before planned daemon replacements.
use std::io::ErrorKind;
use anyhow::Context;
use anyhow::Result;
use crate::Daemon;
pub(crate) fn discard_pending(daemon: &Daemon) -> Result<()> {
match std::fs::remove_file(daemon.recovery_file()?) {
Ok(()) => Ok(()),
Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
Err(err) => Err(err).context("failed to clear daemon recovery file"),
}
}

View File

@@ -0,0 +1,809 @@
//! Owns scheduled and manual installs, daemon restarts, and updater replacement.
use std::collections::VecDeque;
use std::io::Write;
use std::path::Path;
#[cfg(unix)]
use std::process::Command as StdCommand;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::RouteAwareClientPool;
use futures::FutureExt;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
#[cfg(unix)]
use tokio::signal::unix::Signal;
#[cfg(unix)]
use tokio::signal::unix::SignalKind;
#[cfg(unix)]
use tokio::signal::unix::signal;
use tokio::time::Instant;
use tokio::time::sleep;
use tokio::time::sleep_until;
use crate::Daemon;
use crate::RestartIfRunningOutcome;
use crate::RestartMode;
use crate::managed_install::ExecutableIdentity;
use crate::managed_install::executable_identity;
use crate::managed_install::resolved_managed_codex_bin;
#[cfg(any(target_os = "linux", target_os = "macos", windows))]
use crate::settings::DaemonSettings;
use crate::settings::UpdaterSettings;
#[path = "manual_update.rs"]
mod manual_update;
#[path = "migration.rs"]
mod migration;
pub(crate) async fn request_manual_update(
daemon: &Daemon,
http_client_factory: HttpClientFactory,
) -> Result<crate::UpdateOutput> {
if daemon
.pid_file
.file_name()
.is_some_and(|name| name == crate::LEGACY_PID_FILE_NAME)
&& manual_update::supported(daemon)?
{
let http = RouteAwareClientPool::new_without_request_logging(
http_client_factory,
ClientRouteClass::Other,
);
return migration::run(&http, daemon).await;
}
manual_update::request(daemon).await
}
const INITIAL_UPDATE_DELAY: Duration = Duration::from_secs(5 * 60);
const RESTART_RETRY_INTERVAL: Duration = Duration::from_millis(50);
// Manual update responses are capped after JSON serialization. This leaves room for the status,
// envelope, and the worst-case six-byte JSON escape for every captured byte.
const INSTALLER_STDERR_TAIL_BYTES: usize = 2 * 1024;
const INSTALLER_STDERR_DRAIN_TIMEOUT: Duration = Duration::from_secs(1);
#[cfg(unix)]
const INSTALL_URL: &str = "https://chatgpt.com/codex/install.sh";
#[cfg(windows)]
const INSTALL_URL: &str = "https://chatgpt.com/codex/install.ps1";
pub(crate) async fn run(
http_client_factory: HttpClientFactory,
restore_release: Option<String>,
) -> Result<()> {
let daemon = Daemon::from_environment()?;
crate::backend::stderr_log::start(daemon.update_pid_file.with_extension("stderr.log"));
let http = RouteAwareClientPool::new_without_request_logging(
http_client_factory,
ClientRouteClass::Other,
);
run_with_http(
&http,
&daemon,
&current_updater_identity().await?,
restore_release,
)
.await
}
async fn run_with_http(
http: &impl InstallerHttp,
daemon: &Daemon,
running_updater_identity: &ExecutableIdentity,
mut restore_release: Option<String>,
) -> Result<()> {
#[cfg(unix)]
let mut terminate =
signal(SignalKind::terminate()).context("failed to install updater shutdown handler")?;
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
let paths = daemon.backend_paths(&DaemonSettings::default());
for backend in [
crate::backend::pid_backend(paths.clone()),
crate::backend::pid_update_loop_backend(paths),
] {
// Inspection failures must preserve legacy records without blocking updates.
let _ = backend.promote_legacy_identity().await;
}
}
#[cfg(windows)]
let updater = {
// Updater ownership needs only paths, not settings that may be mid-edit.
crate::backend::pid_update_loop_backend(daemon.backend_paths(&DaemonSettings::default()))
};
#[cfg(windows)]
updater.wait_for_ownership().await?;
#[cfg(windows)]
let mut terminate = Signal;
#[cfg(windows)]
let _installer_job = crate::backend::windows::updater_job()?;
let socket_path = daemon.manual_update_socket_path();
codex_uds::prepare_private_socket_directory(
socket_path
.parent()
.context("updater socket has no parent")?,
)
.await?;
#[cfg(unix)]
let (listener, _socket_guard) =
codex_app_server_transport::bind_private_daemon_socket(&socket_path).await?;
#[cfg(windows)]
let listener = {
if socket_path.exists() {
tokio::fs::remove_file(&socket_path).await?;
}
codex_uds::UnixListener::bind(&socket_path).await?
};
let mut listener = Some(listener);
#[cfg(windows)]
updater.mark_ready().await?;
let needs_managed_handoff =
match resolved_managed_codex_bin(&daemon.current_managed_codex_bin()?).await {
Ok(managed_bin) => executable_identity(&managed_bin)
.await
.map_or(true, |identity| identity != *running_updater_identity),
Err(_) => true,
};
let auto_update_enabled = UpdaterSettings::load(&daemon.settings_file)
.await
.map(|settings| settings.auto_update_enabled)
.unwrap_or(true);
let mut next_check = Instant::now()
+ if restore_release.is_some() || needs_managed_handoff || !auto_update_enabled {
Duration::from_secs(15)
} else {
INITIAL_UPDATE_DELAY
};
let mut manual_handoff_pending = needs_managed_handoff;
loop {
tokio::select! {
biased;
_ = terminate.recv() => return Ok(()),
connection = listener.as_mut().context("updater listener closed")?.accept() => {
let connection = connection.context("failed to accept updater request")?;
// Only a manual CLI launch under the operation lock supplies this
// single-use authority. Ordinary socket requests cannot undo a pin.
let restoration = restore_release.take();
let trigger = restoration.as_deref().map_or(UpdateTrigger::Manual, UpdateTrigger::RestoreProduction);
let disposition = match manual_update::handle_request(connection, http, daemon, running_updater_identity, &mut terminate, trigger).await {
Ok(manual_update::RequestDisposition::Stop) => return Ok(()),
Ok(disposition) => disposition,
Err(_) => manual_update::RequestDisposition::Continue,
};
if UpdaterSettings::load(&daemon.settings_file)
.await
.is_ok_and(|settings| !settings.auto_update_enabled)
{
// Drain requests queued during this one-shot update before exiting.
next_check = Instant::now() + Duration::from_millis(100);
continue;
}
if matches!(disposition, manual_update::RequestDisposition::Unchanged) {
continue;
}
manual_handoff_pending = true;
next_check = Instant::now();
}
_ = sleep_until(next_check) => {
// The authorizing CLI may have exited before sending its request.
if restore_release.is_some() {
return Ok(());
}
match UpdaterSettings::load(&daemon.settings_file).await {
Ok(settings) if !settings.auto_update_enabled => return Ok(()),
Err(_) => {
next_check = Instant::now() + Duration::from_secs(60);
continue;
}
Ok(_) => {}
}
// Failed successor cleanup leaves its PID published. The predecessor
// must stop instead of installing again without ownership.
#[cfg(windows)]
updater.wait_for_ownership().await?;
if manual_handoff_pending {
if !daemon.is_stable_standalone_release()? {
if !daemon.has_latest_selection_marker() {
return Ok(());
}
next_check = Instant::now() + Duration::from_secs(30);
continue;
}
match adopt_managed_updater(daemon, running_updater_identity, &mut listener).await {
Ok(UpdateLoopControl::Stop) => return Ok(()),
Ok(UpdateLoopControl::Continue) => {
manual_handoff_pending = false;
let Some(delay) = next_update_delay(daemon).await else {
return Ok(());
};
next_check = Instant::now() + delay;
}
Err(err) => {
if listener.is_none() {
return Err(err);
}
let _ = crate::stderr_writer().write_all(format!("warning: failed to refresh managed updater: {err:#}\n").as_bytes());
next_check = Instant::now() + Duration::from_secs(30);
}
}
continue;
}
let started = std::time::Instant::now();
match update_once(http, daemon, running_updater_identity, &mut terminate, UpdateTrigger::Scheduled).await {
Ok((UpdateLoopControl::Continue, Some(_))) => {
manual_handoff_pending = true;
next_check = Instant::now();
continue;
}
Ok((UpdateLoopControl::Continue, None)) => {}
Err(err) => {
let _ = crate::diagnostics::result::<()>("scheduled_update", started, Err(err));
}
Ok((UpdateLoopControl::Stop, _)) => return Ok(()),
}
let Some(delay) = next_update_delay(daemon).await else {
return Ok(());
};
next_check = Instant::now() + delay;
}
}
}
}
async fn next_update_delay(daemon: &Daemon) -> Option<Duration> {
match UpdaterSettings::load(&daemon.settings_file).await {
Ok(settings) if !settings.auto_update_enabled => None,
Ok(settings) => Some(settings.update_interval(Duration::from_secs(60))),
Err(_) => Some(Duration::from_secs(60)),
}
}
async fn adopt_managed_updater(
daemon: &Daemon,
running_identity: &ExecutableIdentity,
listener: &mut Option<codex_uds::UnixListener>,
) -> Result<UpdateLoopControl> {
let managed_bin = resolved_managed_codex_bin(&daemon.current_managed_codex_bin()?).await?;
if executable_identity(&managed_bin).await? == *running_identity {
return Ok(UpdateLoopControl::Continue);
}
if !crate::managed_install::supports_daemon_update_loop(&managed_bin).await {
return Ok(UpdateLoopControl::Stop);
}
#[cfg(unix)]
{
let _ = listener;
reexec_managed_updater(
&managed_bin,
daemon
.update_pid_file
.parent()
.context("updater pid path has no parent")?,
)
.map(|_| UpdateLoopControl::Stop)
}
#[cfg(windows)]
{
let replacement = crate::backend::pid_update_loop_backend(
daemon.backend_paths_with_bin(&daemon.load_settings().await?, &managed_bin),
);
listener.take();
if let Err(err) = replacement.replace_current_updater().await {
// A failed replacement may still own the PID if its cleanup could
// not terminate the successor. Never reopen our request socket then.
replacement.wait_for_ownership().await?;
let socket_path = daemon.manual_update_socket_path();
if socket_path.exists() {
tokio::fs::remove_file(&socket_path).await?;
}
*listener = Some(codex_uds::UnixListener::bind(&socket_path).await?);
return Err(err);
}
Ok(UpdateLoopControl::Stop)
}
}
async fn sleep_or_terminate(duration: Duration, terminate: &mut Signal) -> bool {
tokio::select! {
_ = sleep(duration) => false,
_ = terminate.recv() => true,
}
}
enum UpdateLoopControl {
Continue,
Stop,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum UpdateTrigger<'a> {
Scheduled,
Manual,
RestoreProduction(&'a str),
}
async fn update_once(
http: &impl InstallerHttp,
daemon: &Daemon,
running_updater_identity: &ExecutableIdentity,
terminate: &mut Signal,
trigger: UpdateTrigger<'_>,
) -> Result<(UpdateLoopControl, Option<RestartIfRunningOutcome>)> {
if trigger == UpdateTrigger::Scheduled
&& !UpdaterSettings::load(&daemon.settings_file)
.await?
.auto_update_enabled
{
return Ok((UpdateLoopControl::Stop, None));
}
if release_selection_unstable(daemon, trigger)? {
// An installer can be between changing current and publishing its
// latest-channel marker. Retry after the interval instead of exiting.
return Ok((UpdateLoopControl::Continue, None));
}
let (package_root, _, previous_release) = selected_release(daemon)?;
let codex_home = package_root
.parent()
.and_then(Path::parent)
.context("daemon package root has no Codex home")?;
let (installer_mode, installer_guard) =
if let UpdateTrigger::RestoreProduction(expected) = trigger {
anyhow::ensure!(
previous_release == expected,
"daemon selection changed; retry the update"
);
(
InstallerMode::RestoreProduction(&previous_release),
"CODEX_INSTALL_IF_CURRENT",
)
} else {
(
InstallerMode::Update(&previous_release),
"CODEX_INSTALL_IF_LATEST",
)
};
let started = std::time::Instant::now();
let script = tokio::select! {
result = fetch_installer_script(http) => crate::diagnostics::result("installer_fetch", started, result)?,
_ = terminate.recv() => return Ok((UpdateLoopControl::Stop, None)),
};
anyhow::ensure!(
script
.windows(installer_guard.len())
.any(|window| window == installer_guard.as_bytes()),
"standalone installer does not support {installer_guard} guarded updates"
);
if package_root.ends_with("app-server-daemon") {
anyhow::ensure!(
script
.windows(b"CODEX_INSTALL_DAEMON_ONLY".len())
.any(|window| window == b"CODEX_INSTALL_DAEMON_ONLY"),
"installer does not support daemon-owned packages"
);
}
if trigger == UpdateTrigger::Scheduled
&& !UpdaterSettings::load(&daemon.settings_file)
.await?
.auto_update_enabled
{
return Ok((UpdateLoopControl::Stop, None));
}
if release_selection_unstable(daemon, trigger)? {
return Ok((UpdateLoopControl::Continue, None));
}
anyhow::ensure!(
crate::managed_install::package_root(codex_home) == package_root,
"daemon package root changed during the update; retry the command"
);
let started = std::time::Instant::now();
#[cfg(unix)]
if matches!(
crate::diagnostics::result(
"installer_run",
started,
run_installer_script(&script, installer_mode, &package_root, terminate.recv()).await
)?,
UpdateLoopControl::Stop
) {
return Ok((UpdateLoopControl::Stop, None));
}
#[cfg(windows)]
tokio::select! {
result = run_installer_script(&script, installer_mode, &package_root) => { crate::diagnostics::result("installer_run", started, result)?; },
_ = terminate.recv() => return Ok((UpdateLoopControl::Stop, None)),
}
anyhow::ensure!(
trigger == UpdateTrigger::Scheduled || daemon.is_stable_standalone_release()?,
"installer did not select a stable latest release; retry the update"
);
if release_selection_unstable(daemon, trigger)? {
return Ok((UpdateLoopControl::Continue, None));
}
let managed_codex_bin =
resolved_managed_codex_bin(&daemon.current_managed_codex_bin()?).await?;
crate::diagnostics::event(
"package_selected",
serde_json::json!({
"release": selected_release(daemon).ok().map(|(_, _, release)| release),
"trigger": if trigger == UpdateTrigger::Scheduled { "scheduled" } else { "manual" },
}),
);
let restart_mode = match trigger {
UpdateTrigger::Manual | UpdateTrigger::RestoreProduction(_) => {
RestartMode::IfBinaryOrVersionChanged
}
// Updater adoption does not imply daemon replacement.
UpdateTrigger::Scheduled
if executable_identity(&managed_codex_bin).await? != *running_updater_identity =>
{
RestartMode::IfBinaryOrVersionChanged
}
UpdateTrigger::Scheduled => RestartMode::IfVersionChanged,
};
loop {
if terminate.recv().now_or_never().flatten().is_some() {
return Ok((UpdateLoopControl::Stop, None));
}
match daemon
.try_restart_if_running(restart_mode, &managed_codex_bin, &package_root)
.await?
{
RestartIfRunningOutcome::Busy => {
if sleep_or_terminate(RESTART_RETRY_INTERVAL, terminate).await {
return Ok((UpdateLoopControl::Stop, None));
}
}
RestartIfRunningOutcome::Restarted => {
return Ok((
UpdateLoopControl::Continue,
Some(RestartIfRunningOutcome::Restarted),
));
}
RestartIfRunningOutcome::NotRunning => {
return Ok((
UpdateLoopControl::Continue,
Some(RestartIfRunningOutcome::NotRunning),
));
}
RestartIfRunningOutcome::AlreadyCurrent
if restart_mode == RestartMode::IfBinaryOrVersionChanged =>
{
anyhow::ensure!(
daemon.is_stable_standalone_release()?
&& resolved_managed_codex_bin(&daemon.current_managed_codex_bin()?).await?
== managed_codex_bin,
"managed daemon changed during the update; retry"
);
return Ok((
UpdateLoopControl::Continue,
Some(RestartIfRunningOutcome::AlreadyCurrent),
));
}
RestartIfRunningOutcome::NotReady
if trigger == UpdateTrigger::Scheduled
&& restart_mode == RestartMode::IfBinaryOrVersionChanged =>
{
return Ok((
UpdateLoopControl::Continue,
Some(RestartIfRunningOutcome::NotReady),
));
}
RestartIfRunningOutcome::NotReady | RestartIfRunningOutcome::AlreadyCurrent => {
anyhow::ensure!(
trigger == UpdateTrigger::Scheduled,
"managed daemon could not restart; retry when it is ready"
);
return Ok((
if daemon.is_stable_standalone_release()? {
UpdateLoopControl::Continue
} else {
UpdateLoopControl::Stop
},
None,
));
}
}
}
}
fn release_selection_unstable(daemon: &Daemon, trigger: UpdateTrigger<'_>) -> Result<bool> {
if daemon.is_stable_standalone_release()?
|| matches!(trigger, UpdateTrigger::RestoreProduction(_))
&& manual_update::supported(daemon)?
{
return Ok(false);
}
anyhow::ensure!(
trigger == UpdateTrigger::Scheduled,
"standalone install selection changed during the update"
);
Ok(true)
}
fn selected_release(daemon: &Daemon) -> Result<(std::path::PathBuf, std::path::PathBuf, String)> {
let home = daemon
.settings_file
.parent()
.and_then(Path::parent)
.context("daemon settings path has no Codex home")?;
let root = crate::managed_install::package_root(home);
let release = std::fs::canonicalize(root.join("current"))?;
let name = release
.file_name()
.context("managed release has no name")?
.to_string_lossy()
.into_owned();
Ok((root, release, name))
}
async fn current_updater_identity() -> Result<ExecutableIdentity> {
let current_exe =
std::env::current_exe().context("failed to resolve current updater executable")?;
executable_identity(&current_exe).await
}
#[cfg(unix)]
pub(crate) fn reexec_managed_updater(managed_codex_bin: &Path, state_dir: &Path) -> Result<()> {
let mut command = StdCommand::new(managed_codex_bin);
command.args(["app-server", "daemon", "pid-update-loop"]);
crate::background_command::set_working_directory(&mut command, state_dir)?;
let err = command.exec();
Err(err).with_context(|| {
format!(
"failed to replace updater with managed Codex binary {}",
managed_codex_bin.display()
)
})
}
enum InstallerMode<'a> {
Update(&'a str),
RestoreProduction(&'a str),
Migration,
}
async fn run_installer_script(
script: &[u8],
mode: InstallerMode<'_>,
package_root: &Path,
#[cfg(unix)] terminate: impl std::future::Future<Output = Option<()>>,
) -> Result<UpdateLoopControl> {
#[cfg(unix)]
let mut command = {
let mut command = Command::new("/bin/sh");
command.arg("-s");
command.process_group(0);
command
};
#[cfg(windows)]
let mut command = {
let mut command = Command::new("powershell.exe");
command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
command.args(["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { Invoke-Expression ([Console]::In.ReadToEnd()) } catch { Write-Error $_; exit 1 }"])
.kill_on_drop(true);
command
};
let (latest_guard, current_guard, previous_release, defer_selection) = match mode {
InstallerMode::Update(release) => ("1", "0", release, "0"),
InstallerMode::RestoreProduction(release) => ("0", "1", release, "0"),
InstallerMode::Migration => ("0", "0", "", "1"),
};
let mut child = command
.env(
"CODEX_HOME",
package_root
.parent()
.and_then(Path::parent)
.context("package root has no Codex home")?,
)
.env("CODEX_INSTALL_DEFER_SELECTION", defer_selection)
.env(
"CODEX_INSTALL_DAEMON_ONLY",
if package_root.ends_with("app-server-daemon") {
"1"
} else {
"0"
},
)
.env("CODEX_RELEASE", "latest")
.env("CODEX_NON_INTERACTIVE", "1")
.env("CODEX_INSTALL_IF_LATEST", latest_guard)
.env("CODEX_INSTALL_IF_CURRENT", current_guard)
.env("CODEX_UPDATE_FROM_RELEASE", previous_release)
.kill_on_drop(true)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.context("failed to invoke standalone Codex updater")?;
let mut stderr = child
.stderr
.take()
.context("standalone Codex updater stderr was unavailable")?;
let stderr_tail = Arc::new(Mutex::new(VecDeque::with_capacity(
INSTALLER_STDERR_TAIL_BYTES,
)));
let captured_tail = Arc::clone(&stderr_tail);
let mut stderr_task = tokio::spawn(async move {
let mut buf = [0; 4096];
loop {
let read = stderr.read(&mut buf).await?;
if read == 0 {
return Ok::<_, std::io::Error>(());
}
let Ok(mut tail) = captured_tail.lock() else {
return Ok(());
};
if read >= INSTALLER_STDERR_TAIL_BYTES {
tail.clear();
tail.extend(
buf[read - INSTALLER_STDERR_TAIL_BYTES..read]
.iter()
.copied(),
);
} else {
let retained = INSTALLER_STDERR_TAIL_BYTES - read;
if tail.len() > retained {
let remove = tail.len() - retained;
tail.drain(..remove);
}
tail.extend(buf[..read].iter().copied());
}
}
});
#[cfg(windows)]
let _installer_job = crate::backend::windows::installer_job(&child)?;
let mut stdin = child
.stdin
.take()
.context("standalone Codex updater stdin was unavailable")?;
#[cfg(unix)]
let mut terminate = std::pin::pin!(terminate);
#[cfg(unix)]
let write_result = tokio::select! {
result = stdin.write_all(script) => Some(result),
_ = &mut terminate => None,
};
#[cfg(windows)]
let write_result = Some(stdin.write_all(script).await);
drop(stdin);
#[cfg(unix)]
if write_result.is_none() {
cancel_installer(&mut child, package_root).await;
stderr_task.abort();
return Ok(UpdateLoopControl::Stop);
}
if let Some(Err(err)) = write_result {
stderr_task.abort();
return Err(err).context("failed to pass standalone Codex updater to shell");
}
#[cfg(unix)]
let status = tokio::select! {
result = child.wait() => result,
_ = &mut terminate => {
cancel_installer(&mut child, package_root).await;
return Ok(UpdateLoopControl::Stop);
}
};
#[cfg(windows)]
let status = child.wait().await;
let status = match status {
Ok(status) => status,
Err(err) => {
stderr_task.abort();
return Err(err).context("failed to wait for standalone Codex updater");
}
};
if status.success() {
stderr_task.abort();
Ok(UpdateLoopControl::Continue)
} else {
let _ = tokio::time::timeout(INSTALLER_STDERR_DRAIN_TIMEOUT, &mut stderr_task).await;
stderr_task.abort();
let bytes = stderr_tail
.lock()
.map(|tail| tail.iter().copied().collect::<Vec<_>>())
.unwrap_or_default();
let detail = String::from_utf8_lossy(&bytes);
let detail = detail.trim();
if detail.is_empty() {
anyhow::bail!("standalone Codex updater exited with status {status}")
}
anyhow::bail!("standalone Codex updater exited with status {status}:\n{detail}")
}
}
#[cfg(unix)]
async fn cancel_installer(child: &mut tokio::process::Child, package_root: &Path) {
let Some(pid) = child.id().and_then(|pid| libc::pid_t::try_from(pid).ok()) else {
return;
};
// Let the shell's EXIT/TERM trap release the installer lock first.
unsafe { libc::kill(-pid, libc::SIGTERM) };
sleep(Duration::from_secs(2)).await;
// Keep the shell unreaped until after the group kill, so its PID cannot
// be reused while descendants that ignored TERM are still running.
unsafe { libc::kill(-pid, libc::SIGKILL) };
// A forced kill can bypass the shell trap on hosts using the mkdir lock.
// The lock is ours only if its recorded owner is this still-unreaped shell.
let lock = package_root.join("install.lock.d");
if std::fs::read_to_string(lock.join("pid")).is_ok_and(|owner| owner.trim() == pid.to_string())
{
let _ = std::fs::remove_dir_all(lock);
}
let _ = child.wait().await;
}
async fn fetch_installer_script(http: &impl InstallerHttp) -> Result<Vec<u8>> {
match http.get(INSTALL_URL).await? {
InstallerResponse::Success(body) => Ok(body),
InstallerResponse::Unsuccessful { status } => {
anyhow::bail!("standalone Codex updater request failed with status {status}")
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum InstallerResponse {
Success(Vec<u8>),
Unsuccessful { status: u16 },
}
/// HTTP boundary used to download the standalone installer.
///
/// Implementations must issue a GET for the supplied URL, return exact response bytes for a
/// successful status, and report a non-success status without buffering its response body.
trait InstallerHttp: Send + Sync {
fn get<'a>(
&'a self,
url: &'a str,
) -> impl std::future::Future<Output = Result<InstallerResponse>> + Send + 'a;
}
impl InstallerHttp for RouteAwareClientPool {
async fn get(&self, url: &str) -> Result<InstallerResponse> {
let response = RouteAwareClientPool::get(self, url)
.send()
.await
.context("failed to fetch standalone Codex updater")?;
if !response.status().is_success() {
return Ok(InstallerResponse::Unsuccessful {
status: response.status().as_u16(),
});
}
let body = response
.bytes()
.await
.context("failed to read standalone Codex updater")?
.to_vec();
Ok(InstallerResponse::Success(body))
}
}
#[cfg(test)]
#[path = "update_loop_tests.rs"]
mod tests;
#[cfg(windows)]
struct Signal;
#[cfg(windows)]
impl Signal {
async fn recv(&mut self) -> Option<()> {
// An unreadable control path must stop the updater rather than disable shutdown.
let _ = codex_app_server_transport::daemon_shutdown_signal().await;
Some(())
}
}

File diff suppressed because it is too large Load Diff