Add typed OpenAI transport spine

This commit is contained in:
Meta Vens 2026-05-13 05:01:33 +01:00
commit c23c16450c
7 changed files with 346 additions and 12 deletions

View file

@ -10,6 +10,12 @@ name = "epiphany_openai_codex_spine"
path = "src/lib.rs"
[dependencies]
anyhow = "1"
codex-api = { path = "../vendor/codex/codex-rs/codex-api" }
codex-app-server-protocol = { path = "../vendor/codex/codex-rs/app-server-protocol" }
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" }
codex-protocol = { path = "../vendor/codex/codex-rs/protocol" }
epiphany-openai-adapter = { path = "../epiphany-openai-adapter" }
futures = "0.3"

View file

@ -1,8 +1,35 @@
use std::str::FromStr;
use std::sync::Arc;
use std::sync::OnceLock;
use anyhow::Context;
use anyhow::Result;
use codex_api::Compression;
use codex_api::ReqwestTransport;
use codex_api::ResponseEvent;
use codex_api::ResponsesApiRequest;
use codex_api::ResponsesClient;
use codex_api::ResponsesOptions;
use codex_app_server_protocol::AuthMode;
use codex_login::AuthManager;
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 codex_protocol::config_types::ReasoningSummary;
use codex_protocol::config_types::ServiceTier;
use codex_protocol::models::ContentItem;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::ReasoningEffort;
use epiphany_openai_adapter::EpiphanyOpenAiAdapterStatus;
use epiphany_openai_adapter::EpiphanyOpenAiAuthMode;
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 futures::StreamExt;
pub const CODEX_SPINE_ADAPTER_ID: &str = "codex-openai-subscription-spine";
@ -48,6 +75,262 @@ pub fn status_from_codex_auth(
}
}
pub struct EpiphanyCodexOpenAiTransport {
auth_manager: Arc<AuthManager>,
provider_info: ModelProviderInfo,
}
impl EpiphanyCodexOpenAiTransport {
pub fn new(auth_manager: Arc<AuthManager>, provider_info: ModelProviderInfo) -> Self {
Self {
auth_manager,
provider_info,
}
}
pub fn openai(auth_manager: Arc<AuthManager>) -> Self {
Self::new(
auth_manager,
ModelProviderInfo::create_openai_provider(/*base_url*/ 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 conversation_id = Some(request.conversation_id.clone());
let request_id = request.request_id.clone();
let model = request.model.clone();
let mut stream = client
.stream_request(
responses_request_from_epiphany(request)?,
ResponsesOptions {
conversation_id,
session_source: None,
extra_headers: Default::default(),
compression: Compression::None,
turn_state: Some(Arc::new(OnceLock::new())),
},
)
.await
.context("failed to open OpenAI Responses stream through Codex spine")?;
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;
}
}
}
Ok(events)
}
}
pub fn responses_request_from_epiphany(
request: EpiphanyOpenAiModelRequest,
) -> Result<ResponsesApiRequest> {
Ok(ResponsesApiRequest {
model: request.model,
instructions: request.instructions,
input: request
.input
.into_iter()
.map(response_item_from_epiphany_input)
.collect(),
tools: Vec::new(),
tool_choice: "auto".to_string(),
parallel_tool_calls: false,
reasoning: Some(codex_api::Reasoning {
effort: parse_reasoning_effort(request.reasoning_effort.as_deref())?,
summary: parse_reasoning_summary(request.reasoning_summary.as_deref())?,
}),
store: true,
stream: true,
include: Vec::new(),
service_tier: parse_service_tier(request.service_tier.as_deref())?
.map(|tier| tier.to_string()),
prompt_cache_key: None,
text: None,
client_metadata: None,
})
}
fn response_item_from_epiphany_input(input: EpiphanyOpenAiInputItem) -> ResponseItem {
match input {
EpiphanyOpenAiInputItem::UserText { text } => ResponseItem::Message {
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText { text }],
end_turn: None,
phase: None,
},
EpiphanyOpenAiInputItem::AssistantText { text } => ResponseItem::Message {
id: None,
role: "assistant".to_string(),
content: vec![ContentItem::OutputText { text }],
end_turn: None,
phase: None,
},
EpiphanyOpenAiInputItem::ToolResult { call_id, output } => {
ResponseItem::FunctionCallOutput {
call_id,
output: FunctionCallOutputPayload::from_text(output),
}
}
}
}
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 })
}
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::OutputItemDone(ResponseItem::FunctionCall {
name,
arguments,
call_id,
..
})
| ResponseEvent::OutputItemAdded(ResponseItem::FunctionCall {
name,
arguments,
call_id,
..
}) => Some(EpiphanyOpenAiStreamPayload::ToolCall {
call_id,
name,
arguments,
}),
ResponseEvent::OutputItemDone(ResponseItem::CustomToolCall {
call_id,
name,
input,
..
})
| ResponseEvent::OutputItemAdded(ResponseItem::CustomToolCall {
call_id,
name,
input,
..
}) => Some(EpiphanyOpenAiStreamPayload::ToolCall {
call_id,
name,
arguments: input,
}),
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);
}
Some(EpiphanyOpenAiStreamPayload::Completed { receipt })
}
ResponseEvent::Created
| ResponseEvent::OutputItemAdded(_)
| ResponseEvent::OutputItemDone(_)
| ResponseEvent::ServerModel(_)
| ResponseEvent::ServerReasoningIncluded(_)
| ResponseEvent::ReasoningSummaryPartAdded { .. }
| ResponseEvent::RateLimits(_)
| ResponseEvent::ModelsEtag(_) => None,
}
}
fn parse_reasoning_effort(value: Option<&str>) -> Result<Option<ReasoningEffort>> {
value
.map(ReasoningEffort::from_str)
.transpose()
.map_err(anyhow::Error::msg)
}
fn parse_reasoning_summary(value: Option<&str>) -> Result<Option<ReasoningSummary>> {
match value {
None => Ok(None),
Some("auto") => Ok(Some(ReasoningSummary::Auto)),
Some("concise") => Ok(Some(ReasoningSummary::Concise)),
Some("detailed") => Ok(Some(ReasoningSummary::Detailed)),
Some("none") => Ok(Some(ReasoningSummary::None)),
Some(other) => anyhow::bail!("invalid reasoning_summary: {other}"),
}
}
fn parse_service_tier(value: Option<&str>) -> Result<Option<ServiceTier>> {
match value {
None => Ok(None),
Some("fast") => Ok(Some(ServiceTier::Fast)),
Some("flex") => Ok(Some(ServiceTier::Flex)),
Some(other) => anyhow::bail!("invalid service_tier: {other}"),
}
}
fn nonnegative_i64_to_u64(value: i64) -> Option<u64> {
u64::try_from(value).ok()
}
fn auth_mode_from_manager(
auth_manager: &AuthManager,
auth: Option<&CodexAuth>,
@ -99,4 +382,29 @@ mod tests {
assert_eq!(status.account_id, None);
assert!(!status.supports_websockets);
}
#[test]
fn maps_typed_request_to_responses_request_without_json_cargo() {
let mut request = EpiphanyOpenAiModelRequest::new(
"req-1",
"conversation-1",
"gpt-5.4",
"Answer plainly.",
);
request.input.push(EpiphanyOpenAiInputItem::UserText {
text: "hello".to_string(),
});
request.reasoning_effort = Some("low".to_string());
request.reasoning_summary = Some("concise".to_string());
request.service_tier = Some("flex".to_string());
let responses = responses_request_from_epiphany(request).expect("request should map");
assert_eq!(responses.model, "gpt-5.4");
assert_eq!(responses.instructions, "Answer plainly.");
assert_eq!(responses.input.len(), 1);
assert!(responses.stream);
assert_eq!(responses.service_tier.as_deref(), Some("flex"));
assert!(responses.tools.is_empty());
}
}

