mirror of
https://github.com/openai/codex.git
synced 2026-11-16 22:00:36 +00:00
[context] Add env context to every turn with gitinfo
This commit is contained in:
+32
-19
@@ -53,6 +53,7 @@ use crate::exec::StdoutStream;
|
||||
use crate::exec::StreamOutput;
|
||||
use crate::exec::process_exec_tool_call;
|
||||
use crate::exec_env::create_env;
|
||||
use crate::git_info::collect_git_info;
|
||||
use crate::mcp_connection_manager::McpConnectionManager;
|
||||
use crate::mcp_tool_call::handle_mcp_tool_call;
|
||||
use crate::model_family::find_family_for_model;
|
||||
@@ -267,6 +268,7 @@ pub(crate) struct TurnContext {
|
||||
pub(crate) shell_environment_policy: ShellEnvironmentPolicy,
|
||||
pub(crate) disable_response_storage: bool,
|
||||
pub(crate) tools_config: ToolsConfig,
|
||||
pub(crate) git_info: Option<crate::git_info::GitInfo>,
|
||||
}
|
||||
|
||||
impl TurnContext {
|
||||
@@ -472,6 +474,9 @@ impl Session {
|
||||
model_reasoning_summary,
|
||||
session_id,
|
||||
);
|
||||
// Collect git info for the initial cwd
|
||||
let git_info_val = collect_git_info(&cwd).await;
|
||||
|
||||
let turn_context = TurnContext {
|
||||
client,
|
||||
tools_config: ToolsConfig::new(
|
||||
@@ -488,6 +493,7 @@ impl Session {
|
||||
shell_environment_policy: config.shell_environment_policy.clone(),
|
||||
cwd,
|
||||
disable_response_storage,
|
||||
git_info: git_info_val,
|
||||
};
|
||||
let sess = Arc::new(Session {
|
||||
session_id,
|
||||
@@ -501,17 +507,11 @@ impl Session {
|
||||
show_raw_agent_reasoning: config.show_raw_agent_reasoning,
|
||||
});
|
||||
|
||||
// record the initial user instructions and environment context,
|
||||
// regardless of whether we restored items.
|
||||
let mut conversation_items = Vec::<ResponseItem>::with_capacity(2);
|
||||
// record the initial user instructions (environment context is recorded per-turn)
|
||||
let mut conversation_items = Vec::<ResponseItem>::with_capacity(1);
|
||||
if let Some(user_instructions) = turn_context.user_instructions.as_deref() {
|
||||
conversation_items.push(Prompt::format_user_instructions_message(user_instructions));
|
||||
}
|
||||
conversation_items.push(ResponseItem::from(EnvironmentContext::new(
|
||||
turn_context.cwd.to_path_buf(),
|
||||
turn_context.approval_policy,
|
||||
turn_context.sandbox_policy.clone(),
|
||||
)));
|
||||
sess.record_conversation_items(&conversation_items).await;
|
||||
|
||||
// Dispatch the SessionConfiguredEvent first and then report any errors.
|
||||
@@ -1051,6 +1051,13 @@ async fn submission_loop(
|
||||
config.include_apply_patch_tool,
|
||||
);
|
||||
|
||||
// Recompute git info if cwd changed
|
||||
let new_git_info = if cwd.is_some() {
|
||||
collect_git_info(&new_cwd).await
|
||||
} else {
|
||||
prev.git_info.clone()
|
||||
};
|
||||
|
||||
let new_turn_context = TurnContext {
|
||||
client,
|
||||
tools_config,
|
||||
@@ -1061,18 +1068,12 @@ async fn submission_loop(
|
||||
shell_environment_policy: prev.shell_environment_policy.clone(),
|
||||
cwd: new_cwd.clone(),
|
||||
disable_response_storage: prev.disable_response_storage,
|
||||
git_info: new_git_info,
|
||||
};
|
||||
|
||||
// Install the new persistent context for subsequent tasks/turns.
|
||||
turn_context = Arc::new(new_turn_context);
|
||||
if cwd.is_some() || approval_policy.is_some() || sandbox_policy.is_some() {
|
||||
sess.record_conversation_items(&[ResponseItem::from(EnvironmentContext::new(
|
||||
new_cwd,
|
||||
new_approval_policy,
|
||||
new_sandbox_policy,
|
||||
))])
|
||||
.await;
|
||||
}
|
||||
// Environment context is recorded at the start of each turn.
|
||||
}
|
||||
Op::UserInput { items } => {
|
||||
// attempt to inject input into current task
|
||||
@@ -1117,6 +1118,9 @@ async fn submission_loop(
|
||||
sess.session_id,
|
||||
);
|
||||
|
||||
// Collect git info for the per-turn cwd
|
||||
let per_turn_git_info = collect_git_info(&cwd).await;
|
||||
|
||||
let fresh_turn_context = TurnContext {
|
||||
client,
|
||||
tools_config: ToolsConfig::new(
|
||||
@@ -1133,8 +1137,8 @@ async fn submission_loop(
|
||||
shell_environment_policy: turn_context.shell_environment_policy.clone(),
|
||||
cwd,
|
||||
disable_response_storage: turn_context.disable_response_storage,
|
||||
git_info: per_turn_git_info,
|
||||
};
|
||||
// TODO: record the new environment context in the conversation history
|
||||
// no current task, spawn a new one with the per‑turn context
|
||||
let task =
|
||||
AgentTask::spawn(sess.clone(), Arc::new(fresh_turn_context), sub.id, items);
|
||||
@@ -1302,8 +1306,17 @@ async fn run_task(
|
||||
}
|
||||
|
||||
let initial_input_for_turn: ResponseInputItem = ResponseInputItem::from(input);
|
||||
sess.record_conversation_items(&[initial_input_for_turn.clone().into()])
|
||||
.await;
|
||||
// Record environment context first, then the user's initial input for this turn.
|
||||
sess.record_conversation_items(&[
|
||||
ResponseItem::from(EnvironmentContext::new(
|
||||
turn_context.cwd.clone(),
|
||||
turn_context.approval_policy,
|
||||
turn_context.sandbox_policy.clone(),
|
||||
turn_context.git_info.clone(),
|
||||
)),
|
||||
initial_input_for_turn.clone().into(),
|
||||
])
|
||||
.await;
|
||||
|
||||
let mut last_agent_message: Option<String> = None;
|
||||
// Although from the perspective of codex.rs, TurnDiffTracker has the lifecycle of a Task which contains
|
||||
|
||||
@@ -2,6 +2,8 @@ use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use strum_macros::Display as DeriveDisplay;
|
||||
|
||||
use crate::git_info::GitInfo;
|
||||
use crate::git_info::fmt_for_env_context;
|
||||
use crate::models::ContentItem;
|
||||
use crate::models::ResponseItem;
|
||||
use crate::protocol::AskForApproval;
|
||||
@@ -28,6 +30,7 @@ pub(crate) struct EnvironmentContext {
|
||||
pub approval_policy: AskForApproval,
|
||||
pub sandbox_mode: SandboxMode,
|
||||
pub network_access: NetworkAccess,
|
||||
pub git_info: Option<GitInfo>,
|
||||
}
|
||||
|
||||
impl EnvironmentContext {
|
||||
@@ -35,6 +38,7 @@ impl EnvironmentContext {
|
||||
cwd: PathBuf,
|
||||
approval_policy: AskForApproval,
|
||||
sandbox_policy: SandboxPolicy,
|
||||
git_info: Option<GitInfo>,
|
||||
) -> Self {
|
||||
Self {
|
||||
cwd,
|
||||
@@ -55,6 +59,7 @@ impl EnvironmentContext {
|
||||
}
|
||||
}
|
||||
},
|
||||
git_info,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,6 +74,7 @@ impl Display for EnvironmentContext {
|
||||
writeln!(f, "Approval policy: {}", self.approval_policy)?;
|
||||
writeln!(f, "Sandbox mode: {}", self.sandbox_mode)?;
|
||||
writeln!(f, "Network access: {}", self.network_access)?;
|
||||
writeln!(f, "{}", fmt_for_env_context(self.git_info.as_ref()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ use tokio::time::timeout;
|
||||
/// Timeout for git commands to prevent freezing on large repositories
|
||||
const GIT_COMMAND_TIMEOUT: TokioDuration = TokioDuration::from_secs(5);
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
|
||||
pub struct GitInfo {
|
||||
/// Current commit hash (SHA)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -20,6 +20,9 @@ pub struct GitInfo {
|
||||
/// Repository URL (if available from remote)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub repository_url: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub diff_stat: Option<String>,
|
||||
}
|
||||
|
||||
/// Collect git repository information from the given working directory using command-line git.
|
||||
@@ -38,16 +41,18 @@ pub async fn collect_git_info(cwd: &Path) -> Option<GitInfo> {
|
||||
}
|
||||
|
||||
// Run all git info collection commands in parallel
|
||||
let (commit_result, branch_result, url_result) = tokio::join!(
|
||||
let (commit_result, branch_result, url_result, diff_result) = tokio::join!(
|
||||
run_git_command_with_timeout(&["rev-parse", "HEAD"], cwd),
|
||||
run_git_command_with_timeout(&["rev-parse", "--abbrev-ref", "HEAD"], cwd),
|
||||
run_git_command_with_timeout(&["remote", "get-url", "origin"], cwd)
|
||||
run_git_command_with_timeout(&["remote", "get-url", "origin"], cwd),
|
||||
run_git_command_with_timeout(&["diff", "--stat", "HEAD"], cwd),
|
||||
);
|
||||
|
||||
let mut git_info = GitInfo {
|
||||
commit_hash: None,
|
||||
branch: None,
|
||||
repository_url: None,
|
||||
diff_stat: None,
|
||||
};
|
||||
|
||||
// Process commit hash
|
||||
@@ -77,9 +82,43 @@ pub async fn collect_git_info(cwd: &Path) -> Option<GitInfo> {
|
||||
git_info.repository_url = Some(url.trim().to_string());
|
||||
}
|
||||
|
||||
// Process diff stat
|
||||
if let Some(output) = diff_result {
|
||||
if output.status.success() {
|
||||
if let Ok(diff_stat) = String::from_utf8(output.stdout) {
|
||||
git_info.diff_stat = Some(diff_stat.trim().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(git_info)
|
||||
}
|
||||
|
||||
/// Format Git information for inclusion in the environment context block.
|
||||
/// When `info` is `None`, it returns a simple "Current git info:\nnone" string.
|
||||
pub fn fmt_for_env_context(info: Option<&GitInfo>) -> String {
|
||||
let mut parts: Vec<String> = vec!["Current git info:".to_string()];
|
||||
if let Some(info) = info {
|
||||
if let Some(hash) = &info.commit_hash {
|
||||
let short = &hash[..std::cmp::min(7, hash.len())];
|
||||
parts.push(format!("commit {short}"));
|
||||
}
|
||||
if let Some(branch) = &info.branch {
|
||||
parts.push(format!("branch {branch}"));
|
||||
}
|
||||
if let Some(url) = &info.repository_url {
|
||||
parts.push(format!("remote {url}"));
|
||||
}
|
||||
if let Some(diff_stat) = &info.diff_stat {
|
||||
parts.push("diff stat:".to_string());
|
||||
parts.push(diff_stat.clone());
|
||||
}
|
||||
} else {
|
||||
parts.push("none".to_string());
|
||||
}
|
||||
parts.join("\n")
|
||||
}
|
||||
|
||||
/// Run a git command with a timeout to prevent blocking on large repositories
|
||||
async fn run_git_command_with_timeout(args: &[&str], cwd: &Path) -> Option<std::process::Output> {
|
||||
let result = timeout(
|
||||
@@ -278,6 +317,7 @@ mod tests {
|
||||
commit_hash: Some("abc123def456".to_string()),
|
||||
branch: Some("main".to_string()),
|
||||
repository_url: Some("https://github.com/example/repo.git".to_string()),
|
||||
diff_stat: Some("1 file changed, 1 insertion(+), 1 deletion(-)".to_string()),
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&git_info).expect("Should serialize GitInfo");
|
||||
@@ -289,6 +329,10 @@ mod tests {
|
||||
parsed["repository_url"],
|
||||
"https://github.com/example/repo.git"
|
||||
);
|
||||
assert_eq!(
|
||||
parsed["diff_stat"],
|
||||
"1 file changed, 1 insertion(+), 1 deletion(-)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -297,6 +341,7 @@ mod tests {
|
||||
commit_hash: None,
|
||||
branch: None,
|
||||
repository_url: None,
|
||||
diff_stat: None,
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&git_info).expect("Should serialize GitInfo");
|
||||
@@ -306,5 +351,6 @@ mod tests {
|
||||
assert!(!parsed.as_object().unwrap().contains_key("commit_hash"));
|
||||
assert!(!parsed.as_object().unwrap().contains_key("branch"));
|
||||
assert!(!parsed.as_object().unwrap().contains_key("repository_url"));
|
||||
assert!(!parsed.as_object().unwrap().contains_key("diff_stat"));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user