Replace Codex API OpenAI transport
This commit is contained in:
parent
a69c5a9c19
commit
ef46f7f5f1
6 changed files with 325 additions and 195 deletions
|
|
@ -11,12 +11,11 @@ path = "src/lib.rs"
|
|||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
codex-api = { path = "../vendor/codex/codex-rs/codex-api" }
|
||||
codex-client = { path = "../vendor/codex/codex-rs/codex-client" }
|
||||
codex-login = { path = "../vendor/codex/codex-rs/login" }
|
||||
codex-model-provider = { path = "../vendor/codex/codex-rs/model-provider" }
|
||||
codex-model-provider-info = { path = "../vendor/codex/codex-rs/model-provider-info" }
|
||||
epiphany-openai-adapter = { path = "../epiphany-openai-adapter" }
|
||||
futures = "0.3"
|
||||
http = "1"
|
||||
serde = "1"
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||
|
|
|
|||
|
|
@ -1,20 +1,18 @@
|
|||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_api::Compression;
|
||||
use codex_api::ReqwestTransport;
|
||||
use codex_api::ResponseEvent;
|
||||
use codex_api::ResponsesClient;
|
||||
use codex_api::build_conversation_headers;
|
||||
use codex_client::HttpTransport;
|
||||
use codex_client::Request;
|
||||
use codex_client::ReqwestTransport;
|
||||
use codex_client::TransportError;
|
||||
use codex_client::sse_stream;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::AuthMode;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::build_reqwest_client;
|
||||
use codex_model_provider::create_model_provider;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiAdapterStatus;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiAuthMode;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiInputItem;
|
||||
|
|
@ -23,8 +21,13 @@ use epiphany_openai_adapter::EpiphanyOpenAiModelRequest;
|
|||
use epiphany_openai_adapter::EpiphanyOpenAiStreamEvent;
|
||||
use epiphany_openai_adapter::EpiphanyOpenAiStreamPayload;
|
||||
use epiphany_openai_adapter::OPENAI_ADAPTER_STATUS_SCHEMA_ID;
|
||||
use futures::StreamExt;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
const CHATGPT_CODEX_BASE_URL: &str = "https://chatgpt.com/backend-api/codex";
|
||||
const OPENAI_API_BASE_URL: &str = "https://api.openai.com/v1";
|
||||
const RESPONSES_STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
|
||||
pub const CODEX_SPINE_ADAPTER_ID: &str = "codex-openai-subscription-spine";
|
||||
|
||||
|
|
@ -93,91 +96,89 @@ pub fn status_from_codex_auth(
|
|||
|
||||
pub struct EpiphanyCodexOpenAiTransport {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
provider_info: ModelProviderInfo,
|
||||
base_url: Option<String>,
|
||||
}
|
||||
|
||||
impl EpiphanyCodexOpenAiTransport {
|
||||
pub fn new(auth_manager: Arc<AuthManager>, provider_info: ModelProviderInfo) -> Self {
|
||||
pub fn new(auth_manager: Arc<AuthManager>, base_url: Option<String>) -> Self {
|
||||
Self {
|
||||
auth_manager,
|
||||
provider_info,
|
||||
base_url,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn openai(auth_manager: Arc<AuthManager>) -> Self {
|
||||
Self::new(
|
||||
auth_manager,
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
|
||||
)
|
||||
Self::new(auth_manager, None)
|
||||
}
|
||||
|
||||
pub async fn collect_model_events(
|
||||
&self,
|
||||
request: EpiphanyOpenAiModelRequest,
|
||||
) -> Result<Vec<EpiphanyOpenAiStreamEvent>> {
|
||||
let model_provider = create_model_provider(
|
||||
self.provider_info.clone(),
|
||||
Some(Arc::clone(&self.auth_manager)),
|
||||
);
|
||||
let api_provider = model_provider.api_provider().await?;
|
||||
let api_auth = model_provider.api_auth().await?;
|
||||
let client = ResponsesClient::new(
|
||||
ReqwestTransport::new(build_reqwest_client()),
|
||||
api_provider,
|
||||
api_auth,
|
||||
);
|
||||
let mut headers = build_conversation_headers(Some(request.conversation_id.clone()));
|
||||
if let Ok(value) = request.conversation_id.parse() {
|
||||
headers.insert("x-client-request-id", value);
|
||||
}
|
||||
let request_id = request.request_id.clone();
|
||||
let model = request.model.clone();
|
||||
let mut stream = client
|
||||
.stream(
|
||||
responses_body_from_epiphany(request)?,
|
||||
headers,
|
||||
Compression::None,
|
||||
Some(Arc::new(OnceLock::new())),
|
||||
)
|
||||
let auth = self
|
||||
.auth_manager
|
||||
.auth()
|
||||
.await
|
||||
.context("failed to open OpenAI Responses stream through Codex spine")?;
|
||||
.ok_or_else(|| anyhow::anyhow!("Codex auth is unavailable"))?;
|
||||
let stream_response = self.open_responses_stream(&auth, request).await?;
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(1600);
|
||||
sse_stream(stream_response.bytes, RESPONSES_STREAM_IDLE_TIMEOUT, tx);
|
||||
|
||||
let mut sequence = 0;
|
||||
let mut events = Vec::new();
|
||||
while let Some(event) = stream.next().await {
|
||||
match event {
|
||||
Ok(event) => {
|
||||
if let Some(payload) = stream_payload_from_response_event(
|
||||
event,
|
||||
request_id.as_str(),
|
||||
model.as_str(),
|
||||
) {
|
||||
events.push(EpiphanyOpenAiStreamEvent {
|
||||
schema_id: epiphany_openai_adapter::OPENAI_ADAPTER_EVENT_SCHEMA_ID
|
||||
.to_string(),
|
||||
request_id: request_id.clone(),
|
||||
sequence,
|
||||
payload,
|
||||
});
|
||||
sequence += 1;
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
events.push(EpiphanyOpenAiStreamEvent {
|
||||
schema_id: epiphany_openai_adapter::OPENAI_ADAPTER_EVENT_SCHEMA_ID
|
||||
.to_string(),
|
||||
request_id: request_id.clone(),
|
||||
sequence,
|
||||
payload: EpiphanyOpenAiStreamPayload::Failed {
|
||||
message: err.to_string(),
|
||||
},
|
||||
});
|
||||
break;
|
||||
}
|
||||
let mut stream_state = EpiphanyResponsesStreamState::new(&request_id, &model);
|
||||
while let Some(frame) = rx.recv().await {
|
||||
match frame {
|
||||
Ok(frame) => stream_state.push_sse_frame(&frame),
|
||||
Err(err) => stream_state.push_failed(err.to_string()),
|
||||
}
|
||||
if stream_state.completed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(events)
|
||||
if stream_state.events.is_empty() {
|
||||
stream_state.push_failed("Responses stream closed without typed events".to_string());
|
||||
}
|
||||
Ok(stream_state.events)
|
||||
}
|
||||
|
||||
async fn open_responses_stream(
|
||||
&self,
|
||||
auth: &CodexAuth,
|
||||
request: EpiphanyOpenAiModelRequest,
|
||||
) -> Result<codex_client::StreamResponse> {
|
||||
let base_url = self
|
||||
.base_url
|
||||
.clone()
|
||||
.unwrap_or_else(|| default_base_url_for_auth(auth).to_string());
|
||||
let url = format!("{}/responses", base_url.trim_end_matches('/'));
|
||||
let conversation_id = request.conversation_id.clone();
|
||||
let mut outbound = Request::new(http::Method::POST, url)
|
||||
.with_json(&responses_body_from_epiphany(request)?);
|
||||
attach_codex_auth_headers(auth, &mut outbound.headers)
|
||||
.context("failed to attach Codex auth headers")?;
|
||||
outbound
|
||||
.headers
|
||||
.insert(http::header::ACCEPT, "text/event-stream".parse()?);
|
||||
outbound
|
||||
.headers
|
||||
.insert("session_id", conversation_id.parse()?);
|
||||
outbound
|
||||
.headers
|
||||
.insert("x-client-request-id", conversation_id.parse()?);
|
||||
attach_optional_env_header(
|
||||
&mut outbound.headers,
|
||||
"OpenAI-Organization",
|
||||
"OPENAI_ORGANIZATION",
|
||||
);
|
||||
attach_optional_env_header(&mut outbound.headers, "OpenAI-Project", "OPENAI_PROJECT");
|
||||
|
||||
let transport = ReqwestTransport::new(build_reqwest_client());
|
||||
transport
|
||||
.stream(outbound)
|
||||
.await
|
||||
.map_err(transport_error_to_anyhow)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -279,51 +280,125 @@ fn openai_input_item_from_epiphany_input(
|
|||
}
|
||||
}
|
||||
|
||||
fn stream_payload_from_response_event(
|
||||
event: ResponseEvent,
|
||||
request_id: &str,
|
||||
requested_model: &str,
|
||||
) -> Option<EpiphanyOpenAiStreamPayload> {
|
||||
match event {
|
||||
ResponseEvent::OutputTextDelta(text) => {
|
||||
Some(EpiphanyOpenAiStreamPayload::TextDelta { text })
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct EpiphanyResponsesStreamEvent {
|
||||
#[serde(rename = "type")]
|
||||
kind: String,
|
||||
response: Option<Value>,
|
||||
item_id: Option<String>,
|
||||
call_id: Option<String>,
|
||||
delta: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct EpiphanyResponseCompleted {
|
||||
id: String,
|
||||
#[serde(default)]
|
||||
usage: Option<EpiphanyResponseCompletedUsage>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct EpiphanyResponseCompletedUsage {
|
||||
input_tokens: i64,
|
||||
output_tokens: i64,
|
||||
output_tokens_details: Option<EpiphanyResponseCompletedOutputTokensDetails>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct EpiphanyResponseCompletedOutputTokensDetails {
|
||||
reasoning_tokens: i64,
|
||||
}
|
||||
|
||||
struct EpiphanyResponsesStreamState {
|
||||
request_id: String,
|
||||
requested_model: String,
|
||||
sequence: u64,
|
||||
completed: bool,
|
||||
events: Vec<EpiphanyOpenAiStreamEvent>,
|
||||
}
|
||||
|
||||
impl EpiphanyResponsesStreamState {
|
||||
fn new(request_id: &str, requested_model: &str) -> Self {
|
||||
Self {
|
||||
request_id: request_id.to_string(),
|
||||
requested_model: requested_model.to_string(),
|
||||
sequence: 0,
|
||||
completed: false,
|
||||
events: Vec::new(),
|
||||
}
|
||||
ResponseEvent::ReasoningSummaryDelta { delta, .. }
|
||||
| ResponseEvent::ReasoningContentDelta { delta, .. } => {
|
||||
Some(EpiphanyOpenAiStreamPayload::ReasoningDelta { text: delta })
|
||||
}
|
||||
ResponseEvent::ToolCallInputDelta {
|
||||
item_id,
|
||||
call_id,
|
||||
delta,
|
||||
} => Some(EpiphanyOpenAiStreamPayload::ToolCall {
|
||||
call_id: call_id.unwrap_or(item_id.clone()),
|
||||
name: item_id,
|
||||
arguments: delta,
|
||||
}),
|
||||
ResponseEvent::Completed {
|
||||
response_id,
|
||||
token_usage,
|
||||
} => {
|
||||
let mut receipt = EpiphanyOpenAiModelReceipt::new(request_id, requested_model);
|
||||
receipt.response_id = Some(response_id);
|
||||
receipt.transport = Some("codex_responses_http".to_string());
|
||||
if let Some(usage) = token_usage {
|
||||
receipt.input_tokens = nonnegative_i64_to_u64(usage.input_tokens);
|
||||
receipt.output_tokens = nonnegative_i64_to_u64(usage.output_tokens);
|
||||
receipt.reasoning_output_tokens =
|
||||
nonnegative_i64_to_u64(usage.reasoning_output_tokens);
|
||||
}
|
||||
|
||||
fn push_sse_frame(&mut self, frame: &str) {
|
||||
let Ok(event) = serde_json::from_str::<EpiphanyResponsesStreamEvent>(frame) else {
|
||||
return;
|
||||
};
|
||||
match event.kind.as_str() {
|
||||
"response.output_text.delta" => {
|
||||
if let Some(text) = event.delta {
|
||||
self.push_payload(EpiphanyOpenAiStreamPayload::TextDelta { text });
|
||||
}
|
||||
}
|
||||
Some(EpiphanyOpenAiStreamPayload::Completed { receipt })
|
||||
"response.reasoning_summary_text.delta" | "response.reasoning_text.delta" => {
|
||||
if let Some(text) = event.delta {
|
||||
self.push_payload(EpiphanyOpenAiStreamPayload::ReasoningDelta { text });
|
||||
}
|
||||
}
|
||||
"response.custom_tool_call_input.delta" => {
|
||||
if let (Some(arguments), Some(name)) =
|
||||
(event.delta, event.item_id.clone().or(event.call_id.clone()))
|
||||
{
|
||||
self.push_payload(EpiphanyOpenAiStreamPayload::ToolCall {
|
||||
call_id: event.call_id.unwrap_or_else(|| name.clone()),
|
||||
name,
|
||||
arguments,
|
||||
});
|
||||
}
|
||||
}
|
||||
"response.completed" => {
|
||||
if let Some(response) = event.response {
|
||||
match serde_json::from_value::<EpiphanyResponseCompleted>(response) {
|
||||
Ok(completed) => self.push_completed(completed),
|
||||
Err(err) => self.push_failed(format!(
|
||||
"failed to parse response.completed event: {err}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
self.completed = true;
|
||||
}
|
||||
"response.failed" | "response.incomplete" => {
|
||||
self.push_failed(response_error_message(event.response.as_ref()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
ResponseEvent::Created
|
||||
| ResponseEvent::OutputItemAdded(_)
|
||||
| ResponseEvent::OutputItemDone(_)
|
||||
| ResponseEvent::ServerModel(_)
|
||||
| ResponseEvent::ServerReasoningIncluded(_)
|
||||
| ResponseEvent::ReasoningSummaryPartAdded { .. }
|
||||
| ResponseEvent::RateLimits(_)
|
||||
| ResponseEvent::ModelsEtag(_) => None,
|
||||
}
|
||||
|
||||
fn push_completed(&mut self, completed: EpiphanyResponseCompleted) {
|
||||
let mut receipt = EpiphanyOpenAiModelReceipt::new(&self.request_id, &self.requested_model);
|
||||
receipt.response_id = Some(completed.id);
|
||||
receipt.transport = Some("epiphany_direct_responses_http".to_string());
|
||||
if let Some(usage) = completed.usage {
|
||||
receipt.input_tokens = nonnegative_i64_to_u64(usage.input_tokens);
|
||||
receipt.output_tokens = nonnegative_i64_to_u64(usage.output_tokens);
|
||||
receipt.reasoning_output_tokens = usage
|
||||
.output_tokens_details
|
||||
.and_then(|details| nonnegative_i64_to_u64(details.reasoning_tokens));
|
||||
}
|
||||
self.push_payload(EpiphanyOpenAiStreamPayload::Completed { receipt });
|
||||
}
|
||||
|
||||
fn push_failed(&mut self, message: String) {
|
||||
self.push_payload(EpiphanyOpenAiStreamPayload::Failed { message });
|
||||
self.completed = true;
|
||||
}
|
||||
|
||||
fn push_payload(&mut self, payload: EpiphanyOpenAiStreamPayload) {
|
||||
self.events.push(EpiphanyOpenAiStreamEvent {
|
||||
schema_id: epiphany_openai_adapter::OPENAI_ADAPTER_EVENT_SCHEMA_ID.to_string(),
|
||||
request_id: self.request_id.clone(),
|
||||
sequence: self.sequence,
|
||||
payload,
|
||||
});
|
||||
self.sequence += 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -357,6 +432,70 @@ fn nonnegative_i64_to_u64(value: i64) -> Option<u64> {
|
|||
u64::try_from(value).ok()
|
||||
}
|
||||
|
||||
fn default_base_url_for_auth(auth: &CodexAuth) -> &'static str {
|
||||
if auth.uses_codex_backend() {
|
||||
CHATGPT_CODEX_BASE_URL
|
||||
} else {
|
||||
OPENAI_API_BASE_URL
|
||||
}
|
||||
}
|
||||
|
||||
fn attach_codex_auth_headers(
|
||||
auth: &CodexAuth,
|
||||
headers: &mut http::HeaderMap,
|
||||
) -> std::io::Result<()> {
|
||||
let token = auth.get_token()?;
|
||||
let value = format!("Bearer {token}");
|
||||
if let Ok(value) = value.parse() {
|
||||
headers.insert(http::header::AUTHORIZATION, value);
|
||||
}
|
||||
if let Some(account_id) = auth.get_account_id()
|
||||
&& let Ok(value) = account_id.parse()
|
||||
{
|
||||
headers.insert("ChatGPT-Account-ID", value);
|
||||
}
|
||||
if auth.is_fedramp_account() {
|
||||
headers.insert("X-OpenAI-Fedramp", "true".parse().expect("valid header"));
|
||||
}
|
||||
headers.insert(
|
||||
"version",
|
||||
env!("CARGO_PKG_VERSION").parse().expect("valid header"),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn attach_optional_env_header(headers: &mut http::HeaderMap, name: &'static str, env_key: &str) {
|
||||
let Ok(value) = std::env::var(env_key) else {
|
||||
return;
|
||||
};
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Ok(value) = value.parse() {
|
||||
headers.insert(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
fn response_error_message(response: Option<&Value>) -> String {
|
||||
response
|
||||
.and_then(|response| response.get("error"))
|
||||
.and_then(|error| error.get("message"))
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| {
|
||||
response
|
||||
.and_then(|response| response.get("incomplete_details"))
|
||||
.and_then(|details| details.get("reason"))
|
||||
.and_then(Value::as_str)
|
||||
})
|
||||
.unwrap_or("Responses stream failed")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn transport_error_to_anyhow(err: TransportError) -> anyhow::Error {
|
||||
anyhow::anyhow!("failed to open direct Responses stream: {err}")
|
||||
}
|
||||
|
||||
fn auth_mode_from_manager(
|
||||
auth_manager: &AuthManager,
|
||||
auth: Option<&CodexAuth>,
|
||||
|
|
|
|||
|
|
@ -9,7 +9,8 @@ here is suspect until proven otherwise.
|
|||
|
||||
- User authentication material from Codex auth storage or an external auth
|
||||
provider.
|
||||
- Model/provider configuration from Codex config and model provider metadata.
|
||||
- Model name and optional endpoint override from Epiphany-owned request/config
|
||||
surfaces.
|
||||
- Per-turn model request data: prompt instructions, formatted input, tools,
|
||||
output schema, reasoning controls, service tier, and model metadata.
|
||||
- Session identity: conversation/thread id, installation id, window id,
|
||||
|
|
@ -21,33 +22,30 @@ here is suspect until proven otherwise.
|
|||
`vendor/codex/codex-rs/login/src/auth/manager.rs`.
|
||||
- Auth token state in `CodexAuth` / `ChatgptAuthState`, including refreshable
|
||||
ChatGPT tokens and account metadata.
|
||||
- Model cache managed by
|
||||
`vendor/codex/codex-rs/models-manager/src/manager.rs`.
|
||||
- Session-scoped model transport state inside
|
||||
`vendor/codex/codex-rs/core/src/client.rs`: provider, auth environment
|
||||
telemetry, conversation id, websocket fallback state, and cached websocket
|
||||
session.
|
||||
- No durable model/provider state is owned by the current OpenAI spine. The
|
||||
model string is request data; catalog/default selection must become a typed
|
||||
Epiphany document before it can be keeper machinery.
|
||||
|
||||
### Transformations
|
||||
|
||||
- `codex-login` loads auth, refreshes ChatGPT access tokens, preserves account
|
||||
metadata, and exposes `CodexAuth`.
|
||||
- `codex-model-provider` converts `CodexAuth` plus provider config into a
|
||||
bearer auth provider and API provider.
|
||||
- `models-manager` uses provider auth to fetch `/models`, cache the catalog,
|
||||
and choose default/model metadata.
|
||||
- `codex-core::client` builds Responses API requests from typed prompt/model
|
||||
structures, adds Codex/OpenAI identity headers, chooses HTTP or websocket
|
||||
transport, streams response events, and handles auth/error/rate-limit
|
||||
telemetry.
|
||||
- `epiphany-openai-codex-spine` converts `CodexAuth` directly into
|
||||
authorization/account headers, chooses the ChatGPT Codex backend or OpenAI API
|
||||
base URL from auth mode, builds a local serializable Responses request body,
|
||||
opens an HTTP/SSE stream through `codex-client`, and parses Responses frames
|
||||
into typed Epiphany stream events.
|
||||
- `codex-login` still drags `codex-config`, `codex-model-provider-info`,
|
||||
`codex-api`, and `codex-protocol` transitively. That is dependency rot, not
|
||||
current request-path ownership.
|
||||
|
||||
### Outputs
|
||||
|
||||
- Bearer-authenticated OpenAI/ChatGPT-compatible model calls.
|
||||
- Streaming model response events.
|
||||
- Compaction/memory/realtime model helper calls that use the same provider
|
||||
setup.
|
||||
- Model catalog and model metadata.
|
||||
- No compaction/memory/realtime helper calls are part of this spine unless a
|
||||
typed Epiphany caller explicitly earns them later.
|
||||
- No model catalog or model metadata store is keeper machinery yet.
|
||||
- Auth and transport telemetry/errors needed to recover or report failure.
|
||||
|
||||
## Keep
|
||||
|
|
@ -56,16 +54,9 @@ here is suspect until proven otherwise.
|
|||
organ. It knows ChatGPT/API-key/agent/external auth modes, refresh semantics,
|
||||
token storage, and account metadata. Long term, wrap it behind an Epiphany
|
||||
`OpenAIAuthAdapter` instead of letting the rest of Epiphany import it.
|
||||
- `model-provider/src/auth.rs` and `model-provider/src/provider.rs`: keep as
|
||||
the provider auth resolver. This is the narrow bridge from Codex auth state to
|
||||
API bearer auth.
|
||||
- `core/src/client.rs`: keep only the model transport subset: provider setup,
|
||||
Responses request construction, HTTP/websocket streaming, identity headers,
|
||||
and auth recovery telemetry. It is too entangled to delete before a native
|
||||
Epiphany model adapter exists.
|
||||
- `models-manager/src/manager.rs`: keep narrowly for model catalog refresh,
|
||||
default model selection, and auth-mode filtering until Epiphany has its own
|
||||
typed model catalog document.
|
||||
- `codex-client`: keep only as a plain HTTP/SSE transport helper for now. It
|
||||
does not own Epiphany request shape, model policy, stream semantics, or durable
|
||||
state.
|
||||
|
||||
## Cut Or Seal
|
||||
|
||||
|
|
@ -78,8 +69,10 @@ here is suspect until proven otherwise.
|
|||
- `codex-core::client` helper calls for memories/realtime/compaction are
|
||||
suspicious unless Epiphany deliberately needs that OpenAI endpoint. Keep them
|
||||
sealed with the transport until the native adapter split can decide.
|
||||
- `models-manager` collaboration mode surfaces are not part of the auth spine.
|
||||
Model catalog yes; collaboration-mode presets no.
|
||||
- `codex-api`, `codex-model-provider`, `codex-model-provider-info`,
|
||||
`codex-core::client`, and `models-manager` are no longer part of the direct
|
||||
OpenAI request path. If a later model catalog is needed, it should be a typed
|
||||
Epiphany catalog document, not a revival of the old Codex provider stack.
|
||||
|
||||
## Extract Target
|
||||
|
||||
|
|
@ -96,11 +89,10 @@ EpiphanyOpenAIModelTransport
|
|||
-> emit typed stream events / receipts
|
||||
```
|
||||
|
||||
The adapter may depend on `codex-login`, `codex-model-provider`,
|
||||
`codex-model-provider-info`, `codex-api`, and the narrow model-transport pieces
|
||||
of `codex-core`. It must not depend on `codex-app-server`,
|
||||
`codex_message_processor`, plugin/app/skill/marketplace modules, or Epiphany
|
||||
state ownership.
|
||||
The adapter may depend on `codex-login` and `codex-client` only while the
|
||||
reliquary survives. It must not depend on
|
||||
`codex-app-server`, `codex_message_processor`, plugin/app/skill/marketplace
|
||||
modules, Codex provider/request construction, or Epiphany state ownership.
|
||||
|
||||
## Next Cut
|
||||
|
||||
|
|
@ -124,15 +116,14 @@ keeper Codex auth types and projects `AuthManager` / `CodexAuth` into a typed
|
|||
the current app-server compatibility shell can compile it without making the
|
||||
pure document crate depend on Codex.
|
||||
|
||||
The first transport wrapper is now also in that spine. It maps typed
|
||||
`EpiphanyOpenAiModelRequest` documents into Codex API `ResponsesApiRequest`,
|
||||
resolves auth/provider through `codex-login` + `codex-model-provider`, opens an
|
||||
HTTP Responses stream with `codex-api`, and converts stream deltas/completion
|
||||
into typed `EpiphanyOpenAiStreamEvent` / `EpiphanyOpenAiModelReceipt`
|
||||
documents. This is still a compatibility reliquary, not final native purity:
|
||||
the next cut is to make an Epiphany-native runtime call this transport boundary
|
||||
directly instead of reaching model turns through `thread/epiphany/*` JSON-RPC or
|
||||
the Codex host brain.
|
||||
The transport wrapper is now also in that spine. It maps typed
|
||||
`EpiphanyOpenAiModelRequest` documents into a local serializable Responses
|
||||
request body, resolves credentials through `codex-login`, chooses the
|
||||
ChatGPT/OpenAI base URL from auth mode, opens an HTTP Responses SSE stream with
|
||||
`codex-client`, and converts stream deltas/completion into typed
|
||||
`EpiphanyOpenAiStreamEvent` / `EpiphanyOpenAiModelReceipt` documents. It no
|
||||
longer directly imports Codex `ResponsesApiRequest`, `ResponsesClient`,
|
||||
`ResponseEvent`, provider config, model-provider, or protocol enums.
|
||||
|
||||
The CultNet paperwork is now public too. `schemas/cultnet/` contains typed
|
||||
schemas for OpenAI adapter status, model request, stream event, and terminal
|
||||
|
|
@ -180,12 +171,13 @@ application. `codex-core` re-exports the contract only as a compatibility
|
|||
alias, and `CodexThread` now calls native state-update functions around its
|
||||
remaining revision check, persistence validation, and rollout/session writeback.
|
||||
|
||||
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
|
||||
surviving Codex dependency surface to credential loading/refresh, provider
|
||||
auth, model selection, and the smallest OpenAI Responses HTTP call that keeps
|
||||
Codex subscription compatibility.
|
||||
The bad news is useful: `cargo tree -i codex-api` still shows `codex-api` and
|
||||
`codex-protocol` entering through `codex-login`'s dependency graph
|
||||
(`codex-config`, `codex-model-provider-info`, and `codex-otel`). That is not
|
||||
proof the request path needs them. It is proof the credential organ is still
|
||||
fat. The next purification should extract or rewrite the minimum auth surface:
|
||||
credential loading, token refresh, account metadata, and header material needed
|
||||
to keep Codex subscription/API-key compatibility.
|
||||
|
||||
The point is ownership: Epiphany calls a model adapter; it does not live inside
|
||||
the Codex host brain.
|
||||
|
|
|
|||
|
|
@ -34,11 +34,11 @@ remembers doctrine; the branch remembers the blade.
|
|||
|
||||
- Do not copy exact branch or HEAD from this note. Run `git status --short --branch` and `git log --oneline -5`.
|
||||
- The active foundation directive is now `notes/codex-starvation-and-cultnet-liberation-plan.md`. The previous Codex app-server control-plane rebuild made Epiphany less rotten inside Codex, but that is not the destination. Epiphany must become a native CultCache/CultNet runtime. Codex is a compatibility reliquary for OpenAI subscription auth and model transport, not the host brain.
|
||||
- `notes/codex-auth-spine-inventory.md` is the source-grounded keeper list for that reliquary: retain `codex-login` credential storage/refresh, `codex-model-provider` auth resolution, the model-transport subset of `codex-core::client`, and the narrow model-catalog subset of `models-manager`; do not treat Codex app-server, apps, skills, marketplace, plugin UX, MCP OAuth handlers, or collaboration-mode surfaces as auth-spine machinery.
|
||||
- `notes/codex-auth-spine-inventory.md` is the source-grounded keeper list for that reliquary: retain `codex-login` credential storage/refresh only while it preserves Codex subscription/API-key compatibility, and keep `codex-client` only as a plain HTTP/SSE helper. `codex-api`, `codex-model-provider`, `codex-model-provider-info`, `codex-core::client`, and `models-manager` are no longer keeper request-path organs; if model catalog/routing grows back, it should be an Epiphany typed document surface.
|
||||
- Edge JSON is allowed for schema description, hostile ingress before immediate typed parsing, sealed forensic artifacts, or named quarantine experiments. When both subsystems are ours, runtime data must remain typed CultCache documents and move over CultNet typed contracts. Generic `serde_json::Value` in worker launch/result/selfPatch/runtime flow is contamination until classified and replaced.
|
||||
- `epiphany-openai-runtime` worker result ingress now parses assistant output directly into typed role/reorient ingress structs selected from the durable launch document, stores nested `statePatch` and `selfPatch` as typed MessagePack in `EpiphanyRuntimeRoleWorkerResult`, and no longer passes worker result data through generic `serde_json::Value`. JSON survives there only as the OpenAI text-output edge before typed deserialization.
|
||||
- Agent self-memory review/application now has typed `AgentSelfPatch` core APIs. JSON-value selfPatch functions are compatibility wrappers for CLI/artifact ingress; native callers should parse once at the edge and then call `review_agent_self_patch_document` / `apply_agent_self_patch_document`.
|
||||
- `epiphany-openai-codex-spine` no longer has a direct `codex-protocol` dependency for outbound model requests. It builds a local serializable OpenAI Responses body instead of Codex `ResponseItem` / reasoning / service-tier protocol enums, then hands JSON to `codex-api::ResponsesClient::stream` at the HTTP edge. This starves one layer, but `codex-api` still brings `codex-protocol` transitively; removing that requires a direct Responses/SSE transport over Codex auth/provider credentials.
|
||||
- `epiphany-openai-codex-spine` no longer uses Codex's Responses client, model-provider layer, `codex-api`, `codex-model-provider`, `codex-model-provider-info`, or `codex-protocol` directly for outbound model requests. It keeps `codex-login` for subscription/API-key auth, builds a local serializable OpenAI Responses body, opens the HTTP/SSE stream through `codex-client`, and parses Responses SSE frames into typed Epiphany stream events. `codex-login` still drags `codex-config` / `codex-model-provider-info` / `codex-api` / `codex-protocol` transitively, so the next real spine cut is a minimal auth crate or extracted credential adapter.
|
||||
- Durable Epiphany state types now live in root crate `epiphany-state-model`. `codex-protocol` re-exports them only so old rollout/API callers keep compiling; do not add new durable `Epiphany*` state structs under `vendor/codex`. `epiphany-core` imports the native model directly and no longer depends on `codex-protocol`. Pressure derives from native `EpiphanyTokenUsageSnapshot`; Codex token telemetry is mapped at the bridge. Codex rollout/event reconstruction now lives in `codex-core::epiphany_rollout`, where the Codex `RolloutItem` / `EventMsg` types belong. Exact retrieval path matching is native to `epiphany-core`, so `epiphany-core` has no direct vendored Codex crate dependency.
|
||||
- The May 2026 foundation migration in `notes/epiphany-ideal-architecture-rebuild-plan.md` is complete enough to defend. Read `notes/epiphany-architectural-teardown.md` before touching Epiphany control-plane code, but do not treat it as an open-ended excuse to keep shaving the altar. The rebuild moved scene projection, freshness derivation, pressure policy, targeted context shards, bounded graph traversal, job/progress view derivation, planning view derivation, reorientation resume/regather verdict policy, pure CRRC recommendation policy, fixed-lane coordinator decision policy, role-board projection policy, role/reorient result interpretation, role self-persistence review policy, and role/reorient acceptance bundle policy into `epiphany-core`; typed acceptance receipts replaced summary-string identity for live accept paths, runtime links are dual-written on launch, and result read-back now prefers runtime links.
|
||||
- Read `notes/epiphany-ideal-architecture-rebuild-plan.md` immediately after the teardown. It defines the smallest coherent replacement architecture: durable `EpiphanyState`, runtime-spine-owned `RuntimeState`, separate role memory/heartbeat state, `epiphany-core` as policy owner, app-server as adapter, Aquarium as reflector, typed acceptance receipts, and derived view lenses instead of a protocol verb zoo.
|
||||
|
|
@ -374,10 +374,12 @@ Do not continue implementation automatically from a rehydrate-only request.
|
|||
The next real move remains Codex starvation, not outward bridge work. The
|
||||
inventory and ledger now exist:
|
||||
|
||||
- `notes/codex-auth-spine-inventory.md` maps the minimal Codex auth/model-call
|
||||
reliquary: `login` auth/token refresh, `codex-api` auth/provider/session and
|
||||
Responses edge, `codex-client` transport, and the suspect current
|
||||
`core/src/client.rs` orchestration.
|
||||
- `notes/codex-auth-spine-inventory.md` maps the shrinking Codex
|
||||
auth/model-call reliquary: `login` auth/token refresh is still kept for
|
||||
subscription compatibility, `codex-client` is a plain HTTP/SSE edge, and
|
||||
`codex-api` / `codex-protocol` are no longer directly used by the OpenAI
|
||||
request path. Their remaining presence comes through `codex-login`'s fat
|
||||
dependency graph.
|
||||
- `notes/json-contamination-ledger.md` classifies the major Epiphany JSON
|
||||
contamination. Edge JSON is allowed only for schema/wire boundaries,
|
||||
hostile ingress before typed parse, sealed forensic artifacts, or named
|
||||
|
|
@ -560,28 +562,27 @@ depends on the pure typed adapter plus the keeper Codex auth types and projects
|
|||
`AuthManager` / `CodexAuth` into a typed `EpiphanyOpenAiAdapterStatus`.
|
||||
`epiphany-codex-bridge` re-exports that spine so the current app-server shell
|
||||
can compile the attachment without contaminating the pure document crate. The
|
||||
same spine now owns the first HTTP Responses transport wrapper: typed
|
||||
`EpiphanyOpenAiModelRequest` documents map into Codex API
|
||||
`ResponsesApiRequest`, auth/provider resolves through `codex-login` and
|
||||
`codex-model-provider`, the stream opens through `codex-api`, and deltas /
|
||||
completion map back into typed `EpiphanyOpenAiStreamEvent` and
|
||||
same spine now owns the HTTP Responses transport wrapper without Codex's
|
||||
Responses client or model-provider layer: typed `EpiphanyOpenAiModelRequest`
|
||||
documents map into a local serializable Responses body, auth comes from
|
||||
`codex-login`, the stream opens through `codex-client`, and Responses SSE frames
|
||||
parse back into typed `EpiphanyOpenAiStreamEvent` and
|
||||
`EpiphanyOpenAiModelReceipt` documents. The spine no longer directly depends on
|
||||
`codex-app-server-protocol` merely to name auth mode; `codex-login` re-exports
|
||||
that type as part of the keeper auth organ. The CultNet schema catalog now
|
||||
advertises OpenAI adapter status, model request, stream event, and receipt
|
||||
document types plus the coordinator-owned model request contract. The native
|
||||
runtime should consume that contract next; do not make a new JSON-RPC model
|
||||
endpoint and pretend the whale got lighter.
|
||||
`codex-app-server-protocol`, `codex-protocol`, `codex-api`,
|
||||
`codex-model-provider`, or `codex-model-provider-info`. The CultNet schema
|
||||
catalog advertises OpenAI adapter status, model request, stream event, and
|
||||
receipt document types plus the coordinator-owned model request contract. The
|
||||
remaining contamination is `codex-login` itself: it still pulls the fat Codex
|
||||
config/model-provider/API/protocol stack transitively.
|
||||
|
||||
The `epiphany-openai-spine` binary is now the first native edge for that
|
||||
wrapper. It can print typed adapter status and consume a serialized
|
||||
`EpiphanyOpenAiModelRequest` document for a model turn outside Codex
|
||||
app-server. Treat its JSON as CLI/file-edge serialization of typed documents,
|
||||
not internal data cargo. The current wrapper still pulls `codex-api` and a
|
||||
large dependency stack, so the next real cut is not celebration; it is routing
|
||||
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.
|
||||
not internal data cargo. The native request path no longer pulls `codex-api`
|
||||
directly, so the next real cut is not celebration; it is extracting or
|
||||
rewriting the minimum `codex-login` credential surface so auth compatibility no
|
||||
longer imports the old Codex config/model-provider/API/protocol stack.
|
||||
|
||||
The native runtime no longer imports `codex-login` directly. The Codex spine now
|
||||
exports the `default_codex_home` and `auth_manager` helpers, so
|
||||
|
|
@ -604,9 +605,8 @@ documents, and completes the original heartbeat/specialist runtime job without
|
|||
Codex worker execution. `roleResult` and `reorientResult` now require those
|
||||
typed worker result documents; generic runtime job summaries are lifecycle
|
||||
receipts, not reviewable findings.
|
||||
The next cut is wiring coordinator/heartbeat automation to invoke `run-worker`
|
||||
for launched runtime job ids, then carving down the `codex-api` dependency
|
||||
weight.
|
||||
The next cut is carving down the remaining `codex-login` dependency weight
|
||||
without losing ChatGPT subscription/API-key compatibility.
|
||||
|
||||
That coordinator cut is now landed for the MVP runner. `epiphany-mvp-coordinator`
|
||||
accepts `--openai-runtime-bin`, resolves the local `epiphany-openai-runtime`
|
||||
|
|
|
|||
Binary file not shown.
File diff suppressed because one or more lines are too long
Reference in a new issue