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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/factory-runner/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ tracing = "0.1.44"

[dev-dependencies]
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "net"] }
toml = "1.2.1"
11 changes: 11 additions & 0 deletions crates/factory-runner/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,3 +200,14 @@ pub fn backend(agent: Agent) -> Option<&'static dyn AgentBackend> {
Agent::Copilot => Some(&CopilotAgent),
}
}

/// Writes `contents` to `dir/name` through a fresh temporary file in `dir` and a
/// rename. A previous worker can leave a symlink at `name`, and a rename replaces
/// the link itself, where an in-place write would follow it out of `dir`.
pub(crate) fn write_replacing(dir: &Path, name: &str, contents: &str) -> std::io::Result<()> {
use std::io::Write as _;
let mut file = tempfile::NamedTempFile::new_in(dir)?;
file.write_all(contents.as_bytes())?;
file.persist(dir.join(name)).map_err(|err| err.error)?;
Ok(())
}
75 changes: 59 additions & 16 deletions crates/factory-runner/src/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,18 @@ use std::path::Path;

use factory_core::Agent;

use crate::agent::{AgentBackend, AgentItem, Credential, PromptStyle, RunResult};
use crate::agent::{AgentBackend, AgentItem, Credential, PromptStyle, RunResult, write_replacing};
use crate::outcome::{Expect, event_from_result};
use crate::stream::{StreamItem, parse_line};
use crate::worker::{
AGENTS_DIR, McpConfig, McpServerEntry, McpUnavailable, SessionRun, WorkerConfig, WorkerRun,
AGENTS_DIR, McpConfig, McpServerEntry, McpUnavailable, STDIO_STARTUP_TIMEOUT_SECS, SessionRun,
WorkerConfig, WorkerRun,
};

/// The Claude Code config directory inside the worker, mounted from the job's
/// `claude` directory on the host. It keeps the session files `--resume` reads.
const CONFIG_DIR: &str = "/claude";
const MCP_CONFIG_FILE: &str = "factory-mcp.json";

/// Settings for every Claude run. Claude Code adds a `Co-Authored-By` trailer
/// to commits and a footer to pull request descriptions unless `attribution`
Expand Down Expand Up @@ -66,6 +68,13 @@ impl AgentBackend for ClaudeAgent {
"claude"
}

fn prepare(&self, run: &WorkerRun) -> std::io::Result<()> {
match run.mcp.as_ref().filter(|mcp| mcp.has_stdio()) {
Some(mcp) => write_replacing(&run.config_dir, MCP_CONFIG_FILE, &mcp_config(mcp)),
None => Ok(()),
}
}

fn session_for(&self, host_config_dir: &Path, id: &str) -> SessionRun {
let transcript = format!("{id}.jsonl");
if contains_file(&host_config_dir.join("projects"), &transcript) {
Expand All @@ -92,7 +101,7 @@ impl AgentBackend for ClaudeAgent {
"--json-schema".into(),
run.expect.schema().to_string(),
"--settings".into(),
AGENT_SETTINGS.into(),
settings(run.mcp.as_ref()),
session_flag.into(),
session_id.clone(),
];
Expand All @@ -113,10 +122,15 @@ impl AgentBackend for ClaudeAgent {
);
// One `http` entry per active MCP server, pointed at the proxy with the
// run token. A run with no active server adds nothing, so its arguments
// match a run from before MCP.
// match a run from before MCP. A run with a stdio server reads the config
// from a file, since its arguments can outgrow one argv element.
if let Some(mcp) = run.mcp.as_ref().filter(|mcp| !mcp.servers.is_empty()) {
claude.push("--mcp-config".into());
claude.push(mcp_config(mcp));
if mcp.has_stdio() {
claude.push(format!("{CONFIG_DIR}/{MCP_CONFIG_FILE}"));
} else {
claude.push(mcp_config(mcp));
}
}
claude.into_iter().map(OsString::from).collect()
}
Expand Down Expand Up @@ -150,22 +164,51 @@ impl AgentBackend for ClaudeAgent {
}
}

