Add native OpenAI runtime route
This commit is contained in:
parent
71eca3889e
commit
6034b52f3f
13 changed files with 737 additions and 6 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -6,6 +6,8 @@ epiphany-openai-adapter/target/
|
|||
epiphany-openai-adapter/Cargo.lock
|
||||
epiphany-openai-codex-spine/target/
|
||||
epiphany-openai-codex-spine/Cargo.lock
|
||||
epiphany-openai-runtime/target/
|
||||
epiphany-openai-runtime/Cargo.lock
|
||||
apps/epiphany-gui/node_modules/
|
||||
apps/epiphany-gui/dist/
|
||||
apps/epiphany-gui/src-tauri/gen/
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ codex-file-search = { path = "../vendor/codex/codex-rs/file-search" }
|
|||
codex-protocol = { path = "../vendor/codex/codex-rs/protocol" }
|
||||
cultcache-rs = { path = "../vendor/cultcache-rs" }
|
||||
cultnet-rs = { path = "../vendor/cultnet-rs" }
|
||||
epiphany-openai-adapter = { path = "../epiphany-openai-adapter" }
|
||||
ignore = "0.4.23"
|
||||
postgres = "0.19"
|
||||
reqwest = { version = "0.12", features = ["blocking", "json"] }
|
||||
|
|
|
|||
|
|
@ -20,6 +20,10 @@ use cultnet_rs::CultNetWireContract;
|
|||
use cultnet_rs::builtin_schema_registry;
|
||||
use cultnet_rs::encode_cultnet_message_to_vec;
|
||||
use cultnet_rs::encode_frame;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiAdapterStatus;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiModelReceipt;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiModelRequest;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiStreamEvent;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
|
@ -330,6 +334,10 @@ pub fn runtime_spine_cache(store_path: impl AsRef<Path>) -> Result<CultCache> {
|
|||
cache.register_entry_type::<EpiphanyRuntimeJob>()?;
|
||||
cache.register_entry_type::<EpiphanyRuntimeJobResult>()?;
|
||||
cache.register_entry_type::<EpiphanyRuntimeEvent>()?;
|
||||
cache.register_entry_type::<EpiphanyOpenAiAdapterStatus>()?;
|
||||
cache.register_entry_type::<EpiphanyOpenAiModelRequest>()?;
|
||||
cache.register_entry_type::<EpiphanyOpenAiStreamEvent>()?;
|
||||
cache.register_entry_type::<EpiphanyOpenAiModelReceipt>()?;
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(
|
||||
store_path.to_path_buf(),
|
||||
));
|
||||
|
|
|
|||
|
|
@ -10,4 +10,5 @@ name = "epiphany_openai_adapter"
|
|||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
cultcache-rs = { path = "../vendor/cultcache-rs" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
use cultcache_rs::DatabaseEntry;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
|
|
@ -14,29 +15,55 @@ pub enum EpiphanyOpenAiAuthMode {
|
|||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.openai_adapter_status.v0",
|
||||
schema = "EpiphanyOpenAiAdapterStatus"
|
||||
)]
|
||||
pub struct EpiphanyOpenAiAdapterStatus {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_id: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub adapter_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub auth_mode: EpiphanyOpenAiAuthMode,
|
||||
#[cultcache(key = 3, default)]
|
||||
pub account_id: Option<String>,
|
||||
#[cultcache(key = 4, default)]
|
||||
pub plan_type: Option<String>,
|
||||
#[cultcache(key = 5, default)]
|
||||
pub default_model: Option<String>,
|
||||
#[cultcache(key = 6)]
|
||||
pub supports_websockets: bool,
|
||||
#[cultcache(key = 7)]
|
||||
pub codex_transport_attached: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.openai_model_request.v0",
|
||||
schema = "EpiphanyOpenAiModelRequest"
|
||||
)]
|
||||
pub struct EpiphanyOpenAiModelRequest {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_id: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub conversation_id: String,
|
||||
#[cultcache(key = 3)]
|
||||
pub model: String,
|
||||
#[cultcache(key = 4)]
|
||||
pub instructions: String,
|
||||
#[cultcache(key = 5, default)]
|
||||
pub input: Vec<EpiphanyOpenAiInputItem>,
|
||||
#[cultcache(key = 6, default)]
|
||||
pub reasoning_effort: Option<String>,
|
||||
#[cultcache(key = 7, default)]
|
||||
pub reasoning_summary: Option<String>,
|
||||
#[cultcache(key = 8, default)]
|
||||
pub service_tier: Option<String>,
|
||||
#[cultcache(key = 9, default)]
|
||||
pub output_contract_id: Option<String>,
|
||||
}
|
||||
|
||||
|
|
@ -69,11 +96,19 @@ pub enum EpiphanyOpenAiInputItem {
|
|||
ToolResult { call_id: String, output: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.openai_model_stream_event.v0",
|
||||
schema = "EpiphanyOpenAiStreamEvent"
|
||||
)]
|
||||
pub struct EpiphanyOpenAiStreamEvent {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_id: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub sequence: u64,
|
||||
#[cultcache(key = 3)]
|
||||
pub payload: EpiphanyOpenAiStreamPayload,
|
||||
}
|
||||
|
||||
|
|
@ -98,15 +133,27 @@ pub enum EpiphanyOpenAiStreamPayload {
|
|||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(
|
||||
type = "epiphany.openai_model_receipt.v0",
|
||||
schema = "EpiphanyOpenAiModelReceipt"
|
||||
)]
|
||||
pub struct EpiphanyOpenAiModelReceipt {
|
||||
#[cultcache(key = 0)]
|
||||
pub schema_id: String,
|
||||
#[cultcache(key = 1)]
|
||||
pub request_id: String,
|
||||
#[cultcache(key = 2)]
|
||||
pub model: String,
|
||||
#[cultcache(key = 3, default)]
|
||||
pub response_id: Option<String>,
|
||||
#[cultcache(key = 4, default)]
|
||||
pub input_tokens: Option<u64>,
|
||||
#[cultcache(key = 5, default)]
|
||||
pub output_tokens: Option<u64>,
|
||||
#[cultcache(key = 6, default)]
|
||||
pub reasoning_output_tokens: Option<u64>,
|
||||
#[cultcache(key = 7, default)]
|
||||
pub transport: Option<String>,
|
||||
}
|
||||
|
||||
|
|
|
|||
36
epiphany-openai-runtime/Cargo.toml
Normal file
36
epiphany-openai-runtime/Cargo.toml
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
[package]
|
||||
name = "epiphany-openai-runtime"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
license-file = "../LICENSE"
|
||||
|
||||
[lib]
|
||||
name = "epiphany_openai_runtime"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
chrono = "0.4.44"
|
||||
codex-login = { path = "../vendor/codex/codex-rs/login" }
|
||||
epiphany-core = { path = "../epiphany-core" }
|
||||
epiphany-openai-adapter = { path = "../epiphany-openai-adapter" }
|
||||
epiphany-openai-codex-spine = { path = "../epiphany-openai-codex-spine" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
[[bin]]
|
||||
name = "epiphany-openai-runtime"
|
||||
path = "src/bin/epiphany-openai-runtime.rs"
|
||||
|
||||
[patch.crates-io]
|
||||
tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "132f5b39c862e3a970f731d709608b3e6276d5f6" }
|
||||
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "9200079d3b54a1ff51072e24d81fd354f085156f" }
|
||||
|
||||
[patch."ssh://git@github.com/openai-oss-forks/tungstenite-rs.git"]
|
||||
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "9200079d3b54a1ff51072e24d81fd354f085156f" }
|
||||
205
epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs
Normal file
205
epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
use std::env;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiInputItem;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiModelReceipt;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiModelRequest;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiStreamEvent;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiStreamPayload;
|
||||
use epiphany_openai_runtime::EpiphanyOpenAiRuntimeOptions;
|
||||
use epiphany_openai_runtime::OPENAI_RUNTIME_ROLE;
|
||||
use epiphany_openai_runtime::default_codex_home;
|
||||
use epiphany_openai_runtime::default_options;
|
||||
use epiphany_openai_runtime::ensure_openai_runtime_ready;
|
||||
use epiphany_openai_runtime::record_openai_events;
|
||||
use epiphany_openai_runtime::run_openai_model_turn;
|
||||
use serde_json::json;
|
||||
use uuid::Uuid;
|
||||
|
||||
const DEFAULT_STORE: &str = "state/runtime-spine.msgpack";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let mut args = env::args().skip(1);
|
||||
let command = args.next().unwrap_or_else(|| "usage".to_string());
|
||||
match command.as_str() {
|
||||
"model-turn" => {
|
||||
let options = parse_model_turn_options(args.collect())?;
|
||||
let request_text = fs::read_to_string(&options.request_path)
|
||||
.with_context(|| format!("failed to read {}", options.request_path.display()))?;
|
||||
let request: EpiphanyOpenAiModelRequest = serde_json::from_str(&request_text)
|
||||
.with_context(|| format!("failed to parse {}", options.request_path.display()))?;
|
||||
let runtime_options = options.into_runtime_options(&request);
|
||||
let summary = run_openai_model_turn(runtime_options, request).await?;
|
||||
print_json(&summary)?;
|
||||
}
|
||||
"smoke" => {
|
||||
let options = parse_smoke_options(args.collect())?;
|
||||
let mut request = EpiphanyOpenAiModelRequest::new(
|
||||
"smoke-request",
|
||||
"smoke-conversation",
|
||||
"gpt-5.4",
|
||||
"Answer with one sentence.",
|
||||
);
|
||||
request.input.push(EpiphanyOpenAiInputItem::UserText {
|
||||
text: "smoke".to_string(),
|
||||
});
|
||||
let runtime_options =
|
||||
default_options(options.store_path.clone(), options.codex_home, &request);
|
||||
ensure_openai_runtime_ready(&runtime_options)?;
|
||||
epiphany_core::ensure_runtime_session(
|
||||
&runtime_options.store_path,
|
||||
epiphany_core::RuntimeSpineSessionOptions {
|
||||
session_id: runtime_options.session_id.clone(),
|
||||
objective: runtime_options.objective.clone(),
|
||||
created_at: now(),
|
||||
coordinator_note: runtime_options.coordinator_note.clone(),
|
||||
},
|
||||
)?;
|
||||
epiphany_core::create_runtime_job(
|
||||
&runtime_options.store_path,
|
||||
epiphany_core::RuntimeSpineJobOptions {
|
||||
job_id: runtime_options.job_id.clone(),
|
||||
session_id: runtime_options.session_id.clone(),
|
||||
role: OPENAI_RUNTIME_ROLE.to_string(),
|
||||
created_at: now(),
|
||||
summary: "Smoke typed OpenAI runtime route.".to_string(),
|
||||
artifact_refs: Vec::new(),
|
||||
},
|
||||
)?;
|
||||
epiphany_openai_runtime::store_openai_request(&runtime_options.store_path, &request)?;
|
||||
let mut receipt = EpiphanyOpenAiModelReceipt::new(&request.request_id, &request.model);
|
||||
receipt.response_id = Some("smoke-response".to_string());
|
||||
receipt.transport = Some("smoke_no_network".to_string());
|
||||
let events = vec![EpiphanyOpenAiStreamEvent {
|
||||
schema_id: epiphany_openai_adapter::OPENAI_ADAPTER_EVENT_SCHEMA_ID.to_string(),
|
||||
request_id: request.request_id.clone(),
|
||||
sequence: 0,
|
||||
payload: EpiphanyOpenAiStreamPayload::Completed { receipt },
|
||||
}];
|
||||
let summary = record_openai_events(
|
||||
&runtime_options.store_path,
|
||||
&runtime_options,
|
||||
&request,
|
||||
&events,
|
||||
)?;
|
||||
print_json(&json!({
|
||||
"summary": summary,
|
||||
"transport": "not-opened"
|
||||
}))?;
|
||||
}
|
||||
_ => return Err(anyhow!(usage())),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct ModelTurnCliOptions {
|
||||
store_path: PathBuf,
|
||||
codex_home: PathBuf,
|
||||
request_path: PathBuf,
|
||||
session_id: Option<String>,
|
||||
job_id: Option<String>,
|
||||
objective: Option<String>,
|
||||
default_model: Option<String>,
|
||||
}
|
||||
|
||||
impl ModelTurnCliOptions {
|
||||
fn into_runtime_options(
|
||||
self,
|
||||
request: &EpiphanyOpenAiModelRequest,
|
||||
) -> EpiphanyOpenAiRuntimeOptions {
|
||||
let mut options = default_options(self.store_path, self.codex_home, request);
|
||||
if let Some(session_id) = self.session_id {
|
||||
options.session_id = session_id;
|
||||
}
|
||||
if let Some(job_id) = self.job_id {
|
||||
options.job_id = job_id;
|
||||
}
|
||||
if let Some(objective) = self.objective {
|
||||
options.objective = objective;
|
||||
}
|
||||
if let Some(default_model) = self.default_model {
|
||||
options.default_model = Some(default_model);
|
||||
}
|
||||
options
|
||||
}
|
||||
}
|
||||
|
||||
struct SmokeCliOptions {
|
||||
store_path: PathBuf,
|
||||
codex_home: PathBuf,
|
||||
}
|
||||
|
||||
fn parse_model_turn_options(args: Vec<String>) -> Result<ModelTurnCliOptions> {
|
||||
let mut store_path = PathBuf::from(DEFAULT_STORE);
|
||||
let mut codex_home = default_codex_home()?;
|
||||
let mut request_path = None;
|
||||
let mut session_id = None;
|
||||
let mut job_id = None;
|
||||
let mut objective = None;
|
||||
let mut default_model = None;
|
||||
let mut iter = args.into_iter();
|
||||
while let Some(arg) = iter.next() {
|
||||
match arg.as_str() {
|
||||
"--store" => store_path = PathBuf::from(next_value(&mut iter, "--store")?),
|
||||
"--codex-home" => codex_home = PathBuf::from(next_value(&mut iter, "--codex-home")?),
|
||||
"--request" => request_path = Some(PathBuf::from(next_value(&mut iter, "--request")?)),
|
||||
"--session-id" => session_id = Some(next_value(&mut iter, "--session-id")?),
|
||||
"--job-id" => job_id = Some(next_value(&mut iter, "--job-id")?),
|
||||
"--objective" => objective = Some(next_value(&mut iter, "--objective")?),
|
||||
"--default-model" => default_model = Some(next_value(&mut iter, "--default-model")?),
|
||||
other => return Err(anyhow!("unknown model-turn argument: {other}")),
|
||||
}
|
||||
}
|
||||
Ok(ModelTurnCliOptions {
|
||||
store_path,
|
||||
codex_home,
|
||||
request_path: request_path.context("model-turn requires --request")?,
|
||||
session_id,
|
||||
job_id,
|
||||
objective,
|
||||
default_model,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_smoke_options(args: Vec<String>) -> Result<SmokeCliOptions> {
|
||||
let mut store_path = PathBuf::from(format!(
|
||||
".epiphany-dogfood/openai-runtime/smoke-{}.msgpack",
|
||||
Uuid::new_v4()
|
||||
));
|
||||
let mut codex_home = default_codex_home()?;
|
||||
let mut iter = args.into_iter();
|
||||
while let Some(arg) = iter.next() {
|
||||
match arg.as_str() {
|
||||
"--store" => store_path = PathBuf::from(next_value(&mut iter, "--store")?),
|
||||
"--codex-home" => codex_home = PathBuf::from(next_value(&mut iter, "--codex-home")?),
|
||||
other => return Err(anyhow!("unknown smoke argument: {other}")),
|
||||
}
|
||||
}
|
||||
Ok(SmokeCliOptions {
|
||||
store_path,
|
||||
codex_home,
|
||||
})
|
||||
}
|
||||
|
||||
fn next_value(iter: &mut impl Iterator<Item = String>, name: &str) -> Result<String> {
|
||||
iter.next()
|
||||
.ok_or_else(|| anyhow!("{name} requires a value"))
|
||||
}
|
||||
|
||||
fn print_json<T: serde::Serialize>(value: &T) -> Result<()> {
|
||||
println!("{}", serde_json::to_string_pretty(value)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn now() -> String {
|
||||
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
|
||||
}
|
||||
|
||||
fn usage() -> &'static str {
|
||||
"usage: epiphany-openai-runtime <model-turn|smoke> [--store path] [--codex-home path] [--request path] [--session-id id] [--job-id id] [--objective text] [--default-model model]"
|
||||
}
|
||||
408
epiphany-openai-runtime/src/lib.rs
Normal file
408
epiphany-openai-runtime/src/lib.rs
Normal file
|
|
@ -0,0 +1,408 @@
|
|||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use chrono::SecondsFormat;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthManager;
|
||||
use epiphany_core::RuntimeSpineEventOptions;
|
||||
use epiphany_core::RuntimeSpineInitOptions;
|
||||
use epiphany_core::RuntimeSpineJobOptions;
|
||||
use epiphany_core::RuntimeSpineJobResultOptions;
|
||||
use epiphany_core::RuntimeSpineSessionOptions;
|
||||
use epiphany_core::append_runtime_event;
|
||||
use epiphany_core::complete_runtime_job;
|
||||
use epiphany_core::create_runtime_job;
|
||||
use epiphany_core::ensure_runtime_session;
|
||||
use epiphany_core::initialize_runtime_spine;
|
||||
use epiphany_core::runtime_spine_cache;
|
||||
use epiphany_core::runtime_spine_status;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiAdapterStatus;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiModelRequest;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiStreamEvent;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiStreamPayload;
|
||||
use epiphany_openai_codex_spine::EpiphanyCodexOpenAiTransport;
|
||||
use epiphany_openai_codex_spine::status_from_auth_manager;
|
||||
|
||||
pub const OPENAI_RUNTIME_ROLE: &str = "openai-model-adapter";
|
||||
pub const OPENAI_RUNTIME_SOURCE: &str = "epiphany-openai-runtime";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EpiphanyOpenAiRuntimeOptions {
|
||||
pub store_path: PathBuf,
|
||||
pub codex_home: PathBuf,
|
||||
pub session_id: String,
|
||||
pub job_id: String,
|
||||
pub objective: String,
|
||||
pub coordinator_note: String,
|
||||
pub default_model: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EpiphanyOpenAiRuntimeRunSummary {
|
||||
pub store: String,
|
||||
pub session_id: String,
|
||||
pub job_id: String,
|
||||
pub request_id: String,
|
||||
pub event_count: usize,
|
||||
pub verdict: String,
|
||||
pub result_id: String,
|
||||
pub receipt_id: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn run_openai_model_turn(
|
||||
options: EpiphanyOpenAiRuntimeOptions,
|
||||
request: EpiphanyOpenAiModelRequest,
|
||||
) -> Result<EpiphanyOpenAiRuntimeRunSummary> {
|
||||
ensure_openai_runtime_ready(&options)?;
|
||||
let auth_manager = auth_manager(options.codex_home.clone());
|
||||
let status = status_from_auth_manager(&auth_manager, options.default_model.clone(), true).await;
|
||||
store_openai_status(&options.store_path, &status)?;
|
||||
store_openai_request(&options.store_path, &request)?;
|
||||
ensure_runtime_session(
|
||||
&options.store_path,
|
||||
RuntimeSpineSessionOptions {
|
||||
session_id: options.session_id.clone(),
|
||||
objective: options.objective.clone(),
|
||||
created_at: now(),
|
||||
coordinator_note: options.coordinator_note.clone(),
|
||||
},
|
||||
)?;
|
||||
create_runtime_job(
|
||||
&options.store_path,
|
||||
RuntimeSpineJobOptions {
|
||||
job_id: options.job_id.clone(),
|
||||
session_id: options.session_id.clone(),
|
||||
role: OPENAI_RUNTIME_ROLE.to_string(),
|
||||
created_at: now(),
|
||||
summary: format!("OpenAI model request {}", request.request_id),
|
||||
artifact_refs: Vec::new(),
|
||||
},
|
||||
)?;
|
||||
append_runtime_event(
|
||||
&options.store_path,
|
||||
RuntimeSpineEventOptions {
|
||||
event_id: format!("event-openai-started-{}", options.job_id),
|
||||
occurred_at: now(),
|
||||
event_type: "openai.model_turn.started".to_string(),
|
||||
source: OPENAI_RUNTIME_SOURCE.to_string(),
|
||||
session_id: Some(options.session_id.clone()),
|
||||
job_id: Some(options.job_id.clone()),
|
||||
summary: format!("Started typed OpenAI request {}.", request.request_id),
|
||||
},
|
||||
)?;
|
||||
|
||||
let transport = EpiphanyCodexOpenAiTransport::openai(auth_manager);
|
||||
let events = match transport.collect_model_events(request.clone()).await {
|
||||
Ok(events) => events,
|
||||
Err(err) => {
|
||||
let failure = EpiphanyOpenAiStreamEvent {
|
||||
schema_id: epiphany_openai_adapter::OPENAI_ADAPTER_EVENT_SCHEMA_ID.to_string(),
|
||||
request_id: request.request_id.clone(),
|
||||
sequence: 0,
|
||||
payload: EpiphanyOpenAiStreamPayload::Failed {
|
||||
message: err.to_string(),
|
||||
},
|
||||
};
|
||||
vec![failure]
|
||||
}
|
||||
};
|
||||
record_openai_events(&options.store_path, &options, &request, &events)
|
||||
}
|
||||
|
||||
pub fn record_openai_events(
|
||||
store_path: impl AsRef<Path>,
|
||||
options: &EpiphanyOpenAiRuntimeOptions,
|
||||
request: &EpiphanyOpenAiModelRequest,
|
||||
events: &[EpiphanyOpenAiStreamEvent],
|
||||
) -> Result<EpiphanyOpenAiRuntimeRunSummary> {
|
||||
let store_path = store_path.as_ref();
|
||||
let mut receipt = None;
|
||||
let mut failure = None;
|
||||
{
|
||||
let mut cache = runtime_spine_cache(store_path)?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
for event in events {
|
||||
let key = openai_event_key(&event.request_id, event.sequence);
|
||||
cache.put(key, event)?;
|
||||
match &event.payload {
|
||||
EpiphanyOpenAiStreamPayload::Completed { receipt: completed } => {
|
||||
cache.put(openai_receipt_key(&completed.request_id), completed)?;
|
||||
receipt = Some(completed.clone());
|
||||
}
|
||||
EpiphanyOpenAiStreamPayload::Failed { message } => {
|
||||
failure = Some(message.clone());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for event in events {
|
||||
append_runtime_event(
|
||||
store_path,
|
||||
RuntimeSpineEventOptions {
|
||||
event_id: format!("event-openai-{}-{}", options.job_id, event.sequence),
|
||||
occurred_at: now(),
|
||||
event_type: openai_event_type(event).to_string(),
|
||||
source: OPENAI_RUNTIME_SOURCE.to_string(),
|
||||
session_id: Some(options.session_id.clone()),
|
||||
job_id: Some(options.job_id.clone()),
|
||||
summary: openai_event_summary(event),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
|
||||
let verdict = if failure.is_some() || receipt.is_none() {
|
||||
"failed"
|
||||
} else {
|
||||
"pass"
|
||||
};
|
||||
let summary = if let Some(message) = failure {
|
||||
format!(
|
||||
"OpenAI model request {} failed: {message}",
|
||||
request.request_id
|
||||
)
|
||||
} else if let Some(receipt) = &receipt {
|
||||
format!(
|
||||
"OpenAI model request {} completed through {}.",
|
||||
request.request_id,
|
||||
receipt
|
||||
.transport
|
||||
.clone()
|
||||
.unwrap_or_else(|| "unknown transport".to_string())
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"OpenAI model request {} ended without a terminal receipt.",
|
||||
request.request_id
|
||||
)
|
||||
};
|
||||
let result_id = format!("result-openai-{}", options.job_id);
|
||||
complete_runtime_job(
|
||||
store_path,
|
||||
RuntimeSpineJobResultOptions {
|
||||
result_id: result_id.clone(),
|
||||
job_id: options.job_id.clone(),
|
||||
completed_at: now(),
|
||||
verdict: verdict.to_string(),
|
||||
summary,
|
||||
next_safe_move: "Review typed OpenAI receipt before accepting downstream state."
|
||||
.to_string(),
|
||||
evidence_refs: Vec::new(),
|
||||
artifact_refs: Vec::new(),
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(EpiphanyOpenAiRuntimeRunSummary {
|
||||
store: store_path.display().to_string(),
|
||||
session_id: options.session_id.clone(),
|
||||
job_id: options.job_id.clone(),
|
||||
request_id: request.request_id.clone(),
|
||||
event_count: events.len(),
|
||||
verdict: verdict.to_string(),
|
||||
result_id,
|
||||
receipt_id: receipt.map(|item| openai_receipt_key(&item.request_id)),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn ensure_openai_runtime_ready(options: &EpiphanyOpenAiRuntimeOptions) -> Result<()> {
|
||||
let status = runtime_spine_status(&options.store_path)?;
|
||||
if status.present {
|
||||
return Ok(());
|
||||
}
|
||||
initialize_runtime_spine(
|
||||
&options.store_path,
|
||||
RuntimeSpineInitOptions {
|
||||
runtime_id: "epiphany-openai-runtime".to_string(),
|
||||
display_name: "Epiphany OpenAI Runtime".to_string(),
|
||||
created_at: now(),
|
||||
},
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn store_openai_status(
|
||||
store_path: impl AsRef<Path>,
|
||||
status: &EpiphanyOpenAiAdapterStatus,
|
||||
) -> Result<()> {
|
||||
let mut cache = runtime_spine_cache(store_path)?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
cache.put(status.adapter_id.clone(), status)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn store_openai_request(
|
||||
store_path: impl AsRef<Path>,
|
||||
request: &EpiphanyOpenAiModelRequest,
|
||||
) -> Result<()> {
|
||||
let mut cache = runtime_spine_cache(store_path)?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
cache.put(request.request_id.clone(), request)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn default_codex_home() -> Result<PathBuf> {
|
||||
if let Ok(path) = std::env::var("CODEX_HOME") {
|
||||
return Ok(PathBuf::from(path));
|
||||
}
|
||||
let home = std::env::var("USERPROFILE")
|
||||
.or_else(|_| std::env::var("HOME"))
|
||||
.context("CODEX_HOME is unset and no home directory environment variable exists")?;
|
||||
Ok(PathBuf::from(home).join(".codex"))
|
||||
}
|
||||
|
||||
pub fn default_options(
|
||||
store_path: PathBuf,
|
||||
codex_home: PathBuf,
|
||||
request: &EpiphanyOpenAiModelRequest,
|
||||
) -> EpiphanyOpenAiRuntimeOptions {
|
||||
EpiphanyOpenAiRuntimeOptions {
|
||||
store_path,
|
||||
codex_home,
|
||||
session_id: format!("openai-session-{}", request.conversation_id),
|
||||
job_id: format!("openai-job-{}", request.request_id),
|
||||
objective: format!("Run typed OpenAI model request {}", request.request_id),
|
||||
coordinator_note: "Native OpenAI runtime route; Codex is auth/model transport only."
|
||||
.to_string(),
|
||||
default_model: Some(request.model.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn auth_manager(codex_home: PathBuf) -> Arc<AuthManager> {
|
||||
AuthManager::shared(
|
||||
codex_home,
|
||||
/*enable_codex_api_key_env*/ true,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*chatgpt_base_url*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn openai_event_key(request_id: &str, sequence: u64) -> String {
|
||||
format!("{request_id}:{sequence:08}")
|
||||
}
|
||||
|
||||
pub fn openai_receipt_key(request_id: &str) -> String {
|
||||
request_id.to_string()
|
||||
}
|
||||
|
||||
fn openai_event_type(event: &EpiphanyOpenAiStreamEvent) -> &'static str {
|
||||
match event.payload {
|
||||
EpiphanyOpenAiStreamPayload::TextDelta { .. } => "openai.model_turn.text_delta",
|
||||
EpiphanyOpenAiStreamPayload::ReasoningDelta { .. } => "openai.model_turn.reasoning_delta",
|
||||
EpiphanyOpenAiStreamPayload::ToolCall { .. } => "openai.model_turn.tool_call",
|
||||
EpiphanyOpenAiStreamPayload::Completed { .. } => "openai.model_turn.completed",
|
||||
EpiphanyOpenAiStreamPayload::Failed { .. } => "openai.model_turn.failed",
|
||||
}
|
||||
}
|
||||
|
||||
fn openai_event_summary(event: &EpiphanyOpenAiStreamEvent) -> String {
|
||||
match &event.payload {
|
||||
EpiphanyOpenAiStreamPayload::TextDelta { text } => {
|
||||
format!(
|
||||
"Text delta for {} ({} chars).",
|
||||
event.request_id,
|
||||
text.len()
|
||||
)
|
||||
}
|
||||
EpiphanyOpenAiStreamPayload::ReasoningDelta { text } => {
|
||||
format!(
|
||||
"Reasoning delta for {} ({} chars).",
|
||||
event.request_id,
|
||||
text.len()
|
||||
)
|
||||
}
|
||||
EpiphanyOpenAiStreamPayload::ToolCall { name, .. } => {
|
||||
format!("Tool call {name} for {}.", event.request_id)
|
||||
}
|
||||
EpiphanyOpenAiStreamPayload::Completed { receipt } => {
|
||||
format!(
|
||||
"OpenAI request {} completed with response {:?}.",
|
||||
event.request_id, receipt.response_id
|
||||
)
|
||||
}
|
||||
EpiphanyOpenAiStreamPayload::Failed { message } => {
|
||||
format!("OpenAI request {} failed: {message}", event.request_id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn now() -> String {
|
||||
chrono::Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use epiphany_core::runtime_job_snapshot;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiModelReceipt;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn records_typed_openai_documents_in_runtime_store() -> Result<()> {
|
||||
let temp = tempdir()?;
|
||||
let store = temp.path().join("runtime.msgpack");
|
||||
let request = EpiphanyOpenAiModelRequest::new(
|
||||
"req-1",
|
||||
"conversation-1",
|
||||
"gpt-5.4",
|
||||
"Answer plainly.",
|
||||
);
|
||||
let options = default_options(store.clone(), PathBuf::from(".codex"), &request);
|
||||
ensure_openai_runtime_ready(&options)?;
|
||||
ensure_runtime_session(
|
||||
&store,
|
||||
RuntimeSpineSessionOptions {
|
||||
session_id: options.session_id.clone(),
|
||||
objective: options.objective.clone(),
|
||||
created_at: now(),
|
||||
coordinator_note: options.coordinator_note.clone(),
|
||||
},
|
||||
)?;
|
||||
create_runtime_job(
|
||||
&store,
|
||||
RuntimeSpineJobOptions {
|
||||
job_id: options.job_id.clone(),
|
||||
session_id: options.session_id.clone(),
|
||||
role: OPENAI_RUNTIME_ROLE.to_string(),
|
||||
created_at: now(),
|
||||
summary: "test job".to_string(),
|
||||
artifact_refs: Vec::new(),
|
||||
},
|
||||
)?;
|
||||
store_openai_request(&store, &request)?;
|
||||
let mut receipt = EpiphanyOpenAiModelReceipt::new("req-1", "gpt-5.4");
|
||||
receipt.response_id = Some("resp-1".to_string());
|
||||
receipt.transport = Some("test".to_string());
|
||||
let events = vec![EpiphanyOpenAiStreamEvent {
|
||||
schema_id: epiphany_openai_adapter::OPENAI_ADAPTER_EVENT_SCHEMA_ID.to_string(),
|
||||
request_id: "req-1".to_string(),
|
||||
sequence: 0,
|
||||
payload: EpiphanyOpenAiStreamPayload::Completed { receipt },
|
||||
}];
|
||||
|
||||
let summary = record_openai_events(&store, &options, &request, &events)?;
|
||||
|
||||
assert_eq!(summary.verdict, "pass");
|
||||
let mut cache = runtime_spine_cache(&store)?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
assert!(cache.get::<EpiphanyOpenAiModelRequest>("req-1")?.is_some());
|
||||
assert!(
|
||||
cache
|
||||
.get::<EpiphanyOpenAiStreamEvent>("req-1:00000000")?
|
||||
.is_some()
|
||||
);
|
||||
assert!(cache.get::<EpiphanyOpenAiModelReceipt>("req-1")?.is_some());
|
||||
assert_eq!(
|
||||
runtime_job_snapshot(&store, &options.job_id)?
|
||||
.expect("snapshot")
|
||||
.job
|
||||
.status,
|
||||
epiphany_core::EpiphanyRuntimeJobStatus::Completed
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -149,6 +149,16 @@ is not the final CultNet daemon. It is a buildable extracted edge that proves
|
|||
the spine can be called from Epiphany-owned code and gives the next cut a place
|
||||
to route through while the old `thread/epiphany/*` model path is starved.
|
||||
|
||||
The native runtime route now exists too. `epiphany-openai-adapter` documents
|
||||
derive CultCache `DatabaseEntry`, `epiphany-core::runtime_spine_cache`
|
||||
registers OpenAI adapter status/request/stream-event/receipt documents, and the
|
||||
outside-vendor `epiphany-openai-runtime` crate records typed OpenAI model-turn
|
||||
requests, stream events, terminal receipts, runtime sessions, jobs, and job
|
||||
results into the native runtime spine. Its `model-turn` command opens the
|
||||
Codex-backed transport through the typed spine; its `smoke` command proves the
|
||||
CultCache route without touching the network. This is the first native caller
|
||||
for the advertised OpenAI CultNet contract.
|
||||
|
||||
The bad news is useful: the current spine still drags in `codex-api` and its
|
||||
large transport dependency stack. That is tolerable as a sealed compatibility
|
||||
reliquary, but not as the final shape. The next purification should shrink the
|
||||
|
|
|
|||
|
|
@ -577,6 +577,17 @@ native runtime/CultNet model calls through this spine and then shrinking the
|
|||
surviving Codex dependency surface to auth, provider/model routing, and the
|
||||
smallest OpenAI Responses call needed for subscription compatibility.
|
||||
|
||||
That native route has now started. `epiphany-openai-adapter` documents are
|
||||
CultCache `DatabaseEntry` types, `epiphany-core::runtime_spine_cache` registers
|
||||
OpenAI adapter status/request/stream-event/receipt records, and the
|
||||
outside-vendor `epiphany-openai-runtime` crate writes typed model-turn
|
||||
requests, stream events, terminal receipts, runtime sessions, jobs, job
|
||||
results, and runtime events into the native runtime spine. Its `model-turn`
|
||||
command calls the Codex-backed typed transport; its `smoke` command proves the
|
||||
storage route without network. The next cut is to move live callers from
|
||||
Codex app-server JSON-RPC onto this runtime route, then carve down the
|
||||
`codex-api` dependency weight.
|
||||
|
||||
Also: MCP itself is allowed to be JSON. The target is not "replace MCP JSON";
|
||||
the target is an Epiphany-owned boundary that speaks typed Epiphany
|
||||
intent/result/receipt documents internally and normal MCP JSON-RPC externally.
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -279,5 +279,5 @@ rejected_paths:
|
|||
reason: making Epiphany cleaner inside Codex still preserves the wrong organ; Codex must be starved down to OpenAI subscription auth/model transport, while Epiphany data and subsystem communication move to typed CultCache/CultNet.
|
||||
|
||||
current_status:
|
||||
summary: The Codex starvation pass has five typing receipts, seventeen processor cuts, a real physical extraction in `epiphany-codex-bridge`, a source-grounded Codex auth spine inventory, the pure native `epiphany-openai-adapter` document boundary, and a buildable Codex auth/model wrapper in `epiphany-openai-codex-spine`. The bridge owns Codex-facing Epiphany adapters for scene, jobs, context/planning/graph query, retrieval, result projection, runtime-spine result adaptation, launch/prompt doctrine, mutation document mechanics, live-state projection, pressure/pre-compaction rendering, freshness/reorientation projection, CRRC/coordinator/role-board projection, and acceptance/evidence signal helpers. Vendored app-server now retains only `epiphany_invalidation.rs` as a root Epiphany module because watcher lifecycle is still app-server machinery; `codex_message_processor.rs` still contains route dispatch and mutation orchestration. The processor is about 10,339 lines, `epiphany_mutation_routes.rs` is about 1,071 lines, and `epiphany_state_helpers.rs` is down to a 19-line rollout-state loader. `epiphany-openai-adapter` defines typed request/event/receipt/auth-status documents with no Codex app-server or generic JSON dependency. `epiphany-openai-codex-spine` projects `AuthManager` / `CodexAuth` into typed `EpiphanyOpenAiAdapterStatus`, maps typed `EpiphanyOpenAiModelRequest` into Codex API `ResponsesApiRequest`, resolves auth/provider through keeper Codex crates, opens HTTP Responses streams through `codex-api`, and maps deltas/completion into typed stream events and receipts. The `epiphany-openai-spine` binary is the first native edge: it prints typed status and can consume serialized typed request documents outside Codex app-server JSON-RPC. Treat that JSON as CLI/file-edge serialization, not internal authority. `epiphany-runtime-spine` advertises OpenAI adapter status/model-request/stream-event/receipt CultNet schemas and mutation contracts, so the next caller can be native instead of JSON-RPC. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON. The current OpenAI spine still pulls `codex-api` and a large transport dependency stack, so its next cut is dependency starvation after native routing exists.
|
||||
next_action: Continue Codex starvation by routing an Epiphany-native runtime/CultNet model-call surface through the typed OpenAI spine, then starve the old model-turn path out of `thread/epiphany/*` JSON-RPC and `codex_message_processor.rs`. After routing is real, shrink the surviving Codex dependency surface to credential refresh, provider/model routing, and the smallest OpenAI Responses call required for Codex subscription compatibility. Do not add Codex app-server, apps, skills, marketplace, or new Epiphany JSON-RPC dependencies.
|
||||
summary: The Codex starvation pass has five typing receipts, seventeen processor cuts, a real physical extraction in `epiphany-codex-bridge`, a source-grounded Codex auth spine inventory, the native `epiphany-openai-adapter` document boundary, a buildable Codex auth/model wrapper in `epiphany-openai-codex-spine`, and the first native runtime caller in `epiphany-openai-runtime`. The bridge owns Codex-facing Epiphany adapters for scene, jobs, context/planning/graph query, retrieval, result projection, runtime-spine result adaptation, launch/prompt doctrine, mutation document mechanics, live-state projection, pressure/pre-compaction rendering, freshness/reorientation projection, CRRC/coordinator/role-board projection, and acceptance/evidence signal helpers. Vendored app-server now retains only `epiphany_invalidation.rs` as a root Epiphany module because watcher lifecycle is still app-server machinery; `codex_message_processor.rs` still contains route dispatch and mutation orchestration. The processor is about 10,339 lines, `epiphany_mutation_routes.rs` is about 1,071 lines, and `epiphany_state_helpers.rs` is down to a 19-line rollout-state loader. `epiphany-openai-adapter` defines CultCache `DatabaseEntry` request/event/receipt/auth-status documents with no Codex app-server or generic JSON dependency. `epiphany-openai-codex-spine` projects `AuthManager` / `CodexAuth` into typed `EpiphanyOpenAiAdapterStatus`, maps typed `EpiphanyOpenAiModelRequest` into Codex API `ResponsesApiRequest`, resolves auth/provider through keeper Codex crates, opens HTTP Responses streams through `codex-api`, and maps deltas/completion into typed stream events and receipts. `epiphany-openai-runtime` writes OpenAI status/request/stream-event/receipt records plus runtime sessions/jobs/results/events into `epiphany-core::runtime_spine_cache`, and its smoke proves the route without network. `epiphany-runtime-spine` advertises OpenAI adapter status/model-request/stream-event/receipt CultNet schemas and mutation contracts, so the native caller now has a real storage route instead of only JSON-RPC. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON. The current OpenAI spine still pulls `codex-api` and a large transport dependency stack, so its next cut is dependency starvation after live callers move.
|
||||
next_action: Continue Codex starvation by moving live model-turn callers from `thread/epiphany/*` JSON-RPC / `codex_message_processor.rs` onto `epiphany-openai-runtime` or the same native CultNet contract. Then shrink the surviving Codex dependency surface to credential refresh, provider/model routing, and the smallest OpenAI Responses call required for Codex subscription compatibility. Do not add Codex app-server, apps, skills, marketplace, or new Epiphany JSON-RPC dependencies.
|
||||
|
|
|
|||
2
vendor/codex/codex-rs/Cargo.lock
generated
vendored
2
vendor/codex/codex-rs/Cargo.lock
generated
vendored
|
|
@ -5245,6 +5245,7 @@ dependencies = [
|
|||
"codex-protocol",
|
||||
"cultcache-rs",
|
||||
"cultnet-rs",
|
||||
"epiphany-openai-adapter",
|
||||
"ignore",
|
||||
"postgres",
|
||||
"reqwest",
|
||||
|
|
@ -5259,6 +5260,7 @@ dependencies = [
|
|||
name = "epiphany-openai-adapter"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"cultcache-rs",
|
||||
"serde",
|
||||
]
|
||||
|
||||
|
|
|
|||
Reference in a new issue