Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion crates/factory-server/examples/e2e_fixture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,13 @@ fn cost(store: &Store, flags: &HashMap<String, Vec<String>>) -> Result<()> {
Ok(flags.get(name).ok_or(format!("--{name} is required"))?[0].as_str())
};
let job = one("job")?.parse()?;
store.add_cost(job, one("usd")?.parse()?, false)?;
let usd = one("usd")?.parse()?;
if flags.contains_key("fetched") {
let at = store.get(job)?.job;
store.add_fetched_cost(job, usd, &at)?;
} else {
store.add_cost(job, usd, false)?;
}
if let Ok(cli) = one("local-cli") {
let cli = Cli::from_id(cli).ok_or("unknown --local-cli")?;
store.session_uuid(job, Session::Planning, Agent::Local)?;
Expand Down Expand Up @@ -511,6 +517,14 @@ fn main() -> Result<()> {
),
"apply" => apply(&store, &flags)?,
"cost" => cost(&store, &flags)?,
"cost-lookup" => {
let job = one("job")?.parse()?;
match one("state")?.as_str() {
"begin" => store.begin_cost_lookup(job)?,
"end" => store.end_cost_lookup(job)?,
_ => return Err("--state is begin or end".into()),
}
}
"log" => {
let job = one("job")?.parse()?;
let text = one("text")?;
Expand Down
5 changes: 3 additions & 2 deletions crates/factory-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,9 @@ pub use mcp::{
McpError, McpProjectSettings, McpServer, McpStages, McpTool, McpToolState, McpTransport,
};
pub use openrouter::{
HttpOpenRouterApi, OPENROUTER_BASE_URL, OpenRouterApi, OpenRouterKeyFuture, OpenRouterModel,
OpenRouterModelsFuture, parse_models,
GenerationError, HttpOpenRouterApi, OPENROUTER_BASE_URL, OpenRouterApi, OpenRouterCosts,
OpenRouterGenerationFuture, OpenRouterKeyFuture, OpenRouterModel, OpenRouterModelsFuture,
parse_generation_cost, parse_models,
};
pub use podman::PodmanExecutor;
pub use projects::{
Expand Down
12 changes: 8 additions & 4 deletions crates/factory-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ use factory_runner::{ForgeKind, Git, GitHub, GitLab, WorkerConfig};
use factory_server::{
Accounts, AgentRegistry, ClaudeToken, CodexLogin, DeviceLogin, Forges, GhRepos, GlabRepos,
HttpForgejoProbe, HttpLocalServerProbe, HttpMcpChecker, HttpOpenRouterApi, LocalSecrets,
LoginSpec, McpChecker, McpRuntime, McpWarnings, OpenRouterApi, PlanUsageCache, PodmanExecutor,
PodmanLogin, Projects, ProxyEvent, ProxyEventFn, RunTokens, Scheduler, SecretStore, Store,
StoreUpstreams, UnavailableSecrets, Upstreams, WorkerSlots, app_with_forgejo_probe,
import_tomls, master_key_from_env, parse_admins, proxy_app_with_roots,
LoginSpec, McpChecker, McpRuntime, McpWarnings, OpenRouterApi, OpenRouterCosts, PlanUsageCache,
PodmanExecutor, PodmanLogin, Projects, ProxyEvent, ProxyEventFn, RunTokens, Scheduler,
SecretStore, Store, StoreUpstreams, UnavailableSecrets, Upstreams, WorkerSlots,
app_with_forgejo_probe, import_tomls, master_key_from_env, parse_admins, proxy_app_with_roots,
};
use tokio::sync::Notify;

Expand Down Expand Up @@ -273,6 +273,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
local_probe: Arc::new(HttpLocalServerProbe::new()),
openrouter: Arc::clone(&openrouter_api),
};
if let Err(err) = store.clear_cost_lookups() {
tracing::error!("clearing cost lookups: {err}");
}
let scheduler = Scheduler::new(
Arc::clone(&store),
Arc::clone(&projects),
Expand All @@ -286,6 +289,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
warnings: Arc::clone(&mcp_warnings),
},
Accounts::new(Arc::clone(&store), Arc::clone(&secrets), forges.clone()),
OpenRouterCosts::new(Arc::clone(&openrouter_api)),
);
slots = scheduler.slots();
tokio::spawn(scheduler.run());
Expand Down
163 changes: 163 additions & 0 deletions crates/factory-server/src/openrouter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use crate::local_server::ModelsError;
Expand All @@ -27,6 +28,40 @@ pub type OpenRouterModelsFuture<'a> =
pub type OpenRouterKeyFuture<'a> =
Pin<Box<dyn Future<Output = Result<(), ModelsError>> + Send + 'a>>;

pub type OpenRouterGenerationFuture<'a> =
Pin<Box<dyn Future<Output = Result<f64, GenerationError>> + Send + 'a>>;

/// Why a generation's cost could not be read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GenerationError {
/// `OpenRouter` does not know the generation yet, or its answer holds no
/// cost yet. It can show up a moment after the run ends.
NotReady,
/// The request failed.
Failed(ModelsError),
}

