chore: ultra-clean artifacts (#13577)

See the readme
This commit is contained in:
jif-oai
2026-03-05 13:03:01 +00:00
committed by GitHub
parent 0cc6835416
commit 5e92f4af12
12 changed files with 1300 additions and 962 deletions
+28
View File
@@ -0,0 +1,28 @@
use codex_package_manager::PackageManagerError;
use std::path::PathBuf;
use thiserror::Error;
/// Errors raised while locating, validating, or installing an artifact runtime.
#[derive(Debug, Error)]
pub enum ArtifactRuntimeError {
#[error(transparent)]
PackageManager(#[from] PackageManagerError),
#[error("{context}")]
Io {
context: String,
#[source]
source: std::io::Error,
},
#[error("invalid manifest at {path}")]
InvalidManifest {
path: PathBuf,
#[source]
source: serde_json::Error,
},
#[error("runtime path `{0}` is invalid")]
InvalidRuntimePath(String),
#[error(
"no compatible JavaScript runtime found for artifact runtime at {root_dir}; install Node or the Codex desktop app"
)]
MissingJsRuntime { root_dir: PathBuf },
}
+200
View File
@@ -0,0 +1,200 @@
use super::ArtifactRuntimeError;
use super::ArtifactRuntimePlatform;
use super::ExtractedRuntimeManifest;
use super::JsRuntime;
use super::codex_app_runtime_candidates;
use super::resolve_js_runtime_from_candidates;
use super::system_electron_runtime;
use super::system_node_runtime;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
/// Loads a previously installed runtime from a caller-provided cache root.
pub fn load_cached_runtime(
cache_root: &Path,
runtime_version: &str,
) -> Result<InstalledArtifactRuntime, ArtifactRuntimeError> {
let platform = ArtifactRuntimePlatform::detect_current()?;
let install_dir = cached_runtime_install_dir(cache_root, runtime_version, platform);
if !install_dir.exists() {
return Err(ArtifactRuntimeError::Io {
context: format!(
"artifact runtime {runtime_version} is not installed at {}",
install_dir.display()
),
source: std::io::Error::new(std::io::ErrorKind::NotFound, "missing artifact runtime"),
});
}
InstalledArtifactRuntime::load(install_dir, platform)
}
/// A validated runtime installation extracted into the local package cache.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InstalledArtifactRuntime {
root_dir: PathBuf,
runtime_version: String,
platform: ArtifactRuntimePlatform,
manifest: ExtractedRuntimeManifest,
node_path: PathBuf,
build_js_path: PathBuf,
render_cli_path: PathBuf,
}
impl InstalledArtifactRuntime {
/// Creates an installed-runtime value from prevalidated paths.
pub fn new(
root_dir: PathBuf,
runtime_version: String,
platform: ArtifactRuntimePlatform,
manifest: ExtractedRuntimeManifest,
node_path: PathBuf,
build_js_path: PathBuf,
render_cli_path: PathBuf,
) -> Self {
Self {
root_dir,
runtime_version,
platform,
manifest,
node_path,
build_js_path,
render_cli_path,
}
}
/// Loads and validates an extracted runtime directory.
pub fn load(
root_dir: PathBuf,
platform: ArtifactRuntimePlatform,
) -> Result<Self, ArtifactRuntimeError> {
let manifest_path = root_dir.join("manifest.json");
let manifest_bytes =
std::fs::read(&manifest_path).map_err(|source| ArtifactRuntimeError::Io {
context: format!("failed to read {}", manifest_path.display()),
source,
})?;
let manifest = serde_json::from_slice::<ExtractedRuntimeManifest>(&manifest_bytes)
.map_err(|source| ArtifactRuntimeError::InvalidManifest {
path: manifest_path,
source,
})?;
let node_path = resolve_relative_runtime_path(&root_dir, &manifest.node.relative_path)?;
let build_js_path =
resolve_relative_runtime_path(&root_dir, &manifest.entrypoints.build_js.relative_path)?;
let render_cli_path = resolve_relative_runtime_path(
&root_dir,
&manifest.entrypoints.render_cli.relative_path,
)?;
verify_required_runtime_path(&build_js_path)?;
verify_required_runtime_path(&render_cli_path)?;
Ok(Self::new(
root_dir,
manifest.runtime_version.clone(),
platform,
manifest,
node_path,
build_js_path,
render_cli_path,
))
}
/// Returns the extracted runtime root directory.
pub fn root_dir(&self) -> &Path {
&self.root_dir
}
/// Returns the runtime version recorded in the extracted manifest.
pub fn runtime_version(&self) -> &str {
&self.runtime_version
}
/// Returns the platform this runtime was installed for.
pub fn platform(&self) -> ArtifactRuntimePlatform {
self.platform
}
/// Returns the parsed extracted-runtime manifest.
pub fn manifest(&self) -> &ExtractedRuntimeManifest {
&self.manifest
}
/// Returns the bundled Node executable path advertised by the runtime manifest.
pub fn node_path(&self) -> &Path {
&self.node_path
}
/// Returns the artifact build entrypoint path.
pub fn build_js_path(&self) -> &Path {
&self.build_js_path
}
/// Returns the artifact render CLI entrypoint path.
pub fn render_cli_path(&self) -> &Path {
&self.render_cli_path
}
/// Resolves the best executable to use for artifact commands.
///
/// Preference order is the bundled Node path, then a machine Node install,
/// then Electron from the machine or a Codex desktop app bundle.
pub fn resolve_js_runtime(&self) -> Result<JsRuntime, ArtifactRuntimeError> {
resolve_js_runtime_from_candidates(
Some(self.node_path()),
system_node_runtime(),
system_electron_runtime(),
codex_app_runtime_candidates(),
)
.ok_or_else(|| ArtifactRuntimeError::MissingJsRuntime {
root_dir: self.root_dir.clone(),
})
}
}
pub(crate) fn cached_runtime_install_dir(
cache_root: &Path,
runtime_version: &str,
platform: ArtifactRuntimePlatform,
) -> PathBuf {
cache_root.join(runtime_version).join(platform.as_str())
}
pub(crate) fn default_cached_runtime_root(codex_home: &Path) -> PathBuf {
codex_home.join(super::DEFAULT_CACHE_ROOT_RELATIVE)
}
fn resolve_relative_runtime_path(
root_dir: &Path,
relative_path: &str,
) -> Result<PathBuf, ArtifactRuntimeError> {
let relative = Path::new(relative_path);
if relative.as_os_str().is_empty() || relative.is_absolute() {
return Err(ArtifactRuntimeError::InvalidRuntimePath(
relative_path.to_string(),
));
}
if relative.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::Prefix(_) | Component::RootDir
)
}) {
return Err(ArtifactRuntimeError::InvalidRuntimePath(
relative_path.to_string(),
));
}
Ok(root_dir.join(relative))
}
fn verify_required_runtime_path(path: &Path) -> Result<(), ArtifactRuntimeError> {
if path.is_file() {
return Ok(());
}
Err(ArtifactRuntimeError::Io {
context: format!("required runtime file is missing: {}", path.display()),
source: std::io::Error::new(std::io::ErrorKind::NotFound, "missing runtime file"),
})
}
@@ -0,0 +1,177 @@
use crate::ArtifactRuntimePlatform;
use crate::runtime::default_cached_runtime_root;
use crate::runtime::load_cached_runtime;
use std::path::Path;
use std::path::PathBuf;
use which::which;
const CODEX_APP_PRODUCT_NAMES: [&str; 6] = [
"Codex",
"Codex (Dev)",
"Codex (Agent)",
"Codex (Nightly)",
"Codex (Alpha)",
"Codex (Beta)",
];
/// The JavaScript runtime used to execute the artifact tool.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum JsRuntimeKind {
Node,
Electron,
}
/// A discovered JavaScript executable and the way it should be invoked.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JsRuntime {
executable_path: PathBuf,
kind: JsRuntimeKind,
}
impl JsRuntime {
pub(crate) fn node(executable_path: PathBuf) -> Self {
Self {
executable_path,
kind: JsRuntimeKind::Node,
}
}
pub(crate) fn electron(executable_path: PathBuf) -> Self {
Self {
executable_path,
kind: JsRuntimeKind::Electron,
}
}
/// Returns the executable to spawn for artifact commands.
pub fn executable_path(&self) -> &Path {
&self.executable_path
}
/// Returns whether the command must set `ELECTRON_RUN_AS_NODE=1`.
pub fn requires_electron_run_as_node(&self) -> bool {
self.kind == JsRuntimeKind::Electron
}
}
/// Returns `true` when artifact execution can find both runtime assets and a JS executable.
pub fn is_js_runtime_available(codex_home: &Path, runtime_version: &str) -> bool {
load_cached_runtime(&default_cached_runtime_root(codex_home), runtime_version)
.ok()
.and_then(|runtime| runtime.resolve_js_runtime().ok())
.or_else(resolve_machine_js_runtime)
.is_some()
}
/// Returns `true` when this machine can use the managed artifact runtime flow.
///
/// This is a platform capability check, not a cache or binary availability check.
/// Callers that rely on `ArtifactRuntimeManager::ensure_installed()` should use this
/// to decide whether the feature can be exposed on the current machine.
pub fn can_manage_artifact_runtime() -> bool {
ArtifactRuntimePlatform::detect_current().is_ok()
}
pub(crate) fn resolve_machine_js_runtime() -> Option<JsRuntime> {
resolve_js_runtime_from_candidates(
None,
system_node_runtime(),
system_electron_runtime(),
codex_app_runtime_candidates(),
)
}
pub(crate) fn resolve_js_runtime_from_candidates(
preferred_node_path: Option<&Path>,
node_runtime: Option<JsRuntime>,
electron_runtime: Option<JsRuntime>,
codex_app_candidates: Vec<PathBuf>,
) -> Option<JsRuntime> {
preferred_node_path
.and_then(node_runtime_from_path)
.or(node_runtime)
.or(electron_runtime)
.or_else(|| {
codex_app_candidates
.into_iter()
.find_map(|candidate| electron_runtime_from_path(&candidate))
})
}
pub(crate) fn system_node_runtime() -> Option<JsRuntime> {
which("node")
.ok()
.and_then(|path| node_runtime_from_path(&path))
}
pub(crate) fn system_electron_runtime() -> Option<JsRuntime> {
which("electron")
.ok()
.and_then(|path| electron_runtime_from_path(&path))
}
pub(crate) fn node_runtime_from_path(path: &Path) -> Option<JsRuntime> {
path.is_file().then(|| JsRuntime::node(path.to_path_buf()))
}
pub(crate) fn electron_runtime_from_path(path: &Path) -> Option<JsRuntime> {
path.is_file()
.then(|| JsRuntime::electron(path.to_path_buf()))
}
pub(crate) fn codex_app_runtime_candidates() -> Vec<PathBuf> {
match std::env::consts::OS {
"macos" => {
let mut roots = vec![PathBuf::from("/Applications")];
if let Some(home) = std::env::var_os("HOME") {
roots.push(PathBuf::from(home).join("Applications"));
}
roots
.into_iter()
.flat_map(|root| {
CODEX_APP_PRODUCT_NAMES
.into_iter()
.map(move |product_name| {
root.join(format!("{product_name}.app"))
.join("Contents")
.join("MacOS")
.join(product_name)
})
})
.collect()
}
"windows" => {
let mut roots = Vec::new();
if let Some(local_app_data) = std::env::var_os("LOCALAPPDATA") {
roots.push(PathBuf::from(local_app_data).join("Programs"));
}
if let Some(program_files) = std::env::var_os("ProgramFiles") {
roots.push(PathBuf::from(program_files));
}
if let Some(program_files_x86) = std::env::var_os("ProgramFiles(x86)") {
roots.push(PathBuf::from(program_files_x86));
}
roots
.into_iter()
.flat_map(|root| {
CODEX_APP_PRODUCT_NAMES
.into_iter()
.map(move |product_name| {
root.join(product_name).join(format!("{product_name}.exe"))
})
})
.collect()
}
"linux" => [PathBuf::from("/opt"), PathBuf::from("/usr/lib")]
.into_iter()
.flat_map(|root| {
CODEX_APP_PRODUCT_NAMES
.into_iter()
.map(move |product_name| root.join(product_name).join(product_name))
})
.collect(),
_ => Vec::new(),
}
}
+253
View File
@@ -0,0 +1,253 @@
use super::ArtifactRuntimeError;
use super::ArtifactRuntimePlatform;
use super::InstalledArtifactRuntime;
use super::ReleaseManifest;
use codex_package_manager::ManagedPackage;
use codex_package_manager::PackageManager;
use codex_package_manager::PackageManagerConfig;
use codex_package_manager::PackageManagerError;
use codex_package_manager::PackageReleaseArchive;
use reqwest::Client;
use std::path::Path;
use std::path::PathBuf;
use url::Url;
/// Release tag prefix used for artifact runtime assets.
pub const DEFAULT_RELEASE_TAG_PREFIX: &str = "artifact-runtime-v";
/// Relative cache root for installed artifact runtimes under `codex_home`.
pub const DEFAULT_CACHE_ROOT_RELATIVE: &str = "packages/artifacts";
/// Base URL used by default when downloading runtime assets from GitHub releases.
pub const DEFAULT_RELEASE_BASE_URL: &str = "https://github.com/openai/codex/releases/download/";
/// Describes where a particular artifact runtime release can be downloaded from.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ArtifactRuntimeReleaseLocator {
base_url: Url,
runtime_version: String,
release_tag_prefix: String,
}
impl ArtifactRuntimeReleaseLocator {
/// Creates a locator for a runtime version under a release base URL.
pub fn new(base_url: Url, runtime_version: impl Into<String>) -> Self {
Self {
base_url,
runtime_version: runtime_version.into(),
release_tag_prefix: DEFAULT_RELEASE_TAG_PREFIX.to_string(),
}
}
/// Overrides the release-tag prefix used when constructing asset names.
pub fn with_tag_prefix(mut self, release_tag_prefix: impl Into<String>) -> Self {
self.release_tag_prefix = release_tag_prefix.into();
self
}
/// Returns the release asset base URL.
pub fn base_url(&self) -> &Url {
&self.base_url
}
/// Returns the expected runtime version.
pub fn runtime_version(&self) -> &str {
&self.runtime_version
}
/// Returns the full release tag for the runtime version.
pub fn release_tag(&self) -> String {
format!("{}{}", self.release_tag_prefix, self.runtime_version)
}
/// Returns the expected manifest filename for the release.
pub fn manifest_file_name(&self) -> String {
format!("{}-manifest.json", self.release_tag())
}
/// Returns the manifest URL for this runtime release.
pub fn manifest_url(&self) -> Result<Url, PackageManagerError> {
self.base_url
.join(&format!(
"{}/{}",
self.release_tag(),
self.manifest_file_name()
))
.map_err(PackageManagerError::InvalidBaseUrl)
}
/// Returns the default GitHub-release locator for a runtime version.
pub fn default(runtime_version: impl Into<String>) -> Self {
Self::new(
match Url::parse(DEFAULT_RELEASE_BASE_URL) {
Ok(url) => url,
Err(error) => {
panic!("hard-coded artifact runtime release base URL must be valid: {error}")
}
},
runtime_version,
)
}
}
/// Configuration for resolving artifact runtimes under a Codex home directory.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ArtifactRuntimeManagerConfig {
package_manager: PackageManagerConfig<ArtifactRuntimePackage>,
release: ArtifactRuntimeReleaseLocator,
}
impl ArtifactRuntimeManagerConfig {
/// Creates a runtime-manager config from a Codex home and explicit release locator.
pub fn new(codex_home: PathBuf, release: ArtifactRuntimeReleaseLocator) -> Self {
Self {
package_manager: PackageManagerConfig::new(
codex_home,
ArtifactRuntimePackage::new(release.clone()),
),
release,
}
}
/// Creates a runtime-manager config that downloads from the default GitHub release location.
pub fn with_default_release(codex_home: PathBuf, runtime_version: impl Into<String>) -> Self {
Self::new(
codex_home,
ArtifactRuntimeReleaseLocator::default(runtime_version),
)
}
/// Overrides the runtime cache root.
pub fn with_cache_root(mut self, cache_root: PathBuf) -> Self {
self.package_manager = self.package_manager.with_cache_root(cache_root);
self
}
/// Returns the runtime cache root.
pub fn cache_root(&self) -> PathBuf {
self.package_manager.cache_root()
}
/// Returns the release locator used by this config.
pub fn release(&self) -> &ArtifactRuntimeReleaseLocator {
&self.release
}
}
/// Package-manager-backed artifact runtime resolver and installer.
#[derive(Clone, Debug)]
pub struct ArtifactRuntimeManager {
package_manager: PackageManager<ArtifactRuntimePackage>,
config: ArtifactRuntimeManagerConfig,
}
impl ArtifactRuntimeManager {
/// Creates a runtime manager using the default `reqwest` client.
pub fn new(config: ArtifactRuntimeManagerConfig) -> Self {
let package_manager = PackageManager::new(config.package_manager.clone());
Self {
package_manager,
config,
}
}
/// Creates a runtime manager with a caller-provided HTTP client.
pub fn with_client(config: ArtifactRuntimeManagerConfig, client: Client) -> Self {
let package_manager = PackageManager::with_client(config.package_manager.clone(), client);
Self {
package_manager,
config,
}
}
/// Returns the manager configuration.
pub fn config(&self) -> &ArtifactRuntimeManagerConfig {
&self.config
}
/// Returns the installed runtime if it is already present and valid.
pub async fn resolve_cached(
&self,
) -> Result<Option<InstalledArtifactRuntime>, ArtifactRuntimeError> {
self.package_manager.resolve_cached().await
}
/// Returns the installed runtime, downloading and caching it if necessary.
pub async fn ensure_installed(&self) -> Result<InstalledArtifactRuntime, ArtifactRuntimeError> {
self.package_manager.ensure_installed().await
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct ArtifactRuntimePackage {
release: ArtifactRuntimeReleaseLocator,
}
impl ArtifactRuntimePackage {
fn new(release: ArtifactRuntimeReleaseLocator) -> Self {
Self { release }
}
}
impl ManagedPackage for ArtifactRuntimePackage {
type Error = ArtifactRuntimeError;
type Installed = InstalledArtifactRuntime;
type ReleaseManifest = ReleaseManifest;
fn default_cache_root_relative(&self) -> &str {
DEFAULT_CACHE_ROOT_RELATIVE
}
fn version(&self) -> &str {
self.release.runtime_version()
}
fn manifest_url(&self) -> Result<Url, PackageManagerError> {
self.release.manifest_url()
}
fn archive_url(&self, archive: &PackageReleaseArchive) -> Result<Url, PackageManagerError> {
self.release
.base_url()
.join(&format!(
"{}/{}",
self.release.release_tag(),
archive.archive
))
.map_err(PackageManagerError::InvalidBaseUrl)
}
fn release_version<'a>(&self, manifest: &'a Self::ReleaseManifest) -> &'a str {
&manifest.runtime_version
}
fn platform_archive(
&self,
manifest: &Self::ReleaseManifest,
platform: ArtifactRuntimePlatform,
) -> Result<PackageReleaseArchive, Self::Error> {
manifest
.platforms
.get(platform.as_str())
.cloned()
.ok_or_else(|| {
PackageManagerError::MissingPlatform(platform.as_str().to_string()).into()
})
}
fn install_dir(&self, cache_root: &Path, platform: ArtifactRuntimePlatform) -> PathBuf {
cache_root.join(self.version()).join(platform.as_str())
}
fn installed_version<'a>(&self, package: &'a Self::Installed) -> &'a str {
package.runtime_version()
}
fn load_installed(
&self,
root_dir: PathBuf,
platform: ArtifactRuntimePlatform,
) -> Result<Self::Installed, Self::Error> {
InstalledArtifactRuntime::load(root_dir, platform)
}
}
@@ -0,0 +1,37 @@
use codex_package_manager::PackageReleaseArchive;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
/// Release metadata published alongside the packaged artifact runtime.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct ReleaseManifest {
pub schema_version: u32,
pub runtime_version: String,
pub release_tag: String,
#[serde(default)]
pub node_version: Option<String>,
pub platforms: BTreeMap<String, PackageReleaseArchive>,
}
/// Manifest shipped inside the extracted runtime payload.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct ExtractedRuntimeManifest {
pub schema_version: u32,
pub runtime_version: String,
pub node: RuntimePathEntry,
pub entrypoints: RuntimeEntrypoints,
}
/// A relative path entry inside an extracted runtime manifest.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct RuntimePathEntry {
pub relative_path: String,
}
/// Entrypoints required to build and render artifacts.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct RuntimeEntrypoints {
pub build_js: RuntimePathEntry,
pub render_cli: RuntimePathEntry,
}
+30
View File
@@ -0,0 +1,30 @@
mod error;
mod installed;
mod js_runtime;
mod manager;
mod manifest;
pub use codex_package_manager::PackagePlatform as ArtifactRuntimePlatform;
pub use error::ArtifactRuntimeError;
pub use installed::InstalledArtifactRuntime;
pub use installed::load_cached_runtime;
pub use js_runtime::JsRuntime;
pub use js_runtime::JsRuntimeKind;
pub use js_runtime::can_manage_artifact_runtime;
pub use js_runtime::is_js_runtime_available;
pub use manager::ArtifactRuntimeManager;
pub use manager::ArtifactRuntimeManagerConfig;
pub use manager::ArtifactRuntimeReleaseLocator;
pub use manager::DEFAULT_CACHE_ROOT_RELATIVE;
pub use manager::DEFAULT_RELEASE_BASE_URL;
pub use manager::DEFAULT_RELEASE_TAG_PREFIX;
pub use manifest::ExtractedRuntimeManifest;
pub use manifest::ReleaseManifest;
pub use manifest::RuntimeEntrypoints;
pub use manifest::RuntimePathEntry;
pub(crate) use installed::default_cached_runtime_root;
pub(crate) use js_runtime::codex_app_runtime_candidates;
pub(crate) use js_runtime::resolve_js_runtime_from_candidates;
pub(crate) use js_runtime::system_electron_runtime;
pub(crate) use js_runtime::system_node_runtime;