View file

@ -122,9 +122,16 @@ The first workspace-verified wrapper now exists as
keeper Codex auth types and projects `AuthManager` / `CodexAuth` into a typed
`EpiphanyOpenAiAdapterStatus`. `epiphany-codex-bridge` re-exports this spine so
the current app-server compatibility shell can compile it without making the
pure document crate depend on Codex. The remaining extraction is model
transport: typed Epiphany model requests must call the keeper Responses API
transport through this boundary rather than route through Epiphany JSON-RPC or
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 point is ownership: Epiphany calls a model adapter; it does not live inside

View file

@ -555,18 +555,25 @@ workspace-verified wrapper now exists as `epiphany-openai-codex-spine`: it
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.
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
`EpiphanyOpenAiModelReceipt` documents.
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.
Continue with the actual whale-carcass cut: add model transport behind the
native typed request/event/receipt surface, using the keeper Responses API
transport identified in `notes/codex-auth-spine-inventory.md`. Success is
Epiphany calling a model adapter rather than living inside the Codex host brain.
Do not resume Rider, Unity, Aquarium, Face, dogfood, planning, app, skill,
marketplace, or bridge expansion until this organ is being cut cleanly.
Continue with the actual whale-carcass cut: make an Epiphany-native runtime
surface call the typed OpenAI adapter/spine directly, then starve the old model
turn path out of `thread/epiphany/*` JSON-RPC and `codex_message_processor.rs`.
Success is Epiphany calling the model adapter from its own CultCache/CultNet
runtime boundary rather than living inside the Codex host brain. Do not resume
Rider, Unity, Aquarium, Face, dogfood, planning, app, skill, marketplace, or
bridge expansion until this organ is being cut cleanly.
The Phase 6 freshness slice is landed. It exposes read-only
`thread/epiphany/freshness` from live retrieval summaries plus graph

Binary file not shown.

View file

@ -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 the first workspace-verified Codex auth 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` depends on the keeper Codex auth types and projects `AuthManager` / `CodexAuth` into typed `EpiphanyOpenAiAdapterStatus`; it compiles through the vendored Codex app-server graph via `epiphany-codex-bridge` without contaminating the pure adapter crate. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON.
next_action: Continue Codex starvation by adding model transport behind the typed `epiphany-openai-adapter` request/event/receipt surface, using the keeper Codex Responses API transport under the workspace-verified spine boundary, without adding Codex app-server, apps, skills, marketplace, or Epiphany JSON-RPC dependencies. Do not resume app/skill/marketplace expansion.
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 workspace-verified 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. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON.
next_action: Continue Codex starvation by making an Epiphany-native runtime surface call the typed OpenAI adapter/spine directly, then starve the old model-turn path out of `thread/epiphany/*` JSON-RPC and `codex_message_processor.rs`, without adding Codex app-server, apps, skills, marketplace, or Epiphany JSON-RPC dependencies. Do not resume app/skill/marketplace expansion.

6
vendor/codex/codex-rs/Cargo.lock generated vendored
View file

@ -5266,9 +5266,15 @@ dependencies = [
name = "epiphany-openai-codex-spine"
version = "0.1.0"
dependencies = [
"anyhow",
"codex-api",
"codex-app-server-protocol",
"codex-login",
"codex-model-provider",
"codex-model-provider-info",
"codex-protocol",
"epiphany-openai-adapter",
"futures",
]
[[package]]