impl GenerationError {
/// Whether asking again later can help. A 401 or 403 means `OpenRouter`
/// refuses the key, which waiting does not change.
#[must_use]
pub fn retryable(&self) -> bool {
!matches!(
self,
GenerationError::Failed(ModelsError::Status(401 | 403))
)
}
}

impl std::fmt::Display for GenerationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
GenerationError::NotReady => f.write_str("OpenRouter has no cost for it yet"),
GenerationError::Failed(error) => error.fmt(f),
}
}
}

/// Talks to `OpenRouter`. A trait so tests can answer without a network.
pub trait OpenRouterApi: Send + Sync {
/// Lists the models that support tool calls, sending `key` as a bearer
Expand All @@ -48,6 +83,90 @@ pub trait OpenRouterApi: Send + Sync {
/// [`ModelsError::Timeout`] when it cannot be reached. The text never holds
/// the key.
fn check_key<'a>(&'a self, key: &'a str) -> OpenRouterKeyFuture<'a>;

/// Reads what `OpenRouter` charged for generation `id` in USD, with one
/// `GET /api/v1/generation?id=<id>` using `key`.
///
/// # Errors
///
/// Returns [`GenerationError::NotReady`] for a 404 or an answer with no
/// `data.total_cost`, which can hold right after a run, and
/// [`GenerationError::Failed`] for any other failure. The text never holds
/// the key.
fn generation<'a>(&'a self, id: &'a str, key: &'a str) -> OpenRouterGenerationFuture<'a>;
}

/// Reads what a run was charged from the generations its output showed.
pub struct OpenRouterCosts {
api: Arc<dyn OpenRouterApi>,
delays: Vec<Duration>,
deadline: Duration,
}

impl OpenRouterCosts {
/// Asks again after 2, 4, 8, 16 and 30 seconds, and gives up after 90
/// seconds in all, requests included.
#[must_use]
pub fn new(api: Arc<dyn OpenRouterApi>) -> Self {
Self::with_limits(
api,
[2, 4, 8, 16, 30].map(Duration::from_secs).to_vec(),
Duration::from_secs(90),
)
}

/// As [`Self::new`], with the waits between the rounds of asking and the
/// time the whole lookup may take given.
#[must_use]
pub fn with_limits(
api: Arc<dyn OpenRouterApi>,
delays: Vec<Duration>,
deadline: Duration,
) -> Self {
OpenRouterCosts {
api,
delays,
deadline,
}
}

/// The sum of the costs of the generations `ids`, read with `key`. Each
/// round asks only for the ids still unread. `None` when an id stays
/// unread after the last round or the deadline, `OpenRouter` refuses the
/// key, or `ids` is empty. A lookup that runs out of time returns no
/// partial sum.
pub async fn total(&self, key: &str, ids: &[String]) -> Option<f64> {
if ids.is_empty() {
return None;
}
tokio::time::timeout(self.deadline, self.read(key, ids))
.await
.ok()
.flatten()
}

async fn read(&self, key: &str, ids: &[String]) -> Option<f64> {
let mut costs: Vec<Option<f64>> = vec![None; ids.len()];
for round in 0..=self.delays.len() {
for (id, slot) in ids.iter().zip(&mut costs) {
if slot.is_some() {
continue;
}
match self.api.generation(id, key).await {
Ok(cost) => *slot = Some(cost),
Err(error) if !error.retryable() => return None,
Err(_) => {}
}
}
if costs.iter().all(Option::is_some) {
break;
}
if let Some(delay) = self.delays.get(round) {
tokio::time::sleep(*delay).await;
}
}
costs.into_iter().sum()
}
}