/// The JSON for `claude --mcp-config`: one `http` entry per active server, each
/// pointing at the proxy and carrying `Authorization: Bearer <token>` as its
/// only header. No stored credential appears here; the proxy adds it.
/// The JSON for `claude --settings`. A run with a stdio server raises Claude's
/// MCP startup timeout, `MCP_TIMEOUT`, through the settings `env` key, because a
/// first start of a package runner downloads the package and the default is 30
/// seconds. Settings carry it, so the container gets no `--env` for it.
fn settings(mcp: Option<&McpConfig>) -> String {
if mcp.is_some_and(McpConfig::has_stdio) {
serde_json::json!({
"attribution": { "commit": "", "pr": "", "sessionUrl": false },
"env": { "MCP_TIMEOUT": (STDIO_STARTUP_TIMEOUT_SECS * 1000).to_string() },
})
.to_string()
} else {
AGENT_SETTINGS.to_owned()
}
}

/// The JSON for `claude --mcp-config`: one entry per active server. A remote
/// server is an `http` entry pointing at the proxy and carrying
/// `Authorization: Bearer <token>` as its only header; no stored credential
/// appears here, the proxy adds it. A stdio server is a `stdio` entry with its
/// command and arguments.
fn mcp_config(mcp: &McpConfig) -> String {
let servers: serde_json::Map<String, serde_json::Value> = mcp
.servers
.iter()
.map(|server| match server {
McpServerEntry::Remote { name } => (
.filter_map(|server| match server {
McpServerEntry::Remote { name } => {
let proxy = mcp.proxy.as_ref()?;
Some((
name.clone(),
serde_json::json!({
"type": "http",
"url": format!("{}/mcp/{name}", proxy.url),
"headers": { "Authorization": format!("Bearer {}", proxy.token) },
}),
))
}
McpServerEntry::Stdio {
name,
command,
args,
} => Some((
name.clone(),
serde_json::json!({
"type": "http",
"url": format!("{}/mcp/{name}", mcp.proxy_url),
"headers": { "Authorization": format!("Bearer {}", mcp.token) },
}),
),
serde_json::json!({ "type": "stdio", "command": command, "args": args }),
)),
})
.collect();
serde_json::json!({ "mcpServers": servers }).to_string()
Expand Down
90 changes: 77 additions & 13 deletions crates/factory-runner/src/codex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,19 @@ use std::ffi::OsString;
use std::fs;
use std::path::Path;

use std::fmt::Write as _;

use factory_core::Agent;
use serde_json::Value;

use crate::agent::{AgentBackend, AgentItem, Credential, PromptStyle, RunResult, TokenUsage};
use crate::agent::{
AgentBackend, AgentItem, Credential, PromptStyle, RunResult, TokenUsage, write_replacing,
};
use crate::outcome::{Expect, event_from_output, failed_event};
use crate::stream::LogLine;
use crate::worker::{McpServerEntry, SessionRun, WorkerConfig, WorkerRun};
use crate::worker::{
McpServerEntry, STDIO_STARTUP_TIMEOUT_SECS, SessionRun, WorkerConfig, WorkerRun,
};

/// The Codex config directory inside the worker, mounted from the job's `codex`
/// directory on the host and passed to Codex as `CODEX_HOME`. It keeps the
Expand Down Expand Up @@ -100,18 +106,42 @@ impl AgentBackend for CodexAgent {
}

fn prepare(&self, run: &WorkerRun) -> std::io::Result<()> {
fs::write(run.config_dir.join(CONFIG_FILE), CONFIG_TOML)?;
let mut config = CONFIG_TOML.to_owned();
for entry in run.mcp.iter().flat_map(|mcp| &mcp.servers) {
if let McpServerEntry::Stdio {
name,
command,
args,
} = entry
{
// Codex's startup timeout defaults to 10 seconds, too short for
// a first download.
let _ = write!(
config,
"\n[mcp_servers.{name}]\ncommand = {}\nargs = {}\nstartup_timeout_sec = {STDIO_STARTUP_TIMEOUT_SECS}\n",
toml_string(command),
toml_array(args)
);
}
}
write_replacing(&run.config_dir, CONFIG_FILE, &config)?;
fs::write(
run.config_dir.join(SCHEMA_FILE),
run.expect.strict_schema().to_string(),
)
}

fn secret_env<'a>(&self, run: &'a WorkerRun) -> Vec<(&'static str, &'a str)> {
// The MCP run token, by name only, for a run with at least one active
// server. A run with none passes none, so it gets no token.
match run.mcp.as_ref().filter(|mcp| !mcp.servers.is_empty()) {
Some(mcp) => vec![(MCP_TOKEN_ENV, mcp.token.as_str())],
// The MCP run token, by name only, for a run with at least one remote
// server. A run with none, such as one with only stdio servers, passes
// none, so it gets no token.
match run
.mcp
.as_ref()
.filter(|mcp| !mcp.servers.is_empty())
.and_then(|mcp| mcp.proxy.as_ref())
{
Some(proxy) => vec![(MCP_TOKEN_ENV, proxy.token.as_str())],
None => Vec::new(),
}
}
Expand Down Expand Up @@ -143,24 +173,30 @@ impl AgentBackend for CodexAgent {
.as_deref()
.unwrap_or_else(|| Agent::Codex.default_effort())
));
// One remote MCP server per active server, pointed at the proxy. The run
// token is passed by name, not value, so it stays out of the arguments;
// the proxy swaps it for the project's stored headers. A run with no
// active server adds nothing.
if let Some(mcp) = run.mcp.as_ref().filter(|mcp| !mcp.servers.is_empty()) {
// A remote MCP server is pointed at the proxy. The run token is passed
// by name, not value, so it stays out of the arguments; the proxy swaps
// it for the project's stored headers. A run with no active server adds
// nothing.
if let Some(mcp) = run.mcp.as_ref() {
for entry in &mcp.servers {
match entry {
McpServerEntry::Remote { name: server } => {
let Some(proxy) = mcp.proxy.as_ref() else {
continue;
};
codex.push("-c".into());
codex.push(format!(
"mcp_servers.{server}.url=\"{}/mcp/{server}\"",
mcp.proxy_url
proxy.url
));
codex.push("-c".into());
codex.push(format!(
"mcp_servers.{server}.bearer_token_env_var=\"{MCP_TOKEN_ENV}\""
));
}
// Stdio entries live in config.toml, since their arguments
// can outgrow one argv element.
McpServerEntry::Stdio { .. } => {}
}
}
}
Expand All @@ -173,6 +209,34 @@ impl AgentBackend for CodexAgent {
}
}

/// `value` as a TOML basic string, which `-c` parses as the override's value.
fn toml_string(value: &str) -> String {
let mut out = String::with_capacity(value.len() + 2);
out.push('"');
for ch in value.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'\u{8}' => out.push_str("\\b"),
'\u{c}' => out.push_str("\\f"),
ch if ch.is_control() => {
let _ = write!(out, "\\u{:04X}", u32::from(ch));
}
ch => out.push(ch),
}
}
out.push('"');
out
}

fn toml_array(values: &[String]) -> String {
let items: Vec<String> = values.iter().map(|value| toml_string(value)).collect();
format!("[{}]", items.join(","))
}

/// Parses one line of `codex exec --json`. A line the factory does not keep,
/// such as `turn.started`, `item.started` or `item.updated`, gives nothing.
fn parse_codex(expect: Expect, line: &str) -> Vec<AgentItem> {
Expand Down
Loading