feat: add proxypilot-rs codex proxy shell

This commit is contained in:
RCD
2026-04-05 14:19:51 +07:00
parent 388a7a127d
commit 85687a4ab7
7 changed files with 3017 additions and 0 deletions
+2345
View File
File diff suppressed because it is too large Load Diff
+33
View File
@@ -0,0 +1,33 @@
use std::path::PathBuf;
use clap::{Parser, Subcommand};
#[derive(Debug, Parser)]
#[command(name = "proxypilot-rs")]
#[command(about = "Experimental terminal-first Rust replatform for ProxyPilot")]
#[command(version)]
pub struct Cli {
#[command(subcommand)]
pub command: Command,
}
#[derive(Debug, Subcommand)]
pub enum Command {
/// Write an example config to disk.
Init {
#[arg(long, default_value = "proxypilot-rs.toml")]
config: PathBuf,
#[arg(long, default_value_t = false)]
force: bool,
},
/// Run the local proxy server.
Run {
#[arg(long, default_value = "proxypilot-rs.toml")]
config: PathBuf,
},
/// Open a terminal operator view for the Rust rewrite.
Tui {
#[arg(long, default_value = "proxypilot-rs.toml")]
config: PathBuf,
},
}
+154
View File
@@ -0,0 +1,154 @@
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig {
#[serde(default)]
pub server: ServerConfig,
#[serde(default)]
pub codex: CodexConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
#[serde(default = "default_bind")]
pub bind: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodexConfig {
#[serde(default = "default_codex_base_url")]
pub upstream_base_url: String,
#[serde(default)]
pub api_key: String,
}
impl Default for AppConfig {
fn default() -> Self {
Self {
server: ServerConfig::default(),
codex: CodexConfig::default(),
}
}
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
bind: default_bind(),
}
}
}
impl Default for CodexConfig {
fn default() -> Self {
Self {
upstream_base_url: default_codex_base_url(),
api_key: "set-me".to_string(),
}
}
}
impl AppConfig {
pub fn load(path: &Path) -> Result<Self> {
let raw = fs::read_to_string(path)
.with_context(|| format!("failed to read config at {}", path.display()))?;
let config: Self = toml::from_str(&raw)
.with_context(|| format!("failed to parse TOML config at {}", path.display()))?;
config.validate()?;
Ok(config)
}
pub fn write_example(path: &Path, force: bool) -> Result<()> {
if path.exists() && !force {
bail!(
"config already exists at {} (pass --force to overwrite)",
path.display()
);
}
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
{
fs::create_dir_all(parent).with_context(|| {
format!("failed to create config directory {}", parent.display())
})?;
}
fs::write(path, Self::example_toml())
.with_context(|| format!("failed to write example config to {}", path.display()))?;
Ok(())
}
pub fn validate(&self) -> Result<()> {
if self.server.bind.trim().is_empty() {
bail!("server.bind cannot be empty");
}
if self.codex.upstream_base_url.trim().is_empty() {
bail!("codex.upstream_base_url cannot be empty");
}
Ok(())
}
pub fn health_url(&self) -> String {
format!("http://{}/healthz", self.server.bind)
}
pub fn config_summary(&self, path: &Path) -> Vec<String> {
vec![
format!("config: {}", path.display()),
format!("listen: {}", self.server.bind),
format!("codex upstream: {}", self.codex.upstream_base_url),
format!(
"codex api key: {}",
if self.codex.api_key.trim().is_empty() {
"missing"
} else {
"configured"
}
),
]
}
pub fn example_toml() -> &'static str {
r#"# ProxyPilot Rust replatform config
#
# This first milestone keeps the config deliberately small:
# one local bind address and one Codex-compatible upstream.
[server]
bind = "127.0.0.1:8318"
[codex]
upstream_base_url = "https://api.openai.com"
api_key = "set-me"
"#
}
}
pub fn default_config_path() -> PathBuf {
PathBuf::from("proxypilot-rs.toml")
}
fn default_bind() -> String {
"127.0.0.1:8318".to_string()
}
fn default_codex_base_url() -> String {
"https://api.openai.com".to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_example_config() {
let config: AppConfig = toml::from_str(AppConfig::example_toml()).unwrap();
assert_eq!(config.server.bind, "127.0.0.1:8318");
assert_eq!(config.codex.upstream_base_url, "https://api.openai.com");
}
}
+4
View File
@@ -0,0 +1,4 @@
pub mod cli;
pub mod config;
pub mod proxy;
pub mod tui;
+49
View File
@@ -0,0 +1,49 @@
use std::path::PathBuf;
use anyhow::Result;
use clap::Parser;
use proxypilot_rs::cli::{Cli, Command};
use proxypilot_rs::config::{AppConfig, default_config_path};
use tracing_subscriber::EnvFilter;
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("proxypilot_rs=info,tower_http=info")),
)
.with_target(false)
.compact()
.init();
let cli = Cli::parse();
match cli.command {
Command::Init { config, force } => {
let path = resolve_config_path(config);
AppConfig::write_example(&path, force)?;
println!("wrote {}", path.display());
}
Command::Run { config } => {
let path = resolve_config_path(config);
let config = AppConfig::load(&path)?;
proxypilot_rs::proxy::run(config).await?;
}
Command::Tui { config } => {
let path = resolve_config_path(config);
let config = AppConfig::load(&path)?;
proxypilot_rs::tui::run(config, &path).await?;
}
}
Ok(())
}
fn resolve_config_path(path: PathBuf) -> PathBuf {
if path.as_os_str().is_empty() {
default_config_path()
} else {
path
}
}
+268
View File
@@ -0,0 +1,268 @@
use std::net::SocketAddr;
use std::sync::Arc;
use anyhow::{Context, Result};
use axum::body::{Body, Bytes};
use axum::extract::{OriginalUri, Path, State};
use axum::http::{HeaderMap, Method, Response, StatusCode};
use axum::response::IntoResponse;
use axum::routing::{any, get};
use axum::{Json, Router};
use reqwest::Client;
use serde_json::json;
use tracing::info;
use crate::config::AppConfig;
#[derive(Clone)]
pub struct AppState {
config: Arc<AppConfig>,
client: Client,
}
impl AppState {
pub fn new(config: AppConfig) -> Self {
Self {
config: Arc::new(config),
client: Client::new(),
}
}
}
pub fn build_app(config: AppConfig) -> Router {
let state = AppState::new(config);
Router::new()
.route("/healthz", get(healthz))
.route("/v1/{*path}", any(proxy_codex))
.with_state(state)
}
pub async fn run(config: AppConfig) -> Result<()> {
let bind_addr: SocketAddr = config
.server
.bind
.parse()
.with_context(|| format!("invalid bind address {}", config.server.bind))?;
let app = build_app(config.clone());
let listener = tokio::net::TcpListener::bind(bind_addr)
.await
.with_context(|| format!("failed to bind {}", bind_addr))?;
info!(
bind = %config.server.bind,
upstream = %config.codex.upstream_base_url,
"proxypilot-rs listening"
);
axum::serve(listener, app)
.await
.context("proxy server exited unexpectedly")?;
Ok(())
}
async fn healthz(State(state): State<AppState>) -> impl IntoResponse {
Json(json!({
"status": "ok",
"provider": "codex",
"listen": state.config.server.bind,
"upstream": state.config.codex.upstream_base_url,
}))
}
async fn proxy_codex(
State(state): State<AppState>,
Path(path): Path<String>,
original_uri: OriginalUri,
method: Method,
headers: HeaderMap,
body: Bytes,
) -> Result<Response<Body>, ProxyError> {
let target = build_upstream_url(&state.config.codex.upstream_base_url, &path, &original_uri)?;
let mut request = state.client.request(method, target);
for (name, value) in &headers {
if should_skip_request_header(name.as_str()) {
continue;
}
request = request.header(name, value);
}
if !state.config.codex.api_key.trim().is_empty() {
request = request.bearer_auth(state.config.codex.api_key.trim());
}
let upstream = request
.body(body)
.send()
.await
.context("failed to reach upstream Codex endpoint")?;
let status = upstream.status();
let response_headers = upstream.headers().clone();
let response_body = upstream
.bytes()
.await
.context("failed to read upstream response body")?;
let mut response = Response::builder().status(status);
for (name, value) in &response_headers {
if should_skip_response_header(name.as_str()) {
continue;
}
response = response.header(name, value);
}
response
.body(Body::from(response_body))
.context("failed to build downstream response")
.map_err(ProxyError::from)
}
fn build_upstream_url(
base_url: &str,
path: &str,
original_uri: &OriginalUri,
) -> Result<String, ProxyError> {
let cleaned_base = base_url.trim_end_matches('/');
let suffix = if path.is_empty() {
original_uri
.0
.path_and_query()
.map(|value| value.as_str())
.unwrap_or("/v1")
} else {
original_uri
.0
.path_and_query()
.map(|value| value.as_str())
.unwrap_or("/v1")
};
if !suffix.starts_with("/v1") {
return Err(ProxyError::bad_request("only /v1/* proxying is supported"));
}
Ok(format!("{cleaned_base}{suffix}"))
}
fn should_skip_request_header(name: &str) -> bool {
matches!(
name.to_ascii_lowercase().as_str(),
"host" | "content-length" | "authorization" | "connection"
)
}
fn should_skip_response_header(name: &str) -> bool {
matches!(
name.to_ascii_lowercase().as_str(),
"content-length" | "transfer-encoding" | "connection"
)
}
pub struct ProxyError {
status: StatusCode,
message: String,
}
impl ProxyError {
fn bad_request(message: impl Into<String>) -> Self {
Self {
status: StatusCode::BAD_REQUEST,
message: message.into(),
}
}
}
impl From<anyhow::Error> for ProxyError {
fn from(value: anyhow::Error) -> Self {
Self {
status: StatusCode::BAD_GATEWAY,
message: value.to_string(),
}
}
}
impl IntoResponse for ProxyError {
fn into_response(self) -> Response<Body> {
let payload = Json(json!({
"error": self.message,
}));
(self.status, payload).into_response()
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::routing::post;
use serde_json::Value;
use tokio::sync::oneshot;
async fn start_listener(app: Router) -> (String, oneshot::Sender<()>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let (tx, rx) = oneshot::channel::<()>();
tokio::spawn(async move {
let server = axum::serve(listener, app).with_graceful_shutdown(async {
let _ = rx.await;
});
let _ = server.await;
});
(format!("http://{}", addr), tx)
}
#[tokio::test]
async fn proxies_chat_completions_and_injects_bearer_token() {
async fn upstream_handler(
headers: HeaderMap,
Json(body_json): Json<Value>,
) -> impl IntoResponse {
let auth = headers
.get("authorization")
.and_then(|value| value.to_str().ok())
.unwrap_or_default()
.to_string();
Json(json!({
"received_authorization": auth,
"echo_model": body_json["model"],
"ok": true
}))
}
let upstream_app = Router::new().route("/v1/chat/completions", post(upstream_handler));
let (upstream_url, upstream_shutdown) = start_listener(upstream_app).await;
let config = AppConfig {
server: crate::config::ServerConfig {
bind: "127.0.0.1:0".to_string(),
},
codex: crate::config::CodexConfig {
upstream_base_url: upstream_url.clone(),
api_key: "test-token".to_string(),
},
};
let proxy_app = build_app(config);
let (proxy_url, proxy_shutdown) = start_listener(proxy_app).await;
let client = Client::new();
let response = client
.post(format!("{proxy_url}/v1/chat/completions"))
.header("authorization", "Bearer wrong-token")
.json(&json!({
"model": "gpt-5.2-codex",
"input": "ping"
}))
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let payload: Value = response.json().await.unwrap();
assert_eq!(payload["received_authorization"], "Bearer test-token");
assert_eq!(payload["echo_model"], "gpt-5.2-codex");
let _ = proxy_shutdown.send(());
let _ = upstream_shutdown.send(());
}
}
+164
View File
@@ -0,0 +1,164 @@
use std::io;
use std::path::Path;
use std::time::{Duration, Instant};
use anyhow::Result;
use crossterm::event::{self, Event, KeyCode};
use crossterm::execute;
use crossterm::terminal::{
EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Direction, Layout};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};
use reqwest::StatusCode;
use crate::config::AppConfig;
pub async fn run(config: AppConfig, config_path: &Path) -> Result<()> {
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let result = run_loop(&mut terminal, config, config_path).await;
disable_raw_mode()?;
execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
terminal.show_cursor()?;
result
}
async fn run_loop(
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
config: AppConfig,
config_path: &Path,
) -> Result<()> {
let mut app = TuiApp::new(config, config_path);
loop {
if app.last_poll.elapsed() >= Duration::from_secs(2) {
app.refresh_health().await;
}
terminal.draw(|frame| render(frame, &app))?;
if event::poll(Duration::from_millis(150))?
&& let Event::Key(key) = event::read()?
{
match key.code {
KeyCode::Char('q') => break,
KeyCode::Char('r') => app.refresh_health().await,
_ => {}
}
}
}
Ok(())
}
struct TuiApp {
config: AppConfig,
config_path: String,
health_status: String,
health_color: Color,
last_poll: Instant,
}
impl TuiApp {
fn new(config: AppConfig, config_path: &Path) -> Self {
Self {
config,
config_path: config_path.display().to_string(),
health_status: "waiting for first health check".to_string(),
health_color: Color::Yellow,
last_poll: Instant::now() - Duration::from_secs(3),
}
}
async fn refresh_health(&mut self) {
self.last_poll = Instant::now();
match reqwest::get(self.config.health_url()).await {
Ok(response) if response.status() == StatusCode::OK => {
self.health_status = "local proxy reachable".to_string();
self.health_color = Color::Green;
}
Ok(response) => {
self.health_status = format!("proxy responded with {}", response.status());
self.health_color = Color::Yellow;
}
Err(err) => {
self.health_status = format!("proxy not running yet: {err}");
self.health_color = Color::Red;
}
}
}
}
fn render(frame: &mut ratatui::Frame<'_>, app: &TuiApp) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(1)
.constraints([
Constraint::Length(4),
Constraint::Length(8),
Constraint::Min(8),
Constraint::Length(3),
])
.split(frame.area());
let title = Paragraph::new(vec![
Line::from(Span::styled(
"ProxyPilot Rust Replatform",
Style::default()
.fg(Color::Cyan)
.add_modifier(Modifier::BOLD),
)),
Line::from("Terminal-first rewrite branch with a real Codex proxy slice."),
])
.block(Block::default().borders(Borders::ALL).title("Overview"));
let health = Paragraph::new(vec![
Line::from(vec![
Span::raw("Health: "),
Span::styled(
app.health_status.as_str(),
Style::default()
.fg(app.health_color)
.add_modifier(Modifier::BOLD),
),
]),
Line::from(format!("Bind: {}", app.config.server.bind)),
Line::from(format!("Upstream: {}", app.config.codex.upstream_base_url)),
Line::from(format!("Config: {}", app.config_path)),
])
.block(Block::default().borders(Borders::ALL).title("Runtime"));
let summary_lines = app
.config
.config_summary(Path::new(&app.config_path))
.into_iter()
.map(Line::from)
.collect::<Vec<_>>();
let summary = Paragraph::new(summary_lines)
.block(
Block::default()
.borders(Borders::ALL)
.title("Config Summary"),
)
.wrap(Wrap { trim: false });
let footer = Paragraph::new("q quit | r refresh health | run the server in another terminal with `proxypilot-rs run`")
.block(Block::default().borders(Borders::ALL).title("Keys"));
frame.render_widget(title, chunks[0]);
frame.render_widget(health, chunks[1]);
frame.render_widget(summary, chunks[2]);
frame.render_widget(footer, chunks[3]);
}