/// The production [`OpenRouterApi`]. It follows no redirect, so the key never
Expand Down Expand Up @@ -131,6 +250,50 @@ impl OpenRouterApi for HttpOpenRouterApi {
}
})
}

fn generation<'a>(&'a self, id: &'a str, key: &'a str) -> OpenRouterGenerationFuture<'a> {
Box::pin(async move {
let client = self
.client
.as_ref()
.ok_or(GenerationError::Failed(ModelsError::Connect))?;
let response = client
.get(format!("{}/v1/generation", self.base_url))
.query(&[("id", id)])
.bearer_auth(key)
.send()
.await
.map_err(|err| GenerationError::Failed(transport(&err)))?;
let status = response.status();
if status == reqwest::StatusCode::NOT_FOUND {
return Err(GenerationError::NotReady);
}
if !status.is_success() {
return Err(GenerationError::Failed(ModelsError::Status(
status.as_u16(),
)));
}
let body = response
.bytes()
.await
.map_err(|err| GenerationError::Failed(transport(&err)))?;
parse_generation_cost(&body)
})
}
}

/// The `data.total_cost` of a generation answer.
///
/// # Errors
///
/// Returns [`GenerationError::NotReady`] when the body holds no non-negative
/// cost.
pub fn parse_generation_cost(body: &[u8]) -> Result<f64, GenerationError> {
serde_json::from_slice::<serde_json::Value>(body)
.ok()
.and_then(|value| value.get("data")?.get("total_cost")?.as_f64())
.filter(|cost| cost.is_finite() && *cost >= 0.0)
.ok_or(GenerationError::NotReady)
}

/// The models of an `OpenRouter` list that support tools, in its order. A model
Expand Down
18 changes: 11 additions & 7 deletions crates/factory-server/src/pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4704,6 +4704,7 @@ pub fn job(
auto_merge: bool,
links: &JobLinks,
prerequisites: &[PrerequisiteView],
cost_pending: bool,
) -> Markup {
let job = &row.job;
let repo_url = Links::of(project);
Expand All @@ -4714,7 +4715,7 @@ pub fn job(
&format!("Job #{id}"),
&html! {},
&html! {
(job_poll(false, id, job))
(job_poll(false, id, job, cost_pending))
(job_header(id, row, label, links, repo_url, cost_usd, estimated))
@if let Some(problem) = project.and_then(|project| project.forge.problem()) {
div.card.failed { (problem) }
Expand Down Expand Up @@ -4771,11 +4772,12 @@ pub fn job_fragment(
auto_merge: bool,
links: &JobLinks,
prerequisites: &[PrerequisiteView],
cost_pending: bool,
) -> Markup {
let job = &row.job;
let repo_url = Links::of(project);
html! {
@if terminal(job) { (job_poll(true, row.id, job)) }
@if terminal(job) { (job_poll(true, row.id, job, cost_pending)) }
(cost_badge(true, cost_usd, any_estimated(events)))
(timeline_region(true, job, events, models, efforts))
(status_region(true, row.id, label, job, settings, auto_merge, links, prerequisites))
Expand All @@ -4789,7 +4791,8 @@ pub fn job_fragment(
}

/// Merged, failed and cancelled jobs do not change again, so their page and
/// its fragments carry no polling attribute.
/// its fragments carry no polling attribute, unless an `OpenRouter` cost lookup
/// is still running and will add a cost and a log line.
fn terminal(job: &Job) -> bool {
matches!(
job.stage(),
Expand All @@ -4800,10 +4803,11 @@ fn terminal(job: &Job) -> bool {
/// The hidden element that polls the job fragment. A running job polls every
/// `POLL_TRIGGER` and lets htmx apply the out-of-band swaps the response
/// carries; `hx-swap="none"` keeps it from swapping the response into itself.
/// A terminal job gets a bare element with no polling attribute, so the loop
/// stops both on first load and when a running page reaches a terminal stage.
fn job_poll(oob: bool, id: i64, job: &Job) -> Markup {
let polling = !terminal(job);
/// A terminal job with no lookup running gets a bare element with no polling
/// attribute, so the loop stops both on first load and when a running page
/// reaches a terminal stage.
fn job_poll(oob: bool, id: i64, job: &Job, cost_pending: bool) -> Markup {
let polling = !terminal(job) || cost_pending;
html! {
div #job-poll hx-swap-oob=[oob.then_some("true")]
hx-get=[polling.then(|| format!("/jobs/{id}/fragment"))]
Expand Down
Loading