mirror of
https://github.com/openai/codex.git
synced 2026-12-06 01:10:58 +00:00
Merge remote-tracking branch 'origin/main' into abhinav/requirements-toml-managed-fields
# Conflicts: # codex-rs/app-server-protocol/schema/typescript/v2/ConfigRequirements.ts # codex-rs/app-server/README.md # codex-rs/config/src/config_requirements.rs # codex-rs/exec/src/lib.rs # codex-rs/tui/src/lib.rs
This commit is contained in:
@@ -55,6 +55,7 @@ fn keep_forked_rollout_item(item: &RolloutItem, preserve_reference_context_item:
|
||||
| ResponseItem::ContextCompaction { .. }
|
||||
| ResponseItem::Other,
|
||||
) => false,
|
||||
RolloutItem::InterAgentCommunication(_) => false,
|
||||
// Full-history forks preserve the cached prompt prefix and can keep diffing
|
||||
// from the parent's durable baseline. Truncated forks drop part of that prompt,
|
||||
// so they must rebuild context on their first child turn.
|
||||
|
||||
+134
-13
@@ -16,6 +16,9 @@
|
||||
//! 3. We do **not** walk past the project root.
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::context::ContextualUserFragment;
|
||||
use crate::context::UserInstructions as ContextUserInstructions;
|
||||
use crate::environment_selection::ResolvedTurnEnvironments;
|
||||
use codex_app_server_protocol::ConfigLayerSource;
|
||||
use codex_config::ConfigLayerStackOrdering;
|
||||
use codex_config::default_project_root_markers;
|
||||
@@ -45,15 +48,26 @@ const AGENTS_MD_SEPARATOR: &str = "\n\n--- project-doc ---\n\n";
|
||||
pub(crate) async fn load_project_instructions(
|
||||
config: &mut Config,
|
||||
user_instructions: Option<UserInstructions>,
|
||||
fs: Option<&dyn ExecutorFileSystem>,
|
||||
environments: &ResolvedTurnEnvironments,
|
||||
) -> Option<LoadedAgentsMd> {
|
||||
let mut loaded = LoadedAgentsMd::from_user_instructions(user_instructions);
|
||||
if let Some(fs) = fs {
|
||||
match read_agents_md(config, fs).await {
|
||||
for turn_environment in &environments.turn_environments {
|
||||
let filesystem = turn_environment.environment.get_filesystem();
|
||||
match read_agents_md(
|
||||
config,
|
||||
filesystem.as_ref(),
|
||||
&turn_environment.environment_id,
|
||||
turn_environment.cwd(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(docs)) => loaded.entries.extend(docs.entries),
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
error!("error trying to find AGENTS.md docs: {e:#}");
|
||||
error!(
|
||||
environment_id = turn_environment.environment_id,
|
||||
"error trying to find AGENTS.md docs: {e:#}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,6 +91,8 @@ pub(crate) async fn load_project_instructions(
|
||||
async fn read_agents_md(
|
||||
config: &mut Config,
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
environment_id: &str,
|
||||
cwd: &AbsolutePathBuf,
|
||||
) -> io::Result<Option<LoadedAgentsMd>> {
|
||||
let max_total = config.project_doc_max_bytes;
|
||||
|
||||
@@ -84,7 +100,7 @@ async fn read_agents_md(
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let paths = agents_md_paths(config, fs).await?;
|
||||
let paths = agents_md_paths(config, cwd, fs).await?;
|
||||
if paths.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -97,7 +113,7 @@ async fn read_agents_md(
|
||||
break;
|
||||
}
|
||||
|
||||
let path_uri = PathUri::from_abs_path(&p)?;
|
||||
let path_uri = PathUri::from_abs_path(&p);
|
||||
match fs.get_metadata(&path_uri, /*sandbox*/ None).await {
|
||||
Ok(metadata) if !metadata.is_file => continue,
|
||||
Ok(_) => {}
|
||||
@@ -129,7 +145,11 @@ async fn read_agents_md(
|
||||
if !text.trim().is_empty() {
|
||||
loaded.entries.push(InstructionEntry {
|
||||
contents: text,
|
||||
provenance: InstructionProvenance::Project(p),
|
||||
provenance: InstructionProvenance::Project {
|
||||
source_path: p,
|
||||
environment_id: environment_id.to_string(),
|
||||
cwd: cwd.clone(),
|
||||
},
|
||||
});
|
||||
remaining = remaining.saturating_sub(data.len() as u64);
|
||||
}
|
||||
@@ -146,9 +166,10 @@ async fn read_agents_md(
|
||||
/// directory, inclusive. Symlinks are allowed.
|
||||
async fn agents_md_paths(
|
||||
config: &Config,
|
||||
cwd: &AbsolutePathBuf,
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
) -> io::Result<Vec<AbsolutePathBuf>> {
|
||||
let dir = config.cwd.clone();
|
||||
let dir = cwd.clone();
|
||||
|
||||
let mut merged = TomlValue::Table(toml::map::Map::new());
|
||||
for layer in config.config_layer_stack.get_layers(
|
||||
@@ -173,7 +194,7 @@ async fn agents_md_paths(
|
||||
for ancestor in dir.ancestors() {
|
||||
for marker in &project_root_markers {
|
||||
let marker_path = ancestor.join(marker);
|
||||
let marker_path_uri = PathUri::from_abs_path(&marker_path)?;
|
||||
let marker_path_uri = PathUri::from_abs_path(&marker_path);
|
||||
let marker_exists = match fs.get_metadata(&marker_path_uri, /*sandbox*/ None).await
|
||||
{
|
||||
Ok(_) => true,
|
||||
@@ -215,7 +236,7 @@ async fn agents_md_paths(
|
||||
for d in search_dirs {
|
||||
for name in &candidate_filenames {
|
||||
let candidate = d.join(name);
|
||||
let candidate_uri = PathUri::from_abs_path(&candidate)?;
|
||||
let candidate_uri = PathUri::from_abs_path(&candidate);
|
||||
match fs.get_metadata(&candidate_uri, /*sandbox*/ None).await {
|
||||
Ok(md) if md.is_file => {
|
||||
found.push(candidate);
|
||||
@@ -309,6 +330,14 @@ impl LoadedAgentsMd {
|
||||
|
||||
/// Returns the concatenated model-visible instruction text.
|
||||
pub fn text(&self) -> String {
|
||||
if self.has_multiple_project_environments() {
|
||||
self.environment_labeled_text()
|
||||
} else {
|
||||
self.legacy_text()
|
||||
}
|
||||
}
|
||||
|
||||
fn legacy_text(&self) -> String {
|
||||
let mut output = String::new();
|
||||
let mut has_previous = false;
|
||||
let mut previous_was_project = false;
|
||||
@@ -317,7 +346,7 @@ impl LoadedAgentsMd {
|
||||
has_previous = true;
|
||||
}
|
||||
for entry in &self.entries {
|
||||
let is_project = matches!(&entry.provenance, InstructionProvenance::Project(_));
|
||||
let is_project = matches!(&entry.provenance, InstructionProvenance::Project { .. });
|
||||
if has_previous {
|
||||
// The project-doc marker tells the model where workspace-scoped
|
||||
// instructions begin, so it is only needed on the transition
|
||||
@@ -336,6 +365,68 @@ impl LoadedAgentsMd {
|
||||
output
|
||||
}
|
||||
|
||||
fn environment_labeled_text(&self) -> String {
|
||||
let mut output = String::new();
|
||||
let mut has_previous = false;
|
||||
let mut previous_environment: Option<(&str, &AbsolutePathBuf)> = None;
|
||||
if let Some(instructions) = &self.user_instructions {
|
||||
output.push_str(&instructions.text);
|
||||
has_previous = true;
|
||||
}
|
||||
for entry in &self.entries {
|
||||
match &entry.provenance {
|
||||
InstructionProvenance::Project {
|
||||
environment_id,
|
||||
cwd,
|
||||
..
|
||||
} => {
|
||||
if has_previous {
|
||||
output.push_str("\n\n");
|
||||
}
|
||||
// One environment can contribute several hierarchical AGENTS.md files from
|
||||
// its project root through its cwd. Label that environment once for the
|
||||
// complete group rather than repeating the label before every file.
|
||||
let environment = (environment_id.as_str(), cwd);
|
||||
if previous_environment != Some(environment) {
|
||||
output.push_str(&format!(
|
||||
"for `{}` with root {}\n\n",
|
||||
environment_id,
|
||||
cwd.display()
|
||||
));
|
||||
}
|
||||
output.push_str(&entry.contents);
|
||||
previous_environment = Some(environment);
|
||||
}
|
||||
InstructionProvenance::Internal => {
|
||||
if has_previous {
|
||||
output.push_str("\n\n");
|
||||
}
|
||||
output.push_str(&entry.contents);
|
||||
previous_environment = None;
|
||||
}
|
||||
}
|
||||
has_previous = true;
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// Returns the complete model-visible contextual user fragment.
|
||||
pub(crate) fn render(&self) -> String {
|
||||
// One contributing project environment retains the legacy cwd wrapper. With two or more,
|
||||
// the body labels every contributing environment itself, so the outer cwd is omitted.
|
||||
let directory = if self.has_multiple_project_environments() {
|
||||
None
|
||||
} else {
|
||||
self.single_project_cwd()
|
||||
.map(|cwd| cwd.to_string_lossy().into_owned())
|
||||
};
|
||||
ContextUserInstructions {
|
||||
directory,
|
||||
text: self.text(),
|
||||
}
|
||||
.render()
|
||||
}
|
||||
|
||||
/// Returns the host-provided user instructions.
|
||||
pub(crate) fn user_instructions(&self) -> Option<&UserInstructions> {
|
||||
self.user_instructions.as_ref()
|
||||
@@ -352,6 +443,31 @@ impl LoadedAgentsMd {
|
||||
.filter_map(|entry| entry.provenance.path()),
|
||||
)
|
||||
}
|
||||
|
||||
fn has_multiple_project_environments(&self) -> bool {
|
||||
let mut first_environment_id = None;
|
||||
self.entries.iter().any(|entry| {
|
||||
let InstructionProvenance::Project { environment_id, .. } = &entry.provenance else {
|
||||
return false;
|
||||
};
|
||||
match first_environment_id {
|
||||
Some(first_environment_id) => first_environment_id != environment_id,
|
||||
None => {
|
||||
first_environment_id = Some(environment_id);
|
||||
false
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn single_project_cwd(&self) -> Option<&AbsolutePathBuf> {
|
||||
self.entries
|
||||
.iter()
|
||||
.find_map(|entry| match &entry.provenance {
|
||||
InstructionProvenance::Project { cwd, .. } => Some(cwd),
|
||||
InstructionProvenance::Internal => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// One model-visible instruction and its provenance.
|
||||
@@ -367,7 +483,12 @@ struct InstructionEntry {
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
enum InstructionProvenance {
|
||||
/// Workspace instructions discovered from project AGENTS.md files.
|
||||
Project(AbsolutePathBuf),
|
||||
Project {
|
||||
/// Exact AGENTS.md file, distinct from the environment's selected cwd.
|
||||
source_path: AbsolutePathBuf,
|
||||
environment_id: String,
|
||||
cwd: AbsolutePathBuf,
|
||||
},
|
||||
|
||||
/// Instructions without a file source, including internally defined guidance.
|
||||
Internal,
|
||||
@@ -376,7 +497,7 @@ enum InstructionProvenance {
|
||||
impl InstructionProvenance {
|
||||
fn path(&self) -> Option<&AbsolutePathBuf> {
|
||||
match self {
|
||||
Self::Project(path) => Some(path),
|
||||
Self::Project { source_path, .. } => Some(source_path),
|
||||
Self::Internal => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
use super::*;
|
||||
use crate::config::ConfigBuilder;
|
||||
use async_trait::async_trait;
|
||||
use crate::environment_selection::ResolvedTurnEnvironments;
|
||||
use crate::session::turn_context::TurnEnvironment;
|
||||
use codex_config::ConfigLayerEntry;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::ConfigRequirements;
|
||||
use codex_config::ConfigRequirementsToml;
|
||||
use codex_exec_server::CopyOptions;
|
||||
use codex_exec_server::CreateDirectoryOptions;
|
||||
use codex_exec_server::Environment;
|
||||
use codex_exec_server::ExecutorFileSystemFuture;
|
||||
use codex_exec_server::FileMetadata;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
@@ -26,6 +29,7 @@ use std::ops::Deref;
|
||||
use std::ops::DerefMut;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -39,8 +43,7 @@ struct FailingFileSystem {
|
||||
failure: InjectedFailure,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ExecutorFileSystem for FailingFileSystem {
|
||||
impl FailingFileSystem {
|
||||
async fn canonicalize(
|
||||
&self,
|
||||
_path: &PathUri,
|
||||
@@ -121,6 +124,85 @@ impl ExecutorFileSystem for FailingFileSystem {
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutorFileSystem for FailingFileSystem {
|
||||
fn canonicalize<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, PathUri> {
|
||||
Box::pin(FailingFileSystem::canonicalize(self, path, sandbox))
|
||||
}
|
||||
|
||||
fn read_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
|
||||
Box::pin(FailingFileSystem::read_file(self, path, sandbox))
|
||||
}
|
||||
|
||||
fn write_file<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
contents: Vec<u8>,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(FailingFileSystem::write_file(self, path, contents, sandbox))
|
||||
}
|
||||
|
||||
fn create_directory<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: CreateDirectoryOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(FailingFileSystem::create_directory(
|
||||
self, path, options, sandbox,
|
||||
))
|
||||
}
|
||||
|
||||
fn get_metadata<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
|
||||
Box::pin(FailingFileSystem::get_metadata(self, path, sandbox))
|
||||
}
|
||||
|
||||
fn read_directory<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, Vec<ReadDirectoryEntry>> {
|
||||
Box::pin(FailingFileSystem::read_directory(self, path, sandbox))
|
||||
}
|
||||
|
||||
fn remove<'a>(
|
||||
&'a self,
|
||||
path: &'a PathUri,
|
||||
options: RemoveOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(FailingFileSystem::remove(self, path, options, sandbox))
|
||||
}
|
||||
|
||||
fn copy<'a>(
|
||||
&'a self,
|
||||
source_path: &'a PathUri,
|
||||
destination_path: &'a PathUri,
|
||||
options: CopyOptions,
|
||||
sandbox: Option<&'a FileSystemSandboxContext>,
|
||||
) -> ExecutorFileSystemFuture<'a, ()> {
|
||||
Box::pin(FailingFileSystem::copy(
|
||||
self,
|
||||
source_path,
|
||||
destination_path,
|
||||
options,
|
||||
sandbox,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
struct TestConfig {
|
||||
config: Config,
|
||||
user_instructions: Option<UserInstructions>,
|
||||
@@ -150,10 +232,11 @@ async fn get_user_instructions(config: &TestConfig) -> Option<String> {
|
||||
async fn load_agents_md(config: &TestConfig, warnings: &mut Vec<String>) -> Option<LoadedAgentsMd> {
|
||||
let mut core_config = config.config.clone();
|
||||
let existing_warning_count = core_config.startup_warnings.len();
|
||||
let environments = resolved_local_environments([("local", core_config.cwd.clone())]);
|
||||
let loaded = load_project_instructions(
|
||||
&mut core_config,
|
||||
config.user_instructions.clone(),
|
||||
Some(LOCAL_FS.as_ref()),
|
||||
&environments,
|
||||
)
|
||||
.await;
|
||||
warnings.extend(
|
||||
@@ -166,7 +249,36 @@ async fn load_agents_md(config: &TestConfig, warnings: &mut Vec<String>) -> Opti
|
||||
}
|
||||
|
||||
async fn agents_md_paths(config: &TestConfig) -> std::io::Result<Vec<AbsolutePathBuf>> {
|
||||
super::agents_md_paths(&config.config, LOCAL_FS.as_ref()).await
|
||||
super::agents_md_paths(&config.config, &config.cwd, LOCAL_FS.as_ref()).await
|
||||
}
|
||||
|
||||
fn resolved_local_environments<const N: usize>(
|
||||
environments: [(&str, AbsolutePathBuf); N],
|
||||
) -> ResolvedTurnEnvironments {
|
||||
ResolvedTurnEnvironments {
|
||||
turn_environments: environments
|
||||
.into_iter()
|
||||
.map(|(environment_id, cwd)| {
|
||||
TurnEnvironment::new(
|
||||
environment_id.to_string(),
|
||||
Arc::new(
|
||||
Environment::create_for_tests(/*exec_server_url*/ None)
|
||||
.expect("local environment"),
|
||||
),
|
||||
cwd,
|
||||
/*shell*/ None,
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn project_provenance(path: AbsolutePathBuf, cwd: AbsolutePathBuf) -> InstructionProvenance {
|
||||
InstructionProvenance::Project {
|
||||
source_path: path,
|
||||
environment_id: "local".to_string(),
|
||||
cwd,
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_invalid_utf8_warning(warnings: &[String], source: &str, path: &Path) {
|
||||
@@ -388,11 +500,14 @@ async fn total_byte_limit_truncates_later_project_docs() {
|
||||
entries: vec![
|
||||
InstructionEntry {
|
||||
contents: "root".to_string(),
|
||||
provenance: InstructionProvenance::Project(repo.path().join("AGENTS.md").abs()),
|
||||
provenance: project_provenance(
|
||||
repo.path().join("AGENTS.md").abs(),
|
||||
config.cwd.clone(),
|
||||
),
|
||||
},
|
||||
InstructionEntry {
|
||||
contents: "abc".to_string(),
|
||||
provenance: InstructionProvenance::Project(config.cwd.join("AGENTS.md")),
|
||||
provenance: project_provenance(config.cwd.join("AGENTS.md"), config.cwd.clone()),
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -412,7 +527,8 @@ async fn read_agents_md_propagates_metadata_errors() {
|
||||
failure: InjectedFailure::Metadata(io::ErrorKind::PermissionDenied),
|
||||
};
|
||||
|
||||
let err = read_agents_md(&mut config.config, &fs)
|
||||
let cwd = config.cwd.clone();
|
||||
let err = read_agents_md(&mut config.config, &fs, "local", &cwd)
|
||||
.await
|
||||
.expect_err("metadata error");
|
||||
|
||||
@@ -429,7 +545,8 @@ async fn read_agents_md_propagates_read_errors() {
|
||||
failure: InjectedFailure::Read(io::ErrorKind::PermissionDenied),
|
||||
};
|
||||
|
||||
let err = read_agents_md(&mut config.config, &fs)
|
||||
let cwd = config.cwd.clone();
|
||||
let err = read_agents_md(&mut config.config, &fs, "local", &cwd)
|
||||
.await
|
||||
.expect_err("read error");
|
||||
|
||||
@@ -446,7 +563,8 @@ async fn read_agents_md_ignores_files_removed_after_discovery() {
|
||||
failure: InjectedFailure::Read(io::ErrorKind::NotFound),
|
||||
};
|
||||
|
||||
let loaded = read_agents_md(&mut config.config, &fs)
|
||||
let cwd = config.cwd.clone();
|
||||
let loaded = read_agents_md(&mut config.config, &fs, "local", &cwd)
|
||||
.await
|
||||
.expect("removed file is recoverable");
|
||||
|
||||
@@ -513,6 +631,240 @@ async fn merges_existing_instructions_with_agents_md() {
|
||||
assert_eq!(res, expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn multiple_environment_docs_use_labeled_layout_and_preserve_source_order() {
|
||||
let primary = tempfile::tempdir().expect("primary tempdir");
|
||||
let secondary = tempfile::tempdir().expect("secondary tempdir");
|
||||
fs::create_dir(primary.path().join(".git")).unwrap();
|
||||
fs::write(primary.path().join("AGENTS.md"), "primary root doc").unwrap();
|
||||
let primary_nested = primary.path().join("nested");
|
||||
fs::create_dir(&primary_nested).unwrap();
|
||||
fs::write(primary_nested.join("AGENTS.md"), "primary nested doc").unwrap();
|
||||
fs::write(secondary.path().join("AGENTS.md"), "secondary doc").unwrap();
|
||||
let mut config = make_config(&primary, /*limit*/ 4096, Some("global instructions")).await;
|
||||
config.cwd = primary_nested.abs();
|
||||
let environments = resolved_local_environments([
|
||||
("primary", config.cwd.clone()),
|
||||
("secondary", secondary.abs()),
|
||||
]);
|
||||
let user_instructions = config.user_instructions.clone();
|
||||
|
||||
let loaded = load_project_instructions(&mut config.config, user_instructions, &environments)
|
||||
.await
|
||||
.expect("instructions expected");
|
||||
let inner = format!(
|
||||
r#"global instructions
|
||||
|
||||
for `primary` with root {}
|
||||
|
||||
primary root doc
|
||||
|
||||
primary nested doc
|
||||
|
||||
for `secondary` with root {}
|
||||
|
||||
secondary doc"#,
|
||||
primary_nested.display(),
|
||||
secondary.path().display(),
|
||||
);
|
||||
|
||||
assert_eq!(loaded.environment_labeled_text(), inner);
|
||||
assert_eq!(loaded.text(), inner);
|
||||
let expected_fragment = format!(
|
||||
r#"# AGENTS.md instructions
|
||||
|
||||
<INSTRUCTIONS>
|
||||
{inner}
|
||||
</INSTRUCTIONS>"#
|
||||
);
|
||||
assert_eq!(loaded.render(), expected_fragment);
|
||||
assert_eq!(
|
||||
loaded.sources().cloned().collect::<Vec<_>>(),
|
||||
vec![
|
||||
config
|
||||
.user_instructions
|
||||
.as_ref()
|
||||
.expect("global instructions")
|
||||
.source
|
||||
.clone(),
|
||||
primary.path().join("AGENTS.md").abs(),
|
||||
primary_nested.join("AGENTS.md").abs(),
|
||||
secondary.path().join("AGENTS.md").abs(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn secondary_only_project_doc_uses_single_contributor_layout() {
|
||||
let primary = tempfile::tempdir().expect("primary tempdir");
|
||||
let secondary = tempfile::tempdir().expect("secondary tempdir");
|
||||
fs::write(secondary.path().join("AGENTS.md"), "secondary doc").unwrap();
|
||||
let mut config = make_config(&primary, /*limit*/ 4096, Some("global instructions")).await;
|
||||
let environments = resolved_local_environments([
|
||||
("primary", config.cwd.clone()),
|
||||
("secondary", secondary.abs()),
|
||||
]);
|
||||
let user_instructions = config.user_instructions.clone();
|
||||
|
||||
let loaded = load_project_instructions(&mut config.config, user_instructions, &environments)
|
||||
.await
|
||||
.expect("instructions expected");
|
||||
let inner = format!("global instructions{AGENTS_MD_SEPARATOR}secondary doc");
|
||||
|
||||
assert_eq!(loaded.legacy_text(), inner);
|
||||
assert_eq!(loaded.text(), inner);
|
||||
let expected_fragment = format!(
|
||||
"# AGENTS.md instructions for {}\n\n<INSTRUCTIONS>\n{inner}\n</INSTRUCTIONS>",
|
||||
secondary.path().display()
|
||||
);
|
||||
assert_eq!(loaded.render(), expected_fragment);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn primary_only_project_doc_preserves_legacy_layout_with_multiple_bound_environments() {
|
||||
let primary = tempfile::tempdir().expect("primary tempdir");
|
||||
let secondary = tempfile::tempdir().expect("secondary tempdir");
|
||||
fs::write(primary.path().join("AGENTS.md"), "primary doc").unwrap();
|
||||
let mut config = make_config(&primary, /*limit*/ 4096, Some("global instructions")).await;
|
||||
let environments = resolved_local_environments([
|
||||
("primary", config.cwd.clone()),
|
||||
("secondary", secondary.abs()),
|
||||
]);
|
||||
let user_instructions = config.user_instructions.clone();
|
||||
|
||||
let loaded = load_project_instructions(&mut config.config, user_instructions, &environments)
|
||||
.await
|
||||
.expect("instructions expected");
|
||||
let inner = format!("global instructions{AGENTS_MD_SEPARATOR}primary doc");
|
||||
|
||||
assert_eq!(loaded.legacy_text(), inner);
|
||||
assert_eq!(loaded.text(), inner);
|
||||
let expected_fragment = format!(
|
||||
"# AGENTS.md instructions for {}\n\n<INSTRUCTIONS>\n{inner}\n</INSTRUCTIONS>",
|
||||
primary.path().display()
|
||||
);
|
||||
assert_eq!(loaded.render(), expected_fragment);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn project_doc_byte_limit_is_applied_independently_per_environment() {
|
||||
let primary = tempfile::tempdir().expect("primary tempdir");
|
||||
let secondary = tempfile::tempdir().expect("secondary tempdir");
|
||||
fs::write(primary.path().join("AGENTS.md"), "ABCDE").unwrap();
|
||||
fs::write(secondary.path().join("AGENTS.md"), "VWXYZ").unwrap();
|
||||
let mut config = make_config(&primary, /*limit*/ 3, /*instructions*/ None).await;
|
||||
let environments = resolved_local_environments([
|
||||
("primary", config.cwd.clone()),
|
||||
("secondary", secondary.abs()),
|
||||
]);
|
||||
let user_instructions = config.user_instructions.clone();
|
||||
|
||||
let loaded = load_project_instructions(&mut config.config, user_instructions, &environments)
|
||||
.await
|
||||
.expect("instructions expected");
|
||||
|
||||
assert_eq!(
|
||||
loaded.text(),
|
||||
format!(
|
||||
"for `primary` with root {}\n\nABC\n\nfor `secondary` with root {}\n\nVWX",
|
||||
primary.path().display(),
|
||||
secondary.path().display()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn multiple_environments_can_exceed_single_environment_project_doc_limit() {
|
||||
// TODO(anp): Add an aggregate cap across environments instead of allowing the combined
|
||||
// project instructions to grow by one full per-environment budget for every binding.
|
||||
const LIMIT: usize = 8;
|
||||
let primary = tempfile::tempdir().expect("primary tempdir");
|
||||
let secondary = tempfile::tempdir().expect("secondary tempdir");
|
||||
let primary_doc = "P".repeat(LIMIT);
|
||||
let secondary_doc = "S".repeat(LIMIT);
|
||||
fs::write(primary.path().join("AGENTS.md"), &primary_doc).unwrap();
|
||||
fs::write(secondary.path().join("AGENTS.md"), &secondary_doc).unwrap();
|
||||
let mut config = make_config(&primary, LIMIT, /*instructions*/ None).await;
|
||||
let environments = resolved_local_environments([
|
||||
("primary", config.cwd.clone()),
|
||||
("secondary", secondary.abs()),
|
||||
]);
|
||||
|
||||
let loaded = load_project_instructions(
|
||||
&mut config.config,
|
||||
/*user_instructions*/ None,
|
||||
&environments,
|
||||
)
|
||||
.await
|
||||
.expect("instructions expected");
|
||||
let project_bytes = loaded
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|entry| matches!(&entry.provenance, InstructionProvenance::Project { .. }))
|
||||
.map(|entry| entry.contents.len())
|
||||
.sum::<usize>();
|
||||
|
||||
assert_eq!(project_bytes, LIMIT * 2);
|
||||
assert!(project_bytes > config.project_doc_max_bytes);
|
||||
assert!(loaded.text().contains(&primary_doc));
|
||||
assert!(loaded.text().contains(&secondary_doc));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn secondary_environment_invalid_utf8_warns_without_suppressing_other_docs() {
|
||||
let primary = tempfile::tempdir().expect("primary tempdir");
|
||||
let secondary = tempfile::tempdir().expect("secondary tempdir");
|
||||
fs::write(primary.path().join("AGENTS.md"), "primary doc").unwrap();
|
||||
fs::write(secondary.path().join("AGENTS.md"), b"secondary\xFFdoc").unwrap();
|
||||
let mut config = make_config(&primary, /*limit*/ 4096, /*instructions*/ None).await;
|
||||
let environments = resolved_local_environments([
|
||||
("primary", config.cwd.clone()),
|
||||
("secondary", secondary.abs()),
|
||||
]);
|
||||
|
||||
let loaded = load_project_instructions(
|
||||
&mut config.config,
|
||||
/*user_instructions*/ None,
|
||||
&environments,
|
||||
)
|
||||
.await
|
||||
.expect("instructions expected");
|
||||
|
||||
assert!(loaded.text().contains("primary doc"));
|
||||
assert!(loaded.text().contains("secondary\u{FFFD}doc"));
|
||||
assert_invalid_utf8_warning(
|
||||
&config.startup_warnings,
|
||||
"Project",
|
||||
secondary.path().join("AGENTS.md").as_path(),
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn child_agents_guidance_is_appended_once_after_environment_groups() {
|
||||
let primary = tempfile::tempdir().expect("primary tempdir");
|
||||
let secondary = tempfile::tempdir().expect("secondary tempdir");
|
||||
fs::write(primary.path().join("AGENTS.md"), "primary doc").unwrap();
|
||||
fs::write(secondary.path().join("AGENTS.md"), "secondary doc").unwrap();
|
||||
let mut config = make_config(&primary, /*limit*/ 4096, /*instructions*/ None).await;
|
||||
config.features.enable(Feature::ChildAgentsMd).unwrap();
|
||||
let environments = resolved_local_environments([
|
||||
("primary", config.cwd.clone()),
|
||||
("secondary", secondary.abs()),
|
||||
]);
|
||||
|
||||
let loaded = load_project_instructions(
|
||||
&mut config.config,
|
||||
/*user_instructions*/ None,
|
||||
&environments,
|
||||
)
|
||||
.await
|
||||
.expect("instructions expected");
|
||||
let text = loaded.text();
|
||||
|
||||
assert_eq!(text.matches(HIERARCHICAL_AGENTS_MESSAGE).count(), 1);
|
||||
assert!(text.ends_with(HIERARCHICAL_AGENTS_MESSAGE));
|
||||
}
|
||||
|
||||
/// If there are existing system instructions but AGENTS.md docs are
|
||||
/// missing we expect the original instructions to be returned unchanged.
|
||||
#[tokio::test]
|
||||
@@ -520,7 +872,6 @@ async fn keeps_existing_instructions_when_doc_missing() {
|
||||
let tmp = tempfile::tempdir().expect("tempdir");
|
||||
|
||||
const INSTRUCTIONS: &str = "some instructions";
|
||||
|
||||
let res =
|
||||
get_user_instructions(&make_config(&tmp, /*limit*/ 4096, Some(INSTRUCTIONS)).await).await;
|
||||
|
||||
@@ -562,11 +913,11 @@ async fn concatenates_root_and_cwd_docs() {
|
||||
entries: vec![
|
||||
InstructionEntry {
|
||||
contents: "root doc".to_string(),
|
||||
provenance: InstructionProvenance::Project(root_agents.clone()),
|
||||
provenance: project_provenance(root_agents.clone(), cfg.cwd.clone()),
|
||||
},
|
||||
InstructionEntry {
|
||||
contents: "crate doc".to_string(),
|
||||
provenance: InstructionProvenance::Project(crate_agents.clone()),
|
||||
provenance: project_provenance(crate_agents.clone(), cfg.cwd.clone()),
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -726,7 +1077,7 @@ async fn instruction_sources_include_global_before_agents_md_docs() {
|
||||
}),
|
||||
entries: vec![InstructionEntry {
|
||||
contents: "project doc".to_string(),
|
||||
provenance: InstructionProvenance::Project(project_agents.clone()),
|
||||
provenance: project_provenance(project_agents.clone(), cfg.cwd.clone()),
|
||||
}],
|
||||
};
|
||||
assert_eq!(loaded, expected);
|
||||
@@ -766,7 +1117,7 @@ async fn child_agents_message_after_project_docs_is_not_an_instruction_source()
|
||||
entries: vec![
|
||||
InstructionEntry {
|
||||
contents: "project doc".to_string(),
|
||||
provenance: InstructionProvenance::Project(project_agents.clone()),
|
||||
provenance: project_provenance(project_agents.clone(), cfg.cwd.clone()),
|
||||
},
|
||||
InstructionEntry {
|
||||
contents: HIERARCHICAL_AGENTS_MESSAGE.to_string(),
|
||||
|
||||
+99
-190
@@ -70,7 +70,6 @@ use codex_login::default_client::build_reqwest_client;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_otel::current_span_w3c_trace_context;
|
||||
|
||||
use codex_protocol::SessionId;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig;
|
||||
use codex_protocol::config_types::Verbosity as VerbosityConfig;
|
||||
@@ -78,8 +77,8 @@ use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig;
|
||||
use codex_protocol::protocol::InternalSessionSource;
|
||||
use codex_protocol::protocol::RealtimeConversationArchitecture;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use codex_rollout_trace::CompactionTraceContext;
|
||||
use codex_rollout_trace::InferenceTraceAttempt;
|
||||
@@ -111,6 +110,8 @@ use crate::client_common::Prompt;
|
||||
use crate::client_common::ResponseEvent;
|
||||
use crate::client_common::ResponseStream;
|
||||
use crate::feedback_tags;
|
||||
use crate::responses_metadata::CodexResponsesMetadata;
|
||||
use crate::responses_metadata::subagent_header_value;
|
||||
use crate::util::emit_feedback_auth_recovery_tags;
|
||||
use codex_api::map_api_error;
|
||||
use codex_feedback::FeedbackRequestTags;
|
||||
@@ -169,13 +170,10 @@ pub(crate) struct CompactConversationRequestSettings {
|
||||
/// configuration is per turn and is passed explicitly to streaming/unary methods.
|
||||
#[derive(Debug)]
|
||||
struct ModelClientState {
|
||||
session_id: SessionId,
|
||||
thread_id: ThreadId,
|
||||
installation_id: String,
|
||||
provider: SharedModelProvider,
|
||||
auth_env_telemetry: AuthEnvTelemetry,
|
||||
session_source: SessionSource,
|
||||
parent_thread_id: Option<ThreadId>,
|
||||
model_verbosity: Option<VerbosityConfig>,
|
||||
enable_request_compression: bool,
|
||||
include_timing_metrics: bool,
|
||||
@@ -319,12 +317,9 @@ impl ModelClient {
|
||||
/// are passed to [`ModelClientSession::stream`] (and other turn-scoped methods) explicitly.
|
||||
pub fn new(
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
session_id: SessionId,
|
||||
thread_id: ThreadId,
|
||||
installation_id: String,
|
||||
provider_info: ModelProviderInfo,
|
||||
session_source: SessionSource,
|
||||
parent_thread_id: Option<ThreadId>,
|
||||
model_verbosity: Option<VerbosityConfig>,
|
||||
enable_request_compression: bool,
|
||||
include_timing_metrics: bool,
|
||||
@@ -341,13 +336,10 @@ impl ModelClient {
|
||||
let include_attestation = model_provider.supports_attestation();
|
||||
Self {
|
||||
state: Arc::new(ModelClientState {
|
||||
session_id,
|
||||
thread_id,
|
||||
installation_id,
|
||||
provider: model_provider,
|
||||
auth_env_telemetry,
|
||||
session_source,
|
||||
parent_thread_id,
|
||||
model_verbosity,
|
||||
enable_request_compression,
|
||||
include_timing_metrics,
|
||||
@@ -441,11 +433,11 @@ impl ModelClient {
|
||||
&self,
|
||||
prompt: &Prompt,
|
||||
model_info: &ModelInfo,
|
||||
turn_state: Option<Arc<OnceLock<String>>>,
|
||||
settings: CompactConversationRequestSettings,
|
||||
session_telemetry: &SessionTelemetry,
|
||||
compaction_trace: &CompactionTraceContext,
|
||||
window_id: &str,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
) -> Result<Vec<ResponseItem>> {
|
||||
if prompt.input.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
@@ -469,7 +461,7 @@ impl ModelClient {
|
||||
settings.effort,
|
||||
settings.summary,
|
||||
settings.service_tier,
|
||||
window_id,
|
||||
responses_metadata,
|
||||
)?;
|
||||
let ResponsesApiRequest {
|
||||
model,
|
||||
@@ -496,18 +488,17 @@ impl ModelClient {
|
||||
};
|
||||
|
||||
let mut extra_headers = ApiHeaderMap::new();
|
||||
if let Ok(header_value) = HeaderValue::from_str(&self.state.installation_id) {
|
||||
if let Ok(header_value) = HeaderValue::from_str(&responses_metadata.installation_id) {
|
||||
extra_headers.insert(X_CODEX_INSTALLATION_ID_HEADER, header_value);
|
||||
}
|
||||
extra_headers.extend(build_responses_headers(
|
||||
self.state.beta_features_header.as_deref(),
|
||||
/*turn_state*/ None,
|
||||
parse_turn_metadata_header(turn_metadata_header).as_ref(),
|
||||
turn_state.as_ref(),
|
||||
));
|
||||
extra_headers.extend(self.build_responses_identity_headers(Some(window_id)));
|
||||
extra_headers.extend(self.build_responses_compatibility_headers(responses_metadata));
|
||||
extra_headers.extend(build_session_headers(
|
||||
Some(self.state.session_id.to_string()),
|
||||
Some(self.state.thread_id.to_string()),
|
||||
Some(responses_metadata.session_id.to_string()),
|
||||
Some(responses_metadata.thread_id.to_string()),
|
||||
));
|
||||
if let Some(header_value) = self.generate_attestation_header_for().await {
|
||||
extra_headers.insert(X_OAI_ATTESTATION_HEADER, header_value);
|
||||
@@ -522,7 +513,12 @@ impl ModelClient {
|
||||
.with_telemetry(Some(request_telemetry));
|
||||
let trace_attempt = compaction_trace.start_attempt(&payload);
|
||||
let result = client
|
||||
.compact_input(&payload, extra_headers, compact_request_timeout)
|
||||
.compact_input(
|
||||
&payload,
|
||||
extra_headers,
|
||||
compact_request_timeout,
|
||||
turn_state.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(map_api_error);
|
||||
trace_attempt.record_result(result.as_deref());
|
||||
@@ -533,7 +529,9 @@ impl ModelClient {
|
||||
&self,
|
||||
sdp: String,
|
||||
session_config: ApiRealtimeSessionConfig,
|
||||
architecture: RealtimeConversationArchitecture,
|
||||
mut extra_headers: ApiHeaderMap,
|
||||
api_provider_override: Option<ApiProvider>,
|
||||
) -> Result<RealtimeWebrtcCallStart> {
|
||||
// Create the media call over HTTP first, then retain matching auth so realtime can attach
|
||||
// the server-side control WebSocket to the call id from that HTTP response.
|
||||
@@ -546,11 +544,16 @@ impl ModelClient {
|
||||
client_setup.api_auth.as_ref(),
|
||||
));
|
||||
let transport = ReqwestTransport::new(build_reqwest_client());
|
||||
let response =
|
||||
ApiRealtimeCallClient::new(transport, client_setup.api_provider, client_setup.api_auth)
|
||||
.create_with_session_and_headers(sdp, session_config, extra_headers)
|
||||
.await
|
||||
.map_err(map_api_error)?;
|
||||
let api_provider = api_provider_override.unwrap_or(client_setup.api_provider);
|
||||
let response = ApiRealtimeCallClient::new(transport, api_provider, client_setup.api_auth)
|
||||
.create_with_session_architecture_and_headers(
|
||||
sdp,
|
||||
session_config,
|
||||
architecture,
|
||||
extra_headers,
|
||||
)
|
||||
.await
|
||||
.map_err(map_api_error)?;
|
||||
Ok(RealtimeWebrtcCallStart {
|
||||
sdp: response.sdp,
|
||||
call_id: response.call_id,
|
||||
@@ -626,50 +629,29 @@ impl ModelClient {
|
||||
extra_headers
|
||||
}
|
||||
|
||||
fn build_responses_identity_headers(&self, window_id: Option<&str>) -> ApiHeaderMap {
|
||||
let mut extra_headers = self.build_subagent_headers();
|
||||
if let Some(parent_thread_id) = parent_thread_id_header_value(self.state.parent_thread_id)
|
||||
&& let Ok(val) = HeaderValue::from_str(&parent_thread_id)
|
||||
{
|
||||
extra_headers.insert(X_CODEX_PARENT_THREAD_ID_HEADER, val);
|
||||
}
|
||||
if let Some(window_id) = window_id
|
||||
&& let Ok(val) = HeaderValue::from_str(window_id)
|
||||
{
|
||||
extra_headers.insert(X_CODEX_WINDOW_ID_HEADER, val);
|
||||
fn build_responses_compatibility_headers(
|
||||
&self,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
) -> ApiHeaderMap {
|
||||
let mut extra_headers = responses_metadata.compatibility_headers();
|
||||
if matches!(
|
||||
self.state.session_source,
|
||||
SessionSource::Internal(InternalSessionSource::MemoryConsolidation)
|
||||
) {
|
||||
extra_headers.insert(
|
||||
X_OPENAI_MEMGEN_REQUEST_HEADER,
|
||||
HeaderValue::from_static("true"),
|
||||
);
|
||||
}
|
||||
extra_headers
|
||||
}
|
||||
|
||||
fn build_ws_client_metadata(
|
||||
&self,
|
||||
window_id: &str,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
use_responses_lite: bool,
|
||||
) -> HashMap<String, String> {
|
||||
let mut client_metadata = HashMap::new();
|
||||
client_metadata.insert(
|
||||
X_CODEX_INSTALLATION_ID_HEADER.to_string(),
|
||||
self.state.installation_id.clone(),
|
||||
);
|
||||
client_metadata.insert(X_CODEX_WINDOW_ID_HEADER.to_string(), window_id.to_string());
|
||||
if let Some(subagent) = subagent_header_value(&self.state.session_source) {
|
||||
client_metadata.insert(X_OPENAI_SUBAGENT_HEADER.to_string(), subagent);
|
||||
}
|
||||
if let Some(parent_thread_id) = parent_thread_id_header_value(self.state.parent_thread_id) {
|
||||
client_metadata.insert(
|
||||
X_CODEX_PARENT_THREAD_ID_HEADER.to_string(),
|
||||
parent_thread_id,
|
||||
);
|
||||
}
|
||||
if let Some(turn_metadata_header) = parse_turn_metadata_header(turn_metadata_header)
|
||||
&& let Ok(turn_metadata) = turn_metadata_header.to_str()
|
||||
{
|
||||
client_metadata.insert(
|
||||
X_CODEX_TURN_METADATA_HEADER.to_string(),
|
||||
turn_metadata.to_string(),
|
||||
);
|
||||
}
|
||||
let mut client_metadata = responses_metadata.client_metadata();
|
||||
if use_responses_lite {
|
||||
client_metadata.insert(
|
||||
WS_REQUEST_HEADER_RESPONSES_LITE_CLIENT_METADATA_KEY.to_string(),
|
||||
@@ -743,7 +725,7 @@ impl ModelClient {
|
||||
effort: Option<ReasoningEffortConfig>,
|
||||
summary: ReasoningSummaryConfig,
|
||||
service_tier: Option<String>,
|
||||
window_id: &str,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
) -> Result<ResponsesApiRequest> {
|
||||
let instructions = &prompt.base_instructions.text;
|
||||
let input = prompt.get_formatted_input_for_request(model_info.use_responses_lite);
|
||||
@@ -786,13 +768,7 @@ impl ModelClient {
|
||||
service_tier,
|
||||
prompt_cache_key,
|
||||
text,
|
||||
client_metadata: Some(HashMap::from([
|
||||
(
|
||||
X_CODEX_INSTALLATION_ID_HEADER.to_string(),
|
||||
self.state.installation_id.clone(),
|
||||
),
|
||||
(X_CODEX_WINDOW_ID_HEADER.to_string(), window_id.to_string()),
|
||||
])),
|
||||
client_metadata: Some(responses_metadata.client_metadata()),
|
||||
};
|
||||
Ok(request)
|
||||
}
|
||||
@@ -835,14 +811,11 @@ impl ModelClient {
|
||||
session_telemetry: &SessionTelemetry,
|
||||
api_provider: codex_api::Provider,
|
||||
api_auth: SharedAuthProvider,
|
||||
turn_state: Option<Arc<OnceLock<String>>>,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
auth_context: AuthRequestTelemetryContext,
|
||||
request_route_telemetry: RequestRouteTelemetry,
|
||||
) -> std::result::Result<ApiWebSocketConnection, ApiError> {
|
||||
let headers = self
|
||||
.build_websocket_headers(turn_state.as_ref(), turn_metadata_header)
|
||||
.await;
|
||||
let headers = self.build_websocket_headers(responses_metadata).await;
|
||||
let websocket_telemetry = ModelClientSession::build_websocket_telemetry(
|
||||
session_telemetry,
|
||||
auth_context,
|
||||
@@ -856,7 +829,7 @@ impl ModelClient {
|
||||
ApiWebSocketResponsesClient::new(api_provider, api_auth).connect(
|
||||
headers,
|
||||
codex_login::default_client::default_headers(),
|
||||
turn_state,
|
||||
/*turn_state*/ None,
|
||||
Some(websocket_telemetry),
|
||||
),
|
||||
)
|
||||
@@ -916,27 +889,22 @@ impl ModelClient {
|
||||
}
|
||||
|
||||
/// Builds websocket handshake headers for both prewarm and turn-time reconnect.
|
||||
///
|
||||
/// Callers should pass the current turn-state lock when available so sticky-routing state is
|
||||
/// replayed on reconnect within the same turn.
|
||||
async fn build_websocket_headers(
|
||||
&self,
|
||||
turn_state: Option<&Arc<OnceLock<String>>>,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
) -> ApiHeaderMap {
|
||||
let turn_metadata_header = parse_turn_metadata_header(turn_metadata_header);
|
||||
let session_id = self.state.session_id.to_string();
|
||||
let thread_id = self.state.thread_id.to_string();
|
||||
let mut headers = build_responses_headers(
|
||||
self.state.beta_features_header.as_deref(),
|
||||
turn_state,
|
||||
turn_metadata_header.as_ref(),
|
||||
/*turn_state*/ None,
|
||||
);
|
||||
if let Ok(header_value) = HeaderValue::from_str(&thread_id) {
|
||||
if let Ok(header_value) = HeaderValue::from_str(&responses_metadata.thread_id) {
|
||||
headers.insert("x-client-request-id", header_value);
|
||||
}
|
||||
headers.extend(build_session_headers(Some(session_id), Some(thread_id)));
|
||||
headers.extend(self.build_responses_identity_headers(/*window_id*/ None));
|
||||
headers.extend(build_session_headers(
|
||||
Some(responses_metadata.session_id.to_string()),
|
||||
Some(responses_metadata.thread_id.to_string()),
|
||||
));
|
||||
headers.extend(self.build_responses_compatibility_headers(responses_metadata));
|
||||
if let Some(header_value) = self.generate_attestation_header_for().await {
|
||||
headers.insert(X_OAI_ATTESTATION_HEADER, header_value);
|
||||
}
|
||||
@@ -963,6 +931,10 @@ impl Drop for ModelClientSession {
|
||||
}
|
||||
|
||||
impl ModelClientSession {
|
||||
pub(crate) fn turn_state(&self) -> Arc<OnceLock<String>> {
|
||||
Arc::clone(&self.turn_state)
|
||||
}
|
||||
|
||||
fn reset_websocket_session(&mut self) {
|
||||
self.websocket_session.connection = None;
|
||||
self.websocket_session.last_request = None;
|
||||
@@ -979,27 +951,22 @@ impl ModelClientSession {
|
||||
/// regardless of transport choice.
|
||||
async fn build_responses_options(
|
||||
&self,
|
||||
window_id: &str,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
compression: Compression,
|
||||
use_responses_lite: bool,
|
||||
) -> ApiResponsesOptions {
|
||||
let turn_metadata_header = parse_turn_metadata_header(turn_metadata_header);
|
||||
let session_id = self.client.state.session_id.to_string();
|
||||
let thread_id = self.client.state.thread_id.to_string();
|
||||
ApiResponsesOptions {
|
||||
session_id: Some(session_id),
|
||||
thread_id: Some(thread_id),
|
||||
session_id: Some(responses_metadata.session_id.to_string()),
|
||||
thread_id: Some(responses_metadata.thread_id.to_string()),
|
||||
session_source: Some(self.client.state.session_source.clone()),
|
||||
extra_headers: {
|
||||
let mut headers = build_responses_headers(
|
||||
self.client.state.beta_features_header.as_deref(),
|
||||
Some(&self.turn_state),
|
||||
turn_metadata_header.as_ref(),
|
||||
);
|
||||
headers.extend(
|
||||
self.client
|
||||
.build_responses_identity_headers(Some(window_id)),
|
||||
.build_responses_compatibility_headers(responses_metadata),
|
||||
);
|
||||
if let Some(header_value) = self.client.generate_attestation_header_for().await {
|
||||
headers.insert(X_OAI_ATTESTATION_HEADER, header_value);
|
||||
@@ -1026,12 +993,12 @@ impl ModelClientSession {
|
||||
let previous_request = self.websocket_session.last_request.as_ref()?;
|
||||
let mut previous_without_input = previous_request.clone();
|
||||
previous_without_input.input.clear();
|
||||
previous_without_input.client_metadata = None;
|
||||
let mut request_without_input = request.clone();
|
||||
request_without_input.input.clear();
|
||||
request_without_input.client_metadata = None;
|
||||
if previous_without_input != request_without_input {
|
||||
trace!(
|
||||
"incremental request failed, properties didn't match {previous_without_input:?} != {request_without_input:?}"
|
||||
);
|
||||
trace!("incremental request failed, websocket reuse properties didn't match");
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -1100,6 +1067,7 @@ impl ModelClientSession {
|
||||
pub async fn preconnect_websocket(
|
||||
&mut self,
|
||||
session_telemetry: &SessionTelemetry,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
) -> std::result::Result<(), ApiError> {
|
||||
if !self.client.responses_websocket_enabled() {
|
||||
return Ok(());
|
||||
@@ -1124,8 +1092,7 @@ impl ModelClientSession {
|
||||
session_telemetry,
|
||||
client_setup.api_provider,
|
||||
client_setup.api_auth,
|
||||
Some(Arc::clone(&self.turn_state)),
|
||||
/*turn_metadata_header*/ None,
|
||||
responses_metadata,
|
||||
auth_context,
|
||||
RequestRouteTelemetry::for_endpoint(RESPONSES_ENDPOINT),
|
||||
)
|
||||
@@ -1145,7 +1112,7 @@ impl ModelClientSession {
|
||||
wire_api = %self.client.state.provider.info().wire_api,
|
||||
transport = "responses_websocket",
|
||||
api.path = "responses",
|
||||
turn.has_metadata_header = params.turn_metadata_header.is_some()
|
||||
turn.has_metadata_header = params.responses_metadata.has_turn_metadata()
|
||||
)
|
||||
)]
|
||||
async fn websocket_connection(
|
||||
@@ -1156,8 +1123,7 @@ impl ModelClientSession {
|
||||
session_telemetry,
|
||||
api_provider,
|
||||
api_auth,
|
||||
turn_metadata_header,
|
||||
options,
|
||||
responses_metadata,
|
||||
auth_context,
|
||||
request_route_telemetry,
|
||||
} = params;
|
||||
@@ -1170,18 +1136,13 @@ impl ModelClientSession {
|
||||
self.websocket_session.last_request = None;
|
||||
self.websocket_session.last_response_rx = None;
|
||||
self.websocket_session.last_response_from_untraced_warmup = false;
|
||||
let turn_state = options
|
||||
.turn_state
|
||||
.clone()
|
||||
.unwrap_or_else(|| Arc::clone(&self.turn_state));
|
||||
let new_conn = match self
|
||||
.client
|
||||
.connect_websocket(
|
||||
session_telemetry,
|
||||
api_provider,
|
||||
api_auth,
|
||||
Some(turn_state),
|
||||
turn_metadata_header,
|
||||
responses_metadata,
|
||||
auth_context,
|
||||
request_route_telemetry,
|
||||
)
|
||||
@@ -1236,19 +1197,18 @@ impl ModelClientSession {
|
||||
transport = "responses_http",
|
||||
http.method = "POST",
|
||||
api.path = "responses",
|
||||
turn.has_metadata_header = turn_metadata_header.is_some()
|
||||
turn.has_metadata_header = responses_metadata.has_turn_metadata()
|
||||
)
|
||||
)]
|
||||
async fn stream_responses_api(
|
||||
&self,
|
||||
window_id: &str,
|
||||
prompt: &Prompt,
|
||||
model_info: &ModelInfo,
|
||||
session_telemetry: &SessionTelemetry,
|
||||
effort: Option<ReasoningEffortConfig>,
|
||||
summary: ReasoningSummaryConfig,
|
||||
service_tier: Option<String>,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
inference_trace: &InferenceTraceContext,
|
||||
) -> Result<ResponseStream> {
|
||||
let auth_manager = self.client.state.provider.auth_manager();
|
||||
@@ -1273,8 +1233,7 @@ impl ModelClientSession {
|
||||
let compression = self.responses_request_compression(client_setup.auth.as_ref());
|
||||
let mut options = self
|
||||
.build_responses_options(
|
||||
window_id,
|
||||
turn_metadata_header,
|
||||
responses_metadata,
|
||||
compression,
|
||||
model_info.use_responses_lite,
|
||||
)
|
||||
@@ -1287,7 +1246,7 @@ impl ModelClientSession {
|
||||
effort.clone(),
|
||||
summary,
|
||||
service_tier.clone(),
|
||||
window_id,
|
||||
responses_metadata,
|
||||
)?;
|
||||
let inference_trace_attempt = inference_trace.start_attempt();
|
||||
inference_trace_attempt.add_request_headers(&mut options.extra_headers);
|
||||
@@ -1355,20 +1314,19 @@ impl ModelClientSession {
|
||||
wire_api = %self.client.state.provider.info().wire_api,
|
||||
transport = "responses_websocket",
|
||||
api.path = "responses",
|
||||
turn.has_metadata_header = turn_metadata_header.is_some(),
|
||||
turn.has_metadata_header = responses_metadata.has_turn_metadata(),
|
||||
websocket.warmup = warmup
|
||||
)
|
||||
)]
|
||||
async fn stream_responses_websocket(
|
||||
&mut self,
|
||||
window_id: &str,
|
||||
prompt: &Prompt,
|
||||
model_info: &ModelInfo,
|
||||
session_telemetry: &SessionTelemetry,
|
||||
effort: Option<ReasoningEffortConfig>,
|
||||
summary: ReasoningSummaryConfig,
|
||||
service_tier: Option<String>,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
warmup: bool,
|
||||
request_trace: Option<W3cTraceContext>,
|
||||
inference_trace: &InferenceTraceContext,
|
||||
@@ -1386,16 +1344,6 @@ impl ModelClientSession {
|
||||
client_setup.api_auth.as_ref(),
|
||||
pending_retry,
|
||||
);
|
||||
let compression = self.responses_request_compression(client_setup.auth.as_ref());
|
||||
|
||||
let options = self
|
||||
.build_responses_options(
|
||||
window_id,
|
||||
turn_metadata_header,
|
||||
compression,
|
||||
model_info.use_responses_lite,
|
||||
)
|
||||
.await;
|
||||
let request = self.client.build_responses_request(
|
||||
&client_setup.api_provider,
|
||||
prompt,
|
||||
@@ -1403,15 +1351,17 @@ impl ModelClientSession {
|
||||
effort.clone(),
|
||||
summary,
|
||||
service_tier.clone(),
|
||||
window_id,
|
||||
responses_metadata,
|
||||
)?;
|
||||
let mut client_metadata = self
|
||||
.client
|
||||
.build_ws_client_metadata(responses_metadata, model_info.use_responses_lite);
|
||||
if let Some(turn_state) = self.turn_state.get() {
|
||||
client_metadata.insert(X_CODEX_TURN_STATE_HEADER.to_string(), turn_state.clone());
|
||||
}
|
||||
let mut ws_payload = ResponseCreateWsRequest {
|
||||
client_metadata: response_create_client_metadata(
|
||||
Some(self.client.build_ws_client_metadata(
|
||||
window_id,
|
||||
turn_metadata_header,
|
||||
model_info.use_responses_lite,
|
||||
)),
|
||||
Some(client_metadata),
|
||||
request_trace.as_ref(),
|
||||
),
|
||||
..ResponseCreateWsRequest::from(&request)
|
||||
@@ -1425,8 +1375,7 @@ impl ModelClientSession {
|
||||
session_telemetry,
|
||||
api_provider: client_setup.api_provider,
|
||||
api_auth: client_setup.api_auth,
|
||||
turn_metadata_header,
|
||||
options: &options,
|
||||
responses_metadata,
|
||||
auth_context: request_auth_context,
|
||||
request_route_telemetry: RequestRouteTelemetry::for_endpoint(
|
||||
RESPONSES_ENDPOINT,
|
||||
@@ -1483,7 +1432,11 @@ impl ModelClientSession {
|
||||
))
|
||||
})?;
|
||||
let stream_result = websocket_connection
|
||||
.stream_request(ws_request, self.websocket_session.connection_reused())
|
||||
.stream_request(
|
||||
ws_request,
|
||||
self.websocket_session.connection_reused(),
|
||||
Some(Arc::clone(&self.turn_state)),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
let response_debug_context =
|
||||
@@ -1544,14 +1497,13 @@ impl ModelClientSession {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn prewarm_websocket(
|
||||
&mut self,
|
||||
window_id: &str,
|
||||
prompt: &Prompt,
|
||||
model_info: &ModelInfo,
|
||||
session_telemetry: &SessionTelemetry,
|
||||
effort: Option<ReasoningEffortConfig>,
|
||||
summary: ReasoningSummaryConfig,
|
||||
service_tier: Option<String>,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
) -> Result<()> {
|
||||
if !self.client.responses_websocket_enabled() {
|
||||
return Ok(());
|
||||
@@ -1563,14 +1515,13 @@ impl ModelClientSession {
|
||||
let disabled_trace = InferenceTraceContext::disabled();
|
||||
match self
|
||||
.stream_responses_websocket(
|
||||
window_id,
|
||||
prompt,
|
||||
model_info,
|
||||
session_telemetry,
|
||||
effort,
|
||||
summary,
|
||||
service_tier,
|
||||
turn_metadata_header,
|
||||
responses_metadata,
|
||||
/*warmup*/ true,
|
||||
current_span_w3c_trace_context(),
|
||||
&disabled_trace,
|
||||
@@ -1607,14 +1558,13 @@ impl ModelClientSession {
|
||||
/// branches.
|
||||
pub async fn stream(
|
||||
&mut self,
|
||||
window_id: &str,
|
||||
prompt: &Prompt,
|
||||
model_info: &ModelInfo,
|
||||
session_telemetry: &SessionTelemetry,
|
||||
effort: Option<ReasoningEffortConfig>,
|
||||
summary: ReasoningSummaryConfig,
|
||||
service_tier: Option<String>,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
inference_trace: &InferenceTraceContext,
|
||||
) -> Result<ResponseStream> {
|
||||
let wire_api = self.client.state.provider.info().wire_api;
|
||||
@@ -1624,14 +1574,13 @@ impl ModelClientSession {
|
||||
let request_trace = current_span_w3c_trace_context();
|
||||
match self
|
||||
.stream_responses_websocket(
|
||||
window_id,
|
||||
prompt,
|
||||
model_info,
|
||||
session_telemetry,
|
||||
effort.clone(),
|
||||
summary,
|
||||
service_tier.clone(),
|
||||
turn_metadata_header,
|
||||
responses_metadata,
|
||||
/*warmup*/ false,
|
||||
request_trace,
|
||||
inference_trace,
|
||||
@@ -1646,14 +1595,13 @@ impl ModelClientSession {
|
||||
}
|
||||
|
||||
self.stream_responses_api(
|
||||
window_id,
|
||||
prompt,
|
||||
model_info,
|
||||
session_telemetry,
|
||||
effort,
|
||||
summary,
|
||||
service_tier,
|
||||
turn_metadata_header,
|
||||
responses_metadata,
|
||||
inference_trace,
|
||||
)
|
||||
.await
|
||||
@@ -1680,14 +1628,6 @@ impl ModelClientSession {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses per-turn metadata into an HTTP header value.
|
||||
///
|
||||
/// Invalid values are treated as absent so callers can compare and propagate
|
||||
/// metadata with the same sanitization path used when constructing headers.
|
||||
fn parse_turn_metadata_header(turn_metadata_header: Option<&str>) -> Option<HeaderValue> {
|
||||
turn_metadata_header.and_then(|value| HeaderValue::from_str(value).ok())
|
||||
}
|
||||
|
||||
/// Stamp a ResponsesWsRequest with the current time.
|
||||
///
|
||||
/// Meant to be called just before sending the request over the socket, to capture realistic
|
||||
@@ -1709,11 +1649,9 @@ fn stamp_ws_stream_request_start_ms(request: &mut ResponsesWsRequest) {
|
||||
///
|
||||
/// - `x-codex-beta-features`: comma-separated beta feature keys enabled for the session.
|
||||
/// - `x-codex-turn-state`: sticky routing token captured earlier in the turn.
|
||||
/// - `x-codex-turn-metadata`: optional per-turn metadata for observability.
|
||||
fn build_responses_headers(
|
||||
beta_features_header: Option<&str>,
|
||||
turn_state: Option<&Arc<OnceLock<String>>>,
|
||||
turn_metadata_header: Option<&HeaderValue>,
|
||||
) -> ApiHeaderMap {
|
||||
let mut headers = ApiHeaderMap::new();
|
||||
if let Some(value) = beta_features_header
|
||||
@@ -1728,9 +1666,6 @@ fn build_responses_headers(
|
||||
{
|
||||
headers.insert(X_CODEX_TURN_STATE_HEADER, header_value);
|
||||
}
|
||||
if let Some(header_value) = turn_metadata_header {
|
||||
headers.insert(X_CODEX_TURN_METADATA_HEADER, header_value.clone());
|
||||
}
|
||||
headers
|
||||
}
|
||||
|
||||
@@ -1743,31 +1678,6 @@ fn add_responses_lite_header(headers: &mut ApiHeaderMap, use_responses_lite: boo
|
||||
}
|
||||
}
|
||||
|
||||
fn subagent_header_value(session_source: &SessionSource) -> Option<String> {
|
||||
match session_source {
|
||||
SessionSource::SubAgent(subagent_source) => match subagent_source {
|
||||
SubAgentSource::Review => Some("review".to_string()),
|
||||
SubAgentSource::Compact => Some("compact".to_string()),
|
||||
SubAgentSource::MemoryConsolidation => Some("memory_consolidation".to_string()),
|
||||
SubAgentSource::ThreadSpawn { .. } => Some("collab_spawn".to_string()),
|
||||
SubAgentSource::Other(label) => Some(label.clone()),
|
||||
},
|
||||
SessionSource::Internal(InternalSessionSource::MemoryConsolidation) => {
|
||||
Some("memory_consolidation".to_string())
|
||||
}
|
||||
SessionSource::Cli
|
||||
| SessionSource::VSCode
|
||||
| SessionSource::Exec
|
||||
| SessionSource::Mcp
|
||||
| SessionSource::Custom(_)
|
||||
| SessionSource::Unknown => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parent_thread_id_header_value(parent_thread_id: Option<ThreadId>) -> Option<String> {
|
||||
parent_thread_id.map(|parent_thread_id| parent_thread_id.to_string())
|
||||
}
|
||||
|
||||
const RESPONSE_STREAM_CHANNEL_CAPACITY: usize = 1600;
|
||||
const STREAM_DROPPED_REASON: &str = "response stream dropped before provider terminal event";
|
||||
|
||||
@@ -2004,8 +1914,7 @@ struct WebsocketConnectParams<'a> {
|
||||
session_telemetry: &'a SessionTelemetry,
|
||||
api_provider: codex_api::Provider,
|
||||
api_auth: SharedAuthProvider,
|
||||
turn_metadata_header: Option<&'a str>,
|
||||
options: &'a ApiResponsesOptions,
|
||||
responses_metadata: &'a CodexResponsesMetadata,
|
||||
auth_context: AuthRequestTelemetryContext,
|
||||
request_route_telemetry: RequestRouteTelemetry,
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ use codex_protocol::models::BaseInstructions;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::FunctionCallOutputContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::InterAgentCommunication;
|
||||
use codex_tools::ToolSpec;
|
||||
use futures::Stream;
|
||||
use serde_json::Value;
|
||||
@@ -55,30 +54,11 @@ impl Default for Prompt {
|
||||
}
|
||||
|
||||
impl Prompt {
|
||||
pub(crate) fn get_formatted_input(&self) -> Vec<ResponseItem> {
|
||||
self.input
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|item| {
|
||||
let ResponseItem::Message { role, content, .. } = &item else {
|
||||
return item;
|
||||
};
|
||||
if role != "assistant" {
|
||||
return item;
|
||||
}
|
||||
InterAgentCommunication::from_message_content(content)
|
||||
.filter(|communication| communication.encrypted_content.is_some())
|
||||
.map(|communication| communication.to_model_input_item())
|
||||
.unwrap_or(item)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn get_formatted_input_for_request(
|
||||
&self,
|
||||
use_responses_lite: bool,
|
||||
) -> Vec<ResponseItem> {
|
||||
let mut input = self.get_formatted_input();
|
||||
let mut input = self.input.clone();
|
||||
if use_responses_lite {
|
||||
strip_image_details(&mut input);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@ use super::X_OPENAI_SUBAGENT_HEADER;
|
||||
use crate::AttestationContext;
|
||||
use crate::AttestationProvider;
|
||||
use crate::GenerateAttestationFuture;
|
||||
use crate::responses_metadata::CodexResponsesMetadata;
|
||||
use crate::test_support::TestCodexResponsesRequestKind;
|
||||
use crate::test_support::responses_metadata as test_responses_metadata;
|
||||
use codex_api::ApiError;
|
||||
use codex_api::ResponseEvent;
|
||||
use codex_app_server_protocol::AuthMode;
|
||||
@@ -21,7 +24,6 @@ use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use codex_model_provider_info::create_oss_provider_with_base_url;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_protocol::SessionId;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
@@ -60,24 +62,16 @@ use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::registry::LookupSpan;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
|
||||
fn test_model_client(session_source: SessionSource) -> ModelClient {
|
||||
test_model_client_with_parent(session_source, /*parent_thread_id*/ None)
|
||||
}
|
||||
const TEST_INSTALLATION_ID: &str = "11111111-1111-4111-8111-111111111111";
|
||||
|
||||
fn test_model_client_with_parent(
|
||||
session_source: SessionSource,
|
||||
parent_thread_id: Option<ThreadId>,
|
||||
) -> ModelClient {
|
||||
fn test_model_client(session_source: SessionSource) -> ModelClient {
|
||||
let provider = create_oss_provider_with_base_url("https://example.com/v1", WireApi::Responses);
|
||||
let thread_id = ThreadId::new();
|
||||
ModelClient::new(
|
||||
/*auth_manager*/ None,
|
||||
thread_id.into(),
|
||||
thread_id,
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
provider,
|
||||
session_source,
|
||||
parent_thread_id,
|
||||
/*model_verbosity*/ None,
|
||||
/*enable_request_compression*/ false,
|
||||
/*include_timing_metrics*/ false,
|
||||
@@ -86,6 +80,26 @@ fn test_model_client_with_parent(
|
||||
)
|
||||
}
|
||||
|
||||
fn test_responses_metadata_for_client(
|
||||
client: &ModelClient,
|
||||
turn_id: Option<&str>,
|
||||
window_id: String,
|
||||
parent_thread_id: Option<ThreadId>,
|
||||
request_kind: TestCodexResponsesRequestKind,
|
||||
) -> CodexResponsesMetadata {
|
||||
let thread_id = client.state.thread_id.to_string();
|
||||
test_responses_metadata(
|
||||
TEST_INSTALLATION_ID,
|
||||
&thread_id,
|
||||
&thread_id,
|
||||
turn_id,
|
||||
window_id,
|
||||
&client.state.session_source,
|
||||
parent_thread_id,
|
||||
request_kind,
|
||||
)
|
||||
}
|
||||
|
||||
fn test_model_info() -> ModelInfo {
|
||||
serde_json::from_value(json!({
|
||||
"slug": "gpt-test",
|
||||
@@ -280,48 +294,63 @@ fn build_subagent_headers_sets_internal_memory_consolidation_label() {
|
||||
#[test]
|
||||
fn build_ws_client_metadata_includes_window_lineage_and_turn_metadata() {
|
||||
let parent_thread_id = ThreadId::new();
|
||||
let client = test_model_client_with_parent(
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id,
|
||||
depth: 2,
|
||||
agent_path: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
}),
|
||||
Some(parent_thread_id),
|
||||
);
|
||||
let client = test_model_client(SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id,
|
||||
depth: 2,
|
||||
agent_path: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
}));
|
||||
|
||||
let thread_id = client.state.thread_id;
|
||||
let window_id = format!("{thread_id}:1");
|
||||
let client_metadata = client.build_ws_client_metadata(
|
||||
&window_id,
|
||||
Some(r#"{"turn_id":"turn-123"}"#),
|
||||
/*use_responses_lite*/ false,
|
||||
let thread_id = client.state.thread_id.to_string();
|
||||
let expected_window_id = format!("{thread_id}:1");
|
||||
let responses_metadata = test_responses_metadata_for_client(
|
||||
&client,
|
||||
Some("turn-123"),
|
||||
expected_window_id.clone(),
|
||||
Some(parent_thread_id),
|
||||
TestCodexResponsesRequestKind::Turn,
|
||||
);
|
||||
let client_metadata =
|
||||
client.build_ws_client_metadata(&responses_metadata, /*use_responses_lite*/ false);
|
||||
let parent_thread_id = parent_thread_id.to_string();
|
||||
let turn_metadata: serde_json::Value = serde_json::from_str(
|
||||
client_metadata
|
||||
.get(X_CODEX_TURN_METADATA_HEADER)
|
||||
.expect("turn metadata"),
|
||||
)
|
||||
.expect("valid turn metadata");
|
||||
for (client_key, metadata_key, expected) in [
|
||||
(
|
||||
X_CODEX_INSTALLATION_ID_HEADER,
|
||||
"installation_id",
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
),
|
||||
("session_id", "session_id", thread_id.as_str()),
|
||||
("thread_id", "thread_id", thread_id.as_str()),
|
||||
("turn_id", "turn_id", "turn-123"),
|
||||
(
|
||||
X_CODEX_WINDOW_ID_HEADER,
|
||||
"window_id",
|
||||
expected_window_id.as_str(),
|
||||
),
|
||||
(
|
||||
X_CODEX_PARENT_THREAD_ID_HEADER,
|
||||
"parent_thread_id",
|
||||
parent_thread_id.as_str(),
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
client_metadata.get(client_key).map(String::as_str),
|
||||
Some(expected)
|
||||
);
|
||||
assert_eq!(turn_metadata[metadata_key].as_str(), Some(expected));
|
||||
}
|
||||
assert_eq!(
|
||||
client_metadata,
|
||||
std::collections::HashMap::from([
|
||||
(
|
||||
X_CODEX_INSTALLATION_ID_HEADER.to_string(),
|
||||
"11111111-1111-4111-8111-111111111111".to_string(),
|
||||
),
|
||||
(
|
||||
X_CODEX_WINDOW_ID_HEADER.to_string(),
|
||||
format!("{thread_id}:1"),
|
||||
),
|
||||
(
|
||||
X_OPENAI_SUBAGENT_HEADER.to_string(),
|
||||
"collab_spawn".to_string(),
|
||||
),
|
||||
(
|
||||
X_CODEX_PARENT_THREAD_ID_HEADER.to_string(),
|
||||
parent_thread_id.to_string(),
|
||||
),
|
||||
(
|
||||
X_CODEX_TURN_METADATA_HEADER.to_string(),
|
||||
r#"{"turn_id":"turn-123"}"#.to_string(),
|
||||
),
|
||||
])
|
||||
client_metadata
|
||||
.get(X_OPENAI_SUBAGENT_HEADER)
|
||||
.map(String::as_str),
|
||||
Some("collab_spawn")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -529,12 +558,9 @@ fn model_client_with_counting_attestation(
|
||||
};
|
||||
let model_client = ModelClient::new(
|
||||
auth_manager,
|
||||
SessionId::new(),
|
||||
ThreadId::new(),
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
provider,
|
||||
SessionSource::Exec,
|
||||
/*parent_thread_id*/ None,
|
||||
/*model_verbosity*/ None,
|
||||
/*enable_request_compression*/ false,
|
||||
/*include_timing_metrics*/ false,
|
||||
@@ -550,9 +576,16 @@ fn model_client_with_counting_attestation(
|
||||
async fn websocket_handshake_includes_attestation_for_chatgpt_codex_responses() {
|
||||
let (model_client, attestation_calls) =
|
||||
model_client_with_counting_attestation(/*include_attestation*/ true);
|
||||
let responses_metadata = test_responses_metadata_for_client(
|
||||
&model_client,
|
||||
/*turn_id*/ None,
|
||||
format!("{}:0", model_client.state.thread_id),
|
||||
/*parent_thread_id*/ None,
|
||||
TestCodexResponsesRequestKind::WebsocketConnection,
|
||||
);
|
||||
|
||||
let headers = model_client
|
||||
.build_websocket_headers(/*turn_state*/ None, /*turn_metadata_header*/ None)
|
||||
.build_websocket_headers(&responses_metadata)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
|
||||
@@ -655,6 +655,7 @@ async fn handle_request_user_input(
|
||||
|
||||
let args = RequestUserInputArgs {
|
||||
questions: event.questions,
|
||||
auto_resolution_ms: event.auto_resolution_ms,
|
||||
};
|
||||
let response_fut =
|
||||
parent_session.request_user_input(parent_ctx, parent_ctx.sub_id.clone(), args);
|
||||
|
||||
@@ -433,6 +433,7 @@ async fn delegated_mcp_guardian_abort_returns_synthetic_decline_answer() {
|
||||
is_secret: false,
|
||||
options: None,
|
||||
}],
|
||||
auto_resolution_ms: None,
|
||||
},
|
||||
&cancel_token,
|
||||
)
|
||||
@@ -476,6 +477,7 @@ async fn delegated_mcp_user_reviewer_returns_none_without_metadata() {
|
||||
is_secret: false,
|
||||
options: None,
|
||||
}],
|
||||
auto_resolution_ms: None,
|
||||
};
|
||||
let response = maybe_auto_review_mcp_request_user_input(
|
||||
&parent_session,
|
||||
|
||||
@@ -550,6 +550,11 @@ impl CodexThread {
|
||||
self.codex.session.get_config().await
|
||||
}
|
||||
|
||||
/// Resolves the MCP runtime configuration using this thread's extension data.
|
||||
pub async fn runtime_mcp_config(&self, config: &crate::config::Config) -> codex_mcp::McpConfig {
|
||||
self.codex.session.runtime_mcp_config(config).await
|
||||
}
|
||||
|
||||
pub fn multi_agent_version(&self) -> Option<MultiAgentVersion> {
|
||||
self.codex.session.multi_agent_version()
|
||||
}
|
||||
|
||||
@@ -8,12 +8,14 @@ use crate::hook_runtime::PostCompactHookOutcome;
|
||||
use crate::hook_runtime::PreCompactHookOutcome;
|
||||
use crate::hook_runtime::run_post_compact_hooks;
|
||||
use crate::hook_runtime::run_pre_compact_hooks;
|
||||
use crate::responses_metadata::CodexResponsesMetadata;
|
||||
use crate::responses_metadata::CodexResponsesRequestKind;
|
||||
use crate::responses_metadata::CompactionTurnMetadata;
|
||||
#[cfg(test)]
|
||||
use crate::session::PreviousTurnSettings;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn::get_last_assistant_message_from_turn;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::turn_metadata::CompactionTurnMetadata;
|
||||
use crate::util::backoff;
|
||||
use codex_analytics::CodexCompactionEvent;
|
||||
use codex_analytics::CompactionImplementation;
|
||||
@@ -215,6 +217,12 @@ async fn run_compact_task_inner_impl(
|
||||
// Reuse one client session so turn-scoped state (sticky routing, websocket incremental
|
||||
// request tracking)
|
||||
// survives retries within this compact turn.
|
||||
let window_id = sess.current_window_id().await;
|
||||
let responses_metadata = turn_context.turn_metadata_state.to_responses_metadata(
|
||||
sess.installation_id.clone(),
|
||||
window_id,
|
||||
CodexResponsesRequestKind::Compaction(compaction_metadata),
|
||||
);
|
||||
|
||||
loop {
|
||||
// Clone is required because of the loop
|
||||
@@ -228,16 +236,11 @@ async fn run_compact_task_inner_impl(
|
||||
personality: turn_context.personality,
|
||||
..Default::default()
|
||||
};
|
||||
let window_id = sess.current_window_id().await;
|
||||
let turn_metadata_header = turn_context
|
||||
.turn_metadata_state
|
||||
.current_header_value_for_compaction(&window_id, compaction_metadata);
|
||||
let attempt_result = drain_to_completed(
|
||||
&sess,
|
||||
turn_context.as_ref(),
|
||||
&mut client_session,
|
||||
&window_id,
|
||||
turn_metadata_header.as_deref(),
|
||||
&responses_metadata,
|
||||
&prompt,
|
||||
)
|
||||
.await;
|
||||
@@ -587,20 +590,18 @@ async fn drain_to_completed(
|
||||
sess: &Session,
|
||||
turn_context: &TurnContext,
|
||||
client_session: &mut ModelClientSession,
|
||||
window_id: &str,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
prompt: &Prompt,
|
||||
) -> CodexResult<()> {
|
||||
let mut stream = client_session
|
||||
.stream(
|
||||
window_id,
|
||||
prompt,
|
||||
&turn_context.model_info,
|
||||
&turn_context.session_telemetry,
|
||||
turn_context.reasoning_effort.clone(),
|
||||
turn_context.reasoning_summary,
|
||||
turn_context.config.service_tier.clone(),
|
||||
turn_metadata_header,
|
||||
responses_metadata,
|
||||
// Rollout tracing currently models remote compaction only; local compaction streams
|
||||
// are left untraced until the reducer has a first-class local compaction lifecycle.
|
||||
&InferenceTraceContext::disabled(),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::Prompt;
|
||||
use crate::client::CompactConversationRequestSettings;
|
||||
@@ -12,10 +13,11 @@ use crate::hook_runtime::PostCompactHookOutcome;
|
||||
use crate::hook_runtime::PreCompactHookOutcome;
|
||||
use crate::hook_runtime::run_post_compact_hooks;
|
||||
use crate::hook_runtime::run_pre_compact_hooks;
|
||||
use crate::responses_metadata::CodexResponsesRequestKind;
|
||||
use crate::responses_metadata::CompactionTurnMetadata;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn::built_tools;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::turn_metadata::CompactionTurnMetadata;
|
||||
use codex_analytics::CompactionImplementation;
|
||||
use codex_analytics::CompactionPhase;
|
||||
use codex_analytics::CompactionReason;
|
||||
@@ -42,6 +44,7 @@ const CONTEXT_WINDOW_TRUNCATED_OUTPUT_MESSAGE: &str =
|
||||
pub(crate) async fn run_inline_remote_auto_compact_task(
|
||||
sess: Arc<Session>,
|
||||
turn_context: Arc<TurnContext>,
|
||||
turn_state: Arc<OnceLock<String>>,
|
||||
initial_context_injection: InitialContextInjection,
|
||||
reason: CompactionReason,
|
||||
phase: CompactionPhase,
|
||||
@@ -49,6 +52,7 @@ pub(crate) async fn run_inline_remote_auto_compact_task(
|
||||
run_remote_compact_task_inner(
|
||||
&sess,
|
||||
&turn_context,
|
||||
Some(turn_state),
|
||||
initial_context_injection,
|
||||
CompactionTrigger::Auto,
|
||||
reason,
|
||||
@@ -74,6 +78,7 @@ pub(crate) async fn run_remote_compact_task(
|
||||
run_remote_compact_task_inner(
|
||||
&sess,
|
||||
&turn_context,
|
||||
/*turn_state*/ None,
|
||||
InitialContextInjection::DoNotInject,
|
||||
CompactionTrigger::Manual,
|
||||
CompactionReason::UserRequested,
|
||||
@@ -86,6 +91,7 @@ pub(crate) async fn run_remote_compact_task(
|
||||
async fn run_remote_compact_task_inner(
|
||||
sess: &Arc<Session>,
|
||||
turn_context: &Arc<TurnContext>,
|
||||
turn_state: Option<Arc<OnceLock<String>>>,
|
||||
initial_context_injection: InitialContextInjection,
|
||||
trigger: CompactionTrigger,
|
||||
reason: CompactionReason,
|
||||
@@ -129,6 +135,7 @@ async fn run_remote_compact_task_inner(
|
||||
let result = run_remote_compact_task_inner_impl(
|
||||
sess,
|
||||
turn_context,
|
||||
turn_state,
|
||||
initial_context_injection,
|
||||
compaction_metadata,
|
||||
&mut analytics_details,
|
||||
@@ -162,6 +169,7 @@ async fn run_remote_compact_task_inner(
|
||||
async fn run_remote_compact_task_inner_impl(
|
||||
sess: &Arc<Session>,
|
||||
turn_context: &Arc<TurnContext>,
|
||||
turn_state: Option<Arc<OnceLock<String>>>,
|
||||
initial_context_injection: InitialContextInjection,
|
||||
compaction_metadata: CompactionTurnMetadata,
|
||||
analytics_details: &mut CompactionAnalyticsDetails,
|
||||
@@ -225,15 +233,18 @@ async fn run_remote_compact_task_inner_impl(
|
||||
output_schema_strict: true,
|
||||
};
|
||||
let window_id = sess.current_window_id().await;
|
||||
let turn_metadata_header = turn_context
|
||||
.turn_metadata_state
|
||||
.current_header_value_for_compaction(&window_id, compaction_metadata);
|
||||
let responses_metadata = turn_context.turn_metadata_state.to_responses_metadata(
|
||||
sess.installation_id.clone(),
|
||||
window_id,
|
||||
CodexResponsesRequestKind::Compaction(compaction_metadata),
|
||||
);
|
||||
let mut new_history = sess
|
||||
.services
|
||||
.model_client
|
||||
.compact_conversation_history(
|
||||
&prompt,
|
||||
&turn_context.model_info,
|
||||
turn_state,
|
||||
CompactConversationRequestSettings {
|
||||
effort: turn_context.reasoning_effort.clone(),
|
||||
summary: turn_context.reasoning_summary,
|
||||
@@ -245,8 +256,7 @@ async fn run_remote_compact_task_inner_impl(
|
||||
},
|
||||
&turn_context.session_telemetry,
|
||||
&compaction_trace,
|
||||
&window_id,
|
||||
turn_metadata_header.as_deref(),
|
||||
&responses_metadata,
|
||||
)
|
||||
.await?;
|
||||
let new_window_id = sess.advance_auto_compact_window_id().await;
|
||||
|
||||
@@ -15,12 +15,14 @@ use crate::hook_runtime::PostCompactHookOutcome;
|
||||
use crate::hook_runtime::PreCompactHookOutcome;
|
||||
use crate::hook_runtime::run_post_compact_hooks;
|
||||
use crate::hook_runtime::run_pre_compact_hooks;
|
||||
use crate::responses_metadata::CodexResponsesMetadata;
|
||||
use crate::responses_metadata::CodexResponsesRequestKind;
|
||||
use crate::responses_metadata::CompactionTurnMetadata;
|
||||
use crate::responses_retry::ResponsesStreamRequest;
|
||||
use crate::responses_retry::handle_retryable_response_stream_error;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn::built_tools;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::turn_metadata::CompactionTurnMetadata;
|
||||
use codex_analytics::CompactionImplementation;
|
||||
use codex_analytics::CompactionPhase;
|
||||
use codex_analytics::CompactionReason;
|
||||
@@ -241,9 +243,11 @@ async fn run_remote_compact_task_inner_impl(
|
||||
};
|
||||
|
||||
let window_id = sess.current_window_id().await;
|
||||
let turn_metadata_header = turn_context
|
||||
.turn_metadata_state
|
||||
.current_header_value_for_compaction(&window_id, compaction_metadata);
|
||||
let responses_metadata = turn_context.turn_metadata_state.to_responses_metadata(
|
||||
sess.installation_id.clone(),
|
||||
window_id,
|
||||
CodexResponsesRequestKind::Compaction(compaction_metadata),
|
||||
);
|
||||
let trace_attempt = compaction_trace.start_attempt(&serde_json::json!({
|
||||
"model": turn_context.model_info.slug.as_str(),
|
||||
"instructions": prompt.base_instructions.text.as_str(),
|
||||
@@ -264,8 +268,7 @@ async fn run_remote_compact_task_inner_impl(
|
||||
turn_context,
|
||||
client_session,
|
||||
&prompt,
|
||||
&window_id,
|
||||
turn_metadata_header.as_deref(),
|
||||
&responses_metadata,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -327,8 +330,7 @@ async fn run_remote_compaction_request_v2(
|
||||
turn_context: &TurnContext,
|
||||
client_session: &mut ModelClientSession,
|
||||
prompt: &Prompt,
|
||||
window_id: &str,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
) -> CodexResult<RemoteCompactionV2Output> {
|
||||
let max_retries = turn_context
|
||||
.provider
|
||||
@@ -339,14 +341,13 @@ async fn run_remote_compaction_request_v2(
|
||||
loop {
|
||||
let result = match client_session
|
||||
.stream(
|
||||
window_id,
|
||||
prompt,
|
||||
&turn_context.model_info,
|
||||
&turn_context.session_telemetry,
|
||||
turn_context.reasoning_effort.clone(),
|
||||
turn_context.reasoning_summary,
|
||||
turn_context.config.service_tier.clone(),
|
||||
turn_metadata_header,
|
||||
responses_metadata,
|
||||
&InferenceTraceContext::disabled(),
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -320,7 +320,7 @@ async fn read_resolved_agent_role_file(
|
||||
path: &AbsolutePathBuf,
|
||||
role_name_hint: Option<&str>,
|
||||
) -> std::io::Result<ResolvedAgentRoleFile> {
|
||||
let path_uri = PathUri::from_abs_path(path)?;
|
||||
let path_uri = PathUri::from_abs_path(path);
|
||||
let contents = fs.read_file_text(&path_uri, /*sandbox*/ None).await?;
|
||||
let config_base_dir = path.parent().unwrap_or_else(|| path.clone());
|
||||
parse_agent_role_file_contents(
|
||||
@@ -393,7 +393,7 @@ async fn validate_agent_role_config_file(
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let config_file_uri = PathUri::from_abs_path(config_file)?;
|
||||
let config_file_uri = PathUri::from_abs_path(config_file);
|
||||
let metadata = fs
|
||||
.get_metadata(&config_file_uri, /*sandbox*/ None)
|
||||
.await
|
||||
@@ -525,7 +525,7 @@ async fn collect_agent_role_files(
|
||||
let mut files = Vec::new();
|
||||
let mut dirs = vec![dir.clone()];
|
||||
while let Some(dir) = dirs.pop() {
|
||||
let dir_uri = PathUri::from_abs_path(&dir)?;
|
||||
let dir_uri = PathUri::from_abs_path(&dir);
|
||||
let entries = match fs.read_directory(&dir_uri, /*sandbox*/ None).await {
|
||||
Ok(entries) => entries,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
use super::Config;
|
||||
use super::ConfigTomlLoadResult;
|
||||
use super::ManagedFeatures;
|
||||
use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_features::Feature;
|
||||
use codex_features::FeatureConfigSource;
|
||||
use codex_features::FeatureOverrides;
|
||||
use codex_features::Features;
|
||||
|
||||
impl Config {
|
||||
pub fn auth_keyring_backend_kind(&self) -> AuthKeyringBackendKind {
|
||||
auth_keyring_backend_kind_from_secret_auth_storage(
|
||||
self.features.enabled(Feature::SecretAuthStorage),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the auth keyring backend from a partially loaded bootstrap config.
|
||||
///
|
||||
/// This is intended for startup paths that must read auth before managed cloud
|
||||
/// requirements can be loaded and before a full [`Config`] exists.
|
||||
pub fn resolve_bootstrap_auth_keyring_backend_kind(
|
||||
bootstrap_config: &ConfigTomlLoadResult,
|
||||
) -> std::io::Result<AuthKeyringBackendKind> {
|
||||
let config_toml = &bootstrap_config.config_toml;
|
||||
let features = Features::from_sources(
|
||||
FeatureConfigSource {
|
||||
features: config_toml.features.as_ref(),
|
||||
experimental_use_unified_exec_tool: config_toml.experimental_use_unified_exec_tool,
|
||||
},
|
||||
FeatureConfigSource::default(),
|
||||
FeatureOverrides::default(),
|
||||
);
|
||||
let managed_features = ManagedFeatures::from_configured(
|
||||
features,
|
||||
bootstrap_config
|
||||
.config_layer_stack
|
||||
.requirements()
|
||||
.feature_requirements
|
||||
.clone(),
|
||||
)?;
|
||||
Ok(auth_keyring_backend_kind_from_secret_auth_storage(
|
||||
managed_features.enabled(Feature::SecretAuthStorage),
|
||||
))
|
||||
}
|
||||
|
||||
fn auth_keyring_backend_kind_from_secret_auth_storage(
|
||||
secret_auth_storage_enabled: bool,
|
||||
) -> AuthKeyringBackendKind {
|
||||
if secret_auth_storage_enabled {
|
||||
AuthKeyringBackendKind::Secrets
|
||||
} else {
|
||||
AuthKeyringBackendKind::Direct
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "auth_keyring_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,79 @@
|
||||
use super::*;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::ConfigRequirements;
|
||||
use codex_config::ConfigRequirementsToml;
|
||||
use codex_config::FeatureRequirementsToml;
|
||||
use codex_config::RequirementSource;
|
||||
use codex_config::Sourced;
|
||||
use codex_config::config_toml::ConfigToml;
|
||||
use codex_features::FeaturesToml;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
fn resolve_bootstrap_auth_keyring_backend_kind_uses_secret_auth_storage_feature()
|
||||
-> std::io::Result<()> {
|
||||
let config_toml = ConfigToml {
|
||||
features: Some(FeaturesToml::from(BTreeMap::from([(
|
||||
"secret_auth_storage".to_string(),
|
||||
true,
|
||||
)]))),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
resolve_bootstrap_auth_keyring_backend_kind(&config_toml_load_result(
|
||||
config_toml,
|
||||
/*feature_requirements*/ None,
|
||||
)?)?,
|
||||
AuthKeyringBackendKind::Secrets
|
||||
);
|
||||
|
||||
let config_toml = ConfigToml {
|
||||
features: Some(FeaturesToml::from(BTreeMap::from([(
|
||||
"secret_auth_storage".to_string(),
|
||||
false,
|
||||
)]))),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
resolve_bootstrap_auth_keyring_backend_kind(&config_toml_load_result(
|
||||
config_toml.clone(),
|
||||
/*feature_requirements*/ None,
|
||||
)?)?,
|
||||
AuthKeyringBackendKind::Direct
|
||||
);
|
||||
|
||||
let requirements = Sourced::new(
|
||||
FeatureRequirementsToml {
|
||||
entries: BTreeMap::from([("secret_auth_storage".to_string(), true)]),
|
||||
},
|
||||
RequirementSource::Unknown,
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_bootstrap_auth_keyring_backend_kind(&config_toml_load_result(
|
||||
config_toml,
|
||||
Some(requirements),
|
||||
)?)?,
|
||||
AuthKeyringBackendKind::Secrets
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn config_toml_load_result(
|
||||
config_toml: ConfigToml,
|
||||
feature_requirements: Option<Sourced<FeatureRequirementsToml>>,
|
||||
) -> std::io::Result<ConfigTomlLoadResult> {
|
||||
let requirements = ConfigRequirements {
|
||||
feature_requirements,
|
||||
..Default::default()
|
||||
};
|
||||
Ok(ConfigTomlLoadResult {
|
||||
config_toml,
|
||||
config_layer_stack: ConfigLayerStack::new(
|
||||
Vec::new(),
|
||||
requirements,
|
||||
ConfigRequirementsToml::default(),
|
||||
)?,
|
||||
})
|
||||
}
|
||||
@@ -4,14 +4,17 @@ use crate::config::edit::apply_blocking;
|
||||
use assert_matches::assert_matches;
|
||||
use codex_config::CONFIG_TOML_FILE;
|
||||
use codex_config::ConfigLayerEntry;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::ProfileV2Name;
|
||||
use codex_config::RequirementSource;
|
||||
use codex_config::Sourced;
|
||||
use codex_config::config_toml::AgentRoleToml;
|
||||
use codex_config::config_toml::AgentsToml;
|
||||
use codex_config::config_toml::AutoReviewToml;
|
||||
use codex_config::config_toml::ConfigToml;
|
||||
use codex_config::config_toml::ExperimentalRequestUserInput;
|
||||
use codex_config::config_toml::ProjectConfig;
|
||||
use codex_config::config_toml::RealtimeArchitecture;
|
||||
use codex_config::config_toml::RealtimeConfig;
|
||||
use codex_config::config_toml::RealtimeToml;
|
||||
use codex_config::config_toml::RealtimeTransport;
|
||||
@@ -8313,6 +8316,7 @@ async fn test_requirements_web_search_mode_allowlist_does_not_warn_when_unset()
|
||||
allowed_web_search_modes: Some(vec![codex_config::WebSearchModeRequirement::Cached]),
|
||||
allow_managed_hooks_only: None,
|
||||
allow_appshots: None,
|
||||
allow_remote_control: None,
|
||||
computer_use: None,
|
||||
windows: None,
|
||||
feature_requirements: None,
|
||||
@@ -9578,12 +9582,15 @@ chatgpt_base_url = "https://user.example/backend-api"
|
||||
r#"
|
||||
cli_auth_credentials_store = "keyring"
|
||||
chatgpt_base_url = "https://managed.example/backend-api"
|
||||
|
||||
[features]
|
||||
secret_auth_storage = true
|
||||
"#,
|
||||
)?;
|
||||
let mut loader_overrides = LoaderOverrides::without_managed_config_for_tests();
|
||||
loader_overrides.system_requirements_path = Some(requirements_path);
|
||||
|
||||
let config = load_bootstrap_config_as_toml_with_cli_and_load_options(
|
||||
let bootstrap_config = load_bootstrap_config_toml_with_layer_stack(
|
||||
codex_home.path(),
|
||||
Some(&codex_home.path().abs()),
|
||||
Vec::new(),
|
||||
@@ -9593,12 +9600,18 @@ chatgpt_base_url = "https://managed.example/backend-api"
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let auth_keyring_backend_kind = resolve_bootstrap_auth_keyring_backend_kind(&bootstrap_config)?;
|
||||
|
||||
assert_eq!(
|
||||
(config.cli_auth_credentials_store, config.chatgpt_base_url,),
|
||||
(
|
||||
bootstrap_config.config_toml.cli_auth_credentials_store,
|
||||
bootstrap_config.config_toml.chatgpt_base_url,
|
||||
auth_keyring_backend_kind,
|
||||
),
|
||||
(
|
||||
Some(AuthCredentialsStoreMode::Keyring),
|
||||
Some("https://managed.example/backend-api".to_string()),
|
||||
AuthKeyringBackendKind::Secrets,
|
||||
)
|
||||
);
|
||||
Ok(())
|
||||
@@ -10808,8 +10821,8 @@ experimental_thread_config_endpoint = "http://127.0.0.1:8061"
|
||||
#[tokio::test]
|
||||
async fn experimental_realtime_ws_base_url_loads_from_config_toml() -> std::io::Result<()> {
|
||||
let cfg: ConfigToml = toml::from_str(
|
||||
r#"
|
||||
experimental_realtime_ws_base_url = "http://127.0.0.1:8011"
|
||||
r#"experimental_realtime_ws_base_url = "http://127.0.0.1:8011"
|
||||
experimental_realtime_webrtc_call_base_url = "http://127.0.0.1:8082/v1"
|
||||
"#,
|
||||
)
|
||||
.expect("TOML deserialization should succeed");
|
||||
@@ -10818,7 +10831,10 @@ experimental_realtime_ws_base_url = "http://127.0.0.1:8011"
|
||||
cfg.experimental_realtime_ws_base_url.as_deref(),
|
||||
Some("http://127.0.0.1:8011")
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
cfg.experimental_realtime_webrtc_call_base_url.as_deref(),
|
||||
Some("http://127.0.0.1:8082/v1")
|
||||
);
|
||||
let codex_home = TempDir::new()?;
|
||||
let config = Config::load_from_base_config_with_overrides(
|
||||
cfg,
|
||||
@@ -10831,6 +10847,10 @@ experimental_realtime_ws_base_url = "http://127.0.0.1:8011"
|
||||
config.experimental_realtime_ws_base_url.as_deref(),
|
||||
Some("http://127.0.0.1:8011")
|
||||
);
|
||||
assert_eq!(
|
||||
config.experimental_realtime_webrtc_call_base_url.as_deref(),
|
||||
Some("http://127.0.0.1:8082/v1")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -10954,6 +10974,7 @@ async fn realtime_loads_from_config_toml() -> std::io::Result<()> {
|
||||
let cfg: ConfigToml = toml::from_str(
|
||||
r#"
|
||||
[realtime]
|
||||
architecture = "avas"
|
||||
version = "v2"
|
||||
type = "transcription"
|
||||
transport = "webrtc"
|
||||
@@ -10965,6 +10986,7 @@ voice = "cedar"
|
||||
assert_eq!(
|
||||
cfg.realtime,
|
||||
Some(RealtimeToml {
|
||||
architecture: Some(RealtimeArchitecture::Avas),
|
||||
version: Some(RealtimeWsVersion::V2),
|
||||
session_type: Some(RealtimeWsMode::Transcription),
|
||||
transport: Some(RealtimeTransport::WebRtc),
|
||||
@@ -10983,6 +11005,7 @@ voice = "cedar"
|
||||
assert_eq!(
|
||||
config.realtime,
|
||||
RealtimeConfig {
|
||||
architecture: RealtimeArchitecture::Avas,
|
||||
version: RealtimeWsVersion::V2,
|
||||
session_type: RealtimeWsMode::Transcription,
|
||||
transport: RealtimeTransport::WebRtc,
|
||||
|
||||
@@ -36,6 +36,7 @@ use codex_config::permissions_toml::PermissionsToml;
|
||||
use codex_config::sandbox_mode_requirement_for_permission_profile;
|
||||
use codex_config::types::ApprovalsReviewer;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_config::types::History;
|
||||
use codex_config::types::McpServerConfig;
|
||||
use codex_config::types::McpServerDisabledReason;
|
||||
@@ -137,6 +138,7 @@ use toml::Value as TomlValue;
|
||||
use toml_edit::DocumentMut;
|
||||
|
||||
pub(crate) mod agent_roles;
|
||||
mod auth_keyring;
|
||||
pub mod edit;
|
||||
mod managed_features;
|
||||
mod network_proxy_spec;
|
||||
@@ -146,6 +148,7 @@ mod requirements;
|
||||
mod resolved_permission_profile;
|
||||
#[cfg(test)]
|
||||
mod schema;
|
||||
pub use auth_keyring::resolve_bootstrap_auth_keyring_backend_kind;
|
||||
pub use codex_config::ConfigLoadOptions;
|
||||
pub use codex_config::Constrained;
|
||||
pub use codex_config::ConstraintError;
|
||||
@@ -203,7 +206,7 @@ All agents in the team, including the agents that you can assign tasks to, are e
|
||||
You can use `spawn_agent` to create a new agent, `followup_task` to give an existing agent a new task and trigger a turn, and `send_message` to pass a message to a running agent without triggering a turn.
|
||||
Child agents can also spawn their own sub-agents.
|
||||
You can decide how much context you want to propagate to your sub-agents with the `fork_turns` parameter.
|
||||
Default to doing the work yourself. Spawn sub-agents only for concrete, bounded subtasks that can run independently alongside useful local work and are likely to materially shorten completion time. Do not delegate simple tasks, small edits, routine searches, or work you can complete quickly yourself.
|
||||
Do not spawn sub-agents unless the user explicitly asks for sub-agents, delegation, or parallel agent work.
|
||||
|
||||
You will receive messages in the analysis channel in the form:
|
||||
```
|
||||
@@ -220,7 +223,7 @@ You can spawn sub-agents to handle subtasks, and those sub-agents can spawn thei
|
||||
|
||||
You can use `spawn_agent` to create a new agent, `followup_task` to give an existing agent a new task and trigger a turn, and `send_message` to pass a message to a running agent.
|
||||
Child agents can also spawn their own sub-agents.
|
||||
Default to doing the work yourself. Spawn sub-agents only for concrete, bounded subtasks that can run independently alongside useful local work and are likely to materially shorten completion time. Do not delegate simple tasks, small edits, routine searches, or work you can complete quickly yourself.
|
||||
Do not spawn sub-agents unless the user explicitly asks for sub-agents, delegation, or parallel agent work.
|
||||
|
||||
When you provide a response in the final channel, that content is immediately delivered back to your parent agent.
|
||||
|
||||
@@ -946,6 +949,9 @@ pub struct Config {
|
||||
/// `/v1/realtime`
|
||||
/// connection) without changing normal provider HTTP requests.
|
||||
pub experimental_realtime_ws_base_url: Option<String>,
|
||||
/// Experimental / do not use. Overrides only the WebRTC realtime call
|
||||
/// creation base URL.
|
||||
pub experimental_realtime_webrtc_call_base_url: Option<String>,
|
||||
/// Experimental / do not use. Selects the realtime websocket model/snapshot
|
||||
/// used for the `Op::RealtimeConversation` connection.
|
||||
pub experimental_realtime_ws_model: Option<String>,
|
||||
@@ -1117,6 +1123,10 @@ impl AuthManagerConfig for Config {
|
||||
self.cli_auth_credentials_store_mode
|
||||
}
|
||||
|
||||
fn auth_keyring_backend_kind(&self) -> AuthKeyringBackendKind {
|
||||
Config::auth_keyring_backend_kind(self)
|
||||
}
|
||||
|
||||
fn forced_chatgpt_workspace_id(&self) -> Option<Vec<String>> {
|
||||
self.forced_chatgpt_workspace_id.clone()
|
||||
}
|
||||
@@ -1434,6 +1444,7 @@ impl Config {
|
||||
apps_mcp_product_sku: self.apps_mcp_product_sku.clone(),
|
||||
codex_home: self.codex_home.to_path_buf(),
|
||||
mcp_oauth_credentials_store_mode: self.mcp_oauth_credentials_store_mode,
|
||||
auth_keyring_backend_kind: self.auth_keyring_backend_kind(),
|
||||
mcp_oauth_callback_port: self.mcp_oauth_callback_port,
|
||||
mcp_oauth_callback_url: self.mcp_oauth_callback_url.clone(),
|
||||
skill_mcp_dependency_install_enabled: self
|
||||
@@ -1645,6 +1656,29 @@ pub async fn load_config_as_toml_with_cli_and_load_options(
|
||||
cli_overrides: Vec<(String, TomlValue)>,
|
||||
options: impl Into<ConfigLoadOptions>,
|
||||
) -> std::io::Result<ConfigToml> {
|
||||
load_config_toml_with_layer_stack(codex_home, cwd, cli_overrides, options)
|
||||
.await
|
||||
.map(|result| result.config_toml)
|
||||
}
|
||||
|
||||
/// Partially loaded config plus the layer stack used to derive it.
|
||||
///
|
||||
/// This is intended for startup paths that must inspect raw config before a
|
||||
/// full [`Config`] can be constructed, but still need access to managed
|
||||
/// requirements loaded with the config layers.
|
||||
pub struct ConfigTomlLoadResult {
|
||||
pub config_toml: ConfigToml,
|
||||
pub config_layer_stack: ConfigLayerStack,
|
||||
}
|
||||
|
||||
/// Loads the partially merged config together with the layer stack used to
|
||||
/// derive it, before constructing a full [`Config`].
|
||||
pub async fn load_config_toml_with_layer_stack(
|
||||
codex_home: &Path,
|
||||
cwd: Option<&AbsolutePathBuf>,
|
||||
cli_overrides: Vec<(String, TomlValue)>,
|
||||
options: impl Into<ConfigLoadOptions>,
|
||||
) -> std::io::Result<ConfigTomlLoadResult> {
|
||||
let config_layer_stack = load_config_layers_state(
|
||||
LOCAL_FS.as_ref(),
|
||||
codex_home,
|
||||
@@ -1661,7 +1695,10 @@ pub async fn load_config_as_toml_with_cli_and_load_options(
|
||||
e
|
||||
})?;
|
||||
|
||||
Ok(cfg)
|
||||
Ok(ConfigTomlLoadResult {
|
||||
config_toml: cfg,
|
||||
config_layer_stack,
|
||||
})
|
||||
}
|
||||
|
||||
/// Load the raw merged config needed to bootstrap cloud requirements, applying
|
||||
@@ -1677,26 +1714,29 @@ pub async fn load_bootstrap_config_as_toml_with_cli_and_load_options(
|
||||
cli_overrides: Vec<(String, TomlValue)>,
|
||||
options: impl Into<ConfigLoadOptions>,
|
||||
) -> std::io::Result<ConfigToml> {
|
||||
let config_layer_stack = load_config_layers_state(
|
||||
LOCAL_FS.as_ref(),
|
||||
codex_home,
|
||||
cwd.cloned(),
|
||||
&cli_overrides,
|
||||
options,
|
||||
&codex_config::NoopThreadConfigLoader,
|
||||
)
|
||||
.await?;
|
||||
load_bootstrap_config_toml_with_layer_stack(codex_home, cwd, cli_overrides, options)
|
||||
.await
|
||||
.map(|result| result.config_toml)
|
||||
}
|
||||
|
||||
let merged_toml = config_layer_stack.effective_config();
|
||||
let mut cfg = deserialize_config_toml_with_base(merged_toml, codex_home)?;
|
||||
let requirements = config_layer_stack.requirements_toml();
|
||||
/// Load the bootstrap config together with its layer stack, applying exact
|
||||
/// auth requirements needed before cloud requirements can be fetched.
|
||||
pub async fn load_bootstrap_config_toml_with_layer_stack(
|
||||
codex_home: &Path,
|
||||
cwd: Option<&AbsolutePathBuf>,
|
||||
cli_overrides: Vec<(String, TomlValue)>,
|
||||
options: impl Into<ConfigLoadOptions>,
|
||||
) -> std::io::Result<ConfigTomlLoadResult> {
|
||||
let mut result =
|
||||
load_config_toml_with_layer_stack(codex_home, cwd, cli_overrides, options).await?;
|
||||
let requirements = result.config_layer_stack.requirements_toml();
|
||||
if let Some(required) = requirements.cli_auth_credentials_store {
|
||||
cfg.cli_auth_credentials_store = Some(required);
|
||||
result.config_toml.cli_auth_credentials_store = Some(required);
|
||||
}
|
||||
if let Some(required) = requirements.chatgpt_base_url.as_ref() {
|
||||
cfg.chatgpt_base_url = Some(required.clone());
|
||||
result.config_toml.chatgpt_base_url = Some(required.clone());
|
||||
}
|
||||
Ok(cfg)
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn deserialize_config_toml_with_base(
|
||||
@@ -2655,6 +2695,7 @@ impl Config {
|
||||
windows_sandbox_private_desktop: _,
|
||||
allow_managed_hooks_only: _,
|
||||
allow_appshots: _,
|
||||
allow_remote_control: _,
|
||||
computer_use: _,
|
||||
feature_requirements,
|
||||
managed_hooks: _,
|
||||
@@ -3599,12 +3640,15 @@ impl Config {
|
||||
speaker: audio.speaker,
|
||||
}),
|
||||
experimental_realtime_ws_base_url: cfg.experimental_realtime_ws_base_url,
|
||||
experimental_realtime_webrtc_call_base_url: cfg
|
||||
.experimental_realtime_webrtc_call_base_url,
|
||||
experimental_realtime_ws_model: cfg.experimental_realtime_ws_model,
|
||||
realtime: cfg
|
||||
.realtime
|
||||
.map_or_else(RealtimeConfig::default, |realtime| {
|
||||
let defaults = RealtimeConfig::default();
|
||||
RealtimeConfig {
|
||||
architecture: realtime.architecture.unwrap_or(defaults.architecture),
|
||||
version: realtime.version.unwrap_or(defaults.version),
|
||||
session_type: realtime.session_type.unwrap_or(defaults.session_type),
|
||||
transport: realtime.transport.unwrap_or(defaults.transport),
|
||||
@@ -3712,7 +3756,7 @@ impl Config {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let path_uri = PathUri::from_abs_path(path)?;
|
||||
let path_uri = PathUri::from_abs_path(path);
|
||||
let contents = fs
|
||||
.read_file_text(&path_uri, /*sandbox*/ None)
|
||||
.await
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use async_trait::async_trait;
|
||||
use codex_config::NetworkConstraints;
|
||||
use codex_execpolicy::Policy;
|
||||
use codex_network_proxy::BlockedRequestObserver;
|
||||
use codex_network_proxy::ConfigReloader;
|
||||
use codex_network_proxy::ConfigReloaderFuture;
|
||||
use codex_network_proxy::ConfigState;
|
||||
use codex_network_proxy::NetworkDecision;
|
||||
use codex_network_proxy::NetworkPolicyDecider;
|
||||
@@ -58,14 +58,13 @@ impl StaticNetworkProxyReloader {
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ConfigReloader for StaticNetworkProxyReloader {
|
||||
async fn maybe_reload(&self) -> anyhow::Result<Option<ConfigState>> {
|
||||
Ok(None)
|
||||
fn maybe_reload(&self) -> ConfigReloaderFuture<'_, Option<ConfigState>> {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
async fn reload_now(&self) -> anyhow::Result<ConfigState> {
|
||||
Ok(self.state.clone())
|
||||
fn reload_now(&self) -> ConfigReloaderFuture<'_, ConfigState> {
|
||||
Box::pin(async { Ok(self.state.clone()) })
|
||||
}
|
||||
|
||||
fn source_label(&self) -> String {
|
||||
|
||||
@@ -18,6 +18,7 @@ use codex_tools::DiscoverableTool;
|
||||
use rmcp::model::ToolAnnotations;
|
||||
use serde::Deserialize;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::instrument;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::config::Config;
|
||||
@@ -280,6 +281,7 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_mcp_manager(
|
||||
let auth_status_entries = compute_auth_statuses(
|
||||
mcp_servers.iter(),
|
||||
config.mcp_oauth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind(),
|
||||
auth.as_ref(),
|
||||
)
|
||||
.await;
|
||||
@@ -291,6 +293,7 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_mcp_manager(
|
||||
let mcp_connection_manager = McpConnectionManager::new(
|
||||
&mcp_servers,
|
||||
config.mcp_oauth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind(),
|
||||
auth_status_entries,
|
||||
&config.permissions.approval_policy,
|
||||
INITIAL_SUBMIT_ID.to_owned(),
|
||||
@@ -458,6 +461,7 @@ fn tool_suggest_connector_ids(
|
||||
connector_ids
|
||||
}
|
||||
|
||||
#[instrument(level = "trace", skip_all)]
|
||||
async fn cached_directory_connectors_for_tool_suggest_with_auth(
|
||||
config: &Config,
|
||||
auth: Option<&CodexAuth>,
|
||||
@@ -601,6 +605,11 @@ pub(crate) fn mcp_approvals_reviewer(
|
||||
connector_id
|
||||
.and_then(|connector_id| apps_config.apps.get(connector_id))
|
||||
.and_then(|app| app.approvals_reviewer)
|
||||
.or_else(|| {
|
||||
apps_config
|
||||
.default
|
||||
.and_then(|defaults| defaults.approvals_reviewer)
|
||||
})
|
||||
})
|
||||
} else {
|
||||
None
|
||||
|
||||
@@ -269,6 +269,7 @@ fn app_tool_policy_uses_global_defaults_for_destructive_hints() {
|
||||
let apps_config = AppsConfigToml {
|
||||
default: Some(AppsDefaultConfig {
|
||||
enabled: true,
|
||||
approvals_reviewer: None,
|
||||
destructive_enabled: false,
|
||||
open_world_enabled: true,
|
||||
}),
|
||||
@@ -298,6 +299,7 @@ fn app_tool_policy_defaults_missing_destructive_hint_to_true() {
|
||||
let apps_config = AppsConfigToml {
|
||||
default: Some(AppsDefaultConfig {
|
||||
enabled: true,
|
||||
approvals_reviewer: None,
|
||||
destructive_enabled: false,
|
||||
open_world_enabled: true,
|
||||
}),
|
||||
@@ -327,6 +329,7 @@ fn app_tool_policy_defaults_missing_open_world_hint_to_true() {
|
||||
let apps_config = AppsConfigToml {
|
||||
default: Some(AppsDefaultConfig {
|
||||
enabled: true,
|
||||
approvals_reviewer: None,
|
||||
destructive_enabled: true,
|
||||
open_world_enabled: false,
|
||||
}),
|
||||
@@ -356,6 +359,7 @@ fn app_is_enabled_uses_default_for_unconfigured_apps() {
|
||||
let apps_config = AppsConfigToml {
|
||||
default: Some(AppsDefaultConfig {
|
||||
enabled: false,
|
||||
approvals_reviewer: None,
|
||||
destructive_enabled: true,
|
||||
open_world_enabled: true,
|
||||
}),
|
||||
@@ -371,6 +375,7 @@ fn app_is_enabled_prefers_per_app_override_over_default() {
|
||||
let apps_config = AppsConfigToml {
|
||||
default: Some(AppsDefaultConfig {
|
||||
enabled: false,
|
||||
approvals_reviewer: None,
|
||||
destructive_enabled: true,
|
||||
open_world_enabled: true,
|
||||
}),
|
||||
@@ -393,19 +398,23 @@ fn app_is_enabled_prefers_per_app_override_over_default() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_approvals_reviewer_overrides_global_reviewer() {
|
||||
for (global, app, expected_global, expected_app) in [
|
||||
async fn app_approvals_reviewer_uses_app_then_default_then_global() {
|
||||
for (global, app_default, app, expected_global, expected_default, expected_app) in [
|
||||
(
|
||||
"user",
|
||||
"auto_review",
|
||||
"user",
|
||||
ApprovalsReviewer::User,
|
||||
ApprovalsReviewer::AutoReview,
|
||||
ApprovalsReviewer::User,
|
||||
),
|
||||
(
|
||||
"auto_review",
|
||||
"user",
|
||||
"auto_review",
|
||||
ApprovalsReviewer::AutoReview,
|
||||
ApprovalsReviewer::User,
|
||||
ApprovalsReviewer::AutoReview,
|
||||
),
|
||||
] {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
@@ -415,6 +424,9 @@ async fn app_approvals_reviewer_overrides_global_reviewer() {
|
||||
r#"
|
||||
approvals_reviewer = "{global}"
|
||||
|
||||
[apps._default]
|
||||
approvals_reviewer = "{app_default}"
|
||||
|
||||
[apps.calendar]
|
||||
approvals_reviewer = "{app}"
|
||||
"#
|
||||
@@ -433,7 +445,15 @@ approvals_reviewer = "{app}"
|
||||
);
|
||||
assert_eq!(
|
||||
mcp_approvals_reviewer(&config, CODEX_APPS_MCP_SERVER_NAME, Some("drive")),
|
||||
expected_global
|
||||
expected_default
|
||||
);
|
||||
assert_eq!(
|
||||
mcp_approvals_reviewer(
|
||||
&config,
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
/*connector_id*/ None
|
||||
),
|
||||
expected_default
|
||||
);
|
||||
assert_eq!(
|
||||
mcp_approvals_reviewer(&config, "custom_server", Some("calendar")),
|
||||
@@ -442,6 +462,36 @@ approvals_reviewer = "{app}"
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn default_app_approvals_reviewer_respects_global_reviewer_requirements() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
std::fs::write(
|
||||
codex_home.path().join(CONFIG_TOML_FILE),
|
||||
r#"
|
||||
approvals_reviewer = "auto_review"
|
||||
|
||||
[apps._default]
|
||||
approvals_reviewer = "user"
|
||||
"#,
|
||||
)
|
||||
.expect("write config");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.cloud_config_bundle(
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement(
|
||||
r#"allowed_approvals_reviewers = ["auto_review"]"#,
|
||||
),
|
||||
)
|
||||
.build()
|
||||
.await
|
||||
.expect("config should build");
|
||||
|
||||
assert_eq!(
|
||||
mcp_approvals_reviewer(&config, CODEX_APPS_MCP_SERVER_NAME, Some("calendar")),
|
||||
ApprovalsReviewer::AutoReview
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_approvals_reviewer_respects_global_reviewer_requirements() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
@@ -756,6 +806,7 @@ fn app_tool_policy_honors_default_app_enabled_false() {
|
||||
let apps_config = AppsConfigToml {
|
||||
default: Some(AppsDefaultConfig {
|
||||
enabled: false,
|
||||
approvals_reviewer: None,
|
||||
destructive_enabled: true,
|
||||
open_world_enabled: true,
|
||||
}),
|
||||
@@ -987,6 +1038,7 @@ fn app_tool_policy_allows_per_app_enable_when_default_is_disabled() {
|
||||
let apps_config = AppsConfigToml {
|
||||
default: Some(AppsDefaultConfig {
|
||||
enabled: false,
|
||||
approvals_reviewer: None,
|
||||
destructive_enabled: true,
|
||||
open_world_enabled: true,
|
||||
}),
|
||||
|
||||
@@ -40,27 +40,17 @@ impl ContextualUserFragment for AvailablePluginsInstructions {
|
||||
fn body(&self) -> String {
|
||||
let mut lines = vec![
|
||||
"## Plugins".to_string(),
|
||||
"A plugin is a local bundle of skills, MCP servers, and apps. Below is the list of plugins that are enabled and available in this session.".to_string(),
|
||||
"### Available plugins".to_string(),
|
||||
"A plugin is a local bundle of skills, MCP servers, and apps.".to_string(),
|
||||
];
|
||||
|
||||
lines.extend(
|
||||
self.plugins
|
||||
.iter()
|
||||
.map(|plugin| match plugin.description.as_deref() {
|
||||
Some(description) => format!("- `{}`: {description}", plugin.display_name),
|
||||
None => format!("- `{}`", plugin.display_name),
|
||||
}),
|
||||
);
|
||||
|
||||
lines.push("### How to use plugins".to_string());
|
||||
lines.push(
|
||||
r###"- Discovery: The list above is the plugins available in this session.
|
||||
- Skill naming: If a plugin contributes skills, those skill entries are prefixed with `plugin_name:` in the Skills list.
|
||||
r###"- Skill naming: If a plugin contributes skills, those skill entries are prefixed with `plugin_name:` in the Skills list.
|
||||
- MCP naming: Plugin-provided MCP tools keep standard MCP identifiers such as `mcp__server__tool`; use tool provenance to tell which plugin they come from.
|
||||
- Trigger rules: If the user explicitly names a plugin, prefer capabilities associated with that plugin for that turn.
|
||||
- Relationship to capabilities: Plugins are not invoked directly. Use their underlying skills, MCP tools, and app tools to help solve the task.
|
||||
- Preference: When a relevant plugin is available, prefer using capabilities associated with that plugin over standalone capabilities that provide similar functionality.
|
||||
- Missing/blocked: If the user requests a plugin that is not listed above, or the plugin does not have relevant callable capabilities for the task, say so briefly and continue with the best fallback."###
|
||||
- Relevance: Determine what a plugin can help with from explicit user mention or from the plugin-associated skills, MCP tools, and apps exposed elsewhere in this turn.
|
||||
- Missing/blocked: If the user requests a plugin that does not have relevant callable capabilities for the task, say so briefly and continue with the best fallback."###
|
||||
.to_string(),
|
||||
);
|
||||
|
||||
|
||||
@@ -17,10 +17,38 @@ fn detects_environment_context_fragment() {
|
||||
|
||||
#[test]
|
||||
fn detects_agents_instructions_fragment() {
|
||||
assert!(is_contextual_user_fragment(&ContentItem::InputText {
|
||||
text: "# AGENTS.md instructions for /tmp\n\n<INSTRUCTIONS>\nbody\n</INSTRUCTIONS>"
|
||||
.to_string(),
|
||||
}));
|
||||
for text in [
|
||||
"# AGENTS.md instructions for /tmp\n\n<INSTRUCTIONS>\nbody\n</INSTRUCTIONS>",
|
||||
"# AGENTS.md instructions\n\n<INSTRUCTIONS>\nbody\n</INSTRUCTIONS>",
|
||||
] {
|
||||
assert!(is_contextual_user_fragment(&ContentItem::InputText {
|
||||
text: text.to_string(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_agents_instructions_with_legacy_directory_header() {
|
||||
assert_eq!(
|
||||
UserInstructions {
|
||||
directory: Some("/tmp".to_string()),
|
||||
text: "body".to_string(),
|
||||
}
|
||||
.render(),
|
||||
"# AGENTS.md instructions for /tmp\n\n<INSTRUCTIONS>\nbody\n</INSTRUCTIONS>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_agents_instructions_without_directory_header() {
|
||||
assert_eq!(
|
||||
UserInstructions {
|
||||
directory: None,
|
||||
text: "body".to_string(),
|
||||
}
|
||||
.render(),
|
||||
"# AGENTS.md instructions\n\n<INSTRUCTIONS>\nbody\n</INSTRUCTIONS>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -46,10 +46,11 @@ impl EnvironmentContextEnvironment {
|
||||
.iter()
|
||||
.map(|environment| Self {
|
||||
id: environment.environment_id.clone(),
|
||||
cwd: environment.cwd.clone(),
|
||||
cwd: environment.cwd().clone(),
|
||||
shell: environment
|
||||
.shell
|
||||
.clone()
|
||||
.as_ref()
|
||||
.map(|shell| shell.name().to_string())
|
||||
.unwrap_or_else(|| shell.name().to_string()),
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
use super::ContextualUserFragment;
|
||||
use codex_protocol::ThreadId;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct TokenBudgetContext {
|
||||
thread_id: ThreadId,
|
||||
window_id: u64,
|
||||
tokens_left: i64,
|
||||
}
|
||||
|
||||
impl TokenBudgetContext {
|
||||
pub(crate) fn new(window_id: u64, tokens_left: i64) -> Self {
|
||||
pub(crate) fn new(thread_id: ThreadId, window_id: u64, tokens_left: i64) -> Self {
|
||||
Self {
|
||||
thread_id,
|
||||
window_id,
|
||||
tokens_left,
|
||||
}
|
||||
@@ -29,10 +32,11 @@ impl ContextualUserFragment for TokenBudgetContext {
|
||||
}
|
||||
|
||||
fn body(&self) -> String {
|
||||
let thread_id = self.thread_id;
|
||||
let window_id = self.window_id;
|
||||
let tokens_left = self.tokens_left;
|
||||
format!(
|
||||
"Current context window {window_id}.\nYou have {tokens_left} tokens left in this context window."
|
||||
"Thread id {thread_id}.\nCurrent context window {window_id}.\nYou have {tokens_left} tokens left in this context window."
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::ContextualUserFragment;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub(crate) struct UserInstructions {
|
||||
pub(crate) directory: String,
|
||||
pub(crate) directory: Option<String>,
|
||||
pub(crate) text: String,
|
||||
}
|
||||
|
||||
@@ -16,10 +16,15 @@ impl ContextualUserFragment for UserInstructions {
|
||||
}
|
||||
|
||||
fn type_markers() -> (&'static str, &'static str) {
|
||||
("# AGENTS.md instructions for ", "</INSTRUCTIONS>")
|
||||
("# AGENTS.md instructions", "</INSTRUCTIONS>")
|
||||
}
|
||||
|
||||
fn body(&self) -> String {
|
||||
format!("{}\n\n<INSTRUCTIONS>\n{}\n", self.directory, self.text)
|
||||
let directory = self
|
||||
.directory
|
||||
.as_ref()
|
||||
.map(|directory| format!(" for {directory}"))
|
||||
.unwrap_or_default();
|
||||
format!("{directory}\n\n<INSTRUCTIONS>\n{}\n", self.text)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,10 @@ use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelection;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
|
||||
use crate::session::turn_context::TurnEnvironment;
|
||||
use crate::shell::Shell;
|
||||
|
||||
pub(crate) fn default_thread_environment_selections(
|
||||
environment_manager: &EnvironmentManager,
|
||||
@@ -19,7 +21,7 @@ pub(crate) fn default_thread_environment_selections(
|
||||
.into_iter()
|
||||
.map(|environment_id| TurnEnvironmentSelection {
|
||||
environment_id,
|
||||
cwd: cwd.clone(),
|
||||
cwd: PathUri::from_abs_path(cwd),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -41,6 +43,7 @@ impl ResolvedTurnEnvironments {
|
||||
self.turn_environments.first()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn primary_environment(&self) -> Option<Arc<codex_exec_server::Environment>> {
|
||||
self.primary()
|
||||
.map(|environment| Arc::clone(&environment.environment))
|
||||
@@ -56,11 +59,11 @@ impl ResolvedTurnEnvironments {
|
||||
return None;
|
||||
};
|
||||
|
||||
(!environment.environment.is_remote()).then_some(&environment.cwd)
|
||||
(!environment.environment.is_remote()).then_some(environment.cwd())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_environment_selections(
|
||||
pub(crate) async fn resolve_environment_selections(
|
||||
environment_manager: &EnvironmentManager,
|
||||
environments: &[TurnEnvironmentSelection],
|
||||
) -> CodexResult<ResolvedTurnEnvironments> {
|
||||
@@ -79,24 +82,45 @@ pub(crate) fn resolve_environment_selections(
|
||||
.ok_or_else(|| {
|
||||
CodexErr::InvalidRequest(format!("unknown turn environment id `{environment_id}`"))
|
||||
})?;
|
||||
turn_environments.push(TurnEnvironment {
|
||||
let shell = match environment.info().await {
|
||||
Ok(info) => match Shell::from_environment_shell_info(info.shell) {
|
||||
Ok(shell) => Some(shell),
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
"failed to resolve shell for environment `{environment_id}`: {err}"
|
||||
);
|
||||
None
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
tracing::warn!("failed to get info for environment `{environment_id}`: {err}");
|
||||
None
|
||||
}
|
||||
};
|
||||
turn_environments.push(TurnEnvironment::new(
|
||||
environment_id,
|
||||
environment,
|
||||
cwd: selected_environment.cwd.clone(),
|
||||
shell: None,
|
||||
});
|
||||
selected_environment.cwd.to_abs_path().map_err(|err| {
|
||||
CodexErr::InvalidRequest(format!(
|
||||
"turn environment cwd `{}` is not valid on this host: {err}",
|
||||
selected_environment.cwd
|
||||
))
|
||||
})?,
|
||||
shell,
|
||||
));
|
||||
}
|
||||
|
||||
Ok(ResolvedTurnEnvironments { turn_environments })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use codex_exec_server::Environment;
|
||||
use codex_exec_server::ExecServerRuntimePaths;
|
||||
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
|
||||
use codex_exec_server::REMOTE_ENVIRONMENT_ID;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelection;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
@@ -112,6 +136,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn default_thread_environment_selections_use_manager_default_id() {
|
||||
let cwd = AbsolutePathBuf::current_dir().expect("cwd");
|
||||
let cwd_uri = PathUri::from_abs_path(&cwd);
|
||||
let manager = EnvironmentManager::create_for_tests(
|
||||
Some("ws://127.0.0.1:8765".to_string()),
|
||||
Some(test_runtime_paths()),
|
||||
@@ -122,7 +147,7 @@ mod tests {
|
||||
default_thread_environment_selections(&manager, &cwd),
|
||||
vec![TurnEnvironmentSelection {
|
||||
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
|
||||
cwd,
|
||||
cwd: cwd_uri,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -140,6 +165,7 @@ url = "ws://127.0.0.1:8765"
|
||||
)
|
||||
.expect("write environments.toml");
|
||||
let cwd = AbsolutePathBuf::current_dir().expect("cwd");
|
||||
let cwd_uri = PathUri::from_abs_path(&cwd);
|
||||
let manager =
|
||||
EnvironmentManager::from_codex_home(temp_dir.path(), Some(test_runtime_paths()))
|
||||
.await
|
||||
@@ -150,11 +176,11 @@ url = "ws://127.0.0.1:8765"
|
||||
vec![
|
||||
TurnEnvironmentSelection {
|
||||
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
cwd: cwd.clone(),
|
||||
cwd: cwd_uri.clone(),
|
||||
},
|
||||
TurnEnvironmentSelection {
|
||||
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
|
||||
cwd,
|
||||
cwd: cwd_uri,
|
||||
},
|
||||
]
|
||||
);
|
||||
@@ -174,6 +200,7 @@ url = "ws://127.0.0.1:8765"
|
||||
#[tokio::test]
|
||||
async fn resolve_environment_selections_rejects_duplicate_ids() {
|
||||
let cwd = AbsolutePathBuf::current_dir().expect("cwd");
|
||||
let cwd_uri = PathUri::from_abs_path(&cwd);
|
||||
let manager = EnvironmentManager::default_for_tests();
|
||||
|
||||
let err = resolve_environment_selections(
|
||||
@@ -181,14 +208,15 @@ url = "ws://127.0.0.1:8765"
|
||||
&[
|
||||
TurnEnvironmentSelection {
|
||||
environment_id: "local".to_string(),
|
||||
cwd: cwd.clone(),
|
||||
cwd: cwd_uri.clone(),
|
||||
},
|
||||
TurnEnvironmentSelection {
|
||||
environment_id: "local".to_string(),
|
||||
cwd: cwd.join("other"),
|
||||
cwd: cwd_uri.join("other").expect("other cwd URI"),
|
||||
},
|
||||
],
|
||||
)
|
||||
.await
|
||||
.expect_err("duplicate environment id should fail");
|
||||
|
||||
assert!(err.to_string().contains("duplicate"));
|
||||
@@ -198,15 +226,17 @@ url = "ws://127.0.0.1:8765"
|
||||
async fn resolved_environment_selections_use_first_selection_as_primary() {
|
||||
let cwd = AbsolutePathBuf::current_dir().expect("cwd");
|
||||
let selected_cwd = cwd.join("selected");
|
||||
let selected_cwd_uri = PathUri::from_abs_path(&selected_cwd);
|
||||
let manager = EnvironmentManager::default_for_tests();
|
||||
|
||||
let resolved = resolve_environment_selections(
|
||||
&manager,
|
||||
&[TurnEnvironmentSelection {
|
||||
environment_id: "local".to_string(),
|
||||
cwd: selected_cwd,
|
||||
cwd: selected_cwd_uri,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("environment selections should resolve");
|
||||
|
||||
assert_eq!(
|
||||
@@ -216,54 +246,60 @@ url = "ws://127.0.0.1:8765"
|
||||
.environment_id,
|
||||
"local"
|
||||
);
|
||||
assert_eq!(resolved.primary().expect("primary environment").shell, None);
|
||||
assert_eq!(
|
||||
resolved.primary().expect("primary environment").shell,
|
||||
Some(
|
||||
Shell::from_environment_shell_info(
|
||||
manager
|
||||
.get_environment("local")
|
||||
.expect("local environment")
|
||||
.info()
|
||||
.await
|
||||
.expect("local environment info")
|
||||
.shell
|
||||
)
|
||||
.expect("resolved shell")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn single_local_environment_cwd_requires_exactly_one_local_environment() {
|
||||
let cwd = AbsolutePathBuf::current_dir().expect("cwd");
|
||||
let cwd_uri = PathUri::from_abs_path(&cwd);
|
||||
let local_manager = EnvironmentManager::default_for_tests();
|
||||
let local = resolve_environment_selections(
|
||||
&local_manager,
|
||||
&[TurnEnvironmentSelection {
|
||||
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
cwd: cwd.clone(),
|
||||
cwd: cwd_uri,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("local environment should resolve");
|
||||
let remote_manager = EnvironmentManager::create_for_tests(
|
||||
Some("ws://127.0.0.1:8765".to_string()),
|
||||
Some(test_runtime_paths()),
|
||||
)
|
||||
.await;
|
||||
let remote = resolve_environment_selections(
|
||||
&remote_manager,
|
||||
&[TurnEnvironmentSelection {
|
||||
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
|
||||
cwd: cwd.clone(),
|
||||
}],
|
||||
)
|
||||
.expect("remote environment should resolve");
|
||||
local_manager
|
||||
.upsert_environment(
|
||||
let remote_environment = Arc::new(
|
||||
Environment::create_for_tests(Some("ws://127.0.0.1:8765".to_string()))
|
||||
.expect("remote environment"),
|
||||
);
|
||||
let remote = ResolvedTurnEnvironments {
|
||||
turn_environments: vec![TurnEnvironment::new(
|
||||
REMOTE_ENVIRONMENT_ID.to_string(),
|
||||
"ws://127.0.0.1:8765".to_string(),
|
||||
)
|
||||
.expect("remote environment should register");
|
||||
let multiple = resolve_environment_selections(
|
||||
&local_manager,
|
||||
&[
|
||||
TurnEnvironmentSelection {
|
||||
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
cwd: cwd.clone(),
|
||||
},
|
||||
TurnEnvironmentSelection {
|
||||
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
|
||||
cwd: cwd.clone(),
|
||||
},
|
||||
remote_environment.clone(),
|
||||
cwd.clone(),
|
||||
/*shell*/ None,
|
||||
)],
|
||||
};
|
||||
let multiple = ResolvedTurnEnvironments {
|
||||
turn_environments: vec![
|
||||
local.primary().expect("local environment").clone(),
|
||||
TurnEnvironment::new(
|
||||
REMOTE_ENVIRONMENT_ID.to_string(),
|
||||
remote_environment,
|
||||
cwd.clone(),
|
||||
/*shell*/ None,
|
||||
),
|
||||
],
|
||||
)
|
||||
.expect("multiple environments should resolve");
|
||||
};
|
||||
|
||||
assert_eq!(local.single_local_environment_cwd(), Some(&cwd));
|
||||
assert_eq!(remote.single_local_environment_cwd(), None);
|
||||
|
||||
@@ -44,6 +44,7 @@ use codex_sandboxing::SandboxType;
|
||||
use codex_sandboxing::SandboxablePreference;
|
||||
use codex_sandboxing::compatibility_sandbox_policy_for_permission_profile;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP;
|
||||
use codex_utils_pty::process_group::kill_child_process_group;
|
||||
|
||||
@@ -372,6 +373,8 @@ pub fn build_exec_request(
|
||||
"command args are empty",
|
||||
))
|
||||
})?;
|
||||
let cwd = PathUri::from_abs_path(&cwd);
|
||||
let sandbox_policy_cwd_uri = PathUri::from_abs_path(sandbox_cwd);
|
||||
|
||||
let manager = SandboxManager::new();
|
||||
let command = SandboxCommand {
|
||||
@@ -392,24 +395,21 @@ pub fn build_exec_request(
|
||||
sandbox: sandbox_type,
|
||||
enforce_managed_network,
|
||||
network: network.as_ref(),
|
||||
sandbox_policy_cwd: sandbox_cwd,
|
||||
sandbox_policy_cwd: &sandbox_policy_cwd_uri,
|
||||
codex_linux_sandbox_exe: codex_linux_sandbox_exe.as_deref(),
|
||||
use_legacy_landlock,
|
||||
windows_sandbox_level,
|
||||
windows_sandbox_private_desktop,
|
||||
})
|
||||
.map(|request| {
|
||||
let windows_sandbox_policy_cwd = AbsolutePathBuf::try_from(sandbox_cwd.to_path_buf())
|
||||
.unwrap_or_else(|_| request.cwd.clone());
|
||||
let windows_sandbox_workspace_roots = if windows_sandbox_workspace_roots.is_empty() {
|
||||
vec![windows_sandbox_policy_cwd.clone()]
|
||||
vec![request.sandbox_policy_cwd.clone()]
|
||||
} else {
|
||||
windows_sandbox_workspace_roots.to_vec()
|
||||
};
|
||||
ExecRequest::from_sandbox_exec_request(
|
||||
request,
|
||||
options,
|
||||
windows_sandbox_policy_cwd,
|
||||
windows_sandbox_workspace_roots,
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use codex_protocol::models::AgentMessageInputContent;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::GuardianRiskLevel;
|
||||
use codex_protocol::protocol::GuardianUserAuthorization;
|
||||
@@ -452,6 +453,22 @@ pub(crate) fn collect_guardian_transcript_entries(
|
||||
ResponseItem::Message { role, content, .. } if role == "assistant" => {
|
||||
content_entry(GuardianTranscriptEntryKind::Assistant, content)
|
||||
}
|
||||
ResponseItem::AgentMessage {
|
||||
author, content, ..
|
||||
} => {
|
||||
let text = content
|
||||
.iter()
|
||||
.filter_map(|content| match content {
|
||||
AgentMessageInputContent::InputText { text } => Some(text.as_str()),
|
||||
AgentMessageInputContent::EncryptedContent { .. } => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
(!text.trim().is_empty()).then(|| GuardianTranscriptEntry {
|
||||
kind: GuardianTranscriptEntryKind::Assistant,
|
||||
text: format!("Agent message from {author}:\n{text}"),
|
||||
})
|
||||
}
|
||||
ResponseItem::LocalShellCall { action, .. } => serialized_entry(
|
||||
GuardianTranscriptEntryKind::Tool("tool shell call".to_string()),
|
||||
serde_json::to_string(action).ok(),
|
||||
|
||||
@@ -706,6 +706,7 @@ async fn run_guardian_review_session_before_deadline(
|
||||
.models_manager
|
||||
.list_models(codex_models_manager::manager::RefreshStrategy::Offline)
|
||||
.await;
|
||||
let default_review_model_id = turn.provider.approval_review_preferred_model();
|
||||
let preferred_reasoning_effort = |supports_low: bool, fallback| {
|
||||
if supports_low {
|
||||
Some(codex_protocol::openai_models::ReasoningEffort::Low)
|
||||
@@ -714,11 +715,15 @@ async fn run_guardian_review_session_before_deadline(
|
||||
}
|
||||
};
|
||||
let model_override = turn.model_info.auto_review_model_override.as_deref();
|
||||
let review_model_id =
|
||||
model_override.unwrap_or_else(|| turn.provider.approval_review_preferred_model());
|
||||
let review_model_id = model_override.unwrap_or(default_review_model_id);
|
||||
let review_model = available_models
|
||||
.iter()
|
||||
.find(|preset| preset.model == review_model_id);
|
||||
let guardian_catalog_contains_auto_review = available_models
|
||||
.iter()
|
||||
.any(|preset| preset.model == default_review_model_id);
|
||||
let guardian_review_model_overridden = model_override.is_some();
|
||||
let guardian_review_model_override = model_override.map(str::to_string);
|
||||
let (guardian_model, guardian_reasoning_effort) = if let Some(preset) = review_model {
|
||||
let reasoning_effort = preferred_reasoning_effort(
|
||||
preset
|
||||
@@ -773,6 +778,10 @@ async fn run_guardian_review_session_before_deadline(
|
||||
schema,
|
||||
model: guardian_model,
|
||||
reasoning_effort: guardian_reasoning_effort,
|
||||
guardian_default_review_model_id: default_review_model_id.to_string(),
|
||||
guardian_catalog_contains_auto_review,
|
||||
guardian_review_model_overridden,
|
||||
guardian_review_model_override,
|
||||
reasoning_summary: turn.reasoning_summary,
|
||||
personality: turn.personality,
|
||||
external_cancel,
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::time::Duration;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use codex_analytics::GuardianReviewAnalyticsResult;
|
||||
use codex_analytics::GuardianReviewSessionAnalyticsParams;
|
||||
use codex_analytics::GuardianReviewSessionKind;
|
||||
use codex_extension_api::UserInstructions;
|
||||
use codex_protocol::ThreadId;
|
||||
@@ -78,6 +79,10 @@ pub(crate) struct GuardianReviewSessionParams {
|
||||
pub(crate) schema: Value,
|
||||
pub(crate) model: String,
|
||||
pub(crate) reasoning_effort: Option<ReasoningEffortConfig>,
|
||||
pub(crate) guardian_default_review_model_id: String,
|
||||
pub(crate) guardian_catalog_contains_auto_review: bool,
|
||||
pub(crate) guardian_review_model_overridden: bool,
|
||||
pub(crate) guardian_review_model_override: Option<String>,
|
||||
pub(crate) reasoning_summary: ReasoningSummaryConfig,
|
||||
pub(crate) personality: Option<Personality>,
|
||||
pub(crate) external_cancel: Option<CancellationToken>,
|
||||
@@ -680,13 +685,19 @@ async fn run_review_on_session(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut analytics_result = GuardianReviewAnalyticsResult::from_session(
|
||||
review_session.codex.session.thread_id.to_string(),
|
||||
guardian_session_kind,
|
||||
params.model.clone(),
|
||||
guardian_reasoning_effort.map(|effort| effort.to_string()),
|
||||
had_prior_review_context(&prompt_mode),
|
||||
);
|
||||
let mut analytics_result =
|
||||
GuardianReviewAnalyticsResult::from_session(GuardianReviewSessionAnalyticsParams {
|
||||
guardian_thread_id: review_session.codex.session.thread_id.to_string(),
|
||||
guardian_session_kind,
|
||||
guardian_model: params.model.clone(),
|
||||
guardian_reasoning_effort: guardian_reasoning_effort.map(|effort| effort.to_string()),
|
||||
guardian_default_review_model_id: params.guardian_default_review_model_id.clone(),
|
||||
guardian_catalog_contains_auto_review: params.guardian_catalog_contains_auto_review,
|
||||
guardian_review_model_overridden: params.guardian_review_model_overridden,
|
||||
guardian_review_model_override: params.guardian_review_model_override.clone(),
|
||||
guardian_model_provider_id: params.spawn_config.model_provider_id.clone(),
|
||||
had_prior_review_context: had_prior_review_context(&prompt_mode),
|
||||
});
|
||||
if send_followup_reminder {
|
||||
append_guardian_followup_reminder(review_session).await;
|
||||
}
|
||||
@@ -743,7 +754,7 @@ async fn run_review_on_session(
|
||||
.parent_turn
|
||||
.environments
|
||||
.primary()
|
||||
.map(|environment| environment.cwd.clone())
|
||||
.map(|environment| environment.cwd().clone())
|
||||
.unwrap_or_else(|| params.parent_turn.config.cwd.clone());
|
||||
|
||||
let submit_result = run_before_review_deadline(
|
||||
@@ -1172,6 +1183,10 @@ mod tests {
|
||||
schema: super::super::prompt::guardian_output_schema(),
|
||||
model,
|
||||
reasoning_effort,
|
||||
guardian_default_review_model_id: "codex-auto-review".to_string(),
|
||||
guardian_catalog_contains_auto_review: true,
|
||||
guardian_review_model_overridden: false,
|
||||
guardian_review_model_override: None,
|
||||
reasoning_summary,
|
||||
personality,
|
||||
external_cancel: None,
|
||||
|
||||
@@ -25,6 +25,8 @@ use codex_model_provider::create_model_provider;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_GPT_5_4_MODEL_ID;
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_PROVIDER_ID;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::OPENAI_PROVIDER_ID;
|
||||
use codex_models_manager::manager::StaticModelsManager;
|
||||
use codex_network_proxy::NetworkProxyConfig;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::approvals::NetworkApprovalProtocol;
|
||||
@@ -32,6 +34,7 @@ use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
@@ -1346,9 +1349,20 @@ fn guardian_output_schema_requires_only_outcome_and_allows_optional_details() {
|
||||
);
|
||||
}
|
||||
|
||||
async fn guardian_request_model_for_auto_review_override(
|
||||
enum GuardianTestCatalog {
|
||||
Bundled,
|
||||
ParentOnly,
|
||||
}
|
||||
|
||||
async fn guardian_request_model_for_auto_review(
|
||||
auto_review_model_override: Option<String>,
|
||||
) -> anyhow::Result<(String, String, String)> {
|
||||
catalog: GuardianTestCatalog,
|
||||
) -> anyhow::Result<(
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
codex_analytics::GuardianReviewAnalyticsResult,
|
||||
)> {
|
||||
let server = start_mock_server().await;
|
||||
let guardian_assessment = serde_json::json!({
|
||||
"outcome": "allow",
|
||||
@@ -1364,7 +1378,24 @@ async fn guardian_request_model_for_auto_review_override(
|
||||
)
|
||||
.await;
|
||||
|
||||
let (session, mut turn) = guardian_test_session_and_turn(&server).await;
|
||||
let (mut session, mut turn) = guardian_test_session_and_turn(&server).await;
|
||||
match catalog {
|
||||
GuardianTestCatalog::Bundled => {}
|
||||
GuardianTestCatalog::ParentOnly => {
|
||||
let parent_model = turn.model_info.clone();
|
||||
let auth_manager = Arc::clone(&session.services.auth_manager);
|
||||
let models_manager = StaticModelsManager::new(
|
||||
Some(auth_manager),
|
||||
ModelsResponse {
|
||||
models: vec![parent_model],
|
||||
},
|
||||
);
|
||||
Arc::get_mut(&mut session)
|
||||
.expect("session should be unique")
|
||||
.services
|
||||
.models_manager = Arc::new(models_manager);
|
||||
}
|
||||
}
|
||||
Arc::get_mut(&mut turn)
|
||||
.expect("turn should be unique")
|
||||
.model_info
|
||||
@@ -1373,7 +1404,7 @@ async fn guardian_request_model_for_auto_review_override(
|
||||
let preferred_model = turn.provider.approval_review_preferred_model().to_string();
|
||||
seed_guardian_parent_history(&session, &turn).await;
|
||||
|
||||
let outcome = run_guardian_review_session_for_test(
|
||||
let (outcome, analytics_result) = run_guardian_review_session_for_test(
|
||||
Arc::clone(&session),
|
||||
turn,
|
||||
GuardianApprovalRequest::Shell {
|
||||
@@ -1390,19 +1421,24 @@ async fn guardian_request_model_for_auto_review_override(
|
||||
/*max_attempts*/ 1,
|
||||
)
|
||||
.await;
|
||||
let (GuardianReviewOutcome::Completed(_), _) = outcome else {
|
||||
let GuardianReviewOutcome::Completed(_) = outcome else {
|
||||
panic!("expected guardian assessment");
|
||||
};
|
||||
|
||||
let request_model = request_log
|
||||
.single_request()
|
||||
let request = request_log.single_request();
|
||||
let request_model = request
|
||||
.body_json()
|
||||
.get("model")
|
||||
.and_then(|value| value.as_str())
|
||||
.expect("guardian request should include a model")
|
||||
.to_string();
|
||||
|
||||
Ok((request_model, parent_model, preferred_model))
|
||||
Ok((
|
||||
request_model,
|
||||
parent_model,
|
||||
preferred_model,
|
||||
analytics_result,
|
||||
))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
@@ -1411,12 +1447,36 @@ async fn guardian_review_uses_model_catalog_override_when_preferred_review_model
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let override_model = "guardian-review-model-override".to_string();
|
||||
let (request_model, parent_model, preferred_model) =
|
||||
guardian_request_model_for_auto_review_override(Some(override_model.clone())).await?;
|
||||
let (request_model, parent_model, preferred_model, analytics_result) =
|
||||
guardian_request_model_for_auto_review(
|
||||
Some(override_model.clone()),
|
||||
GuardianTestCatalog::Bundled,
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert_eq!(request_model, override_model);
|
||||
assert_ne!(request_model, parent_model);
|
||||
assert_ne!(request_model, preferred_model);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_catalog_contains_auto_review,
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_default_review_model_id.as_deref(),
|
||||
Some(preferred_model.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_review_model_overridden,
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_review_model_override.as_deref(),
|
||||
Some(override_model.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_model_provider_id.as_deref(),
|
||||
Some(OPENAI_PROVIDER_ID)
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1426,12 +1486,73 @@ async fn guardian_review_uses_preferred_review_model_without_model_catalog_overr
|
||||
-> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let (request_model, parent_model, preferred_model) =
|
||||
guardian_request_model_for_auto_review_override(/*auto_review_model_override*/ None)
|
||||
.await?;
|
||||
let (request_model, parent_model, preferred_model, analytics_result) =
|
||||
guardian_request_model_for_auto_review(
|
||||
/*auto_review_model_override*/ None,
|
||||
GuardianTestCatalog::Bundled,
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert_eq!(request_model, preferred_model);
|
||||
assert_ne!(request_model, parent_model);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_catalog_contains_auto_review,
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_default_review_model_id.as_deref(),
|
||||
Some(preferred_model.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_review_model_overridden,
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_review_model_override.as_deref(),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_model_provider_id.as_deref(),
|
||||
Some(OPENAI_PROVIDER_ID)
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn guardian_review_records_missing_auto_review_model_in_analytics_metadata()
|
||||
-> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let (request_model, parent_model, preferred_model, analytics_result) =
|
||||
guardian_request_model_for_auto_review(
|
||||
/*auto_review_model_override*/ None,
|
||||
GuardianTestCatalog::ParentOnly,
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert_eq!(request_model, parent_model);
|
||||
assert_ne!(request_model, preferred_model);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_catalog_contains_auto_review,
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_default_review_model_id.as_deref(),
|
||||
Some(preferred_model.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_review_model_overridden,
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_review_model_override.as_deref(),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
analytics_result.guardian_model_provider_id.as_deref(),
|
||||
Some(OPENAI_PROVIDER_ID)
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -528,6 +528,10 @@ pub(crate) async fn inspect_pending_input(
|
||||
should_stop: false,
|
||||
additional_contexts: Vec::new(),
|
||||
},
|
||||
TurnInput::InterAgentCommunication(_) => HookRuntimeOutcome {
|
||||
should_stop: false,
|
||||
additional_contexts: Vec::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -550,6 +554,10 @@ pub(crate) async fn record_pending_input(
|
||||
sess.record_conversation_items(turn_context, std::slice::from_ref(&item))
|
||||
.await;
|
||||
}
|
||||
TurnInput::InterAgentCommunication(communication) => {
|
||||
sess.record_inter_agent_communication(turn_context, communication)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
record_additional_contexts(sess, turn_context, additional_contexts).await;
|
||||
}
|
||||
|
||||
@@ -12,9 +12,12 @@ mod client_common;
|
||||
mod realtime_context;
|
||||
mod realtime_conversation;
|
||||
mod realtime_prompt;
|
||||
mod responses_metadata;
|
||||
mod responses_retry;
|
||||
pub(crate) mod session;
|
||||
pub use responses_metadata::CodexResponsesMetadata;
|
||||
pub use session::SteerInputError;
|
||||
pub use turn_metadata::detached_memory_responses_metadata;
|
||||
mod codex_thread;
|
||||
mod compact_remote;
|
||||
mod compact_remote_v2;
|
||||
@@ -190,7 +193,6 @@ pub use exec_policy::check_execpolicy_for_warnings;
|
||||
pub use exec_policy::format_exec_policy_error_with_source;
|
||||
pub use exec_policy::load_exec_policy;
|
||||
pub use installation_id::resolve_installation_id;
|
||||
pub use turn_metadata::build_turn_metadata_header;
|
||||
pub mod compact;
|
||||
mod memory_usage;
|
||||
pub mod otel_init;
|
||||
|
||||
@@ -4,8 +4,10 @@ use std::sync::Arc;
|
||||
use crate::config::Config;
|
||||
use codex_config::McpServerConfig;
|
||||
use codex_core_plugins::PluginsManager;
|
||||
use codex_extension_api::ExtensionDataInit;
|
||||
use codex_extension_api::ExtensionRegistry;
|
||||
use codex_extension_api::McpServerContribution;
|
||||
use codex_extension_api::McpServerContributionContext;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::EffectiveMcpServer;
|
||||
@@ -45,6 +47,24 @@ impl McpManager {
|
||||
/// Returns the MCP config after applying compatibility built-ins and
|
||||
/// runtime-only extension overlays.
|
||||
pub async fn runtime_config(&self, config: &Config) -> McpConfig {
|
||||
self.runtime_config_with_context(config, /*thread_init*/ None)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn runtime_config_for_thread(
|
||||
&self,
|
||||
config: &Config,
|
||||
thread_init: &ExtensionDataInit,
|
||||
) -> McpConfig {
|
||||
self.runtime_config_with_context(config, Some(thread_init))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn runtime_config_with_context(
|
||||
&self,
|
||||
config: &Config,
|
||||
thread_init: Option<&ExtensionDataInit>,
|
||||
) -> McpConfig {
|
||||
let mut mcp_config = config.to_mcp_config(self.plugins_manager.as_ref()).await;
|
||||
let mut catalog = mcp_config.mcp_server_catalog.to_builder();
|
||||
if mcp_config.apps_enabled {
|
||||
@@ -63,9 +83,13 @@ impl McpManager {
|
||||
);
|
||||
}
|
||||
|
||||
let context = match thread_init {
|
||||
Some(thread_init) => McpServerContributionContext::for_thread(config, thread_init),
|
||||
None => McpServerContributionContext::global(config),
|
||||
};
|
||||
let mut contribution_order = 0;
|
||||
for contributor in self.extensions.mcp_server_contributors() {
|
||||
for contribution in contributor.contribute(config).await {
|
||||
for contribution in contributor.contribute(context).await {
|
||||
match contribution {
|
||||
McpServerContribution::Set {
|
||||
name,
|
||||
|
||||
@@ -53,11 +53,7 @@ pub(crate) async fn maybe_prompt_and_install_mcp_dependencies(
|
||||
return;
|
||||
}
|
||||
|
||||
let installed = sess
|
||||
.services
|
||||
.mcp_manager
|
||||
.runtime_servers(config.as_ref())
|
||||
.await;
|
||||
let installed = sess.runtime_mcp_servers(config.as_ref()).await;
|
||||
let missing = collect_missing_mcp_dependencies(mentioned_skills, &installed);
|
||||
if missing.is_empty() {
|
||||
return;
|
||||
@@ -98,7 +94,7 @@ pub(crate) async fn maybe_install_mcp_dependencies(
|
||||
}
|
||||
|
||||
let codex_home = config.codex_home.clone();
|
||||
let installed = sess.services.mcp_manager.runtime_servers(config).await;
|
||||
let installed = sess.runtime_mcp_servers(config).await;
|
||||
let missing = collect_missing_mcp_dependencies(mentioned_skills, &installed);
|
||||
if missing.is_empty() {
|
||||
return;
|
||||
@@ -156,6 +152,7 @@ pub(crate) async fn maybe_install_mcp_dependencies(
|
||||
&name,
|
||||
&oauth_config.url,
|
||||
config.mcp_oauth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind(),
|
||||
oauth_config.http_headers.clone(),
|
||||
oauth_config.env_http_headers.clone(),
|
||||
&resolved_scopes.scopes,
|
||||
@@ -172,6 +169,7 @@ pub(crate) async fn maybe_install_mcp_dependencies(
|
||||
&name,
|
||||
&oauth_config.url,
|
||||
config.mcp_oauth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind(),
|
||||
oauth_config.http_headers,
|
||||
oauth_config.env_http_headers,
|
||||
&[],
|
||||
@@ -201,15 +199,12 @@ pub(crate) async fn maybe_install_mcp_dependencies(
|
||||
warn!("failed to refresh MCP dependencies for mentioned skills: {err}");
|
||||
return;
|
||||
}
|
||||
let refresh_servers = sess
|
||||
.services
|
||||
.mcp_manager
|
||||
.runtime_servers(&refresh_config)
|
||||
.await;
|
||||
let refresh_servers = sess.runtime_mcp_servers(&refresh_config).await;
|
||||
sess.refresh_mcp_servers_now(
|
||||
turn_context,
|
||||
refresh_servers,
|
||||
config.mcp_oauth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind(),
|
||||
elicitation_reviewer,
|
||||
)
|
||||
.await;
|
||||
@@ -254,6 +249,7 @@ async fn should_install_mcp_dependencies(
|
||||
};
|
||||
let args = RequestUserInputArgs {
|
||||
questions: vec![question],
|
||||
auto_resolution_ms: None,
|
||||
};
|
||||
let sub_id = &turn_context.sub_id;
|
||||
let call_id = format!("mcp-deps-{sub_id}");
|
||||
|
||||
@@ -1297,6 +1297,7 @@ async fn maybe_request_mcp_tool_approval(
|
||||
|
||||
let args = RequestUserInputArgs {
|
||||
questions: vec![question],
|
||||
auto_resolution_ms: None,
|
||||
};
|
||||
let response = sess
|
||||
.request_user_input(turn_context.as_ref(), call_id.to_string(), args)
|
||||
|
||||
@@ -1260,6 +1260,7 @@ async fn install_host_owned_codex_apps_manager(session: &Session, turn_context:
|
||||
let manager = codex_mcp::McpConnectionManager::new(
|
||||
&HashMap::new(),
|
||||
turn_context.config.mcp_oauth_credentials_store_mode,
|
||||
turn_context.config.auth_keyring_backend_kind(),
|
||||
HashMap::new(),
|
||||
&turn_context.approval_policy,
|
||||
turn_context.sub_id.clone(),
|
||||
|
||||
@@ -7,7 +7,6 @@ use crate::exec_policy::format_exec_policy_error_with_source;
|
||||
use crate::exec_policy::load_exec_policy;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use codex_app_server_protocol::ConfigLayerSource;
|
||||
use codex_config::CONFIG_TOML_FILE;
|
||||
use codex_config::ConfigLayerStack;
|
||||
@@ -23,6 +22,7 @@ use codex_config::permissions_toml::PermissionsToml;
|
||||
use codex_config::permissions_toml::overlay_network_domain_permissions;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_network_proxy::ConfigReloader;
|
||||
use codex_network_proxy::ConfigReloaderFuture;
|
||||
use codex_network_proxy::ConfigState;
|
||||
use codex_network_proxy::NetworkMode;
|
||||
use codex_network_proxy::NetworkProxyConfig;
|
||||
@@ -361,13 +361,6 @@ impl MtimeConfigReloader {
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ConfigReloader for MtimeConfigReloader {
|
||||
fn source_label(&self) -> String {
|
||||
"config layers".to_string()
|
||||
}
|
||||
|
||||
async fn maybe_reload(&self) -> Result<Option<ConfigState>> {
|
||||
if !self.needs_reload().await {
|
||||
@@ -388,6 +381,20 @@ impl ConfigReloader for MtimeConfigReloader {
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigReloader for MtimeConfigReloader {
|
||||
fn source_label(&self) -> String {
|
||||
"config layers".to_string()
|
||||
}
|
||||
|
||||
fn maybe_reload(&self) -> ConfigReloaderFuture<'_, Option<ConfigState>> {
|
||||
Box::pin(MtimeConfigReloader::maybe_reload(self))
|
||||
}
|
||||
|
||||
fn reload_now(&self) -> ConfigReloaderFuture<'_, ConfigState> {
|
||||
Box::pin(MtimeConfigReloader::reload_now(self))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "network_proxy_loader_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -88,6 +88,7 @@ async fn has_threads(store: &LocalThreadStore, archived: bool) -> io::Result<boo
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
parent_thread_id: None,
|
||||
archived,
|
||||
search_term: None,
|
||||
use_state_db_only: false,
|
||||
|
||||
@@ -5,7 +5,9 @@ use codex_core_plugins::ToolSuggestPluginDiscoveryInput;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_tools::DiscoverablePluginInfo;
|
||||
use std::collections::HashSet;
|
||||
use tracing::instrument;
|
||||
|
||||
#[instrument(level = "trace", skip_all)]
|
||||
pub(crate) async fn list_tool_suggest_discoverable_plugins(
|
||||
config: &Config,
|
||||
plugins_manager: &PluginsManager,
|
||||
|
||||
@@ -1,24 +1,15 @@
|
||||
use crate::plugins::test_support::load_plugins_config;
|
||||
use crate::plugins::test_support::write_curated_plugin;
|
||||
use crate::plugins::test_support::write_curated_plugin_sha;
|
||||
use crate::plugins::test_support::write_file;
|
||||
use crate::plugins::test_support::write_openai_curated_marketplace;
|
||||
use crate::plugins::test_support::write_plugins_feature_config;
|
||||
use codex_core_plugins::OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
use codex_core_plugins::PluginInstallRequest;
|
||||
use codex_core_plugins::PluginsManager;
|
||||
use codex_core_plugins::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
|
||||
use codex_core_plugins::remote::RemotePluginServiceConfig;
|
||||
use codex_core_plugins::remote::fetch_and_cache_global_remote_plugin_catalog;
|
||||
use codex_core_plugins::startup_sync::curated_plugins_repo_path;
|
||||
use codex_protocol::protocol::Product;
|
||||
use codex_tools::DiscoverablePluginInfo;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
use tempfile::tempdir;
|
||||
use tracing::Level;
|
||||
use tracing_subscriber::fmt::format::FmtSpan;
|
||||
use tracing_test::internal::MockWriter;
|
||||
|
||||
async fn list_discoverable_plugins(
|
||||
config: &crate::config::Config,
|
||||
@@ -33,7 +24,11 @@ async fn list_discoverable_plugins_with_auth(
|
||||
auth: Option<&codex_login::CodexAuth>,
|
||||
loaded_plugin_app_connector_ids: &[String],
|
||||
) -> anyhow::Result<Vec<DiscoverablePluginInfo>> {
|
||||
let plugins_manager = PluginsManager::new(config.codex_home.to_path_buf());
|
||||
let plugins_manager = PluginsManager::new_with_options(
|
||||
config.codex_home.to_path_buf(),
|
||||
Some(Product::Codex),
|
||||
auth.map(codex_login::CodexAuth::api_auth_mode),
|
||||
);
|
||||
list_discoverable_plugins_with_manager_and_auth(
|
||||
config,
|
||||
&plugins_manager,
|
||||
@@ -58,101 +53,6 @@ async fn list_discoverable_plugins_with_manager_and_auth(
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_returns_fallback_plugins_without_installed_apps() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["sample", "slack", "openai-developers"]);
|
||||
write_plugins_feature_config(codex_home.path());
|
||||
|
||||
let config = load_plugins_config(codex_home.path()).await;
|
||||
let discoverable_plugins = list_discoverable_plugins(&config, &[]).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| plugin.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
"openai-developers@openai-curated".to_string(),
|
||||
"slack@openai-curated".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_filters_non_fallback_by_installed_apps() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["sample", "slack", "hubspot"]);
|
||||
write_plugin_app(&curated_root, "sample", "sample", "connector_sample");
|
||||
write_plugins_feature_config(codex_home.path());
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "slack").await;
|
||||
|
||||
let config = load_plugins_config(codex_home.path()).await;
|
||||
let discoverable_plugins = list_discoverable_plugins(&config, &[]).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| plugin.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["hubspot@openai-curated".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_filters_by_loaded_plugin_apps() {
|
||||
let hubspot_app_id = "asdk_app_697acb8e53d88191bf7a79e62012ae14";
|
||||
let granola_app_id = "asdk_app_697761cab6f48191b5ed345919a3ce8b";
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["hubspot", "granola"]);
|
||||
write_plugin_app(&curated_root, "hubspot", "hubspot", hubspot_app_id);
|
||||
write_plugin_app(&curated_root, "granola", "granola", granola_app_id);
|
||||
write_plugins_feature_config(codex_home.path());
|
||||
|
||||
let config = load_plugins_config(codex_home.path()).await;
|
||||
let discoverable_plugins = list_discoverable_plugins(&config, &[hubspot_app_id.to_string()])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| plugin.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["hubspot@openai-curated".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_filters_microsoft_by_installed_apps() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(
|
||||
&curated_root,
|
||||
&["teams", "sharepoint", "outlook-email", "outlook-calendar"],
|
||||
);
|
||||
write_plugins_feature_config(codex_home.path());
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "teams").await;
|
||||
|
||||
let config = load_plugins_config(codex_home.path()).await;
|
||||
let discoverable_plugins = list_discoverable_plugins(&config, &[]).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| plugin.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
"outlook-calendar@openai-curated".to_string(),
|
||||
"outlook-email@openai-curated".to_string(),
|
||||
"sharepoint@openai-curated".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_includes_cached_remote_global_plugins() {
|
||||
use codex_login::CodexAuth;
|
||||
@@ -431,216 +331,6 @@ disabled_tools = [
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_filters_sales_apps_by_marketplace() {
|
||||
let hubspot_app_id = "asdk_app_697acb8e53d88191bf7a79e62012ae14";
|
||||
let granola_app_id = "asdk_app_697761cab6f48191b5ed345919a3ce8b";
|
||||
let test_app_id = "asdk_app_test_source";
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["hubspot", "granola", "test-source"]);
|
||||
write_plugin_app(&curated_root, "hubspot", "hubspot", hubspot_app_id);
|
||||
write_plugin_app(&curated_root, "granola", "granola", granola_app_id);
|
||||
write_plugin_app(&curated_root, "test-source", "test_source", test_app_id);
|
||||
|
||||
let sales_marketplace_name = "oai-maintained-plugins";
|
||||
let sales_marketplace_root = codex_home
|
||||
.path()
|
||||
.join(format!(".tmp/marketplaces/{sales_marketplace_name}"));
|
||||
write_file(
|
||||
&sales_marketplace_root.join(".agents/plugins/marketplace.json"),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{sales_marketplace_name}",
|
||||
"plugins": [
|
||||
{{"name": "sales", "source": {{"source": "local", "path": "./plugins/sales"}}}}
|
||||
]
|
||||
}}
|
||||
"#
|
||||
),
|
||||
);
|
||||
write_curated_plugin(&sales_marketplace_root, "sales");
|
||||
write_file(
|
||||
&sales_marketplace_root.join("plugins/sales/.app.json"),
|
||||
&format!(
|
||||
r#"{{
|
||||
"apps": {{
|
||||
"hubspot": {{
|
||||
"id": "{hubspot_app_id}"
|
||||
}},
|
||||
"granola": {{
|
||||
"id": "{granola_app_id}"
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
"#
|
||||
),
|
||||
);
|
||||
write_file(
|
||||
&codex_home.path().join(crate::config::CONFIG_TOML_FILE),
|
||||
&format!(
|
||||
r#"[features]
|
||||
plugins = true
|
||||
|
||||
[marketplaces.{sales_marketplace_name}]
|
||||
source_type = "git"
|
||||
source = "/tmp/{sales_marketplace_name}"
|
||||
"#
|
||||
),
|
||||
);
|
||||
install_marketplace_plugin(codex_home.path(), sales_marketplace_root.as_path(), "sales").await;
|
||||
|
||||
let config = load_plugins_config(codex_home.path()).await;
|
||||
let discoverable_plugins = list_discoverable_plugins(&config, &[]).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| plugin.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
"granola@openai-curated".to_string(),
|
||||
"hubspot@openai-curated".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_omits_openai_curated_when_remote_enabled() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["slack"]);
|
||||
|
||||
let bundled_marketplace_name = OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
let bundled_marketplace_root = codex_home
|
||||
.path()
|
||||
.join(format!(".tmp/marketplaces/{bundled_marketplace_name}"));
|
||||
write_file(
|
||||
&bundled_marketplace_root.join(".agents/plugins/marketplace.json"),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{bundled_marketplace_name}",
|
||||
"plugins": [
|
||||
{{"name": "chrome", "source": {{"source": "local", "path": "./plugins/chrome"}}}}
|
||||
]
|
||||
}}
|
||||
"#
|
||||
),
|
||||
);
|
||||
write_curated_plugin(&bundled_marketplace_root, "chrome");
|
||||
write_file(
|
||||
&codex_home.path().join(crate::config::CONFIG_TOML_FILE),
|
||||
&format!(
|
||||
r#"[features]
|
||||
plugins = true
|
||||
remote_plugin = true
|
||||
|
||||
[marketplaces.{bundled_marketplace_name}]
|
||||
source_type = "git"
|
||||
source = "/tmp/{bundled_marketplace_name}"
|
||||
"#
|
||||
),
|
||||
);
|
||||
|
||||
let config = load_plugins_config(codex_home.path()).await;
|
||||
let discoverable_plugins = list_discoverable_plugins(&config, &[]).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| plugin.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["chrome@openai-bundled".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_deduplicates_configured_marketplace_plugin() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let plugin_name = "sample";
|
||||
let marketplace_name = OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
let plugin_id = format!("{plugin_name}@{marketplace_name}");
|
||||
let marketplace_root = codex_home
|
||||
.path()
|
||||
.join(format!(".tmp/marketplaces/{marketplace_name}"));
|
||||
write_file(
|
||||
&marketplace_root.join(".agents/plugins/marketplace.json"),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{marketplace_name}",
|
||||
"plugins": [
|
||||
{{"name": "{plugin_name}", "source": {{"source": "local", "path": "./plugins/{plugin_name}"}}}}
|
||||
]
|
||||
}}
|
||||
"#
|
||||
),
|
||||
);
|
||||
write_curated_plugin(&marketplace_root, plugin_name);
|
||||
write_file(
|
||||
&codex_home.path().join(crate::config::CONFIG_TOML_FILE),
|
||||
&format!(
|
||||
r#"[features]
|
||||
plugins = true
|
||||
|
||||
[marketplaces.{marketplace_name}]
|
||||
source_type = "git"
|
||||
source = "/tmp/{marketplace_name}"
|
||||
|
||||
[tool_suggest]
|
||||
discoverables = [{{ type = "plugin", id = "{plugin_id}" }}]
|
||||
"#
|
||||
),
|
||||
);
|
||||
|
||||
let config = load_plugins_config(codex_home.path()).await;
|
||||
let discoverable_plugins = list_discoverable_plugins(&config, &[]).await.unwrap();
|
||||
|
||||
assert_eq!(discoverable_plugins.len(), 1);
|
||||
assert_eq!(discoverable_plugins[0].id, plugin_id.as_str());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_ignores_missing_marketplace_plugin() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["installed", "slack"]);
|
||||
let marketplace_name = OPENAI_BUNDLED_MARKETPLACE_NAME;
|
||||
let marketplace_root = codex_home
|
||||
.path()
|
||||
.join(format!(".tmp/marketplaces/{marketplace_name}"));
|
||||
write_file(
|
||||
&marketplace_root.join(".agents/plugins/marketplace.json"),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{marketplace_name}",
|
||||
"plugins": [
|
||||
{{"name": "sample", "source": {{"source": "local", "path": "./plugins/sample"}}}}
|
||||
]
|
||||
}}
|
||||
"#
|
||||
),
|
||||
);
|
||||
write_file(
|
||||
&codex_home.path().join(crate::config::CONFIG_TOML_FILE),
|
||||
&format!(
|
||||
r#"[features]
|
||||
plugins = true
|
||||
|
||||
[marketplaces.{marketplace_name}]
|
||||
source_type = "git"
|
||||
source = "/tmp/{marketplace_name}"
|
||||
"#
|
||||
),
|
||||
);
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "installed").await;
|
||||
|
||||
let config = load_plugins_config(codex_home.path()).await;
|
||||
let discoverable_plugins = list_discoverable_plugins(&config, &[]).await.unwrap();
|
||||
|
||||
assert_eq!(discoverable_plugins.len(), 1);
|
||||
assert_eq!(discoverable_plugins[0].id, "slack@openai-curated");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_returns_empty_when_plugins_feature_disabled() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
@@ -659,65 +349,6 @@ plugins = false
|
||||
assert_eq!(discoverable_plugins, Vec::<DiscoverablePluginInfo>::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_normalizes_description() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["installed", "slack"]);
|
||||
write_plugins_feature_config(codex_home.path());
|
||||
write_file(
|
||||
&curated_root.join("plugins/slack/.codex-plugin/plugin.json"),
|
||||
r#"{
|
||||
"name": "slack",
|
||||
"description": " Plugin\n with extra spacing "
|
||||
}"#,
|
||||
);
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "installed").await;
|
||||
|
||||
let config = load_plugins_config(codex_home.path()).await;
|
||||
let discoverable_plugins = list_discoverable_plugins(&config, &[]).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins,
|
||||
vec![DiscoverablePluginInfo {
|
||||
id: "slack@openai-curated".to_string(),
|
||||
remote_plugin_id: None,
|
||||
name: "slack".to_string(),
|
||||
description: Some("Plugin with extra spacing".to_string()),
|
||||
has_skills: true,
|
||||
mcp_server_names: vec!["sample-docs".to_string()],
|
||||
app_connector_ids: vec!["connector_calendar".to_string()],
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_omits_installed_curated_plugins() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["slack"]);
|
||||
write_curated_plugin_sha(codex_home.path());
|
||||
write_plugins_feature_config(codex_home.path());
|
||||
|
||||
PluginsManager::new(codex_home.path().to_path_buf())
|
||||
.install_plugin(PluginInstallRequest {
|
||||
plugin_name: "slack".to_string(),
|
||||
marketplace_path: AbsolutePathBuf::try_from(
|
||||
curated_root.join(".agents/plugins/marketplace.json"),
|
||||
)
|
||||
.expect("marketplace path"),
|
||||
})
|
||||
.await
|
||||
.expect("plugin should install");
|
||||
|
||||
let refreshed_config = load_plugins_config(codex_home.path()).await;
|
||||
let discoverable_plugins = list_discoverable_plugins(&refreshed_config, &[])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(discoverable_plugins, Vec::<DiscoverablePluginInfo>::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_omits_disabled_tool_suggestions() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
@@ -741,61 +372,6 @@ disabled_tools = [
|
||||
assert_eq!(discoverable_plugins, Vec::<DiscoverablePluginInfo>::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_omits_not_available_curated_plugins() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_file(
|
||||
&curated_root.join(".agents/plugins/marketplace.json"),
|
||||
r#"{
|
||||
"name": "openai-curated",
|
||||
"plugins": [
|
||||
{
|
||||
"name": "installed",
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": "./plugins/installed"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "slack",
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": "./plugins/slack"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "gmail",
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": "./plugins/gmail"
|
||||
},
|
||||
"policy": {
|
||||
"installation": "NOT_AVAILABLE"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
"#,
|
||||
);
|
||||
write_curated_plugin(&curated_root, "installed");
|
||||
write_curated_plugin(&curated_root, "slack");
|
||||
write_curated_plugin(&curated_root, "gmail");
|
||||
write_plugins_feature_config(codex_home.path());
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "installed").await;
|
||||
|
||||
let config = load_plugins_config(codex_home.path()).await;
|
||||
let discoverable_plugins = list_discoverable_plugins(&config, &[]).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.into_iter()
|
||||
.map(|plugin| plugin.id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["slack@openai-curated".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_includes_configured_plugin_ids() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
@@ -829,98 +405,3 @@ discoverables = [{ type = "plugin", id = "sample@openai-curated" }]
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_tool_suggest_discoverable_plugins_does_not_reload_marketplace_per_plugin() {
|
||||
let codex_home = tempdir().expect("tempdir should succeed");
|
||||
let curated_root = curated_plugins_repo_path(codex_home.path());
|
||||
write_openai_curated_marketplace(&curated_root, &["slack", "gmail", "openai-developers"]);
|
||||
write_plugins_feature_config(codex_home.path());
|
||||
install_marketplace_plugin(codex_home.path(), curated_root.as_path(), "slack").await;
|
||||
|
||||
let too_long_prompt = "x".repeat(129);
|
||||
for plugin_name in ["gmail", "openai-developers"] {
|
||||
write_file(
|
||||
&curated_root.join(format!("plugins/{plugin_name}/.codex-plugin/plugin.json")),
|
||||
&format!(
|
||||
r#"{{
|
||||
"name": "{plugin_name}",
|
||||
"description": "Plugin that includes skills, MCP servers, and app connectors",
|
||||
"interface": {{
|
||||
"defaultPrompt": "{too_long_prompt}"
|
||||
}}
|
||||
}}"#
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
let config = load_plugins_config(codex_home.path()).await;
|
||||
let buffer: &'static std::sync::Mutex<Vec<u8>> =
|
||||
Box::leak(Box::new(std::sync::Mutex::new(Vec::new())));
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_level(true)
|
||||
.with_ansi(false)
|
||||
.with_max_level(Level::WARN)
|
||||
.with_span_events(FmtSpan::NONE)
|
||||
.with_writer(MockWriter::new(buffer))
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
|
||||
let discoverable_plugins = list_discoverable_plugins(&config, &[]).await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
discoverable_plugins
|
||||
.iter()
|
||||
.map(|plugin| plugin.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["gmail@openai-curated", "openai-developers@openai-curated"]
|
||||
);
|
||||
|
||||
let logs = String::from_utf8(buffer.lock().expect("buffer lock").clone())
|
||||
.expect("utf8 logs")
|
||||
.replace('\\', "/");
|
||||
assert_eq!(logs.matches("ignoring interface.defaultPrompt").count(), 8);
|
||||
let normalized_logs = logs.replace('\\', "/");
|
||||
assert_eq!(
|
||||
normalized_logs
|
||||
.matches("gmail/.codex-plugin/plugin.json")
|
||||
.count(),
|
||||
4
|
||||
);
|
||||
assert_eq!(
|
||||
normalized_logs
|
||||
.matches("openai-developers/.codex-plugin/plugin.json")
|
||||
.count(),
|
||||
4
|
||||
);
|
||||
}
|
||||
|
||||
async fn install_marketplace_plugin(codex_home: &Path, marketplace_root: &Path, plugin_name: &str) {
|
||||
write_curated_plugin_sha(codex_home);
|
||||
PluginsManager::new(codex_home.to_path_buf())
|
||||
.install_plugin(PluginInstallRequest {
|
||||
plugin_name: plugin_name.to_string(),
|
||||
marketplace_path: AbsolutePathBuf::try_from(
|
||||
marketplace_root.join(".agents/plugins/marketplace.json"),
|
||||
)
|
||||
.expect("marketplace path"),
|
||||
})
|
||||
.await
|
||||
.expect("plugin should install");
|
||||
}
|
||||
|
||||
fn write_plugin_app(root: &Path, plugin_name: &str, app_name: &str, app_id: &str) {
|
||||
write_file(
|
||||
&root.join(format!("plugins/{plugin_name}/.app.json")),
|
||||
&format!(
|
||||
r#"{{
|
||||
"apps": {{
|
||||
"{app_name}": {{
|
||||
"id": "{app_id}"
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
"#
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ fn render_plugins_section_returns_none_for_empty_plugins() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_plugins_section_includes_descriptions_and_skill_naming_guidance() {
|
||||
fn render_plugins_section_keeps_plugin_usage_guidance_without_listing_plugins() {
|
||||
let rendered = render_plugins_section(&[PluginCapabilitySummary {
|
||||
config_name: "sample@test".to_string(),
|
||||
display_name: "sample".to_string(),
|
||||
@@ -17,7 +17,7 @@ fn render_plugins_section_includes_descriptions_and_skill_naming_guidance() {
|
||||
}])
|
||||
.expect("plugin section should render");
|
||||
|
||||
let expected = "<plugins_instructions>\n## Plugins\nA plugin is a local bundle of skills, MCP servers, and apps. Below is the list of plugins that are enabled and available in this session.\n### Available plugins\n- `sample`: inspect sample data\n### How to use plugins\n- Discovery: The list above is the plugins available in this session.\n- Skill naming: If a plugin contributes skills, those skill entries are prefixed with `plugin_name:` in the Skills list.\n- Trigger rules: If the user explicitly names a plugin, prefer capabilities associated with that plugin for that turn.\n- Relationship to capabilities: Plugins are not invoked directly. Use their underlying skills, MCP tools, and app tools to help solve the task.\n- Preference: When a relevant plugin is available, prefer using capabilities associated with that plugin over standalone capabilities that provide similar functionality.\n- Missing/blocked: If the user requests a plugin that is not listed above, or the plugin does not have relevant callable capabilities for the task, say so briefly and continue with the best fallback.\n</plugins_instructions>";
|
||||
let expected = "<plugins_instructions>\n## Plugins\nA plugin is a local bundle of skills, MCP servers, and apps.\n### How to use plugins\n- Skill naming: If a plugin contributes skills, those skill entries are prefixed with `plugin_name:` in the Skills list.\n- MCP naming: Plugin-provided MCP tools keep standard MCP identifiers such as `mcp__server__tool`; use tool provenance to tell which plugin they come from.\n- Trigger rules: If the user explicitly names a plugin, prefer capabilities associated with that plugin for that turn.\n- Relationship to capabilities: Plugins are not invoked directly. Use their underlying skills, MCP tools, and app tools to help solve the task.\n- Relevance: Determine what a plugin can help with from explicit user mention or from the plugin-associated skills, MCP tools, and apps exposed elsewhere in this turn.\n- Missing/blocked: If the user requests a plugin that does not have relevant callable capabilities for the task, say so briefly and continue with the best fallback.\n</plugins_instructions>";
|
||||
|
||||
assert_eq!(rendered, expected);
|
||||
}
|
||||
|
||||
@@ -98,5 +98,5 @@ pub(crate) async fn build_prompt_input_from_session(
|
||||
base_instructions,
|
||||
);
|
||||
|
||||
Ok(prompt.get_formatted_input())
|
||||
Ok(prompt.input)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ use crate::session::session::Session;
|
||||
use chrono::Utc;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_git_utils::resolve_root_git_project_for_trust;
|
||||
use codex_protocol::models::AgentMessageInputContent;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_thread_store::ListThreadsParams;
|
||||
use codex_thread_store::SortDirection;
|
||||
@@ -136,6 +137,7 @@ async fn load_recent_threads(sess: &Session) -> Vec<StoredThread> {
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
parent_thread_id: None,
|
||||
archived: false,
|
||||
search_term: None,
|
||||
use_state_db_only: false,
|
||||
@@ -238,6 +240,23 @@ fn build_current_thread_section(items: &[ResponseItem]) -> Option<String> {
|
||||
}
|
||||
current_assistant.push(text);
|
||||
}
|
||||
ResponseItem::AgentMessage {
|
||||
author, content, ..
|
||||
} => {
|
||||
let text = content
|
||||
.iter()
|
||||
.filter_map(|content| match content {
|
||||
AgentMessageInputContent::InputText { text } => Some(text.as_str()),
|
||||
AgentMessageInputContent::EncryptedContent { .. } => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
if text.trim().is_empty() || current_user.is_empty() && current_assistant.is_empty()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
current_assistant.push(format!("Agent message from {author}:\n{text}"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,9 +35,11 @@ use codex_protocol::protocol::ConversationAudioParams;
|
||||
use codex_protocol::protocol::ConversationStartParams;
|
||||
use codex_protocol::protocol::ConversationStartTransport;
|
||||
use codex_protocol::protocol::ConversationTextParams;
|
||||
use codex_protocol::protocol::ConversationTextRole;
|
||||
use codex_protocol::protocol::ErrorEvent;
|
||||
use codex_protocol::protocol::Event;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::RealtimeConversationArchitecture;
|
||||
use codex_protocol::protocol::RealtimeConversationClosedEvent;
|
||||
use codex_protocol::protocol::RealtimeConversationRealtimeEvent;
|
||||
use codex_protocol::protocol::RealtimeConversationSdpEvent;
|
||||
@@ -61,7 +63,7 @@ use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
const AUDIO_IN_QUEUE_CAPACITY: usize = 256;
|
||||
const USER_TEXT_IN_QUEUE_CAPACITY: usize = 64;
|
||||
const TEXT_IN_QUEUE_CAPACITY: usize = 64;
|
||||
const HANDOFF_OUT_QUEUE_CAPACITY: usize = 64;
|
||||
const OUTPUT_EVENTS_QUEUE_CAPACITY: usize = 256;
|
||||
const REALTIME_STARTUP_CONTEXT_TOKEN_BUDGET: usize = 5_300;
|
||||
@@ -193,7 +195,7 @@ impl RealtimeResponseCreateQueue {
|
||||
struct RealtimeInputTask {
|
||||
writer: RealtimeWebsocketWriter,
|
||||
events: RealtimeWebsocketEvents,
|
||||
user_text_rx: Receiver<String>,
|
||||
text_rx: Receiver<ConversationTextParams>,
|
||||
handoff_output_rx: Receiver<HandoffOutput>,
|
||||
audio_rx: Receiver<RealtimeAudioFrame>,
|
||||
events_tx: Sender<RealtimeEvent>,
|
||||
@@ -203,7 +205,7 @@ struct RealtimeInputTask {
|
||||
}
|
||||
|
||||
struct RealtimeInputChannels {
|
||||
user_text_rx: Receiver<String>,
|
||||
text_rx: Receiver<ConversationTextParams>,
|
||||
handoff_output_rx: Receiver<HandoffOutput>,
|
||||
audio_rx: Receiver<RealtimeAudioFrame>,
|
||||
}
|
||||
@@ -222,7 +224,7 @@ impl RealtimeHandoffState {
|
||||
#[allow(dead_code)]
|
||||
struct ConversationState {
|
||||
audio_tx: Sender<RealtimeAudioFrame>,
|
||||
user_text_tx: Sender<String>,
|
||||
text_tx: Sender<ConversationTextParams>,
|
||||
session_kind: RealtimeSessionKind,
|
||||
handoff: RealtimeHandoffState,
|
||||
input_task: JoinHandle<()>,
|
||||
@@ -232,7 +234,9 @@ struct ConversationState {
|
||||
|
||||
struct RealtimeStart {
|
||||
api_provider: ApiProvider,
|
||||
architecture: RealtimeConversationArchitecture,
|
||||
extra_headers: Option<HeaderMap>,
|
||||
realtime_call_api_provider: Option<ApiProvider>,
|
||||
session_config: RealtimeSessionConfig,
|
||||
model_client: ModelClient,
|
||||
sdp: Option<String>,
|
||||
@@ -284,7 +288,9 @@ impl RealtimeConversationManager {
|
||||
async fn start_inner(&self, start: RealtimeStart) -> CodexResult<RealtimeStartOutput> {
|
||||
let RealtimeStart {
|
||||
api_provider,
|
||||
architecture,
|
||||
extra_headers,
|
||||
realtime_call_api_provider,
|
||||
session_config,
|
||||
model_client,
|
||||
sdp,
|
||||
@@ -297,8 +303,8 @@ impl RealtimeConversationManager {
|
||||
|
||||
let (audio_tx, audio_rx) =
|
||||
async_channel::bounded::<RealtimeAudioFrame>(AUDIO_IN_QUEUE_CAPACITY);
|
||||
let (user_text_tx, user_text_rx) =
|
||||
async_channel::bounded::<String>(USER_TEXT_IN_QUEUE_CAPACITY);
|
||||
let (text_tx, text_rx) =
|
||||
async_channel::bounded::<ConversationTextParams>(TEXT_IN_QUEUE_CAPACITY);
|
||||
let (handoff_output_tx, handoff_output_rx) =
|
||||
async_channel::bounded::<HandoffOutput>(HANDOFF_OUT_QUEUE_CAPACITY);
|
||||
let (events_tx, events_rx) =
|
||||
@@ -307,7 +313,7 @@ impl RealtimeConversationManager {
|
||||
let realtime_active = Arc::new(AtomicBool::new(true));
|
||||
let handoff = RealtimeHandoffState::new(handoff_output_tx, session_kind);
|
||||
let input_channels = RealtimeInputChannels {
|
||||
user_text_rx,
|
||||
text_rx,
|
||||
handoff_output_rx,
|
||||
audio_rx,
|
||||
};
|
||||
@@ -318,7 +324,9 @@ impl RealtimeConversationManager {
|
||||
.create_realtime_call_with_headers(
|
||||
sdp,
|
||||
session_config.clone(),
|
||||
architecture,
|
||||
extra_headers.unwrap_or_default(),
|
||||
realtime_call_api_provider,
|
||||
)
|
||||
.await?;
|
||||
let task = spawn_webrtc_sideband_input_task(RealtimeWebrtcSidebandInputTask {
|
||||
@@ -346,7 +354,7 @@ impl RealtimeConversationManager {
|
||||
let task = spawn_realtime_input_task(RealtimeInputTask {
|
||||
writer: connection.writer(),
|
||||
events: connection.events(),
|
||||
user_text_rx: input_channels.user_text_rx,
|
||||
text_rx: input_channels.text_rx,
|
||||
handoff_output_rx: input_channels.handoff_output_rx,
|
||||
audio_rx: input_channels.audio_rx,
|
||||
events_tx,
|
||||
@@ -360,7 +368,7 @@ impl RealtimeConversationManager {
|
||||
let mut guard = self.state.lock().await;
|
||||
*guard = Some(ConversationState {
|
||||
audio_tx,
|
||||
user_text_tx,
|
||||
text_tx,
|
||||
session_kind,
|
||||
handoff,
|
||||
input_task: task,
|
||||
@@ -433,12 +441,12 @@ impl RealtimeConversationManager {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn text_in(&self, text: String) -> CodexResult<()> {
|
||||
pub(crate) async fn text_in(&self, mut params: ConversationTextParams) -> CodexResult<()> {
|
||||
let sender = {
|
||||
let guard = self.state.lock().await;
|
||||
guard
|
||||
.as_ref()
|
||||
.map(|state| (state.user_text_tx.clone(), state.session_kind))
|
||||
.map(|state| (state.text_tx.clone(), state.session_kind))
|
||||
};
|
||||
|
||||
let Some((sender, session_kind)) = sender else {
|
||||
@@ -447,9 +455,12 @@ impl RealtimeConversationManager {
|
||||
));
|
||||
};
|
||||
|
||||
let text = prefix_realtime_text(text, REALTIME_USER_TEXT_PREFIX, session_kind);
|
||||
if params.role == ConversationTextRole::User {
|
||||
params.text =
|
||||
prefix_realtime_text(params.text, REALTIME_USER_TEXT_PREFIX, session_kind);
|
||||
}
|
||||
sender
|
||||
.send(text)
|
||||
.send(params)
|
||||
.await
|
||||
.map_err(|_| CodexErr::InvalidRequest("conversation is not running".to_string()))?;
|
||||
Ok(())
|
||||
@@ -613,7 +624,9 @@ pub(crate) async fn handle_start(
|
||||
|
||||
struct PreparedRealtimeConversationStart {
|
||||
api_provider: ApiProvider,
|
||||
architecture: RealtimeConversationArchitecture,
|
||||
extra_headers: Option<HeaderMap>,
|
||||
realtime_call_api_provider: Option<ApiProvider>,
|
||||
requested_realtime_session_id: Option<String>,
|
||||
version: RealtimeWsVersion,
|
||||
session_config: RealtimeSessionConfig,
|
||||
@@ -639,7 +652,23 @@ async fn prepare_realtime_start(
|
||||
if let Some(realtime_ws_base_url) = &config.experimental_realtime_ws_base_url {
|
||||
api_provider.base_url = realtime_ws_base_url.clone();
|
||||
}
|
||||
let realtime_call_api_provider =
|
||||
if let Some(realtime_call_base_url) = &config.experimental_realtime_webrtc_call_base_url {
|
||||
let mut api_provider = provider.to_api_provider(Some(AuthMode::ApiKey))?;
|
||||
api_provider.base_url = realtime_call_base_url.clone();
|
||||
Some(api_provider)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let version = params.version.unwrap_or(config.realtime.version);
|
||||
// TODO(pbakkum): Remove the realtimeapi/AVAS branch once WebRTC realtime sessions always use AVAS.
|
||||
let architecture = params.architecture.unwrap_or(config.realtime.architecture);
|
||||
validate_realtime_architecture(
|
||||
architecture,
|
||||
version,
|
||||
&transport,
|
||||
config.realtime.session_type,
|
||||
)?;
|
||||
let session_config = build_realtime_session_config(
|
||||
sess,
|
||||
params.model,
|
||||
@@ -670,7 +699,9 @@ async fn prepare_realtime_start(
|
||||
};
|
||||
Ok(PreparedRealtimeConversationStart {
|
||||
api_provider,
|
||||
architecture,
|
||||
extra_headers,
|
||||
realtime_call_api_provider,
|
||||
requested_realtime_session_id,
|
||||
version,
|
||||
session_config,
|
||||
@@ -678,6 +709,33 @@ async fn prepare_realtime_start(
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_realtime_architecture(
|
||||
architecture: RealtimeConversationArchitecture,
|
||||
version: RealtimeWsVersion,
|
||||
transport: &ConversationStartTransport,
|
||||
session_type: RealtimeWsMode,
|
||||
) -> CodexResult<()> {
|
||||
if architecture != RealtimeConversationArchitecture::Avas {
|
||||
return Ok(());
|
||||
}
|
||||
if version != RealtimeWsVersion::V1 {
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"AVAS realtime architecture requires realtime v1".to_string(),
|
||||
));
|
||||
}
|
||||
if !matches!(transport, ConversationStartTransport::Webrtc { .. }) {
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"AVAS realtime architecture requires WebRTC transport".to_string(),
|
||||
));
|
||||
}
|
||||
if session_type != RealtimeWsMode::Conversational {
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"AVAS realtime architecture requires conversational realtime".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn build_realtime_session_config(
|
||||
sess: &Arc<Session>,
|
||||
model: Option<String>,
|
||||
@@ -786,7 +844,9 @@ async fn handle_start_inner(
|
||||
) -> CodexResult<()> {
|
||||
let PreparedRealtimeConversationStart {
|
||||
api_provider,
|
||||
architecture,
|
||||
extra_headers,
|
||||
realtime_call_api_provider,
|
||||
requested_realtime_session_id,
|
||||
version,
|
||||
session_config,
|
||||
@@ -799,7 +859,9 @@ async fn handle_start_inner(
|
||||
};
|
||||
let start = RealtimeStart {
|
||||
api_provider,
|
||||
architecture,
|
||||
extra_headers,
|
||||
realtime_call_api_provider,
|
||||
session_config,
|
||||
model_client: sess.services.model_client.clone(),
|
||||
sdp,
|
||||
@@ -1016,7 +1078,7 @@ pub(crate) async fn handle_text(
|
||||
params: ConversationTextParams,
|
||||
) {
|
||||
debug!(text = %params.text, "[realtime-text] appending realtime conversation text input");
|
||||
if let Err(err) = sess.conversation.text_in(params.text).await {
|
||||
if let Err(err) = sess.conversation.text_in(params).await {
|
||||
error!("failed to append realtime text: {err}");
|
||||
if sess.conversation.running_state().await.is_some() {
|
||||
warn!("realtime text input failed while the session was already ending");
|
||||
@@ -1096,7 +1158,7 @@ fn spawn_webrtc_sideband_input_task(input: RealtimeWebrtcSidebandInputTask) -> J
|
||||
run_realtime_input_task(RealtimeInputTask {
|
||||
writer: connection.writer(),
|
||||
events: connection.events(),
|
||||
user_text_rx: input_channels.user_text_rx,
|
||||
text_rx: input_channels.text_rx,
|
||||
handoff_output_rx: input_channels.handoff_output_rx,
|
||||
audio_rx: input_channels.audio_rx,
|
||||
events_tx,
|
||||
@@ -1112,7 +1174,7 @@ async fn run_realtime_input_task(input: RealtimeInputTask) {
|
||||
let RealtimeInputTask {
|
||||
writer,
|
||||
events,
|
||||
user_text_rx,
|
||||
text_rx,
|
||||
handoff_output_rx,
|
||||
audio_rx,
|
||||
events_tx,
|
||||
@@ -1126,10 +1188,10 @@ async fn run_realtime_input_task(input: RealtimeInputTask) {
|
||||
|
||||
loop {
|
||||
let result = tokio::select! {
|
||||
// Text typed by the user that should be sent into realtime.
|
||||
user_text = user_text_rx.recv() => {
|
||||
handle_user_text_input(
|
||||
user_text,
|
||||
// Text input that should be sent into realtime.
|
||||
text = text_rx.recv() => {
|
||||
handle_text_input(
|
||||
text,
|
||||
&writer,
|
||||
&events_tx,
|
||||
)
|
||||
@@ -1172,14 +1234,17 @@ async fn run_realtime_input_task(input: RealtimeInputTask) {
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_user_text_input(
|
||||
text: Result<String, RecvError>,
|
||||
async fn handle_text_input(
|
||||
params: Result<ConversationTextParams, RecvError>,
|
||||
writer: &RealtimeWebsocketWriter,
|
||||
events_tx: &Sender<RealtimeEvent>,
|
||||
) -> anyhow::Result<()> {
|
||||
let text = text.context("user text input channel closed")?;
|
||||
let params = params.context("text input channel closed")?;
|
||||
|
||||
if let Err(err) = writer.send_conversation_item_create(text).await {
|
||||
if let Err(err) = writer
|
||||
.send_conversation_item_create(params.text, params.role)
|
||||
.await
|
||||
{
|
||||
let mapped_error = map_api_error(err);
|
||||
warn!("failed to send input text: {mapped_error}");
|
||||
let _ = events_tx
|
||||
@@ -1226,7 +1291,10 @@ async fn handle_handoff_output(
|
||||
},
|
||||
RealtimeEventParser::RealtimeV2 => match handoff_output {
|
||||
HandoffOutput::StandaloneAssistantOutput { output_text } => {
|
||||
if let Err(err) = writer.send_conversation_item_create(output_text).await {
|
||||
if let Err(err) = writer
|
||||
.send_conversation_item_create(output_text, ConversationTextRole::User)
|
||||
.await
|
||||
{
|
||||
Err(err)
|
||||
} else {
|
||||
return response_create_queue
|
||||
@@ -1246,7 +1314,9 @@ async fn handle_handoff_output(
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
writer.send_conversation_item_create(output_text).await
|
||||
writer
|
||||
.send_conversation_item_create(output_text, ConversationTextRole::User)
|
||||
.await
|
||||
}
|
||||
HandoffOutput::FinalUpdate {
|
||||
handoff_id,
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use codex_analytics::CompactionImplementation;
|
||||
use codex_analytics::CompactionPhase;
|
||||
use codex_analytics::CompactionReason;
|
||||
use codex_analytics::CompactionStrategy;
|
||||
use codex_analytics::CompactionTrigger;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::InternalSessionSource;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_utils_string::to_ascii_json_string;
|
||||
use http::HeaderMap as ApiHeaderMap;
|
||||
use http::HeaderValue;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::client::X_CODEX_INSTALLATION_ID_HEADER;
|
||||
use crate::client::X_CODEX_PARENT_THREAD_ID_HEADER;
|
||||
use crate::client::X_CODEX_TURN_METADATA_HEADER;
|
||||
use crate::client::X_CODEX_WINDOW_ID_HEADER;
|
||||
use crate::client::X_OPENAI_SUBAGENT_HEADER;
|
||||
|
||||
pub(crate) const INSTALLATION_ID_KEY: &str = "installation_id";
|
||||
pub(crate) const SESSION_ID_KEY: &str = "session_id";
|
||||
pub(crate) const THREAD_ID_KEY: &str = "thread_id";
|
||||
pub(crate) const TURN_ID_KEY: &str = "turn_id";
|
||||
pub(crate) const WINDOW_ID_KEY: &str = "window_id";
|
||||
pub(crate) const REQUEST_KIND_KEY: &str = "request_kind";
|
||||
pub(crate) const COMPACTION_KEY: &str = "compaction";
|
||||
pub(crate) const TURN_STARTED_AT_UNIX_MS_KEY: &str = "turn_started_at_unix_ms";
|
||||
|
||||
pub(crate) const FORKED_FROM_THREAD_ID_KEY: &str = "forked_from_thread_id";
|
||||
pub(crate) const PARENT_THREAD_ID_KEY: &str = "parent_thread_id";
|
||||
pub(crate) const SUBAGENT_KIND_KEY: &str = "subagent_kind";
|
||||
pub(crate) const SANDBOX_KEY: &str = "sandbox";
|
||||
pub(crate) const WORKSPACES_KEY: &str = "workspaces";
|
||||
|
||||
// App-server clients can specify additional metadata in the `responsesapi_client_metadata` param
|
||||
// when submitting a turn, but they must not override fields owned by core.
|
||||
const RESERVED_METADATA_KEYS: &[&str] = &[
|
||||
INSTALLATION_ID_KEY,
|
||||
X_CODEX_INSTALLATION_ID_HEADER,
|
||||
SESSION_ID_KEY,
|
||||
THREAD_ID_KEY,
|
||||
TURN_ID_KEY,
|
||||
WINDOW_ID_KEY,
|
||||
X_CODEX_WINDOW_ID_HEADER,
|
||||
X_CODEX_TURN_METADATA_HEADER,
|
||||
X_CODEX_PARENT_THREAD_ID_HEADER,
|
||||
X_OPENAI_SUBAGENT_HEADER,
|
||||
REQUEST_KIND_KEY,
|
||||
COMPACTION_KEY,
|
||||
TURN_STARTED_AT_UNIX_MS_KEY,
|
||||
FORKED_FROM_THREAD_ID_KEY,
|
||||
PARENT_THREAD_ID_KEY,
|
||||
SUBAGENT_KIND_KEY,
|
||||
SANDBOX_KEY,
|
||||
WORKSPACES_KEY,
|
||||
];
|
||||
|
||||
/// Metadata attached to model requests whose purpose is conversation compaction.
|
||||
///
|
||||
/// This covers both local compaction requests sent through the normal `/responses` path and remote
|
||||
/// compaction requests sent through `/responses/compact`. These fields describe the operation at
|
||||
/// dispatch time. Post-response outcomes such as status, error, duration, and token deltas remain
|
||||
/// in compaction analytics events.
|
||||
#[derive(Clone, Copy, Debug, Serialize)]
|
||||
pub(crate) struct CompactionTurnMetadata {
|
||||
trigger: CompactionTrigger,
|
||||
reason: CompactionReason,
|
||||
implementation: CompactionImplementation,
|
||||
phase: CompactionPhase,
|
||||
strategy: CompactionStrategy,
|
||||
}
|
||||
|
||||
impl CompactionTurnMetadata {
|
||||
pub(crate) fn new(
|
||||
trigger: CompactionTrigger,
|
||||
reason: CompactionReason,
|
||||
implementation: CompactionImplementation,
|
||||
phase: CompactionPhase,
|
||||
) -> Self {
|
||||
Self {
|
||||
trigger,
|
||||
reason,
|
||||
implementation,
|
||||
phase,
|
||||
strategy: CompactionStrategy::Memento,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) enum CodexResponsesRequestKind {
|
||||
Turn,
|
||||
Prewarm,
|
||||
Compaction(CompactionTurnMetadata),
|
||||
Memory,
|
||||
}
|
||||
|
||||
impl CodexResponsesRequestKind {
|
||||
fn metadata(self) -> (&'static str, Option<CompactionTurnMetadata>) {
|
||||
match self {
|
||||
CodexResponsesRequestKind::Turn => ("turn", None),
|
||||
CodexResponsesRequestKind::Prewarm => ("prewarm", None),
|
||||
CodexResponsesRequestKind::Compaction(metadata) => ("compaction", Some(metadata)),
|
||||
CodexResponsesRequestKind::Memory => ("memory", None),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_turn_identity(self) -> bool {
|
||||
!matches!(self, CodexResponsesRequestKind::Memory)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Default)]
|
||||
pub(crate) struct TurnMetadataWorkspace {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) associated_remote_urls: Option<BTreeMap<String, String>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) latest_git_commit_hash: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) has_changes: Option<bool>,
|
||||
}
|
||||
|
||||
/// Caller-owned snapshot of Codex metadata sent to ResponsesAPI.
|
||||
///
|
||||
/// The full Codex turn metadata blob is transported canonically as
|
||||
/// `client_metadata["x-codex-turn-metadata"]`. Flat `client_metadata` keys and direct HTTP/ws
|
||||
/// headers are generated compatibility projections of this snapshot, not separate sources of
|
||||
/// truth.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CodexResponsesMetadata {
|
||||
pub(crate) installation_id: String,
|
||||
pub(crate) session_id: String,
|
||||
pub(crate) thread_id: String,
|
||||
pub(crate) turn_id: Option<String>,
|
||||
pub(crate) window_id: String,
|
||||
pub(crate) request_kind: Option<CodexResponsesRequestKind>,
|
||||
pub(crate) forked_from_thread_id: Option<ThreadId>,
|
||||
pub(crate) parent_thread_id: Option<ThreadId>,
|
||||
pub(crate) subagent_header: Option<String>,
|
||||
pub(crate) subagent_kind: Option<String>,
|
||||
pub(crate) sandbox: Option<String>,
|
||||
pub(crate) workspaces: BTreeMap<String, TurnMetadataWorkspace>,
|
||||
pub(crate) turn_started_at_unix_ms: Option<i64>,
|
||||
pub(crate) extra: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl CodexResponsesMetadata {
|
||||
pub(crate) fn new(
|
||||
installation_id: String,
|
||||
session_id: String,
|
||||
thread_id: String,
|
||||
window_id: String,
|
||||
) -> Self {
|
||||
Self {
|
||||
installation_id,
|
||||
session_id,
|
||||
thread_id,
|
||||
turn_id: None,
|
||||
window_id,
|
||||
request_kind: None,
|
||||
forked_from_thread_id: None,
|
||||
parent_thread_id: None,
|
||||
subagent_header: None,
|
||||
subagent_kind: None,
|
||||
sandbox: None,
|
||||
workspaces: BTreeMap::new(),
|
||||
turn_started_at_unix_ms: None,
|
||||
extra: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn has_turn_metadata(&self) -> bool {
|
||||
self.request_kind.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn turn_metadata_json(&self) -> Option<String> {
|
||||
to_ascii_json_string(&self.turn_metadata_payload()).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn turn_metadata_value(&self) -> Option<Value> {
|
||||
serde_json::to_value(self.turn_metadata_payload()).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn client_metadata(&self) -> HashMap<String, String> {
|
||||
let mut client_metadata = HashMap::from([
|
||||
(
|
||||
X_CODEX_INSTALLATION_ID_HEADER.to_string(),
|
||||
self.installation_id.clone(),
|
||||
),
|
||||
(SESSION_ID_KEY.to_string(), self.session_id.clone()),
|
||||
(THREAD_ID_KEY.to_string(), self.thread_id.clone()),
|
||||
(X_CODEX_WINDOW_ID_HEADER.to_string(), self.window_id.clone()),
|
||||
]);
|
||||
if let Some(turn_id) = &self.turn_id {
|
||||
client_metadata.insert(TURN_ID_KEY.to_string(), turn_id.clone());
|
||||
}
|
||||
if let Some(subagent_header) = &self.subagent_header {
|
||||
client_metadata.insert(
|
||||
X_OPENAI_SUBAGENT_HEADER.to_string(),
|
||||
subagent_header.clone(),
|
||||
);
|
||||
}
|
||||
if let Some(parent_thread_id) = self.parent_thread_id {
|
||||
client_metadata.insert(
|
||||
X_CODEX_PARENT_THREAD_ID_HEADER.to_string(),
|
||||
parent_thread_id.to_string(),
|
||||
);
|
||||
}
|
||||
if self.has_turn_metadata()
|
||||
&& let Some(turn_metadata_json) = self.turn_metadata_json()
|
||||
{
|
||||
client_metadata.insert(X_CODEX_TURN_METADATA_HEADER.to_string(), turn_metadata_json);
|
||||
}
|
||||
client_metadata
|
||||
}
|
||||
|
||||
pub(crate) fn compatibility_headers(&self) -> ApiHeaderMap {
|
||||
let mut headers = ApiHeaderMap::new();
|
||||
insert_header(&mut headers, X_CODEX_WINDOW_ID_HEADER, &self.window_id);
|
||||
// Direct x-codex-turn-metadata is compatibility output. New per-request consumers should
|
||||
// prefer client_metadata["x-codex-turn-metadata"], which is rendered from this same object.
|
||||
if self.has_turn_metadata()
|
||||
&& let Some(turn_metadata_json) = self.turn_metadata_json()
|
||||
{
|
||||
insert_header(
|
||||
&mut headers,
|
||||
X_CODEX_TURN_METADATA_HEADER,
|
||||
&turn_metadata_json,
|
||||
);
|
||||
}
|
||||
if let Some(parent_thread_id) = self.parent_thread_id {
|
||||
insert_header(
|
||||
&mut headers,
|
||||
X_CODEX_PARENT_THREAD_ID_HEADER,
|
||||
&parent_thread_id.to_string(),
|
||||
);
|
||||
}
|
||||
if let Some(subagent_header) = &self.subagent_header {
|
||||
insert_header(&mut headers, X_OPENAI_SUBAGENT_HEADER, subagent_header);
|
||||
}
|
||||
headers
|
||||
}
|
||||
|
||||
fn turn_metadata_payload(&self) -> CodexTurnMetadataPayload<'_> {
|
||||
let request_kind = self.request_kind;
|
||||
let (request_kind_value, compaction) = request_kind.map_or((None, None), |request_kind| {
|
||||
let (request_kind, compaction) = request_kind.metadata();
|
||||
(Some(request_kind), compaction)
|
||||
});
|
||||
let has_turn_identity =
|
||||
request_kind.is_none_or(CodexResponsesRequestKind::has_turn_identity);
|
||||
let has_request_identity =
|
||||
request_kind.is_some_and(CodexResponsesRequestKind::has_turn_identity);
|
||||
CodexTurnMetadataPayload {
|
||||
installation_id: has_request_identity.then_some(self.installation_id.as_str()),
|
||||
session_id: has_turn_identity.then_some(self.session_id.as_str()),
|
||||
thread_id: has_turn_identity.then_some(self.thread_id.as_str()),
|
||||
turn_id: has_turn_identity
|
||||
.then_some(self.turn_id.as_deref())
|
||||
.flatten(),
|
||||
window_id: has_request_identity.then_some(self.window_id.as_str()),
|
||||
request_kind: request_kind_value,
|
||||
forked_from_thread_id: self.forked_from_thread_id,
|
||||
parent_thread_id: self.parent_thread_id,
|
||||
subagent_kind: self.subagent_kind.as_deref(),
|
||||
sandbox: self.sandbox.as_deref(),
|
||||
workspaces: non_empty_workspaces(&self.workspaces),
|
||||
turn_started_at_unix_ms: self.turn_started_at_unix_ms,
|
||||
compaction,
|
||||
// responsesapi_client_metadata enriches the Codex turn metadata blob, not literal
|
||||
// top-level Responses client_metadata. Reserved Codex-owned keys are filtered when
|
||||
// these extras enter turn state.
|
||||
extra: &self.extra,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn subagent_header_value(session_source: &SessionSource) -> Option<String> {
|
||||
match session_source {
|
||||
SessionSource::SubAgent(subagent_source) => match subagent_source {
|
||||
SubAgentSource::Review => Some("review".to_string()),
|
||||
SubAgentSource::Compact => Some("compact".to_string()),
|
||||
SubAgentSource::MemoryConsolidation => Some("memory_consolidation".to_string()),
|
||||
SubAgentSource::ThreadSpawn { .. } => Some("collab_spawn".to_string()),
|
||||
SubAgentSource::Other(label) => Some(label.clone()),
|
||||
},
|
||||
SessionSource::Internal(InternalSessionSource::MemoryConsolidation) => {
|
||||
Some("memory_consolidation".to_string())
|
||||
}
|
||||
SessionSource::Cli
|
||||
| SessionSource::VSCode
|
||||
| SessionSource::Exec
|
||||
| SessionSource::Mcp
|
||||
| SessionSource::Custom(_)
|
||||
| SessionSource::Unknown => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn subagent_metadata_kind(session_source: &SessionSource) -> Option<String> {
|
||||
match session_source {
|
||||
SessionSource::SubAgent(subagent_source) => Some(subagent_source.kind().to_string()),
|
||||
SessionSource::Cli
|
||||
| SessionSource::VSCode
|
||||
| SessionSource::Exec
|
||||
| SessionSource::Mcp
|
||||
| SessionSource::Custom(_)
|
||||
| SessionSource::Internal(_)
|
||||
| SessionSource::Unknown => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_header(headers: &mut ApiHeaderMap, name: &'static str, value: &str) {
|
||||
if let Ok(header_value) = HeaderValue::from_str(value) {
|
||||
headers.insert(name, header_value);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn filter_extra_metadata(extra: HashMap<String, String>) -> BTreeMap<String, String> {
|
||||
extra
|
||||
.into_iter()
|
||||
.filter(|(key, _)| !RESERVED_METADATA_KEYS.contains(&key.as_str()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn non_empty_workspaces(
|
||||
workspaces: &BTreeMap<String, TurnMetadataWorkspace>,
|
||||
) -> Option<&BTreeMap<String, TurnMetadataWorkspace>> {
|
||||
(!workspaces.is_empty()).then_some(workspaces)
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct CodexTurnMetadataPayload<'a> {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
installation_id: Option<&'a str>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
session_id: Option<&'a str>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
thread_id: Option<&'a str>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
turn_id: Option<&'a str>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
window_id: Option<&'a str>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
request_kind: Option<&'static str>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
forked_from_thread_id: Option<ThreadId>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
parent_thread_id: Option<ThreadId>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
subagent_kind: Option<&'a str>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
sandbox: Option<&'a str>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
workspaces: Option<&'a BTreeMap<String, TurnMetadataWorkspace>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
turn_started_at_unix_ms: Option<i64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
compaction: Option<CompactionTurnMetadata>,
|
||||
#[serde(flatten)]
|
||||
extra: &'a BTreeMap<String, String>,
|
||||
}
|
||||
@@ -103,12 +103,12 @@ impl ExecRequest {
|
||||
pub(crate) fn from_sandbox_exec_request(
|
||||
request: SandboxExecRequest,
|
||||
options: ExecOptions,
|
||||
windows_sandbox_policy_cwd: AbsolutePathBuf,
|
||||
windows_sandbox_workspace_roots: Vec<AbsolutePathBuf>,
|
||||
) -> Self {
|
||||
let SandboxExecRequest {
|
||||
command,
|
||||
cwd,
|
||||
sandbox_policy_cwd: windows_sandbox_policy_cwd,
|
||||
mut env,
|
||||
network,
|
||||
sandbox,
|
||||
|
||||
@@ -273,7 +273,7 @@ pub(super) async fn user_input_or_turn_inner(
|
||||
}
|
||||
}
|
||||
|
||||
/// Records an inter-agent assistant envelope, then lets the shared pending-work scheduler
|
||||
/// Queues an inter-agent message, then lets the shared pending-work scheduler
|
||||
/// decide whether an idle session should start a regular turn.
|
||||
pub async fn inter_agent_communication(
|
||||
sess: &Arc<Session>,
|
||||
|
||||
@@ -16,6 +16,7 @@ pub(crate) enum TurnInput {
|
||||
client_id: Option<String>,
|
||||
},
|
||||
ResponseItem(ResponseItem),
|
||||
InterAgentCommunication(InterAgentCommunication),
|
||||
}
|
||||
|
||||
/// Turn-local pending input storage owned by the input queue flow.
|
||||
@@ -70,12 +71,12 @@ impl InputQueue {
|
||||
.any(|mail| mail.trigger_turn)
|
||||
}
|
||||
|
||||
pub(crate) async fn drain_mailbox_input_items(&self) -> Vec<ResponseItem> {
|
||||
pub(crate) async fn drain_mailbox_input_items(&self) -> Vec<TurnInput> {
|
||||
self.mailbox_pending_mails
|
||||
.lock()
|
||||
.await
|
||||
.drain(..)
|
||||
.map(|mail| ResponseItem::from(mail.to_response_input_item()))
|
||||
.map(TurnInput::InterAgentCommunication)
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -189,11 +190,7 @@ impl InputQueue {
|
||||
if !accepts_mailbox_delivery {
|
||||
return pending_input;
|
||||
}
|
||||
let mailbox_items = self
|
||||
.drain_mailbox_input_items()
|
||||
.await
|
||||
.into_iter()
|
||||
.map(TurnInput::ResponseItem);
|
||||
let mailbox_items = self.drain_mailbox_input_items().await.into_iter();
|
||||
if pending_input.is_empty() {
|
||||
mailbox_items.collect()
|
||||
} else {
|
||||
@@ -290,7 +287,7 @@ mod tests {
|
||||
AgentPath::try_from("/root/worker").expect("agent path"),
|
||||
AgentPath::root(),
|
||||
"two",
|
||||
/*trigger_turn*/ false,
|
||||
/*trigger_turn*/ true,
|
||||
);
|
||||
|
||||
input_queue
|
||||
@@ -303,8 +300,8 @@ mod tests {
|
||||
assert_eq!(
|
||||
input_queue.drain_mailbox_input_items().await,
|
||||
vec![
|
||||
ResponseItem::from(mail_one.to_response_input_item()),
|
||||
ResponseItem::from(mail_two.to_response_input_item())
|
||||
TurnInput::InterAgentCommunication(mail_one),
|
||||
TurnInput::InterAgentCommunication(mail_two)
|
||||
]
|
||||
);
|
||||
assert!(!input_queue.has_pending_mailbox_items().await);
|
||||
|
||||
@@ -74,6 +74,20 @@ impl ElicitationReviewer for GuardianMcpElicitationReviewer {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub(crate) async fn runtime_mcp_config(&self, config: &Config) -> McpConfig {
|
||||
self.services
|
||||
.mcp_manager
|
||||
.runtime_config_for_thread(config, &self.services.mcp_thread_init)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn runtime_mcp_servers(
|
||||
&self,
|
||||
config: &Config,
|
||||
) -> HashMap<String, McpServerConfig> {
|
||||
codex_mcp::configured_mcp_servers(&self.runtime_mcp_config(config).await)
|
||||
}
|
||||
|
||||
pub(crate) fn mcp_elicitation_reviewer(self: &Arc<Self>) -> ElicitationReviewerHandle {
|
||||
Arc::new(GuardianMcpElicitationReviewer::new(self))
|
||||
}
|
||||
@@ -285,26 +299,28 @@ impl Session {
|
||||
turn_context: &TurnContext,
|
||||
mcp_servers: HashMap<String, McpServerConfig>,
|
||||
store_mode: OAuthCredentialsStoreMode,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
elicitation_reviewer: Option<ElicitationReviewerHandle>,
|
||||
) {
|
||||
let auth = self.services.auth_manager.auth().await;
|
||||
let config = self.get_config().await;
|
||||
let mcp_config = self
|
||||
.services
|
||||
.mcp_manager
|
||||
.runtime_config(config.as_ref())
|
||||
.await;
|
||||
let mcp_config = self.runtime_mcp_config(config.as_ref()).await;
|
||||
let tool_plugin_provenance = codex_mcp::tool_plugin_provenance(&mcp_config);
|
||||
let mcp_servers =
|
||||
effective_mcp_servers_from_configured(mcp_servers, &mcp_config, auth.as_ref());
|
||||
let host_owned_codex_apps_enabled =
|
||||
host_owned_codex_apps_enabled(&mcp_config, auth.as_ref());
|
||||
let auth_statuses =
|
||||
compute_auth_statuses(mcp_servers.iter(), store_mode, auth.as_ref()).await;
|
||||
let auth_statuses = compute_auth_statuses(
|
||||
mcp_servers.iter(),
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
auth.as_ref(),
|
||||
)
|
||||
.await;
|
||||
let mcp_runtime_context = match turn_context.environments.primary() {
|
||||
Some(turn_environment) => McpRuntimeContext::new(
|
||||
Arc::clone(&self.services.environment_manager),
|
||||
turn_environment.cwd.to_path_buf(),
|
||||
turn_environment.cwd().to_path_buf(),
|
||||
),
|
||||
None => McpRuntimeContext::new(
|
||||
Arc::clone(&self.services.environment_manager),
|
||||
@@ -322,6 +338,7 @@ impl Session {
|
||||
let refreshed_manager = McpConnectionManager::new(
|
||||
&mcp_servers,
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
auth_statuses,
|
||||
&turn_context.approval_policy,
|
||||
turn_context.sub_id.clone(),
|
||||
@@ -361,6 +378,7 @@ impl Session {
|
||||
let McpServerRefreshConfig {
|
||||
mcp_servers,
|
||||
mcp_oauth_credentials_store_mode,
|
||||
auth_keyring_backend_kind,
|
||||
} = refresh_config;
|
||||
|
||||
let mcp_servers =
|
||||
@@ -380,9 +398,23 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
};
|
||||
let keyring_backend_kind =
|
||||
match serde_json::from_value::<AuthKeyringBackendKind>(auth_keyring_backend_kind) {
|
||||
Ok(kind) => kind,
|
||||
Err(err) => {
|
||||
warn!("failed to parse MCP auth keyring backend refresh config: {err}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
self.refresh_mcp_servers_inner(turn_context, mcp_servers, store_mode, elicitation_reviewer)
|
||||
.await;
|
||||
self.refresh_mcp_servers_inner(
|
||||
turn_context,
|
||||
mcp_servers,
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
elicitation_reviewer,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(crate) async fn refresh_mcp_servers_now(
|
||||
@@ -390,10 +422,17 @@ impl Session {
|
||||
turn_context: &TurnContext,
|
||||
mcp_servers: HashMap<String, McpServerConfig>,
|
||||
store_mode: OAuthCredentialsStoreMode,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
elicitation_reviewer: Option<ElicitationReviewerHandle>,
|
||||
) {
|
||||
self.refresh_mcp_servers_inner(turn_context, mcp_servers, store_mode, elicitation_reviewer)
|
||||
.await;
|
||||
self.refresh_mcp_servers_inner(
|
||||
turn_context,
|
||||
mcp_servers,
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
elicitation_reviewer,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -50,6 +50,7 @@ use codex_analytics::SubAgentThreadStartedInput;
|
||||
use codex_analytics::TurnCodexErrorFact;
|
||||
use codex_app_server_protocol::McpServerElicitationRequest;
|
||||
use codex_app_server_protocol::McpServerElicitationRequestParams;
|
||||
use codex_config::types::AuthKeyringBackendKind;
|
||||
use codex_config::types::OAuthCredentialsStoreMode;
|
||||
use codex_exec_server::Environment;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
@@ -148,6 +149,7 @@ use codex_thread_store::ResumeThreadParams;
|
||||
use codex_thread_store::ThreadPersistenceMetadata;
|
||||
use codex_thread_store::ThreadStore;
|
||||
use codex_utils_output_truncation::TruncationPolicy;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use futures::future::BoxFuture;
|
||||
use futures::future::Shared;
|
||||
use futures::prelude::*;
|
||||
@@ -294,7 +296,6 @@ use crate::SkillLoadOutcome;
|
||||
use crate::SkillMetadata;
|
||||
use crate::SkillsManager;
|
||||
use crate::agents_md::load_project_instructions;
|
||||
use crate::context::UserInstructions;
|
||||
use crate::exec_policy::ExecPolicyUpdateError;
|
||||
use crate::guardian::GuardianReviewSessionManager;
|
||||
use crate::mcp::McpManager;
|
||||
@@ -324,6 +325,7 @@ use crate::unified_exec::UnifiedExecProcessManager;
|
||||
use crate::windows_sandbox::WindowsSandboxLevelExt;
|
||||
use codex_core_plugins::PluginsManager;
|
||||
use codex_git_utils::get_git_repo_root;
|
||||
use codex_mcp::McpConfig;
|
||||
use codex_mcp::compute_auth_statuses;
|
||||
use codex_mcp::effective_mcp_servers_from_configured;
|
||||
use codex_mcp::host_owned_codex_apps_enabled;
|
||||
@@ -527,13 +529,9 @@ impl Codex {
|
||||
config
|
||||
.startup_warnings
|
||||
.extend(user_instruction_provider_warnings);
|
||||
// TODO(anp) assemble instructions from multiple environments
|
||||
let primary_environment = environment_selections.primary_environment();
|
||||
let primary_fs = primary_environment
|
||||
.as_ref()
|
||||
.map(|environment| environment.get_filesystem());
|
||||
let loaded_agents_md =
|
||||
load_project_instructions(&mut config, user_instructions, primary_fs.as_deref()).await;
|
||||
load_project_instructions(&mut config, user_instructions, &environment_selections)
|
||||
.await;
|
||||
|
||||
let exec_policy = if crate::guardian::is_guardian_reviewer_source(&session_source) {
|
||||
// Guardian review should rely on the built-in shell safety checks,
|
||||
@@ -1106,6 +1104,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Flush rollout writes and return the final durability-barrier result.
|
||||
#[instrument(name = "session.flush_rollout", level = "trace", skip_all)]
|
||||
pub(crate) async fn flush_rollout(&self) -> std::io::Result<()> {
|
||||
if let Some(live_thread) = self.live_thread() {
|
||||
live_thread.flush().await.map_err(std::io::Error::other)
|
||||
@@ -1310,6 +1309,14 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(
|
||||
level = "trace",
|
||||
skip_all,
|
||||
fields(
|
||||
thread_id = %self.thread_id(),
|
||||
rollout_item_count = rollout_items.len()
|
||||
)
|
||||
)]
|
||||
async fn apply_rollout_reconstruction(
|
||||
&self,
|
||||
turn_context: &TurnContext,
|
||||
@@ -2200,6 +2207,18 @@ impl Session {
|
||||
}
|
||||
|
||||
let requested_permissions = args.permissions;
|
||||
// TODO(anp): Migrate request_permissions to support paths from foreign environments.
|
||||
let Ok(native_environment_cwd) = environment.cwd.to_abs_path() else {
|
||||
warn!(
|
||||
cwd = %environment.cwd,
|
||||
"request_permissions requires a cwd native to the Codex host"
|
||||
);
|
||||
return Some(RequestPermissionsResponse {
|
||||
permissions: RequestPermissionProfile::default(),
|
||||
scope: PermissionGrantScope::Turn,
|
||||
strict_auto_review: false,
|
||||
});
|
||||
};
|
||||
|
||||
if crate::guardian::routes_approval_to_guardian(turn_context.as_ref()) {
|
||||
let originating_turn_state = {
|
||||
@@ -2267,7 +2286,7 @@ impl Session {
|
||||
let response = Self::normalize_request_permissions_response(
|
||||
requested_permissions,
|
||||
response,
|
||||
environment.cwd.as_path(),
|
||||
native_environment_cwd.as_path(),
|
||||
);
|
||||
self.record_granted_request_permissions_for_turn(
|
||||
&response,
|
||||
@@ -2307,7 +2326,7 @@ impl Session {
|
||||
started_at_ms: now_unix_timestamp_ms(),
|
||||
reason: args.reason,
|
||||
permissions: requested_permissions,
|
||||
cwd: Some(environment.cwd),
|
||||
cwd: Some(native_environment_cwd),
|
||||
});
|
||||
self.send_event(turn_context.as_ref(), event).await;
|
||||
tokio::select! {
|
||||
@@ -2348,7 +2367,7 @@ impl Session {
|
||||
});
|
||||
};
|
||||
let mut environment = turn_environment.selection();
|
||||
environment.cwd = cwd;
|
||||
environment.cwd = PathUri::from_abs_path(&cwd);
|
||||
self.request_permissions_for_environment(
|
||||
turn_context,
|
||||
call_id,
|
||||
@@ -2390,6 +2409,7 @@ impl Session {
|
||||
call_id,
|
||||
turn_id: turn_context.sub_id.clone(),
|
||||
questions: args.questions,
|
||||
auto_resolution_ms: args.auto_resolution_ms,
|
||||
});
|
||||
turn_context
|
||||
.turn_metadata_state
|
||||
@@ -2450,11 +2470,26 @@ impl Session {
|
||||
};
|
||||
match entry {
|
||||
Some(entry) => {
|
||||
let response = Self::normalize_request_permissions_response(
|
||||
entry.requested_permissions,
|
||||
response,
|
||||
entry.environment.cwd.as_path(),
|
||||
);
|
||||
// TODO(anp): Migrate request_permissions to support paths from foreign environments.
|
||||
let response = match entry.environment.cwd.to_abs_path() {
|
||||
Ok(native_environment_cwd) => Self::normalize_request_permissions_response(
|
||||
entry.requested_permissions,
|
||||
response,
|
||||
native_environment_cwd.as_path(),
|
||||
),
|
||||
Err(err) => {
|
||||
warn!(
|
||||
cwd = %entry.environment.cwd,
|
||||
%err,
|
||||
"request_permissions requires a cwd native to the Codex host"
|
||||
);
|
||||
RequestPermissionsResponse {
|
||||
permissions: RequestPermissionProfile::default(),
|
||||
scope: PermissionGrantScope::Turn,
|
||||
strict_auto_review: false,
|
||||
}
|
||||
}
|
||||
};
|
||||
self.record_granted_request_permissions_for_turn(
|
||||
&response,
|
||||
&entry.environment.environment_id,
|
||||
@@ -2661,6 +2696,26 @@ impl Session {
|
||||
self.send_raw_response_items(turn_context, items).await;
|
||||
}
|
||||
|
||||
pub(crate) async fn record_inter_agent_communication(
|
||||
&self,
|
||||
turn_context: &TurnContext,
|
||||
communication: InterAgentCommunication,
|
||||
) {
|
||||
let response_item = communication.to_model_input_item();
|
||||
let items = self.prepare_conversation_items_for_history(
|
||||
turn_context,
|
||||
std::slice::from_ref(&response_item),
|
||||
);
|
||||
let items = items.as_ref();
|
||||
{
|
||||
let mut state = self.state.lock().await;
|
||||
state.record_items(items.iter(), turn_context.truncation_policy);
|
||||
}
|
||||
self.persist_rollout_items(&[RolloutItem::InterAgentCommunication(communication)])
|
||||
.await;
|
||||
self.send_raw_response_items(turn_context, items).await;
|
||||
}
|
||||
|
||||
async fn maybe_warn_on_server_model_mismatch(
|
||||
self: &Arc<Self>,
|
||||
turn_context: &Arc<TurnContext>,
|
||||
@@ -2976,14 +3031,7 @@ impl Session {
|
||||
}
|
||||
}
|
||||
if let Some(user_instructions) = turn_context.user_instructions.as_deref() {
|
||||
contextual_user_sections.push(
|
||||
UserInstructions {
|
||||
text: user_instructions.to_string(),
|
||||
#[allow(deprecated)]
|
||||
directory: turn_context.cwd.to_string_lossy().into_owned(),
|
||||
}
|
||||
.render(),
|
||||
);
|
||||
contextual_user_sections.push(user_instructions.to_string());
|
||||
}
|
||||
// This is full-context metadata. Steady-state context diffs should not re-emit it.
|
||||
if turn_context.features.enabled(Feature::TokenBudget)
|
||||
@@ -2991,6 +3039,7 @@ impl Session {
|
||||
{
|
||||
developer_sections.push(
|
||||
crate::context::TokenBudgetContext::new(
|
||||
self.thread_id(),
|
||||
auto_compact_window_id,
|
||||
model_context_window,
|
||||
)
|
||||
|
||||
@@ -91,7 +91,6 @@ pub(super) async fn spawn_review_thread(
|
||||
forked_from_thread_id,
|
||||
parent_turn_context.parent_thread_id,
|
||||
&session_source,
|
||||
parent_turn_context.thread_source.clone(),
|
||||
review_turn_id.clone(),
|
||||
#[allow(deprecated)]
|
||||
parent_turn_context.cwd.clone(),
|
||||
|
||||
@@ -220,6 +220,11 @@ impl Session {
|
||||
active_segment.get_or_insert_with(ActiveReplaySegment::default);
|
||||
active_segment.counts_as_user_turn |= is_user_turn_boundary(response_item);
|
||||
}
|
||||
RolloutItem::InterAgentCommunication(_) => {
|
||||
let active_segment =
|
||||
active_segment.get_or_insert_with(ActiveReplaySegment::default);
|
||||
active_segment.counts_as_user_turn = true;
|
||||
}
|
||||
RolloutItem::EventMsg(_) | RolloutItem::SessionMeta(_) => {}
|
||||
}
|
||||
|
||||
@@ -269,6 +274,13 @@ impl Session {
|
||||
turn_context.truncation_policy,
|
||||
);
|
||||
}
|
||||
RolloutItem::InterAgentCommunication(communication) => {
|
||||
let response_item = communication.to_model_input_item();
|
||||
history.record_items(
|
||||
std::iter::once(&response_item),
|
||||
turn_context.truncation_policy,
|
||||
);
|
||||
}
|
||||
RolloutItem::Compacted(compacted) => {
|
||||
if let Some(replacement_history) = &compacted.replacement_history {
|
||||
// This should actually never happen, because the reverse loop above (to build rollout_suffix)
|
||||
|
||||
@@ -52,6 +52,31 @@ fn inter_agent_assistant_message(text: &str) -> ResponseItem {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn record_initial_history_reconstructs_typed_inter_agent_message() {
|
||||
let (session, _turn_context) = make_session_and_context().await;
|
||||
let communication = InterAgentCommunication::new(
|
||||
AgentPath::root().join("worker").expect("worker path"),
|
||||
AgentPath::root(),
|
||||
Vec::new(),
|
||||
"child done".to_string(),
|
||||
/*trigger_turn*/ false,
|
||||
);
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
conversation_id: ThreadId::default(),
|
||||
history: vec![RolloutItem::InterAgentCommunication(communication.clone())],
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
}))
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
session.state.lock().await.clone_history().raw_items(),
|
||||
&[communication.to_model_input_item()]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn record_initial_history_resumed_bare_turn_context_does_not_hydrate_previous_turn_settings()
|
||||
{
|
||||
|
||||
@@ -444,6 +444,7 @@ async fn warm_plugins_and_skills_for_session_init(
|
||||
environment_manager.as_ref(),
|
||||
&environments,
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|resolved| resolved.primary_filesystem());
|
||||
let plugins_input = config.plugins_config_input();
|
||||
@@ -515,6 +516,11 @@ impl Session {
|
||||
}
|
||||
InitialHistory::Resumed(resumed_history) => resumed_history.conversation_id,
|
||||
};
|
||||
let mcp_thread_init = thread_extension_init.clone();
|
||||
let thread_extension_data = codex_extension_api::ExtensionData::new_with_init(
|
||||
thread_id.to_string(),
|
||||
thread_extension_init,
|
||||
);
|
||||
// Kick off independent async setup tasks in parallel to reduce startup latency.
|
||||
//
|
||||
// - initialize thread persistence with new or resumed session info
|
||||
@@ -526,53 +532,47 @@ impl Session {
|
||||
} else {
|
||||
let live_thread = match &initial_history {
|
||||
InitialHistory::New | InitialHistory::Cleared | InitialHistory::Forked(_) => {
|
||||
LiveThread::create(
|
||||
Arc::clone(&thread_store),
|
||||
CreateThreadParams {
|
||||
thread_id,
|
||||
extra_config: config.extra_config.clone(),
|
||||
forked_from_id,
|
||||
parent_thread_id,
|
||||
source: session_source,
|
||||
thread_source: session_configuration.thread_source.clone(),
|
||||
base_instructions: BaseInstructions {
|
||||
text: session_configuration.base_instructions.clone(),
|
||||
},
|
||||
dynamic_tools: session_configuration.dynamic_tools.clone(),
|
||||
multi_agent_version: initial_multi_agent_version,
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: Some(config.cwd.to_path_buf()),
|
||||
model_provider: config.model_provider_id.clone(),
|
||||
memory_mode: if config.memories.generate_memories {
|
||||
ThreadMemoryMode::Enabled
|
||||
} else {
|
||||
ThreadMemoryMode::Disabled
|
||||
},
|
||||
let params = CreateThreadParams {
|
||||
thread_id,
|
||||
extra_config: config.extra_config.clone(),
|
||||
forked_from_id,
|
||||
parent_thread_id,
|
||||
source: session_source,
|
||||
thread_source: session_configuration.thread_source.clone(),
|
||||
base_instructions: BaseInstructions {
|
||||
text: session_configuration.base_instructions.clone(),
|
||||
},
|
||||
dynamic_tools: session_configuration.dynamic_tools.clone(),
|
||||
multi_agent_version: initial_multi_agent_version,
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: Some(config.cwd.to_path_buf()),
|
||||
model_provider: config.model_provider_id.clone(),
|
||||
memory_mode: if config.memories.generate_memories {
|
||||
ThreadMemoryMode::Enabled
|
||||
} else {
|
||||
ThreadMemoryMode::Disabled
|
||||
},
|
||||
},
|
||||
)
|
||||
.await?
|
||||
};
|
||||
LiveThread::create(Arc::clone(&thread_store), params).await?
|
||||
}
|
||||
InitialHistory::Resumed(resumed_history) => {
|
||||
LiveThread::resume(
|
||||
Arc::clone(&thread_store),
|
||||
ResumeThreadParams {
|
||||
thread_id: resumed_history.conversation_id,
|
||||
rollout_path: resumed_history.rollout_path.clone(),
|
||||
history: Some(resumed_history.history.clone()),
|
||||
include_archived: true,
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: Some(config.cwd.to_path_buf()),
|
||||
model_provider: config.model_provider_id.clone(),
|
||||
memory_mode: if config.memories.generate_memories {
|
||||
ThreadMemoryMode::Enabled
|
||||
} else {
|
||||
ThreadMemoryMode::Disabled
|
||||
},
|
||||
let params = ResumeThreadParams {
|
||||
thread_id: resumed_history.conversation_id,
|
||||
rollout_path: resumed_history.rollout_path.clone(),
|
||||
history: Some(resumed_history.history.clone()),
|
||||
include_archived: true,
|
||||
metadata: ThreadPersistenceMetadata {
|
||||
cwd: Some(config.cwd.to_path_buf()),
|
||||
model_provider: config.model_provider_id.clone(),
|
||||
memory_mode: if config.memories.generate_memories {
|
||||
ThreadMemoryMode::Enabled
|
||||
} else {
|
||||
ThreadMemoryMode::Disabled
|
||||
},
|
||||
},
|
||||
)
|
||||
.await?
|
||||
};
|
||||
LiveThread::resume(Arc::clone(&thread_store), params).await?
|
||||
}
|
||||
};
|
||||
Ok(Some(live_thread))
|
||||
@@ -603,14 +603,18 @@ impl Session {
|
||||
let auth_manager_clone = Arc::clone(&auth_manager);
|
||||
let config_for_mcp = Arc::clone(&config);
|
||||
let mcp_manager_for_mcp = Arc::clone(&mcp_manager);
|
||||
let mcp_thread_init_for_startup = &mcp_thread_init;
|
||||
let auth_and_mcp_fut = async move {
|
||||
let auth = auth_manager_clone.auth().await;
|
||||
let mcp_config = mcp_manager_for_mcp.runtime_config(&config_for_mcp).await;
|
||||
let mcp_config = mcp_manager_for_mcp
|
||||
.runtime_config_for_thread(&config_for_mcp, mcp_thread_init_for_startup)
|
||||
.await;
|
||||
let mcp_servers = codex_mcp::effective_mcp_servers(&mcp_config, auth.as_ref());
|
||||
let tool_plugin_provenance = codex_mcp::tool_plugin_provenance(&mcp_config);
|
||||
let auth_statuses = compute_auth_statuses(
|
||||
mcp_servers.iter(),
|
||||
config_for_mcp.mcp_oauth_credentials_store_mode,
|
||||
config_for_mcp.auth_keyring_backend_kind(),
|
||||
auth.as_ref(),
|
||||
)
|
||||
.await;
|
||||
@@ -960,10 +964,6 @@ impl Session {
|
||||
session_extension_data.insert(McpResourceClient::new(Arc::clone(
|
||||
&mcp_connection_manager,
|
||||
)));
|
||||
let thread_extension_data = codex_extension_api::ExtensionData::new_with_init(
|
||||
thread_id.to_string(),
|
||||
thread_extension_init,
|
||||
);
|
||||
for contributor in extensions.thread_lifecycle_contributors() {
|
||||
contributor.on_thread_start(codex_extension_api::ThreadStartInput {
|
||||
config: config.as_ref(),
|
||||
@@ -1010,6 +1010,7 @@ impl Session {
|
||||
// TODO(jif): extract session to share between sub-agents
|
||||
session_extension_data,
|
||||
thread_extension_data,
|
||||
mcp_thread_init,
|
||||
agent_control,
|
||||
network_proxy: arc_swap::ArcSwapOption::from(network_proxy.map(Arc::new)),
|
||||
network_proxy_audit_metadata,
|
||||
@@ -1021,12 +1022,9 @@ impl Session {
|
||||
attestation_provider: attestation_provider.clone(),
|
||||
model_client: ModelClient::new(
|
||||
Some(Arc::clone(&auth_manager)),
|
||||
session_id,
|
||||
thread_id,
|
||||
installation_id.clone(),
|
||||
session_configuration.provider.clone(),
|
||||
session_configuration.session_source.clone(),
|
||||
session_configuration.parent_thread_id,
|
||||
config.model_verbosity,
|
||||
config.features.enabled(Feature::EnableRequestCompression),
|
||||
config.features.enabled(Feature::RuntimeMetrics),
|
||||
@@ -1126,6 +1124,7 @@ impl Session {
|
||||
sess.services.environment_manager.as_ref(),
|
||||
session_configuration.environment_selections(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
CodexErr::InvalidRequest(err.to_string().replace(
|
||||
"unknown turn environment id",
|
||||
@@ -1137,7 +1136,7 @@ impl Session {
|
||||
let mcp_runtime_context = match turn_environment {
|
||||
Some(turn_environment) => McpRuntimeContext::new(
|
||||
Arc::clone(&sess.services.environment_manager),
|
||||
turn_environment.cwd.to_path_buf(),
|
||||
turn_environment.cwd().to_path_buf(),
|
||||
),
|
||||
None => McpRuntimeContext::new(
|
||||
Arc::clone(&sess.services.environment_manager),
|
||||
@@ -1147,6 +1146,7 @@ impl Session {
|
||||
let mcp_connection_manager = McpConnectionManager::new(
|
||||
&mcp_servers,
|
||||
config.mcp_oauth_credentials_store_mode,
|
||||
config.auth_keyring_backend_kind(),
|
||||
auth_statuses,
|
||||
&session_configuration.approval_policy,
|
||||
INITIAL_SUBMIT_ID.to_owned(),
|
||||
|
||||
@@ -55,10 +55,10 @@ use codex_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::protocol::NonSteerableTurnKind;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelection;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelections;
|
||||
use codex_protocol::request_permissions::PermissionGrantScope;
|
||||
use codex_protocol::request_permissions::RequestPermissionProfile;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use tracing::Span;
|
||||
|
||||
use crate::rollout::recorder::RolloutRecorder;
|
||||
@@ -423,12 +423,9 @@ fn test_model_client_session() -> crate::client::ModelClientSession {
|
||||
.expect("test thread id should be valid");
|
||||
crate::client::ModelClient::new(
|
||||
/*auth_manager*/ None,
|
||||
thread_id.into(),
|
||||
thread_id,
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
ModelProviderInfo::create_openai_provider(/* base_url */ /*base_url*/ None),
|
||||
codex_protocol::protocol::SessionSource::Exec,
|
||||
/*parent_thread_id*/ None,
|
||||
/*model_verbosity*/ None,
|
||||
/*enable_request_compression*/ false,
|
||||
/*include_timing_metrics*/ false,
|
||||
@@ -4039,12 +4036,12 @@ fn turn_environments_for_tests(
|
||||
cwd: &codex_utils_absolute_path::AbsolutePathBuf,
|
||||
) -> crate::environment_selection::ResolvedTurnEnvironments {
|
||||
crate::environment_selection::ResolvedTurnEnvironments {
|
||||
turn_environments: vec![TurnEnvironment {
|
||||
environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
environment: Arc::clone(environment),
|
||||
cwd: cwd.clone(),
|
||||
shell: None,
|
||||
}],
|
||||
turn_environments: vec![TurnEnvironment::new(
|
||||
codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
Arc::clone(environment),
|
||||
cwd.clone(),
|
||||
/*shell*/ None,
|
||||
)],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4709,7 +4706,7 @@ async fn cwd_update_rewrites_sticky_environment_cwd() {
|
||||
assert_eq!(state.session_configuration.cwd(), &updated_cwd);
|
||||
assert_eq!(
|
||||
state.session_configuration.environment_selections()[0].cwd,
|
||||
updated_cwd
|
||||
PathUri::from_abs_path(&updated_cwd)
|
||||
);
|
||||
assert_ne!(environment_cwd, updated_cwd);
|
||||
}
|
||||
@@ -4982,6 +4979,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
agent_control.session_id().to_string(),
|
||||
),
|
||||
thread_extension_data: codex_extension_api::ExtensionData::new(thread_id.to_string()),
|
||||
mcp_thread_init: codex_extension_api::ExtensionDataInit::default(),
|
||||
agent_control,
|
||||
network_proxy: arc_swap::ArcSwapOption::from(None),
|
||||
network_proxy_audit_metadata: crate::config::NetworkProxyAuditMetadata::default(),
|
||||
@@ -4996,12 +4994,9 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
attestation_provider: None,
|
||||
model_client: ModelClient::new(
|
||||
Some(auth_manager.clone()),
|
||||
thread_id.into(),
|
||||
thread_id,
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
session_configuration.provider.clone(),
|
||||
session_configuration.session_source.clone(),
|
||||
session_configuration.parent_thread_id,
|
||||
config.model_verbosity,
|
||||
config.features.enabled(Feature::EnableRequestCompression),
|
||||
config.features.enabled(Feature::RuntimeMetrics),
|
||||
@@ -5662,8 +5657,13 @@ async fn request_permissions_tool_resolves_relative_paths_against_selected_envir
|
||||
mcp_elicitations: true,
|
||||
}))
|
||||
.expect("test setup should allow updating approval policy");
|
||||
turn_context_mut.environments.turn_environments[0].environment_id = "remote".to_string();
|
||||
turn_context_mut.environments.turn_environments[0].cwd = environment_cwd.clone();
|
||||
let current_environment = turn_context_mut.environments.turn_environments[0].clone();
|
||||
turn_context_mut.environments.turn_environments[0] = TurnEnvironment::new(
|
||||
"remote".to_string(),
|
||||
current_environment.environment,
|
||||
environment_cwd.clone(),
|
||||
current_environment.shell,
|
||||
);
|
||||
|
||||
let call_id = "call-1".to_string();
|
||||
let handler = RequestPermissionsHandler;
|
||||
@@ -6255,12 +6255,12 @@ async fn primary_environment_uses_first_turn_environment() {
|
||||
turn_context
|
||||
.environments
|
||||
.turn_environments
|
||||
.push(TurnEnvironment {
|
||||
environment_id: "second".to_string(),
|
||||
environment: Arc::clone(&first_environment.environment),
|
||||
cwd: second_cwd.clone(),
|
||||
shell: None,
|
||||
});
|
||||
.push(TurnEnvironment::new(
|
||||
"second".to_string(),
|
||||
Arc::clone(&first_environment.environment),
|
||||
second_cwd.clone(),
|
||||
/*shell*/ None,
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
turn_context
|
||||
@@ -6277,13 +6277,13 @@ async fn primary_environment_uses_first_turn_environment() {
|
||||
.iter()
|
||||
.find(|environment| environment.environment_id == "second")
|
||||
.expect("second environment")
|
||||
.cwd,
|
||||
second_cwd
|
||||
.cwd(),
|
||||
&second_cwd
|
||||
);
|
||||
assert_eq!(turn_context.environments.turn_environments.len(), 2);
|
||||
assert_eq!(
|
||||
turn_context.environments.turn_environments[1].cwd,
|
||||
second_cwd
|
||||
turn_context.environments.turn_environments[1].cwd(),
|
||||
&second_cwd
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6313,82 +6313,6 @@ async fn empty_turn_environments_clear_primary_environment() {
|
||||
assert_eq!(turn_context.config.cwd, session.get_config().await.cwd);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_turn_environment_returns_error() {
|
||||
let (session, _turn_context, _rx) = make_session_and_context_with_rx().await;
|
||||
let original_configuration = {
|
||||
let state = session.state.lock().await;
|
||||
state.session_configuration.clone()
|
||||
};
|
||||
|
||||
let err = session
|
||||
.new_turn_with_sub_id(
|
||||
"sub-1".to_string(),
|
||||
SessionSettingsUpdate {
|
||||
environments: Some(TurnEnvironmentSelections::new(
|
||||
original_configuration.cwd().clone(),
|
||||
vec![TurnEnvironmentSelection {
|
||||
environment_id: "missing".to_string(),
|
||||
cwd: original_configuration.cwd().clone(),
|
||||
}],
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("unknown environment should fail");
|
||||
|
||||
let current_configuration = {
|
||||
let state = session.state.lock().await;
|
||||
state.session_configuration.clone()
|
||||
};
|
||||
assert!(matches!(err, CodexErr::InvalidRequest(_)));
|
||||
assert!(err.to_string().contains("missing"));
|
||||
assert_eq!(current_configuration.cwd(), original_configuration.cwd());
|
||||
assert_eq!(
|
||||
current_configuration.environment_selections(),
|
||||
original_configuration.environment_selections()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicate_turn_environment_returns_error_without_mutating_session() {
|
||||
let (session, _turn_context, _rx) = make_session_and_context_with_rx().await;
|
||||
let original_configuration = {
|
||||
let state = session.state.lock().await;
|
||||
state.session_configuration.clone()
|
||||
};
|
||||
|
||||
let err = session
|
||||
.new_turn_with_sub_id(
|
||||
"sub-1".to_string(),
|
||||
SessionSettingsUpdate {
|
||||
environments: Some(TurnEnvironmentSelections::new(
|
||||
original_configuration.cwd().clone(),
|
||||
vec![
|
||||
local(original_configuration.cwd().clone()),
|
||||
local(original_configuration.cwd().join("second")),
|
||||
],
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("duplicate environment should fail");
|
||||
|
||||
let current_configuration = {
|
||||
let state = session.state.lock().await;
|
||||
state.session_configuration.clone()
|
||||
};
|
||||
assert!(matches!(err, CodexErr::InvalidRequest(_)));
|
||||
assert!(err.to_string().contains("duplicate"));
|
||||
assert_eq!(current_configuration.cwd(), original_configuration.cwd());
|
||||
assert_eq!(
|
||||
current_configuration.environment_selections(),
|
||||
original_configuration.environment_selections()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spawn_task_turn_span_inherits_dispatch_trace_context() {
|
||||
struct TraceCaptureTask {
|
||||
@@ -7060,6 +6984,7 @@ where
|
||||
agent_control.session_id().to_string(),
|
||||
),
|
||||
thread_extension_data: codex_extension_api::ExtensionData::new(thread_id.to_string()),
|
||||
mcp_thread_init: codex_extension_api::ExtensionDataInit::default(),
|
||||
agent_control,
|
||||
network_proxy: arc_swap::ArcSwapOption::from(None),
|
||||
network_proxy_audit_metadata: crate::config::NetworkProxyAuditMetadata::default(),
|
||||
@@ -7074,12 +6999,9 @@ where
|
||||
attestation_provider: None,
|
||||
model_client: ModelClient::new(
|
||||
Some(Arc::clone(&auth_manager)),
|
||||
thread_id.into(),
|
||||
thread_id,
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
session_configuration.provider.clone(),
|
||||
session_configuration.session_source.clone(),
|
||||
session_configuration.parent_thread_id,
|
||||
config.model_verbosity,
|
||||
config.features.enabled(Feature::EnableRequestCompression),
|
||||
config.features.enabled(Feature::RuntimeMetrics),
|
||||
@@ -7181,9 +7103,12 @@ async fn refresh_mcp_servers_is_deferred_until_next_turn() {
|
||||
|
||||
let mcp_oauth_credentials_store_mode =
|
||||
serde_json::to_value(OAuthCredentialsStoreMode::Auto).expect("serialize store mode");
|
||||
let auth_keyring_backend_kind =
|
||||
serde_json::to_value(AuthKeyringBackendKind::Secrets).expect("serialize keyring backend");
|
||||
let refresh_config = McpServerRefreshConfig {
|
||||
mcp_servers: json!({}),
|
||||
mcp_oauth_credentials_store_mode,
|
||||
auth_keyring_backend_kind,
|
||||
};
|
||||
{
|
||||
let mut guard = session.pending_mcp_server_refresh_config.lock().await;
|
||||
@@ -7332,7 +7257,11 @@ async fn environment_context_uses_session_shell_when_environment_shell_is_absent
|
||||
.turn_environments
|
||||
.first_mut()
|
||||
.expect("primary environment");
|
||||
primary_environment.shell = Some("cmd".to_string());
|
||||
primary_environment.shell = Some(crate::shell::Shell {
|
||||
shell_type: crate::shell::ShellType::Cmd,
|
||||
shell_path: PathBuf::from("cmd"),
|
||||
shell_snapshot: crate::shell::empty_shell_snapshot_receiver(),
|
||||
});
|
||||
|
||||
let environment_context = crate::context::EnvironmentContext::from_turn_context(
|
||||
&turn_context,
|
||||
@@ -9293,9 +9222,7 @@ async fn queue_only_mailbox_mail_waits_for_next_turn_after_answer_boundary() {
|
||||
|
||||
assert_eq!(
|
||||
sess.input_queue.get_pending_input(&sess.active_turn).await,
|
||||
vec![TurnInput::ResponseItem(ResponseItem::from(
|
||||
communication.to_response_input_item()
|
||||
))],
|
||||
vec![TurnInput::InterAgentCommunication(communication)],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9384,7 +9311,7 @@ async fn steered_input_reopens_mailbox_delivery_for_current_turn() {
|
||||
}],
|
||||
client_id: None
|
||||
},
|
||||
TurnInput::ResponseItem(ResponseItem::from(communication.to_response_input_item())),
|
||||
TurnInput::InterAgentCommunication(communication),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -9442,7 +9369,7 @@ async fn stale_defer_mailbox_delivery_does_not_override_steered_input() {
|
||||
}],
|
||||
client_id: None
|
||||
},
|
||||
TurnInput::ResponseItem(ResponseItem::from(communication.to_response_input_item())),
|
||||
TurnInput::InterAgentCommunication(communication),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -9497,9 +9424,7 @@ async fn tool_calls_reopen_mailbox_delivery_for_current_turn() {
|
||||
assert!(output.tool_future.is_some());
|
||||
assert_eq!(
|
||||
sess.input_queue.get_pending_input(&sess.active_turn).await,
|
||||
vec![TurnInput::ResponseItem(ResponseItem::from(
|
||||
communication.to_response_input_item()
|
||||
))],
|
||||
vec![TurnInput::InterAgentCommunication(communication)],
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,8 @@ use crate::mentions::collect_explicit_app_ids;
|
||||
use crate::mentions::collect_explicit_plugin_mentions;
|
||||
use crate::mentions::collect_tool_mentions_from_messages;
|
||||
use crate::plugins::build_plugin_injections;
|
||||
use crate::responses_metadata::CodexResponsesMetadata;
|
||||
use crate::responses_metadata::CodexResponsesRequestKind;
|
||||
use crate::responses_retry::ResponsesStreamRequest;
|
||||
use crate::responses_retry::handle_retryable_response_stream_error;
|
||||
use crate::session::PreviousTurnSettings;
|
||||
@@ -223,9 +225,11 @@ pub(crate) async fn run_turn(
|
||||
.await;
|
||||
|
||||
let window_id = sess.current_window_id().await;
|
||||
let turn_metadata_header = turn_context
|
||||
.turn_metadata_state
|
||||
.current_header_value_for_model_request(&window_id);
|
||||
let responses_metadata = turn_context.turn_metadata_state.to_responses_metadata(
|
||||
sess.installation_id.clone(),
|
||||
window_id,
|
||||
CodexResponsesRequestKind::Turn,
|
||||
);
|
||||
let tokens_before_sampling = sess.get_total_token_usage().await;
|
||||
match run_sampling_request(
|
||||
Arc::clone(&sess),
|
||||
@@ -233,8 +237,7 @@ pub(crate) async fn run_turn(
|
||||
Arc::clone(&turn_extension_data),
|
||||
Arc::clone(&turn_diff_tracker),
|
||||
&mut client_session,
|
||||
&window_id,
|
||||
turn_metadata_header.as_deref(),
|
||||
&responses_metadata,
|
||||
sampling_request_input.clone(),
|
||||
cancellation_token.child_token(),
|
||||
)
|
||||
@@ -413,10 +416,10 @@ async fn turn_diff_display_roots(turn_context: &TurnContext) -> Vec<(String, Pat
|
||||
for turn_environment in &turn_context.environments.turn_environments {
|
||||
let root = get_git_repo_root_with_fs(
|
||||
turn_environment.environment.get_filesystem().as_ref(),
|
||||
&turn_environment.cwd,
|
||||
turn_environment.cwd(),
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|| turn_environment.cwd.clone())
|
||||
.unwrap_or_else(|| turn_environment.cwd().clone())
|
||||
.into_path_buf();
|
||||
display_roots.push((turn_environment.environment_id.clone(), root));
|
||||
}
|
||||
@@ -463,7 +466,7 @@ async fn build_skills_and_plugins(
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
TurnInput::UserInput { content, .. } => Some(content.as_slice()),
|
||||
TurnInput::ResponseItem(_) => None,
|
||||
TurnInput::ResponseItem(_) | TurnInput::InterAgentCommunication(_) => None,
|
||||
})
|
||||
.flatten()
|
||||
.cloned()
|
||||
@@ -627,7 +630,7 @@ async fn build_extension_turn_input_items(
|
||||
.enumerate()
|
||||
.map(|(index, environment)| TurnInputEnvironment {
|
||||
environment_id: environment.environment_id.clone(),
|
||||
cwd: environment.cwd.as_path().to_path_buf(),
|
||||
cwd: environment.cwd().as_path().to_path_buf(),
|
||||
is_primary: index == 0,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -682,7 +685,7 @@ async fn track_turn_resolved_config_analytics(
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
TurnInput::UserInput { content, .. } => Some(content.as_slice()),
|
||||
TurnInput::ResponseItem(_) => None,
|
||||
TurnInput::ResponseItem(_) | TurnInput::InterAgentCommunication(_) => None,
|
||||
})
|
||||
.flatten()
|
||||
.filter(|item| {
|
||||
@@ -919,6 +922,7 @@ async fn run_auto_compact(
|
||||
run_inline_remote_auto_compact_task(
|
||||
Arc::clone(sess),
|
||||
Arc::clone(turn_context),
|
||||
client_session.turn_state(),
|
||||
initial_context_injection,
|
||||
reason,
|
||||
phase,
|
||||
@@ -1029,8 +1033,7 @@ async fn run_sampling_request(
|
||||
turn_store: Arc<codex_extension_api::ExtensionData>,
|
||||
turn_diff_tracker: SharedTurnDiffTracker,
|
||||
client_session: &mut ModelClientSession,
|
||||
window_id: &str,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
input: Vec<ResponseItem>,
|
||||
cancellation_token: CancellationToken,
|
||||
) -> CodexResult<SamplingRequestResult> {
|
||||
@@ -1073,8 +1076,7 @@ async fn run_sampling_request(
|
||||
Arc::clone(&turn_context),
|
||||
Arc::clone(&turn_store),
|
||||
client_session,
|
||||
window_id,
|
||||
turn_metadata_header,
|
||||
responses_metadata,
|
||||
Arc::clone(&turn_diff_tracker),
|
||||
&prompt,
|
||||
cancellation_token.child_token(),
|
||||
@@ -1763,6 +1765,7 @@ async fn handle_assistant_item_done_in_plan_mode(
|
||||
false
|
||||
}
|
||||
|
||||
#[instrument(level = "trace", skip_all)]
|
||||
async fn drain_in_flight(
|
||||
in_flight: &mut FuturesOrdered<BoxFuture<'static, CodexResult<ResponseInputItem>>>,
|
||||
sess: Arc<Session>,
|
||||
@@ -1803,8 +1806,7 @@ async fn try_run_sampling_request(
|
||||
turn_context: Arc<TurnContext>,
|
||||
turn_store: Arc<codex_extension_api::ExtensionData>,
|
||||
client_session: &mut ModelClientSession,
|
||||
window_id: &str,
|
||||
turn_metadata_header: Option<&str>,
|
||||
responses_metadata: &CodexResponsesMetadata,
|
||||
turn_diff_tracker: SharedTurnDiffTracker,
|
||||
prompt: &Prompt,
|
||||
cancellation_token: CancellationToken,
|
||||
@@ -1825,14 +1827,13 @@ async fn try_run_sampling_request(
|
||||
let sampling_timing_guard = turn_context.turn_timing_state.begin_sampling();
|
||||
let mut stream = client_session
|
||||
.stream(
|
||||
window_id,
|
||||
prompt,
|
||||
&turn_context.model_info,
|
||||
&turn_context.session_telemetry,
|
||||
turn_context.reasoning_effort.clone(),
|
||||
turn_context.reasoning_summary,
|
||||
turn_context.config.service_tier.clone(),
|
||||
turn_metadata_header,
|
||||
responses_metadata,
|
||||
&inference_trace,
|
||||
)
|
||||
.instrument(trace_span!("stream_request"))
|
||||
|
||||
@@ -17,8 +17,10 @@ use codex_protocol::protocol::TurnEnvironmentSelection;
|
||||
use codex_sandboxing::compatibility_sandbox_policy_for_permission_profile;
|
||||
use codex_sandboxing::policy_transforms::effective_file_system_sandbox_policy;
|
||||
use codex_sandboxing::policy_transforms::effective_network_sandbox_policy;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use tracing::instrument;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct TurnSkillsContext {
|
||||
@@ -39,15 +41,45 @@ impl TurnSkillsContext {
|
||||
pub(crate) struct TurnEnvironment {
|
||||
pub(crate) environment_id: String,
|
||||
pub(crate) environment: Arc<Environment>,
|
||||
pub(crate) cwd: AbsolutePathBuf,
|
||||
pub(crate) shell: Option<String>,
|
||||
// Keep both representations together while cwd consumers migrate to URI semantics. Keeping
|
||||
// them synchronized means neither representation can be exposed through a mutable reference;
|
||||
// updates must rebuild the validated pair through `TurnEnvironment::new`. Once
|
||||
// `TurnEnvironment::cwd` itself becomes a `PathUri`, convert only at native filesystem and
|
||||
// process-launch boundaries and remove this paired migration state.
|
||||
cwd: AbsolutePathBuf,
|
||||
cwd_uri: PathUri,
|
||||
pub(crate) shell: Option<shell::Shell>,
|
||||
}
|
||||
|
||||
impl TurnEnvironment {
|
||||
pub(crate) fn new(
|
||||
environment_id: String,
|
||||
environment: Arc<Environment>,
|
||||
cwd: AbsolutePathBuf,
|
||||
shell: Option<shell::Shell>,
|
||||
) -> Self {
|
||||
let cwd_uri = PathUri::from_abs_path(&cwd);
|
||||
Self {
|
||||
environment_id,
|
||||
environment,
|
||||
cwd,
|
||||
cwd_uri,
|
||||
shell,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cwd(&self) -> &AbsolutePathBuf {
|
||||
&self.cwd
|
||||
}
|
||||
|
||||
pub(crate) fn cwd_uri(&self) -> &PathUri {
|
||||
&self.cwd_uri
|
||||
}
|
||||
|
||||
pub(crate) fn selection(&self) -> TurnEnvironmentSelection {
|
||||
TurnEnvironmentSelection {
|
||||
environment_id: self.environment_id.clone(),
|
||||
cwd: self.cwd.clone(),
|
||||
cwd: self.cwd_uri.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -291,7 +323,7 @@ impl TurnContext {
|
||||
pub(crate) fn file_system_sandbox_context(
|
||||
&self,
|
||||
additional_permissions: Option<AdditionalPermissionProfile>,
|
||||
cwd: &AbsolutePathBuf,
|
||||
cwd: &PathUri,
|
||||
) -> FileSystemSandboxContext {
|
||||
let (base_file_system_sandbox_policy, base_network_sandbox_policy) =
|
||||
self.permission_profile.to_runtime_permissions();
|
||||
@@ -517,7 +549,6 @@ impl Session {
|
||||
session_configuration.forked_from_thread_id,
|
||||
session_configuration.parent_thread_id,
|
||||
&session_configuration.session_source,
|
||||
session_configuration.thread_source.clone(),
|
||||
sub_id.clone(),
|
||||
cwd.clone(),
|
||||
&session_configuration.permission_profile(),
|
||||
@@ -554,7 +585,7 @@ impl Session {
|
||||
user_instructions: session_configuration
|
||||
.loaded_agents_md
|
||||
.as_ref()
|
||||
.map(LoadedAgentsMd::text),
|
||||
.map(LoadedAgentsMd::render),
|
||||
collaboration_mode: session_configuration.collaboration_mode.clone(),
|
||||
multi_agent_version,
|
||||
personality: session_configuration.personality,
|
||||
@@ -591,8 +622,6 @@ impl Session {
|
||||
let mut state = self.state.lock().await;
|
||||
match state.session_configuration.clone().apply(&updates) {
|
||||
Ok(next) => {
|
||||
let turn_environments =
|
||||
self.resolve_turn_environments(next.environment_selections())?;
|
||||
let previous_cwd = state.session_configuration.cwd().clone();
|
||||
let previous_permission_profile =
|
||||
state.session_configuration.permission_profile();
|
||||
@@ -609,7 +638,6 @@ impl Session {
|
||||
state.session_configuration = next.clone();
|
||||
Ok((
|
||||
next,
|
||||
turn_environments,
|
||||
permission_profile_changed,
|
||||
previous_cwd,
|
||||
codex_home,
|
||||
@@ -624,7 +652,6 @@ impl Session {
|
||||
|
||||
let (
|
||||
session_configuration,
|
||||
turn_environments,
|
||||
permission_profile_changed,
|
||||
previous_cwd,
|
||||
codex_home,
|
||||
@@ -665,33 +692,20 @@ impl Session {
|
||||
sub_id,
|
||||
session_configuration,
|
||||
updates.final_output_json_schema,
|
||||
turn_environments,
|
||||
)
|
||||
.await)
|
||||
}
|
||||
|
||||
fn resolve_turn_environments(
|
||||
&self,
|
||||
environments: &[TurnEnvironmentSelection],
|
||||
) -> CodexResult<ResolvedTurnEnvironments> {
|
||||
crate::environment_selection::resolve_environment_selections(
|
||||
self.services.environment_manager.as_ref(),
|
||||
environments,
|
||||
)
|
||||
}
|
||||
|
||||
async fn new_turn_from_configuration(
|
||||
&self,
|
||||
sub_id: String,
|
||||
session_configuration: SessionConfiguration,
|
||||
final_output_json_schema: Option<Option<Value>>,
|
||||
turn_environments: ResolvedTurnEnvironments,
|
||||
) -> Arc<TurnContext> {
|
||||
self.new_turn_context_from_configuration(
|
||||
sub_id,
|
||||
session_configuration,
|
||||
final_output_json_schema,
|
||||
turn_environments,
|
||||
TurnMultiAgentRuntime::ResolveAndStore,
|
||||
)
|
||||
.await
|
||||
@@ -701,30 +715,37 @@ impl Session {
|
||||
&self,
|
||||
sub_id: String,
|
||||
session_configuration: SessionConfiguration,
|
||||
turn_environments: ResolvedTurnEnvironments,
|
||||
) -> Arc<TurnContext> {
|
||||
self.new_turn_context_from_configuration(
|
||||
sub_id,
|
||||
session_configuration,
|
||||
/*final_output_json_schema*/ None,
|
||||
turn_environments,
|
||||
TurnMultiAgentRuntime::Preview,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[instrument(name = "turn_context.build", level = "trace", skip_all)]
|
||||
async fn new_turn_context_from_configuration(
|
||||
&self,
|
||||
sub_id: String,
|
||||
session_configuration: SessionConfiguration,
|
||||
final_output_json_schema: Option<Option<Value>>,
|
||||
turn_environments: ResolvedTurnEnvironments,
|
||||
multi_agent_runtime: TurnMultiAgentRuntime,
|
||||
) -> Arc<TurnContext> {
|
||||
let turn_environments = crate::environment_selection::resolve_environment_selections(
|
||||
self.services.environment_manager.as_ref(),
|
||||
session_configuration.environment_selections(),
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|err| {
|
||||
warn!("failed to resolve turn environments: {err}");
|
||||
ResolvedTurnEnvironments::default()
|
||||
});
|
||||
let primary_turn_environment = turn_environments.primary().cloned();
|
||||
let cwd = primary_turn_environment
|
||||
.as_ref()
|
||||
.map(|turn_environment| turn_environment.cwd.clone())
|
||||
.map(|turn_environment| turn_environment.cwd().clone())
|
||||
.unwrap_or_else(|| session_configuration.cwd().clone());
|
||||
let per_turn_config = Self::build_per_turn_config(&session_configuration, cwd.clone());
|
||||
{
|
||||
@@ -833,13 +854,11 @@ impl Session {
|
||||
}
|
||||
|
||||
pub(crate) async fn new_default_turn_with_sub_id(&self, sub_id: String) -> Arc<TurnContext> {
|
||||
let (session_configuration, turn_environments) =
|
||||
self.default_turn_configuration_and_environments().await;
|
||||
let session_configuration = self.default_turn_configuration().await;
|
||||
self.new_turn_from_configuration(
|
||||
sub_id,
|
||||
session_configuration,
|
||||
/*final_output_json_schema*/ None,
|
||||
turn_environments,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -848,31 +867,13 @@ impl Session {
|
||||
&self,
|
||||
sub_id: String,
|
||||
) -> Arc<TurnContext> {
|
||||
let (session_configuration, turn_environments) =
|
||||
self.default_turn_configuration_and_environments().await;
|
||||
self.new_startup_prewarm_turn_from_configuration(
|
||||
sub_id,
|
||||
session_configuration,
|
||||
turn_environments,
|
||||
)
|
||||
.await
|
||||
let session_configuration = self.default_turn_configuration().await;
|
||||
self.new_startup_prewarm_turn_from_configuration(sub_id, session_configuration)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn default_turn_configuration_and_environments(
|
||||
&self,
|
||||
) -> (SessionConfiguration, ResolvedTurnEnvironments) {
|
||||
let session_configuration = {
|
||||
let state = self.state.lock().await;
|
||||
state.session_configuration.clone()
|
||||
};
|
||||
let turn_environments =
|
||||
match self.resolve_turn_environments(session_configuration.environment_selections()) {
|
||||
Ok(turn_environments) => turn_environments,
|
||||
Err(err) => {
|
||||
warn!("failed to resolve stored session environments: {err}");
|
||||
ResolvedTurnEnvironments::default()
|
||||
}
|
||||
};
|
||||
(session_configuration, turn_environments)
|
||||
async fn default_turn_configuration(&self) -> SessionConfiguration {
|
||||
let state = self.state.lock().await;
|
||||
state.session_configuration.clone()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,11 @@ use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
use tracing::info;
|
||||
use tracing::instrument;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::client::ModelClientSession;
|
||||
use crate::responses_metadata::CodexResponsesRequestKind;
|
||||
use crate::session::INITIAL_SUBMIT_ID;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn::build_prompt;
|
||||
@@ -52,6 +54,7 @@ impl SessionStartupPrewarmHandle {
|
||||
let _ = self.task.await;
|
||||
}
|
||||
|
||||
#[instrument(name = "startup_prewarm.resolve", level = "trace", skip_all)]
|
||||
async fn resolve(
|
||||
self,
|
||||
session_telemetry: &SessionTelemetry,
|
||||
@@ -267,21 +270,24 @@ async fn schedule_startup_prewarm_inner(
|
||||
/*status*/ None,
|
||||
);
|
||||
let window_id = session.current_window_id().await;
|
||||
let startup_turn_metadata_header = startup_turn_context
|
||||
let responses_metadata = startup_turn_context
|
||||
.turn_metadata_state
|
||||
.current_header_value_for_prewarm(&window_id);
|
||||
.to_responses_metadata(
|
||||
session.installation_id.clone(),
|
||||
window_id,
|
||||
CodexResponsesRequestKind::Prewarm,
|
||||
);
|
||||
let mut client_session = session.services.model_client.new_session();
|
||||
let websocket_warmup_started_at = Instant::now();
|
||||
client_session
|
||||
.prewarm_websocket(
|
||||
&window_id,
|
||||
&startup_prompt,
|
||||
&startup_turn_context.model_info,
|
||||
&startup_turn_context.session_telemetry,
|
||||
startup_turn_context.reasoning_effort.clone(),
|
||||
startup_turn_context.reasoning_summary,
|
||||
startup_turn_context.config.service_tier.clone(),
|
||||
startup_turn_metadata_header.as_deref(),
|
||||
&responses_metadata,
|
||||
)
|
||||
.await?;
|
||||
startup_turn_context.session_telemetry.record_startup_phase(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::shell_snapshot::ShellSnapshot;
|
||||
use codex_exec_server::ShellInfo;
|
||||
use codex_shell_command::shell_detect::DetectedShell;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
@@ -85,6 +86,25 @@ impl From<DetectedShell> for Shell {
|
||||
}
|
||||
}
|
||||
|
||||
impl Shell {
|
||||
pub(crate) fn from_environment_shell_info(shell_info: ShellInfo) -> anyhow::Result<Self> {
|
||||
let shell_type = match shell_info.name.as_str() {
|
||||
"zsh" => ShellType::Zsh,
|
||||
"bash" => ShellType::Bash,
|
||||
"powershell" => ShellType::PowerShell,
|
||||
"sh" => ShellType::Sh,
|
||||
"cmd" => ShellType::Cmd,
|
||||
name => anyhow::bail!("unknown environment shell `{name}`"),
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
shell_type,
|
||||
shell_path: PathBuf::from(shell_info.path),
|
||||
shell_snapshot: empty_shell_snapshot_receiver(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
fn ultimate_fallback_shell() -> Shell {
|
||||
codex_shell_command::shell_detect::ultimate_fallback_shell().into()
|
||||
|
||||
@@ -22,6 +22,7 @@ use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_core_plugins::PluginsManager;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionDataInit;
|
||||
use codex_extension_api::ExtensionRegistry;
|
||||
use codex_hooks::Hooks;
|
||||
use codex_login::AuthManager;
|
||||
@@ -67,6 +68,7 @@ pub(crate) struct SessionServices {
|
||||
pub(crate) extensions: Arc<ExtensionRegistry<crate::config::Config>>,
|
||||
pub(crate) session_extension_data: ExtensionData,
|
||||
pub(crate) thread_extension_data: ExtensionData,
|
||||
pub(crate) mcp_thread_init: ExtensionDataInit,
|
||||
pub(crate) agent_control: AgentControl,
|
||||
pub(crate) network_proxy: ArcSwapOption<StartedNetworkProxy>,
|
||||
pub(crate) network_proxy_audit_metadata: NetworkProxyAuditMetadata,
|
||||
|
||||
@@ -578,7 +578,9 @@ pub(crate) async fn finalize_turn_item(
|
||||
agent_message.memory_citation = memory_citation;
|
||||
}
|
||||
}
|
||||
if let TurnItem::ImageGeneration(image_item) = &mut *turn_item {
|
||||
if let TurnItem::ImageGeneration(image_item) = &mut *turn_item
|
||||
&& image_item.status == "completed"
|
||||
{
|
||||
persist_image_generation_item(sess, turn_context, image_item).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ use tracing::Span;
|
||||
use tracing::field;
|
||||
use tracing::info_span;
|
||||
use tracing::trace;
|
||||
use tracing::trace_span;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::codex_thread::BackgroundTerminalInfo;
|
||||
@@ -400,6 +401,7 @@ impl Session {
|
||||
task_input,
|
||||
task_cancellation_token.child_token(),
|
||||
)
|
||||
.instrument(trace_span!("session_task.run"))
|
||||
.await;
|
||||
let sess = session_ctx.clone_session();
|
||||
if let Err(err) = sess.flush_rollout().await {
|
||||
|
||||
@@ -45,19 +45,22 @@ impl SessionTask for RegularTask {
|
||||
let run_turn_span = trace_span!("run_turn");
|
||||
// Regular turns emit `TurnStarted` inline so first-turn lifecycle does
|
||||
// not wait on startup prewarm resolution.
|
||||
let event = EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_id: ctx.sub_id.clone(),
|
||||
trace_id: ctx.trace_id.clone(),
|
||||
started_at: ctx.turn_timing_state.started_at_unix_secs().await,
|
||||
model_context_window: ctx.model_context_window(),
|
||||
collaboration_mode_kind: ctx.collaboration_mode.mode,
|
||||
});
|
||||
sess.send_event(ctx.as_ref(), event).await;
|
||||
sess.set_server_reasoning_included(/*included*/ false).await;
|
||||
let prewarmed_client_session = match sess
|
||||
.consume_startup_prewarm_for_regular_turn(&cancellation_token)
|
||||
.await
|
||||
{
|
||||
let prewarmed_client_session = async {
|
||||
let event = EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_id: ctx.sub_id.clone(),
|
||||
trace_id: ctx.trace_id.clone(),
|
||||
started_at: ctx.turn_timing_state.started_at_unix_secs().await,
|
||||
model_context_window: ctx.model_context_window(),
|
||||
collaboration_mode_kind: ctx.collaboration_mode.mode,
|
||||
});
|
||||
sess.send_event(ctx.as_ref(), event).await;
|
||||
sess.set_server_reasoning_included(/*included*/ false).await;
|
||||
sess.consume_startup_prewarm_for_regular_turn(&cancellation_token)
|
||||
.await
|
||||
}
|
||||
.instrument(trace_span!("regular_task.prepare_run_turn"))
|
||||
.await;
|
||||
let prewarmed_client_session = match prewarmed_client_session {
|
||||
SessionStartupPrewarmResolution::Cancelled => return None,
|
||||
SessionStartupPrewarmResolution::Unavailable { .. } => None,
|
||||
SessionStartupPrewarmResolution::Ready(prewarmed_client_session) => {
|
||||
|
||||
@@ -65,7 +65,7 @@ impl SessionTask for ReviewTask {
|
||||
for item in input {
|
||||
match item {
|
||||
TurnInput::UserInput { mut content, .. } => user_input.append(&mut content),
|
||||
TurnInput::ResponseItem(_) => {}
|
||||
TurnInput::ResponseItem(_) | TurnInput::InterAgentCommunication(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,13 +20,19 @@ use codex_models_manager::collaboration_mode_presets;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
use codex_models_manager::test_support::construct_model_info_offline_for_tests;
|
||||
use codex_models_manager::test_support::get_model_offline_for_tests;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::config_types::CollaborationModeMask;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::openai_models::ModelPreset;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
use crate::ThreadManager;
|
||||
use crate::config::Config;
|
||||
use crate::responses_metadata::CodexResponsesMetadata;
|
||||
use crate::responses_metadata::CodexResponsesRequestKind;
|
||||
use crate::responses_metadata::subagent_header_value;
|
||||
use crate::responses_metadata::subagent_metadata_kind;
|
||||
use crate::thread_manager;
|
||||
use crate::unified_exec;
|
||||
|
||||
@@ -146,6 +152,44 @@ pub fn construct_model_info_offline(model: &str, config: &Config) -> ModelInfo {
|
||||
construct_model_info_offline_for_tests(model, &config.to_models_manager_config())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum TestCodexResponsesRequestKind {
|
||||
Turn,
|
||||
Prewarm,
|
||||
WebsocketConnection,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn responses_metadata(
|
||||
installation_id: &str,
|
||||
session_id: &str,
|
||||
thread_id: &str,
|
||||
turn_id: Option<&str>,
|
||||
window_id: String,
|
||||
session_source: &SessionSource,
|
||||
parent_thread_id: Option<ThreadId>,
|
||||
request_kind: TestCodexResponsesRequestKind,
|
||||
) -> CodexResponsesMetadata {
|
||||
let request_kind = match request_kind {
|
||||
TestCodexResponsesRequestKind::Turn => Some(CodexResponsesRequestKind::Turn),
|
||||
TestCodexResponsesRequestKind::Prewarm => Some(CodexResponsesRequestKind::Prewarm),
|
||||
TestCodexResponsesRequestKind::WebsocketConnection => None,
|
||||
};
|
||||
CodexResponsesMetadata {
|
||||
turn_id: request_kind.and(turn_id.map(ToString::to_string)),
|
||||
request_kind,
|
||||
parent_thread_id,
|
||||
subagent_header: subagent_header_value(session_source),
|
||||
subagent_kind: request_kind.and_then(|_| subagent_metadata_kind(session_source)),
|
||||
..CodexResponsesMetadata::new(
|
||||
installation_id.to_string(),
|
||||
session_id.to_string(),
|
||||
thread_id.to_string(),
|
||||
window_id,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn all_model_presets() -> &'static Vec<ModelPreset> {
|
||||
&TEST_MODEL_PRESETS
|
||||
}
|
||||
|
||||
@@ -78,6 +78,7 @@ use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::sync::broadcast;
|
||||
use tracing::instrument;
|
||||
use tracing::warn;
|
||||
|
||||
const THREAD_CREATED_CHANNEL_CAPACITY: usize = 1024;
|
||||
@@ -272,11 +273,11 @@ impl ThreadManager {
|
||||
let codex_home = config.codex_home.clone();
|
||||
let restriction_product = session_source.restriction_product();
|
||||
let (thread_created_tx, _) = broadcast::channel(THREAD_CREATED_CHANNEL_CAPACITY);
|
||||
let plugins_manager = Arc::new(PluginsManager::new_with_restriction_product(
|
||||
let plugins_manager = Arc::new(PluginsManager::new_with_options(
|
||||
codex_home.to_path_buf(),
|
||||
restriction_product,
|
||||
auth_manager.get_api_auth_mode(),
|
||||
));
|
||||
plugins_manager.set_auth_mode(auth_manager.get_api_auth_mode());
|
||||
let mcp_manager = Arc::new(McpManager::new_with_extensions(
|
||||
Arc::clone(&plugins_manager),
|
||||
Arc::clone(&extensions),
|
||||
@@ -367,11 +368,11 @@ impl ThreadManager {
|
||||
};
|
||||
let (thread_created_tx, _) = broadcast::channel(THREAD_CREATED_CHANNEL_CAPACITY);
|
||||
let restriction_product = SessionSource::Exec.restriction_product();
|
||||
let plugins_manager = Arc::new(PluginsManager::new_with_restriction_product(
|
||||
let plugins_manager = Arc::new(PluginsManager::new_with_options(
|
||||
codex_home.clone(),
|
||||
restriction_product,
|
||||
auth_manager.get_api_auth_mode(),
|
||||
));
|
||||
plugins_manager.set_auth_mode(auth_manager.get_api_auth_mode());
|
||||
let mcp_manager = Arc::new(McpManager::new(Arc::clone(&plugins_manager)));
|
||||
let skills_manager = Arc::new(SkillsManager::new_with_restriction_product(
|
||||
skills_codex_home,
|
||||
@@ -451,8 +452,25 @@ impl ThreadManager {
|
||||
&self,
|
||||
environments: &[TurnEnvironmentSelection],
|
||||
) -> CodexResult<()> {
|
||||
resolve_environment_selections(self.state.environment_manager.as_ref(), environments)
|
||||
.map(|_| ())
|
||||
let mut environment_ids = HashSet::with_capacity(environments.len());
|
||||
for environment in environments {
|
||||
if !environment_ids.insert(environment.environment_id.as_str()) {
|
||||
return Err(CodexErr::InvalidRequest(format!(
|
||||
"duplicate turn environment id `{}`",
|
||||
environment.environment_id
|
||||
)));
|
||||
}
|
||||
self.state
|
||||
.environment_manager
|
||||
.get_environment(&environment.environment_id)
|
||||
.ok_or_else(|| {
|
||||
CodexErr::InvalidRequest(format!(
|
||||
"unknown turn environment id `{}`",
|
||||
environment.environment_id
|
||||
))
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_models_manager(&self) -> SharedModelsManager {
|
||||
@@ -685,6 +703,7 @@ impl ThreadManager {
|
||||
.await
|
||||
}
|
||||
|
||||
#[instrument(level = "trace", skip_all)]
|
||||
pub async fn resume_thread_with_history(
|
||||
&self,
|
||||
config: Config,
|
||||
@@ -1365,7 +1384,8 @@ impl ThreadManagerState {
|
||||
}
|
||||
}
|
||||
let environment_selections =
|
||||
resolve_environment_selections(self.environment_manager.as_ref(), &environments)?;
|
||||
resolve_environment_selections(self.environment_manager.as_ref(), &environments)
|
||||
.await?;
|
||||
let user_instructions = self
|
||||
.user_instructions_for_spawn(&session_source, parent_thread_id, forked_from_thread_id)
|
||||
.await;
|
||||
|
||||
@@ -9,6 +9,8 @@ use crate::tasks::InterruptedTurnHistoryMarker;
|
||||
use crate::tasks::interrupted_turn_history_marker;
|
||||
use codex_extension_api::empty_extension_registry;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ReasoningItemReasoningSummary;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
@@ -21,6 +23,7 @@ use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadSource;
|
||||
use codex_protocol::protocol::TurnStartedEvent;
|
||||
use codex_protocol::protocol::UserMessageEvent;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use core_test_support::PathBufExt;
|
||||
use core_test_support::PathExt;
|
||||
use core_test_support::responses::mount_models_once;
|
||||
@@ -329,7 +332,7 @@ async fn start_thread_rejects_explicit_local_environment_when_default_provider_i
|
||||
parent_trace: None,
|
||||
environments: vec![TurnEnvironmentSelection {
|
||||
environment_id: "local".to_string(),
|
||||
cwd: config.cwd.clone(),
|
||||
cwd: PathUri::from_abs_path(&config.cwd),
|
||||
}],
|
||||
thread_extension_init: Default::default(),
|
||||
})
|
||||
@@ -387,11 +390,10 @@ async fn start_thread_keeps_internal_threads_hidden_from_normal_lookups() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_thread_seeds_extension_data_before_lifecycle_contributors_run() {
|
||||
struct InitialMarker(&'static str);
|
||||
|
||||
async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors() {
|
||||
struct InitialDataRecorder {
|
||||
observed: Arc<std::sync::Mutex<Option<(String, String)>>>,
|
||||
lifecycle_observed: Arc<std::sync::Mutex<Vec<(String, String)>>>,
|
||||
mcp_observed: Arc<std::sync::Mutex<Vec<String>>>,
|
||||
}
|
||||
|
||||
impl codex_extension_api::ThreadLifecycleContributor<Config> for InitialDataRecorder {
|
||||
@@ -400,17 +402,56 @@ async fn start_thread_seeds_extension_data_before_lifecycle_contributors_run() {
|
||||
input: codex_extension_api::ThreadStartInput<'a, Config>,
|
||||
) -> codex_extension_api::ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let marker = input
|
||||
let selected_root = input
|
||||
.thread_store
|
||||
.get::<InitialMarker>()
|
||||
.expect("initial extension data should be available");
|
||||
*self
|
||||
.observed
|
||||
.get::<Vec<SelectedCapabilityRoot>>()
|
||||
.and_then(|roots| roots.first().cloned())
|
||||
.expect("selected root should be available");
|
||||
self.lifecycle_observed
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some((
|
||||
input.thread_store.level_id().to_string(),
|
||||
marker.0.to_string(),
|
||||
));
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push((input.thread_store.level_id().to_string(), selected_root.id));
|
||||
input
|
||||
.thread_store
|
||||
.insert(Vec::<SelectedCapabilityRoot>::new());
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl codex_extension_api::McpServerContributor<Config> for InitialDataRecorder {
|
||||
fn id(&self) -> &'static str {
|
||||
"selected_root_test"
|
||||
}
|
||||
|
||||
fn contribute<'a>(
|
||||
&'a self,
|
||||
context: codex_extension_api::McpServerContributionContext<'a, Config>,
|
||||
) -> codex_extension_api::ExtensionFuture<'a, Vec<codex_extension_api::McpServerContribution>>
|
||||
{
|
||||
Box::pin(async move {
|
||||
let thread_init = context
|
||||
.thread_init()
|
||||
.expect("initial MCP resolution should be thread-scoped");
|
||||
let selected_root = thread_init
|
||||
.get::<Vec<SelectedCapabilityRoot>>()
|
||||
.and_then(|roots| roots.first().cloned())
|
||||
.expect("selected root should be available");
|
||||
self.mcp_observed
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(selected_root.id.clone());
|
||||
let mut server = codex_mcp::codex_apps_mcp_server_config(
|
||||
"https://selected.invalid",
|
||||
/*apps_mcp_product_sku*/ None,
|
||||
);
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } =
|
||||
&selected_root.location;
|
||||
server.environment_id = environment_id.clone();
|
||||
server.enabled = false;
|
||||
vec![codex_extension_api::McpServerContribution::Set {
|
||||
name: selected_root.id,
|
||||
config: Box::new(server),
|
||||
}]
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -421,11 +462,15 @@ async fn start_thread_seeds_extension_data_before_lifecycle_contributors_run() {
|
||||
config.cwd = config.codex_home.abs();
|
||||
std::fs::create_dir_all(&config.codex_home).expect("create codex home");
|
||||
|
||||
let observed = Arc::new(std::sync::Mutex::new(None));
|
||||
let lifecycle_observed = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let mcp_observed = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let recorder = Arc::new(InitialDataRecorder {
|
||||
lifecycle_observed: Arc::clone(&lifecycle_observed),
|
||||
mcp_observed: Arc::clone(&mcp_observed),
|
||||
});
|
||||
let mut extensions = codex_extension_api::ExtensionRegistryBuilder::new();
|
||||
extensions.thread_lifecycle_contributor(Arc::new(InitialDataRecorder {
|
||||
observed: Arc::clone(&observed),
|
||||
}));
|
||||
extensions.thread_lifecycle_contributor(recorder.clone());
|
||||
extensions.mcp_server_contributor(recorder);
|
||||
let manager = ThreadManager::new(
|
||||
&config,
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
|
||||
@@ -439,12 +484,21 @@ async fn start_thread_seeds_extension_data_before_lifecycle_contributors_run() {
|
||||
TEST_INSTALLATION_ID.to_string(),
|
||||
/*attestation_provider*/ None,
|
||||
);
|
||||
let mut thread_extension_init = codex_extension_api::ExtensionDataInit::new();
|
||||
thread_extension_init.insert(InitialMarker("seeded"));
|
||||
let selected_root_init = |id: &str, environment_id: &str| {
|
||||
let mut init = codex_extension_api::ExtensionDataInit::new();
|
||||
init.insert(vec![SelectedCapabilityRoot {
|
||||
id: id.to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: environment_id.to_string(),
|
||||
path: format!("/plugins/{id}"),
|
||||
},
|
||||
}]);
|
||||
init
|
||||
};
|
||||
|
||||
let thread = manager
|
||||
let first_thread = manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config,
|
||||
config: config.clone(),
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
@@ -452,17 +506,64 @@ async fn start_thread_seeds_extension_data_before_lifecycle_contributors_run() {
|
||||
metrics_service_name: None,
|
||||
parent_trace: None,
|
||||
environments: Vec::new(),
|
||||
thread_extension_init,
|
||||
thread_extension_init: selected_root_init("selected-a", "env-a"),
|
||||
})
|
||||
.await
|
||||
.expect("start thread");
|
||||
.expect("start first thread");
|
||||
let second_thread = manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config: config.clone(),
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
dynamic_tools: Vec::new(),
|
||||
metrics_service_name: None,
|
||||
parent_trace: None,
|
||||
environments: Vec::new(),
|
||||
thread_extension_init: selected_root_init("selected-b", "env-b"),
|
||||
})
|
||||
.await
|
||||
.expect("start second thread");
|
||||
let first_resolved = first_thread.thread.runtime_mcp_config(&config).await;
|
||||
let second_resolved = second_thread.thread.runtime_mcp_config(&config).await;
|
||||
|
||||
assert_eq!(
|
||||
observed
|
||||
*lifecycle_observed
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone(),
|
||||
Some((thread.thread_id.to_string(), "seeded".to_string()))
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner),
|
||||
vec![
|
||||
(first_thread.thread_id.to_string(), "selected-a".to_string()),
|
||||
(
|
||||
second_thread.thread_id.to_string(),
|
||||
"selected-b".to_string()
|
||||
),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
*mcp_observed
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner),
|
||||
vec![
|
||||
"selected-a".to_string(),
|
||||
"selected-b".to_string(),
|
||||
"selected-a".to_string(),
|
||||
"selected-b".to_string(),
|
||||
]
|
||||
);
|
||||
let selected_servers = |config: &codex_mcp::McpConfig| {
|
||||
codex_mcp::configured_mcp_servers(config)
|
||||
.into_iter()
|
||||
.filter(|(name, _)| name.starts_with("selected-"))
|
||||
.map(|(name, server)| (name, server.environment_id))
|
||||
.collect::<std::collections::BTreeMap<_, _>>()
|
||||
};
|
||||
assert_eq!(
|
||||
selected_servers(&first_resolved),
|
||||
std::collections::BTreeMap::from([("selected-a".to_string(), "env-a".to_string())])
|
||||
);
|
||||
assert_eq!(
|
||||
selected_servers(&second_resolved),
|
||||
std::collections::BTreeMap::from([("selected-b".to_string(), "env-b".to_string())])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -491,14 +592,17 @@ async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() {
|
||||
);
|
||||
let selected_cwd =
|
||||
AbsolutePathBuf::try_from(config.cwd.as_path().join("selected")).expect("absolute path");
|
||||
std::fs::create_dir_all(&selected_cwd).expect("create selected cwd");
|
||||
let environments = vec![TurnEnvironmentSelection {
|
||||
environment_id: "local".to_string(),
|
||||
cwd: selected_cwd.clone(),
|
||||
cwd: PathUri::from_abs_path(&selected_cwd),
|
||||
}];
|
||||
let default_cwd = config.cwd.clone();
|
||||
let mut source_config = config.clone();
|
||||
source_config.cwd = selected_cwd.clone();
|
||||
let source = manager
|
||||
.start_thread_with_options(StartThreadOptions {
|
||||
config: config.clone(),
|
||||
config: source_config,
|
||||
initial_history: InitialHistory::New,
|
||||
session_source: None,
|
||||
thread_source: None,
|
||||
@@ -545,12 +649,12 @@ async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() {
|
||||
.expect("build resumed turn context");
|
||||
assert_eq!(resumed_turn.environments.turn_environments.len(), 1);
|
||||
assert_eq!(
|
||||
resumed_turn.environments.turn_environments[0].cwd,
|
||||
default_cwd
|
||||
resumed_turn.environments.turn_environments[0].cwd(),
|
||||
&default_cwd
|
||||
);
|
||||
assert_ne!(
|
||||
resumed_turn.environments.turn_environments[0].cwd,
|
||||
selected_cwd
|
||||
resumed_turn.environments.turn_environments[0].cwd(),
|
||||
&selected_cwd
|
||||
);
|
||||
|
||||
let forked = manager
|
||||
@@ -572,12 +676,12 @@ async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() {
|
||||
.expect("build forked turn context");
|
||||
assert_eq!(forked_turn.environments.turn_environments.len(), 1);
|
||||
assert_eq!(
|
||||
forked_turn.environments.turn_environments[0].cwd,
|
||||
default_cwd
|
||||
forked_turn.environments.turn_environments[0].cwd(),
|
||||
&default_cwd
|
||||
);
|
||||
assert_ne!(
|
||||
forked_turn.environments.turn_environments[0].cwd,
|
||||
selected_cwd
|
||||
forked_turn.environments.turn_environments[0].cwd(),
|
||||
&selected_cwd
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ pub(crate) fn initial_history_has_prior_user_turns(conversation_history: &Initia
|
||||
fn rollout_item_is_user_turn_boundary(item: &RolloutItem) -> bool {
|
||||
match item {
|
||||
RolloutItem::ResponseItem(item) => is_user_turn_boundary(item),
|
||||
RolloutItem::InterAgentCommunication(_) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -58,7 +59,8 @@ pub(crate) fn user_message_positions_in_rollout(items: &[RolloutItem]) -> Vec<us
|
||||
///
|
||||
/// A fork-turn boundary is either:
|
||||
/// - a real user message boundary, or
|
||||
/// - an assistant inter-agent envelope whose parsed `trigger_turn` is `true`.
|
||||
/// - an inter-agent communication whose `trigger_turn` is `true`, or
|
||||
/// - a legacy assistant inter-agent envelope with the same flag.
|
||||
///
|
||||
/// Like `user_message_positions_in_rollout`, this applies `ThreadRolledBack` markers so indexing
|
||||
/// reflects the effective post-rollback history. Rollback counts instruction turns, so a rollback
|
||||
@@ -77,6 +79,12 @@ pub(crate) fn fork_turn_positions_in_rollout(items: &[RolloutItem]) -> Vec<usize
|
||||
fork_turn_positions.push(idx);
|
||||
}
|
||||
}
|
||||
RolloutItem::InterAgentCommunication(communication) => {
|
||||
rollback_turn_positions.push(idx);
|
||||
if communication.trigger_turn {
|
||||
fork_turn_positions.push(idx);
|
||||
}
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::ThreadRolledBack(rollback)) => {
|
||||
let num_turns = usize::try_from(rollback.num_turns).unwrap_or(usize::MAX);
|
||||
if num_turns == 0 {
|
||||
|
||||
@@ -51,6 +51,16 @@ fn inter_agent_msg(text: &str, trigger_turn: bool) -> ResponseItem {
|
||||
communication.to_response_input_item().into()
|
||||
}
|
||||
|
||||
fn inter_agent_communication(text: &str, trigger_turn: bool) -> RolloutItem {
|
||||
RolloutItem::InterAgentCommunication(InterAgentCommunication::new(
|
||||
AgentPath::root(),
|
||||
AgentPath::try_from("/root/worker").expect("agent path"),
|
||||
Vec::new(),
|
||||
text.to_string(),
|
||||
trigger_turn,
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncates_rollout_from_start_before_nth_user_only() {
|
||||
let items = [
|
||||
@@ -208,6 +218,20 @@ fn truncates_rollout_to_last_n_fork_turns_counts_trigger_turn_messages() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fork_turn_positions_use_inter_agent_delivery_metadata() {
|
||||
let rollout = vec![
|
||||
RolloutItem::ResponseItem(user_msg("user task")),
|
||||
inter_agent_communication("queued during user turn", /*trigger_turn*/ false),
|
||||
RolloutItem::ResponseItem(assistant_msg("first answer")),
|
||||
inter_agent_communication("follow-up task", /*trigger_turn*/ true),
|
||||
RolloutItem::ResponseItem(assistant_msg("second answer")),
|
||||
RolloutItem::ResponseItem(user_msg("next user task")),
|
||||
];
|
||||
|
||||
assert_eq!(fork_turn_positions_in_rollout(&rollout), vec![0, 3, 5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncates_rollout_to_last_n_fork_turns_drops_startup_prefix_even_when_under_limit() {
|
||||
let rollout = vec![
|
||||
|
||||
@@ -312,5 +312,5 @@ fn single_local_environment_cwd(turn: &TurnContext) -> Result<&AbsolutePathBuf,
|
||||
));
|
||||
}
|
||||
|
||||
Ok(&turn_environment.cwd)
|
||||
Ok(turn_environment.cwd())
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ use codex_sandboxing::policy_transforms::normalize_additional_permissions;
|
||||
use codex_tools::ToolName;
|
||||
use codex_tools::ToolSpec;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
|
||||
const APPLY_PATCH_ARGUMENT_DIFF_BUFFER_INTERVAL: Duration = Duration::from_millis(500);
|
||||
/// Handles freeform `apply_patch` requests and routes verified patches to the
|
||||
@@ -358,9 +359,12 @@ impl ApplyPatchHandler {
|
||||
"apply_patch is unavailable in this session".to_string(),
|
||||
));
|
||||
};
|
||||
let cwd = turn_environment.cwd.clone();
|
||||
let cwd = turn_environment.cwd().clone();
|
||||
let fs = turn_environment.environment.get_filesystem();
|
||||
let sandbox = turn.file_system_sandbox_context(/*additional_permissions*/ None, &cwd);
|
||||
let sandbox = turn.file_system_sandbox_context(
|
||||
/*additional_permissions*/ None,
|
||||
turn_environment.cwd_uri(),
|
||||
);
|
||||
match codex_apply_patch::verify_apply_patch_args(args, &cwd, fs.as_ref(), Some(&sandbox))
|
||||
.await
|
||||
{
|
||||
@@ -522,7 +526,9 @@ pub(crate) async fn intercept_apply_patch(
|
||||
call_id: &str,
|
||||
tool_name: &str,
|
||||
) -> Result<Option<FunctionToolOutput>, FunctionCallError> {
|
||||
let sandbox = turn.file_system_sandbox_context(/*additional_permissions*/ None, cwd);
|
||||
let sandbox_cwd = PathUri::from_abs_path(cwd);
|
||||
let sandbox =
|
||||
turn.file_system_sandbox_context(/*additional_permissions*/ None, &sandbox_cwd);
|
||||
match codex_apply_patch::maybe_parse_apply_patch_verified(command, cwd, fs, Some(&sandbox))
|
||||
.await
|
||||
{
|
||||
|
||||
@@ -5,18 +5,21 @@ use codex_protocol::items::TurnItem;
|
||||
use codex_tools::ConversationHistory;
|
||||
use codex_tools::ExtensionTurnItem;
|
||||
use codex_tools::ToolCall as ExtensionToolCall;
|
||||
use codex_tools::ToolEnvironment;
|
||||
use codex_tools::ToolName;
|
||||
use codex_tools::ToolSearchInfo;
|
||||
use codex_tools::ToolSpec;
|
||||
use codex_tools::TurnItemEmissionFuture;
|
||||
use codex_tools::TurnItemEmitter;
|
||||
|
||||
use crate::sandboxing::SandboxPermissions;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::stream_events_utils::TurnItemContributorPolicy;
|
||||
use crate::stream_events_utils::finalize_turn_item;
|
||||
use crate::tools::context::ToolInvocation;
|
||||
use crate::tools::context::ToolPayload;
|
||||
use crate::tools::handlers::apply_granted_turn_permissions;
|
||||
use crate::tools::registry::CoreToolRuntime;
|
||||
use crate::tools::registry::ToolExecutor;
|
||||
|
||||
@@ -109,6 +112,27 @@ impl TurnItemEmitter for CoreTurnItemEmitter {
|
||||
async fn to_extension_call(invocation: &ToolInvocation) -> ExtensionToolCall {
|
||||
let conversation_history =
|
||||
ConversationHistory::new(invocation.session.clone_history().await.into_raw_items());
|
||||
let mut environments = Vec::with_capacity(invocation.turn.environments.turn_environments.len());
|
||||
for environment in &invocation.turn.environments.turn_environments {
|
||||
let additional_permissions = apply_granted_turn_permissions(
|
||||
invocation.session.as_ref(),
|
||||
&environment.environment_id,
|
||||
environment.cwd().as_path(),
|
||||
SandboxPermissions::UseDefault,
|
||||
/*additional_permissions*/ None,
|
||||
)
|
||||
.await
|
||||
.additional_permissions;
|
||||
let file_system_sandbox_context = invocation
|
||||
.turn
|
||||
.file_system_sandbox_context(additional_permissions, environment.cwd_uri());
|
||||
environments.push(ToolEnvironment {
|
||||
environment_id: environment.environment_id.clone(),
|
||||
cwd: environment.cwd().clone(),
|
||||
file_system: environment.environment.get_filesystem(),
|
||||
file_system_sandbox_context,
|
||||
});
|
||||
}
|
||||
ExtensionToolCall {
|
||||
turn_id: invocation.turn.sub_id.clone(),
|
||||
call_id: invocation.call_id.clone(),
|
||||
@@ -120,6 +144,7 @@ async fn to_extension_call(invocation: &ToolInvocation) -> ExtensionToolCall {
|
||||
session: Arc::downgrade(&invocation.session),
|
||||
turn: Arc::downgrade(&invocation.turn),
|
||||
}),
|
||||
environments,
|
||||
payload: invocation.payload.clone(),
|
||||
}
|
||||
}
|
||||
@@ -286,6 +311,12 @@ mod tests {
|
||||
let turn_id = turn.sub_id.clone();
|
||||
let model = turn.model_info.slug.clone();
|
||||
let truncation_policy = turn.truncation_policy;
|
||||
let expected_sandbox_cwds = turn
|
||||
.environments
|
||||
.turn_environments
|
||||
.iter()
|
||||
.map(|environment| Some(environment.cwd_uri().clone()))
|
||||
.collect::<Vec<_>>();
|
||||
let history_item = ResponseItem::Message {
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
@@ -330,6 +361,14 @@ mod tests {
|
||||
);
|
||||
assert_eq!(captured_call.model, model);
|
||||
assert_eq!(captured_call.truncation_policy, truncation_policy);
|
||||
assert_eq!(
|
||||
captured_call
|
||||
.environments
|
||||
.iter()
|
||||
.map(|environment| environment.file_system_sandbox_context.cwd.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
expected_sandbox_cwds
|
||||
);
|
||||
assert_eq!(
|
||||
captured_call.conversation_history.items(),
|
||||
std::slice::from_ref(&history_item)
|
||||
|
||||
@@ -2,14 +2,59 @@ use crate::context::ContextualUserFragment;
|
||||
use crate::function_tool::FunctionCallError;
|
||||
use crate::tools::context::FunctionToolOutput;
|
||||
use crate::tools::context::ToolInvocation;
|
||||
use crate::tools::context::ToolOutput;
|
||||
use crate::tools::context::ToolPayload;
|
||||
use crate::tools::context::boxed_tool_output;
|
||||
use crate::tools::handlers::get_context_remaining_spec::GET_CONTEXT_REMAINING_TOOL_NAME;
|
||||
use crate::tools::handlers::get_context_remaining_spec::create_get_context_remaining_tool;
|
||||
use crate::tools::registry::CoreToolRuntime;
|
||||
use crate::tools::registry::ToolExecutor;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_tools::ToolName;
|
||||
use codex_tools::ToolSpec;
|
||||
use serde_json::Value as JsonValue;
|
||||
use serde_json::json;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct GetContextRemainingOutput {
|
||||
tokens_left: Option<i64>,
|
||||
}
|
||||
|
||||
impl GetContextRemainingOutput {
|
||||
fn new(tokens_left: Option<i64>) -> Self {
|
||||
Self { tokens_left }
|
||||
}
|
||||
|
||||
fn fragment(&self) -> String {
|
||||
match self.tokens_left {
|
||||
Some(tokens_left) => {
|
||||
crate::context::TokenBudgetRemainingContext::new(tokens_left).render()
|
||||
}
|
||||
None => crate::context::TokenBudgetRemainingContext::unknown().render(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolOutput for GetContextRemainingOutput {
|
||||
fn log_preview(&self) -> String {
|
||||
self.fragment()
|
||||
}
|
||||
|
||||
fn success_for_logging(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
|
||||
FunctionToolOutput::from_text(self.fragment(), Some(true))
|
||||
.to_response_item(call_id, payload)
|
||||
}
|
||||
|
||||
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
|
||||
json!({
|
||||
"tokens_left": self.tokens_left,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GetContextRemainingHandler;
|
||||
|
||||
@@ -31,22 +76,18 @@ impl ToolExecutor<ToolInvocation> for GetContextRemainingHandler {
|
||||
}
|
||||
|
||||
let Some(model_context_window) = invocation.turn.model_context_window() else {
|
||||
let fragment = crate::context::TokenBudgetRemainingContext::unknown().render();
|
||||
return Ok(boxed_tool_output(FunctionToolOutput::from_text(
|
||||
fragment,
|
||||
Some(true),
|
||||
return Ok(boxed_tool_output(GetContextRemainingOutput::new(
|
||||
/*tokens_left*/ None,
|
||||
)));
|
||||
};
|
||||
let active_context_tokens = invocation.session.get_total_token_usage().await.max(0);
|
||||
let tokens_left = model_context_window
|
||||
.saturating_sub(active_context_tokens)
|
||||
.max(0);
|
||||
let fragment = crate::context::TokenBudgetRemainingContext::new(tokens_left).render();
|
||||
|
||||
Ok(boxed_tool_output(FunctionToolOutput::from_text(
|
||||
fragment,
|
||||
Some(true),
|
||||
)))
|
||||
Ok(boxed_tool_output(GetContextRemainingOutput::new(Some(
|
||||
tokens_left,
|
||||
))))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use codex_tools::JsonSchema;
|
||||
use codex_tools::ResponsesApiTool;
|
||||
use codex_tools::ToolSpec;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(crate) const GET_CONTEXT_REMAINING_TOOL_NAME: &str = "get_context_remaining";
|
||||
@@ -12,6 +14,23 @@ pub fn create_get_context_remaining_tool() -> ToolSpec {
|
||||
strict: false,
|
||||
defer_loading: None,
|
||||
parameters: JsonSchema::object(BTreeMap::new(), /*required*/ None, Some(false.into())),
|
||||
output_schema: None,
|
||||
output_schema: Some(get_context_remaining_output_schema()),
|
||||
})
|
||||
}
|
||||
|
||||
fn get_context_remaining_output_schema() -> Value {
|
||||
json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"tokens_left": {
|
||||
"anyOf": [
|
||||
{ "type": "integer" },
|
||||
{ "type": "null" }
|
||||
],
|
||||
"description": "Remaining tokens in the current context window, or null when unavailable."
|
||||
}
|
||||
},
|
||||
"required": ["tokens_left"],
|
||||
"additionalProperties": false
|
||||
})
|
||||
}
|
||||
|
||||
@@ -680,16 +680,9 @@ fn spawn_agent_tool_description(
|
||||
{tool_description}
|
||||
This spawn_agent tool provides you access to sub-agents that inherit your current model by default. Do not set the `model` field unless the user explicitly asks for a different model or there is a clear task-specific reason. You should follow the rules and guidelines below to use this tool.
|
||||
|
||||
Only use `spawn_agent` if and only if the user explicitly asks for sub-agents, delegation, or parallel agent work.
|
||||
Requests for depth, thoroughness, research, investigation, or detailed codebase analysis do not count as permission to spawn.
|
||||
Do not spawn sub-agents unless the user explicitly asks for sub-agents, delegation, or parallel agent work.
|
||||
{agent_role_usage_hint}
|
||||
|
||||
### When to delegate vs. do the subtask yourself
|
||||
- First, quickly analyze the overall user task and form a succinct high-level plan. Identify which tasks are immediate blockers on the critical path, and which tasks are sidecar tasks that are needed but can run in parallel without blocking the next local step. As part of that plan, explicitly decide what immediate task you should do locally right now. Do this planning step before delegating to agents so you do not hand off the immediate blocking task to a submodel and then waste time waiting on it.
|
||||
- Use a subagent when a subtask is easy enough for it to handle and can run in parallel with your local work. Prefer delegating concrete, bounded sidecar tasks that materially advance the main task without blocking your immediate next local step.
|
||||
- Do not delegate urgent blocking work when your immediate next step depends on that result. If the very next action is blocked on that task, the main rollout should usually do it locally to keep the critical path moving.
|
||||
- Keep work local when the subtask is too difficult to delegate well and when it is tightly coupled, urgent, or likely to block your immediate next step.
|
||||
|
||||
### Designing delegated subtasks
|
||||
- Subtasks must be concrete, well-defined, and self-contained.
|
||||
- Delegated subtasks must materially advance the main task.
|
||||
|
||||
@@ -71,7 +71,7 @@ impl RequestPermissionsHandler {
|
||||
));
|
||||
};
|
||||
let mut args: RequestPermissionsArgs =
|
||||
parse_arguments_with_base_path(&arguments, &turn_environment.cwd)?;
|
||||
parse_arguments_with_base_path(&arguments, turn_environment.cwd())?;
|
||||
args.permissions = normalize_additional_permissions(args.permissions.into())
|
||||
.map(codex_protocol::request_permissions::RequestPermissionProfile::from)
|
||||
.map_err(FunctionCallError::RespondToModel)?;
|
||||
|
||||
@@ -6,6 +6,8 @@ use codex_tools::ToolSpec;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub const REQUEST_USER_INPUT_TOOL_NAME: &str = "request_user_input";
|
||||
pub const MIN_AUTO_RESOLUTION_MS: u64 = 60_000;
|
||||
pub const MAX_AUTO_RESOLUTION_MS: u64 = 240_000;
|
||||
|
||||
pub fn create_request_user_input_tool(description: String) -> ToolSpec {
|
||||
let option_props = BTreeMap::from([
|
||||
@@ -66,7 +68,14 @@ pub fn create_request_user_input_tool(description: String) -> ToolSpec {
|
||||
Some("Questions to show the user. Prefer 1 and do not exceed 3".to_string()),
|
||||
);
|
||||
|
||||
let properties = BTreeMap::from([("questions".to_string(), questions_schema)]);
|
||||
let auto_resolution_ms_schema = JsonSchema::number(Some(format!(
|
||||
"Optional auto-resolution window in milliseconds, from {MIN_AUTO_RESOLUTION_MS} to {MAX_AUTO_RESOLUTION_MS}. Include this only when the question is useful but non-blocking and continuing with best judgment is acceptable if the user does not answer; omit it when explicit user input is required before continuing. Use {MIN_AUTO_RESOLUTION_MS} for lightly helpful context and up to {MAX_AUTO_RESOLUTION_MS} when the answer would materially unblock better work."
|
||||
)));
|
||||
|
||||
let properties = BTreeMap::from([
|
||||
("questions".to_string(), questions_schema),
|
||||
("autoResolutionMs".to_string(), auto_resolution_ms_schema),
|
||||
]);
|
||||
|
||||
ToolSpec::Function(ResponsesApiTool {
|
||||
name: REQUEST_USER_INPUT_TOOL_NAME.to_string(),
|
||||
@@ -111,13 +120,26 @@ pub fn normalize_request_user_input_args(
|
||||
question.is_other = true;
|
||||
}
|
||||
|
||||
if let Some(auto_resolution_ms) = args.auto_resolution_ms {
|
||||
let clamped_auto_resolution_ms =
|
||||
auto_resolution_ms.clamp(MIN_AUTO_RESOLUTION_MS, MAX_AUTO_RESOLUTION_MS);
|
||||
if clamped_auto_resolution_ms != auto_resolution_ms {
|
||||
tracing::warn!(
|
||||
auto_resolution_ms,
|
||||
clamped_auto_resolution_ms,
|
||||
"clamped request_user_input autoResolutionMs to supported range"
|
||||
);
|
||||
args.auto_resolution_ms = Some(clamped_auto_resolution_ms);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
pub fn request_user_input_tool_description(available_modes: &[ModeKind]) -> String {
|
||||
let allowed_modes = format_allowed_modes(available_modes);
|
||||
format!(
|
||||
"Request user input for one to three short questions and wait for the response. This tool is only available in {allowed_modes}."
|
||||
"Request user input for one to three short questions and wait for the response. Set autoResolutionMs, from {MIN_AUTO_RESOLUTION_MS} to {MAX_AUTO_RESOLUTION_MS} milliseconds, only when the question is useful but non-blocking and continuing with best judgment is acceptable if the user does not answer; omit it when explicit user input is required. This tool is only available in {allowed_modes}."
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ use super::*;
|
||||
use codex_features::Feature;
|
||||
use codex_features::Features;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::request_user_input::RequestUserInputQuestion;
|
||||
use codex_protocol::request_user_input::RequestUserInputQuestionOption;
|
||||
use codex_tools::JsonSchema;
|
||||
use codex_tools::request_user_input_available_modes;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -26,7 +28,15 @@ fn request_user_input_tool_includes_questions_schema() {
|
||||
description: "Ask the user to choose.".to_string(),
|
||||
strict: false,
|
||||
defer_loading: None,
|
||||
parameters: JsonSchema::object(BTreeMap::from([(
|
||||
parameters: JsonSchema::object(BTreeMap::from([
|
||||
(
|
||||
"autoResolutionMs".to_string(),
|
||||
JsonSchema::number(Some(
|
||||
"Optional auto-resolution window in milliseconds, from 60000 to 240000. Include this only when the question is useful but non-blocking and continuing with best judgment is acceptable if the user does not answer; omit it when explicit user input is required before continuing. Use 60000 for lightly helpful context and up to 240000 when the answer would materially unblock better work."
|
||||
.to_string(),
|
||||
)),
|
||||
),
|
||||
(
|
||||
"questions".to_string(),
|
||||
JsonSchema::array(
|
||||
JsonSchema::object(
|
||||
@@ -96,12 +106,97 @@ fn request_user_input_tool_includes_questions_schema() {
|
||||
"Questions to show the user. Prefer 1 and do not exceed 3".to_string(),
|
||||
),
|
||||
),
|
||||
)]), Some(vec!["questions".to_string()]), Some(false.into())),
|
||||
),
|
||||
]), Some(vec!["questions".to_string()]), Some(false.into())),
|
||||
output_schema: None,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_request_user_input_args_clamps_out_of_range_auto_resolution_ms() {
|
||||
let args = RequestUserInputArgs {
|
||||
questions: vec![RequestUserInputQuestion {
|
||||
id: "confirm".to_string(),
|
||||
header: "Confirm".to_string(),
|
||||
question: "Proceed?".to_string(),
|
||||
is_other: false,
|
||||
is_secret: false,
|
||||
options: Some(vec![RequestUserInputQuestionOption {
|
||||
label: "Yes (Recommended)".to_string(),
|
||||
description: "Continue.".to_string(),
|
||||
}]),
|
||||
}],
|
||||
auto_resolution_ms: Some(MIN_AUTO_RESOLUTION_MS - 1),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
normalize_request_user_input_args(args.clone()),
|
||||
Ok(RequestUserInputArgs {
|
||||
questions: vec![RequestUserInputQuestion {
|
||||
is_other: true,
|
||||
..args.questions[0].clone()
|
||||
}],
|
||||
auto_resolution_ms: Some(MIN_AUTO_RESOLUTION_MS),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_request_user_input_args(RequestUserInputArgs {
|
||||
auto_resolution_ms: Some(MAX_AUTO_RESOLUTION_MS + 1),
|
||||
..args.clone()
|
||||
}),
|
||||
Ok(RequestUserInputArgs {
|
||||
questions: vec![RequestUserInputQuestion {
|
||||
is_other: true,
|
||||
..args.questions[0].clone()
|
||||
}],
|
||||
auto_resolution_ms: Some(MAX_AUTO_RESOLUTION_MS),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_request_user_input_args_accepts_auto_resolution_boundaries() {
|
||||
let args = RequestUserInputArgs {
|
||||
questions: vec![RequestUserInputQuestion {
|
||||
id: "confirm".to_string(),
|
||||
header: "Confirm".to_string(),
|
||||
question: "Proceed?".to_string(),
|
||||
is_other: false,
|
||||
is_secret: false,
|
||||
options: Some(vec![RequestUserInputQuestionOption {
|
||||
label: "Yes (Recommended)".to_string(),
|
||||
description: "Continue.".to_string(),
|
||||
}]),
|
||||
}],
|
||||
auto_resolution_ms: Some(MIN_AUTO_RESOLUTION_MS),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
normalize_request_user_input_args(args.clone()),
|
||||
Ok(RequestUserInputArgs {
|
||||
questions: vec![RequestUserInputQuestion {
|
||||
is_other: true,
|
||||
..args.questions[0].clone()
|
||||
}],
|
||||
auto_resolution_ms: Some(MIN_AUTO_RESOLUTION_MS),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_request_user_input_args(RequestUserInputArgs {
|
||||
auto_resolution_ms: Some(MAX_AUTO_RESOLUTION_MS),
|
||||
..args.clone()
|
||||
}),
|
||||
Ok(RequestUserInputArgs {
|
||||
questions: vec![RequestUserInputQuestion {
|
||||
is_other: true,
|
||||
..args.questions[0].clone()
|
||||
}],
|
||||
auto_resolution_ms: Some(MAX_AUTO_RESOLUTION_MS),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_user_input_unavailable_messages_respect_default_mode_feature_flag() {
|
||||
assert_eq!(
|
||||
@@ -136,10 +231,10 @@ fn request_user_input_unavailable_messages_respect_default_mode_feature_flag() {
|
||||
fn request_user_input_tool_description_mentions_available_modes() {
|
||||
assert_eq!(
|
||||
request_user_input_tool_description(&default_available_modes()),
|
||||
"Request user input for one to three short questions and wait for the response. This tool is only available in Plan mode.".to_string()
|
||||
"Request user input for one to three short questions and wait for the response. Set autoResolutionMs, from 60000 to 240000 milliseconds, only when the question is useful but non-blocking and continuing with best judgment is acceptable if the user does not answer; omit it when explicit user input is required. This tool is only available in Plan mode.".to_string()
|
||||
);
|
||||
assert_eq!(
|
||||
request_user_input_tool_description(&default_mode_enabled_available_modes()),
|
||||
"Request user input for one to three short questions and wait for the response. This tool is only available in Default or Plan mode.".to_string()
|
||||
"Request user input for one to three short questions and wait for the response. Set autoResolutionMs, from 60000 to 240000 milliseconds, only when the question is useful but non-blocking and continuing with best judgment is acceptable if the user does not answer; omit it when explicit user input is required. This tool is only available in Default or Plan mode.".to_string()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -134,8 +134,8 @@ impl ExecCommandHandler {
|
||||
.as_deref()
|
||||
.filter(|workdir| !workdir.is_empty())
|
||||
.map_or_else(
|
||||
|| turn_environment.cwd.clone(),
|
||||
|workdir| turn_environment.cwd.join(workdir),
|
||||
|| turn_environment.cwd().clone(),
|
||||
|workdir| turn_environment.cwd().join(workdir),
|
||||
);
|
||||
let environment = Arc::clone(&turn_environment.environment);
|
||||
let fs = environment.get_filesystem();
|
||||
@@ -151,9 +151,16 @@ impl ExecCommandHandler {
|
||||
let process_id = manager.allocate_process_id().await;
|
||||
let shell_mode =
|
||||
shell_mode_for_environment(&turn.unified_exec_shell_mode, environment.as_ref());
|
||||
// Remote environments may use a different OS and must build commands with their native
|
||||
// shell; fall back to the session shell when the environment did not report one.
|
||||
let shell = turn_environment
|
||||
.shell
|
||||
.clone()
|
||||
.map(Arc::new)
|
||||
.unwrap_or_else(|| session.user_shell());
|
||||
let resolved_command = get_command(
|
||||
&args,
|
||||
session.user_shell(),
|
||||
shell,
|
||||
&shell_mode,
|
||||
turn.config.permissions.allow_login_shell,
|
||||
)
|
||||
@@ -270,7 +277,7 @@ impl ExecCommandHandler {
|
||||
yield_time_ms,
|
||||
max_output_tokens,
|
||||
cwd,
|
||||
sandbox_cwd: turn_environment.cwd.clone(),
|
||||
sandbox_cwd: turn_environment.cwd().clone(),
|
||||
environment,
|
||||
shell_mode,
|
||||
network: context.turn.network.clone(),
|
||||
|
||||
@@ -143,16 +143,14 @@ impl ViewImageHandler {
|
||||
"view_image is unavailable in this session".to_string(),
|
||||
));
|
||||
};
|
||||
let cwd = turn_environment.cwd.clone();
|
||||
let cwd = turn_environment.cwd().clone();
|
||||
let abs_path = cwd.join(path);
|
||||
let sandbox = turn.file_system_sandbox_context(/*additional_permissions*/ None, &cwd);
|
||||
let sandbox = turn.file_system_sandbox_context(
|
||||
/*additional_permissions*/ None,
|
||||
turn_environment.cwd_uri(),
|
||||
);
|
||||
let fs = turn_environment.environment.get_filesystem();
|
||||
let path_uri = PathUri::from_abs_path(&abs_path).map_err(|error| {
|
||||
FunctionCallError::RespondToModel(format!(
|
||||
"unable to locate image at `{}`: {error}",
|
||||
abs_path.display()
|
||||
))
|
||||
})?;
|
||||
let path_uri = PathUri::from_abs_path(&abs_path);
|
||||
|
||||
let metadata = fs
|
||||
.get_metadata(&path_uri, Some(&sandbox))
|
||||
@@ -268,16 +266,33 @@ impl ToolOutput for ViewImageOutput {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::session::tests::make_session_and_context;
|
||||
use crate::session::turn_context::TurnEnvironment;
|
||||
use crate::tools::context::ToolCallSource;
|
||||
use crate::tools::context::ToolInvocation;
|
||||
use crate::turn_diff_tracker::TurnDiffTracker;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use core_test_support::TempDirExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
fn replace_primary_environment_cwd(turn: &mut crate::TurnContext, cwd: AbsolutePathBuf) {
|
||||
let current = turn
|
||||
.environments
|
||||
.turn_environments
|
||||
.first()
|
||||
.cloned()
|
||||
.expect("default local turn environment");
|
||||
turn.environments.turn_environments[0] = TurnEnvironment::new(
|
||||
current.environment_id,
|
||||
current.environment,
|
||||
cwd,
|
||||
current.shell,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_preview_omits_image_data() {
|
||||
let output = ViewImageOutput {
|
||||
@@ -314,11 +329,7 @@ mod tests {
|
||||
let image_dir = tempfile::tempdir().expect("create image temp dir");
|
||||
let image_cwd = image_dir.abs();
|
||||
|
||||
turn.environments
|
||||
.turn_environments
|
||||
.first_mut()
|
||||
.expect("default local turn environment")
|
||||
.cwd = image_cwd.clone();
|
||||
replace_primary_environment_cwd(&mut turn, image_cwd.clone());
|
||||
let image_path = image_cwd.join("image.png");
|
||||
std::fs::write(image_path.as_path(), b"not a real image").expect("write test image");
|
||||
turn.permission_profile = PermissionProfile::read_only();
|
||||
@@ -381,11 +392,7 @@ mod tests {
|
||||
let image_dir = tempfile::tempdir().expect("create image temp dir");
|
||||
let image_cwd = image_dir.abs();
|
||||
|
||||
turn.environments
|
||||
.turn_environments
|
||||
.first_mut()
|
||||
.expect("default local turn environment")
|
||||
.cwd = image_cwd.clone();
|
||||
replace_primary_environment_cwd(&mut turn, image_cwd.clone());
|
||||
let image_path = image_cwd.join("image.png");
|
||||
std::fs::write(image_path.as_path(), b"not a real image").expect("write test image");
|
||||
turn.permission_profile = PermissionProfile::Disabled;
|
||||
|
||||
@@ -39,6 +39,7 @@ use codex_protocol::protocol::NetworkPolicyRuleAction;
|
||||
use codex_protocol::protocol::ReviewDecision;
|
||||
use codex_sandboxing::SandboxManager;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::time::Instant;
|
||||
|
||||
pub(crate) struct ToolOrchestrator {
|
||||
@@ -239,13 +240,14 @@ impl ToolOrchestrator {
|
||||
let use_legacy_landlock = turn_ctx.features.use_legacy_landlock();
|
||||
#[allow(deprecated)]
|
||||
let sandbox_cwd = tool.sandbox_cwd(req).unwrap_or(&turn_ctx.cwd);
|
||||
let sandbox_policy_cwd = PathUri::from_abs_path(sandbox_cwd);
|
||||
let workspace_roots = turn_ctx.config.effective_workspace_roots();
|
||||
let initial_attempt = SandboxAttempt {
|
||||
sandbox: initial_sandbox,
|
||||
permissions: &turn_ctx.permission_profile,
|
||||
enforce_managed_network: managed_network_active,
|
||||
manager: &self.sandbox,
|
||||
sandbox_cwd,
|
||||
sandbox_cwd: &sandbox_policy_cwd,
|
||||
workspace_roots: workspace_roots.as_slice(),
|
||||
codex_linux_sandbox_exe: turn_ctx.codex_linux_sandbox_exe.as_ref(),
|
||||
use_legacy_landlock,
|
||||
@@ -418,7 +420,7 @@ impl ToolOrchestrator {
|
||||
permissions: &turn_ctx.permission_profile,
|
||||
enforce_managed_network: managed_network_active,
|
||||
manager: &self.sandbox,
|
||||
sandbox_cwd,
|
||||
sandbox_cwd: &sandbox_policy_cwd,
|
||||
workspace_roots: workspace_roots.as_slice(),
|
||||
codex_linux_sandbox_exe: retry_codex_linux_sandbox_exe,
|
||||
use_legacy_landlock,
|
||||
|
||||
@@ -11,16 +11,17 @@ use codex_sandboxing::SandboxManager;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_sandboxing::policy_transforms::effective_file_system_sandbox_policy;
|
||||
use codex_sandboxing::policy_transforms::effective_network_sandbox_policy;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use core_test_support::PathBufExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
fn test_turn_environment(environment_id: &str) -> crate::session::turn_context::TurnEnvironment {
|
||||
crate::session::turn_context::TurnEnvironment {
|
||||
environment_id: environment_id.to_string(),
|
||||
environment: std::sync::Arc::new(codex_exec_server::Environment::default_for_tests()),
|
||||
cwd: std::env::temp_dir().abs(),
|
||||
shell: None,
|
||||
}
|
||||
crate::session::turn_context::TurnEnvironment::new(
|
||||
environment_id.to_string(),
|
||||
std::sync::Arc::new(codex_exec_server::Environment::default_for_tests()),
|
||||
std::env::temp_dir().abs(),
|
||||
/*shell*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -206,12 +207,13 @@ async fn file_system_sandbox_context_uses_active_attempt() {
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
);
|
||||
let manager = SandboxManager::new();
|
||||
let sandbox_policy_cwd = PathUri::from_abs_path(&path);
|
||||
let attempt = SandboxAttempt {
|
||||
sandbox: SandboxType::MacosSeatbelt,
|
||||
permissions: &permissions,
|
||||
enforce_managed_network: false,
|
||||
manager: &manager,
|
||||
sandbox_cwd: &path,
|
||||
sandbox_cwd: &sandbox_policy_cwd,
|
||||
workspace_roots: std::slice::from_ref(&path),
|
||||
codex_linux_sandbox_exe: None,
|
||||
use_legacy_landlock: true,
|
||||
@@ -232,7 +234,10 @@ async fn file_system_sandbox_context_uses_active_attempt() {
|
||||
let expected_permissions =
|
||||
PermissionProfile::from_runtime_permissions(&file_system_policy, network_policy);
|
||||
assert_eq!(sandbox.permissions, expected_permissions);
|
||||
assert_eq!(sandbox.cwd, Some(path.clone()));
|
||||
assert_eq!(
|
||||
sandbox.cwd,
|
||||
Some(codex_utils_path_uri::PathUri::from_abs_path(&path))
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox.windows_sandbox_level,
|
||||
WindowsSandboxLevel::RestrictedToken
|
||||
@@ -260,12 +265,13 @@ async fn no_sandbox_attempt_has_no_file_system_context() {
|
||||
};
|
||||
let permissions = PermissionProfile::Disabled;
|
||||
let manager = SandboxManager::new();
|
||||
let sandbox_policy_cwd = PathUri::from_abs_path(&path);
|
||||
let attempt = SandboxAttempt {
|
||||
sandbox: SandboxType::None,
|
||||
permissions: &permissions,
|
||||
enforce_managed_network: false,
|
||||
manager: &manager,
|
||||
sandbox_cwd: &path,
|
||||
sandbox_cwd: &sandbox_policy_cwd,
|
||||
workspace_roots: std::slice::from_ref(&path),
|
||||
codex_linux_sandbox_exe: None,
|
||||
use_legacy_landlock: false,
|
||||
|
||||
@@ -25,6 +25,7 @@ use codex_protocol::models::AdditionalPermissionProfile;
|
||||
use codex_sandboxing::SandboxCommand;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::collections::HashMap;
|
||||
#[cfg(unix)]
|
||||
use std::path::Path;
|
||||
@@ -33,8 +34,8 @@ pub(crate) mod apply_patch;
|
||||
pub(crate) mod shell;
|
||||
pub(crate) mod unified_exec;
|
||||
|
||||
/// Shared helper to construct sandbox transform inputs from a tokenized command line.
|
||||
/// Validates that at least a program is present.
|
||||
/// Shared helper to construct sandbox transform inputs from a tokenized command line and native
|
||||
/// working directory. Validates that at least a program is present.
|
||||
pub(crate) fn build_sandbox_command(
|
||||
command: &[String],
|
||||
cwd: &AbsolutePathBuf,
|
||||
@@ -44,10 +45,11 @@ pub(crate) fn build_sandbox_command(
|
||||
let (program, args) = command
|
||||
.split_first()
|
||||
.ok_or_else(|| ToolError::Rejected("command args are empty".to_string()))?;
|
||||
let cwd = PathUri::from_abs_path(cwd);
|
||||
Ok(SandboxCommand {
|
||||
program: program.clone().into(),
|
||||
args: args.to_vec(),
|
||||
cwd: cwd.clone(),
|
||||
cwd,
|
||||
env: env.clone(),
|
||||
additional_permissions,
|
||||
})
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::tools::sandboxing::managed_network_for_sandbox_permissions;
|
||||
use codex_network_proxy::CODEX_PROXY_GIT_SSH_COMMAND_MARKER;
|
||||
use codex_network_proxy::CUSTOM_CA_ENV_KEYS;
|
||||
use codex_network_proxy::ConfigReloader;
|
||||
use codex_network_proxy::ConfigReloaderFuture;
|
||||
use codex_network_proxy::ConfigState;
|
||||
use codex_network_proxy::NetworkProxy;
|
||||
use codex_network_proxy::NetworkProxyConfig;
|
||||
@@ -24,6 +25,7 @@ use codex_protocol::models::PermissionProfile;
|
||||
use codex_sandboxing::SandboxManager;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use core_test_support::PathBufExt;
|
||||
use core_test_support::PathExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -35,18 +37,17 @@ use tokio::sync::watch;
|
||||
|
||||
struct StaticReloader;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ConfigReloader for StaticReloader {
|
||||
fn source_label(&self) -> String {
|
||||
"test config state".to_string()
|
||||
}
|
||||
|
||||
async fn maybe_reload(&self) -> anyhow::Result<Option<ConfigState>> {
|
||||
Ok(None)
|
||||
fn maybe_reload(&self) -> ConfigReloaderFuture<'_, Option<ConfigState>> {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
async fn reload_now(&self) -> anyhow::Result<ConfigState> {
|
||||
Err(anyhow::anyhow!("force reload is not supported in tests"))
|
||||
fn reload_now(&self) -> ConfigReloaderFuture<'_, ConfigState> {
|
||||
Box::pin(async { Err(anyhow::anyhow!("force reload is not supported in tests")) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,18 +89,21 @@ async fn test_network_proxy() -> anyhow::Result<NetworkProxy> {
|
||||
async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow::Result<()> {
|
||||
let proxy = test_network_proxy().await?;
|
||||
let dir = tempdir().expect("create temp dir");
|
||||
let cwd = dir.path().abs();
|
||||
let command_cwd = dir.path().join("command").abs();
|
||||
let native_sandbox_policy_cwd = dir.path().join("sandbox-policy").abs();
|
||||
let mut env = HashMap::from([("CUSTOM_ENV".to_string(), "kept".to_string())]);
|
||||
proxy.apply_to_env(&mut env);
|
||||
|
||||
let command = vec!["/bin/echo".to_string(), "ok".to_string()];
|
||||
let command = build_sandbox_command(
|
||||
&command,
|
||||
&cwd,
|
||||
&command_cwd,
|
||||
&exec_env_for_sandbox_permissions(&env, SandboxPermissions::RequireEscalated),
|
||||
/*additional_permissions*/ None,
|
||||
)
|
||||
.expect("build sandbox command");
|
||||
assert_eq!(command.cwd, PathUri::from_abs_path(&command_cwd));
|
||||
let sandbox_policy_cwd = PathUri::from_abs_path(&native_sandbox_policy_cwd);
|
||||
let options = ExecOptions {
|
||||
expiration: ExecExpiration::DefaultTimeout,
|
||||
capture_policy: ExecCapturePolicy::ShellTool,
|
||||
@@ -111,8 +115,8 @@ async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow::
|
||||
permissions: &permissions,
|
||||
enforce_managed_network: false,
|
||||
manager: &manager,
|
||||
sandbox_cwd: &cwd,
|
||||
workspace_roots: std::slice::from_ref(&cwd),
|
||||
sandbox_cwd: &sandbox_policy_cwd,
|
||||
workspace_roots: std::slice::from_ref(&native_sandbox_policy_cwd),
|
||||
codex_linux_sandbox_exe: None,
|
||||
use_legacy_landlock: false,
|
||||
windows_sandbox_level: WindowsSandboxLevel::Disabled,
|
||||
@@ -131,6 +135,11 @@ async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow::
|
||||
)
|
||||
.expect("prepare exec request");
|
||||
|
||||
assert_eq!(exec_request.cwd, command_cwd);
|
||||
assert_eq!(
|
||||
exec_request.windows_sandbox_policy_cwd,
|
||||
native_sandbox_policy_cwd
|
||||
);
|
||||
assert_eq!(exec_request.network, None);
|
||||
for key in PROXY_ENV_KEYS {
|
||||
assert_eq!(exec_request.env.get(*key), None, "{key} should be unset");
|
||||
|
||||
@@ -310,7 +310,7 @@ impl ToolRuntime<ShellRequest, ExecToolCallOutput> for ShellRuntime {
|
||||
};
|
||||
let env = attempt
|
||||
.env_for(command, options, managed_network)
|
||||
.map_err(|err| ToolError::Codex(err.into()))?;
|
||||
.map_err(ToolError::Codex)?;
|
||||
let out = execute_env(env, Self::stdout_stream(ctx))
|
||||
.await
|
||||
.map_err(ToolError::Codex)?;
|
||||
|
||||
@@ -56,14 +56,17 @@ use codex_shell_escalation::EscalationDecision;
|
||||
use codex_shell_escalation::EscalationExecution;
|
||||
use codex_shell_escalation::EscalationPermissions;
|
||||
use codex_shell_escalation::EscalationPolicy;
|
||||
use codex_shell_escalation::EscalationPolicyFuture;
|
||||
use codex_shell_escalation::EscalationSession;
|
||||
use codex_shell_escalation::ExecParams;
|
||||
use codex_shell_escalation::ExecResult;
|
||||
use codex_shell_escalation::PreparedExec;
|
||||
use codex_shell_escalation::ResolvedPermissionProfile;
|
||||
use codex_shell_escalation::ShellCommandExecutor;
|
||||
use codex_shell_escalation::ShellCommandExecutorFuture;
|
||||
use codex_shell_escalation::Stopwatch;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
@@ -141,7 +144,7 @@ pub(super) async fn try_run_zsh_fork(
|
||||
options,
|
||||
managed_network_for_sandbox_permissions(req.network.as_ref(), req.sandbox_permissions),
|
||||
)
|
||||
.map_err(|err| ToolError::Codex(err.into()))?;
|
||||
.map_err(ToolError::Codex)?;
|
||||
let crate::sandboxing::ExecRequest {
|
||||
command,
|
||||
cwd: sandbox_cwd,
|
||||
@@ -597,8 +600,7 @@ impl CoreShellActionProvider {
|
||||
// execve interception.
|
||||
const ENABLE_INTERCEPTED_EXEC_POLICY_SHELL_WRAPPER_PARSING: bool = false;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl EscalationPolicy for CoreShellActionProvider {
|
||||
impl CoreShellActionProvider {
|
||||
async fn determine_action(
|
||||
&self,
|
||||
program: &AbsolutePathBuf,
|
||||
@@ -665,6 +667,19 @@ impl EscalationPolicy for CoreShellActionProvider {
|
||||
}
|
||||
}
|
||||
|
||||
impl EscalationPolicy for CoreShellActionProvider {
|
||||
fn determine_action<'a>(
|
||||
&'a self,
|
||||
program: &'a AbsolutePathBuf,
|
||||
argv: &'a [String],
|
||||
workdir: &'a AbsolutePathBuf,
|
||||
) -> EscalationPolicyFuture<'a> {
|
||||
Box::pin(CoreShellActionProvider::determine_action(
|
||||
self, program, argv, workdir,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn evaluate_intercepted_exec_policy(
|
||||
policy: &Policy,
|
||||
program: &AbsolutePathBuf,
|
||||
@@ -787,15 +802,43 @@ struct PrepareSandboxedExecParams<'a> {
|
||||
additional_permissions: Option<AdditionalPermissionProfile>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ShellCommandExecutor for CoreShellCommandExecutor {
|
||||
async fn run(
|
||||
fn run(
|
||||
&self,
|
||||
_command: Vec<String>,
|
||||
_cwd: PathBuf,
|
||||
env_overlay: HashMap<String, String>,
|
||||
cancel_rx: CancellationToken,
|
||||
after_spawn: Option<Box<dyn FnOnce() + Send>>,
|
||||
) -> ShellCommandExecutorFuture<'_, ExecResult> {
|
||||
Box::pin(CoreShellCommandExecutor::run(
|
||||
self,
|
||||
env_overlay,
|
||||
cancel_rx,
|
||||
after_spawn,
|
||||
))
|
||||
}
|
||||
|
||||
fn prepare_escalated_exec<'a>(
|
||||
&'a self,
|
||||
program: &'a AbsolutePathBuf,
|
||||
argv: &'a [String],
|
||||
workdir: &'a AbsolutePathBuf,
|
||||
env: HashMap<String, String>,
|
||||
execution: EscalationExecution,
|
||||
) -> ShellCommandExecutorFuture<'a, PreparedExec> {
|
||||
Box::pin(CoreShellCommandExecutor::prepare_escalated_exec(
|
||||
self, program, argv, workdir, env, execution,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl CoreShellCommandExecutor {
|
||||
async fn run(
|
||||
&self,
|
||||
env_overlay: HashMap<String, String>,
|
||||
cancel_rx: CancellationToken,
|
||||
after_spawn: Option<Box<dyn FnOnce() + Send>>,
|
||||
) -> anyhow::Result<ExecResult> {
|
||||
let mut exec_env = self.env.clone();
|
||||
// `env_overlay` comes from `EscalationSession::env()`, so merge only the
|
||||
@@ -900,9 +943,7 @@ impl ShellCommandExecutor for CoreShellCommandExecutor {
|
||||
|
||||
Ok(prepared)
|
||||
}
|
||||
}
|
||||
|
||||
impl CoreShellCommandExecutor {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn prepare_sandboxed_exec(
|
||||
&self,
|
||||
@@ -928,10 +969,12 @@ impl CoreShellCommandExecutor {
|
||||
self.windows_sandbox_level,
|
||||
self.network.is_some(),
|
||||
);
|
||||
let cwd = PathUri::from_abs_path(workdir);
|
||||
let sandbox_policy_cwd = PathUri::from_abs_path(&self.sandbox_policy_cwd);
|
||||
let command = SandboxCommand {
|
||||
program: program.clone().into(),
|
||||
args: args.to_vec(),
|
||||
cwd: workdir.clone(),
|
||||
cwd,
|
||||
env,
|
||||
additional_permissions,
|
||||
};
|
||||
@@ -945,7 +988,7 @@ impl CoreShellCommandExecutor {
|
||||
sandbox,
|
||||
enforce_managed_network: self.network.is_some(),
|
||||
network: self.network.as_ref(),
|
||||
sandbox_policy_cwd: &self.sandbox_policy_cwd,
|
||||
sandbox_policy_cwd: &sandbox_policy_cwd,
|
||||
codex_linux_sandbox_exe: self.codex_linux_sandbox_exe.as_deref(),
|
||||
use_legacy_landlock: self.use_legacy_landlock,
|
||||
windows_sandbox_level: self.windows_sandbox_level,
|
||||
@@ -954,7 +997,6 @@ impl CoreShellCommandExecutor {
|
||||
let mut exec_request = crate::sandboxing::ExecRequest::from_sandbox_exec_request(
|
||||
exec_request,
|
||||
options,
|
||||
self.sandbox_policy_cwd.clone(),
|
||||
self.windows_sandbox_workspace_roots.clone(),
|
||||
);
|
||||
if let Some(network) = exec_request.network.as_ref() {
|
||||
|
||||
@@ -38,7 +38,6 @@ use codex_shell_escalation::EscalationExecution;
|
||||
use codex_shell_escalation::EscalationPermissions;
|
||||
use codex_shell_escalation::ExecResult;
|
||||
use codex_shell_escalation::ResolvedPermissionProfile;
|
||||
use codex_shell_escalation::ShellCommandExecutor;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -326,11 +326,16 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
|
||||
if let UnifiedExecShellMode::ZshFork(zsh_fork_config) = &self.shell_mode {
|
||||
let command =
|
||||
build_sandbox_command(&command, &req.cwd, &env, req.additional_permissions.clone())
|
||||
.map_err(|_| ToolError::Rejected("missing command line for PTY".to_string()))?;
|
||||
.map_err(|error| match error {
|
||||
ToolError::Rejected(_) => {
|
||||
ToolError::Rejected("missing command line for PTY".to_string())
|
||||
}
|
||||
error @ ToolError::Codex(_) => error,
|
||||
})?;
|
||||
let options = unified_exec_options(attempt.network_denial_cancellation_token.clone());
|
||||
let mut exec_env = attempt
|
||||
.env_for(command, options, managed_network)
|
||||
.map_err(|err| ToolError::Codex(err.into()))?;
|
||||
.map_err(ToolError::Codex)?;
|
||||
exec_env.exec_server_env_config = req.exec_server_env_config.clone();
|
||||
match zsh_fork_backend::maybe_prepare_unified_exec(
|
||||
req,
|
||||
@@ -377,11 +382,16 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
|
||||
}
|
||||
let command =
|
||||
build_sandbox_command(&command, &req.cwd, &env, req.additional_permissions.clone())
|
||||
.map_err(|_| ToolError::Rejected("missing command line for PTY".to_string()))?;
|
||||
.map_err(|error| match error {
|
||||
ToolError::Rejected(_) => {
|
||||
ToolError::Rejected("missing command line for PTY".to_string())
|
||||
}
|
||||
error @ ToolError::Codex(_) => error,
|
||||
})?;
|
||||
let options = unified_exec_options(attempt.network_denial_cancellation_token.clone());
|
||||
let mut exec_env = attempt
|
||||
.env_for(command, options, managed_network)
|
||||
.map_err(|err| ToolError::Codex(err.into()))?;
|
||||
.map_err(ToolError::Codex)?;
|
||||
exec_env.exec_server_env_config = req.exec_server_env_config.clone();
|
||||
self.manager
|
||||
.open_session_with_exec_env(
|
||||
|
||||
@@ -21,12 +21,12 @@ use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::ReviewDecision;
|
||||
use codex_sandboxing::SandboxCommand;
|
||||
use codex_sandboxing::SandboxManager;
|
||||
use codex_sandboxing::SandboxTransformError;
|
||||
use codex_sandboxing::SandboxTransformRequest;
|
||||
use codex_sandboxing::SandboxType;
|
||||
use codex_sandboxing::SandboxablePreference;
|
||||
use codex_tools::ToolName;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use futures::Future;
|
||||
use futures::future::BoxFuture;
|
||||
use serde::Serialize;
|
||||
@@ -411,7 +411,7 @@ pub(crate) struct SandboxAttempt<'a> {
|
||||
pub permissions: &'a codex_protocol::models::PermissionProfile,
|
||||
pub enforce_managed_network: bool,
|
||||
pub(crate) manager: &'a SandboxManager,
|
||||
pub(crate) sandbox_cwd: &'a AbsolutePathBuf,
|
||||
pub(crate) sandbox_cwd: &'a PathUri,
|
||||
pub(crate) workspace_roots: &'a [AbsolutePathBuf],
|
||||
pub codex_linux_sandbox_exe: Option<&'a std::path::PathBuf>,
|
||||
pub use_legacy_landlock: bool,
|
||||
@@ -426,8 +426,9 @@ impl<'a> SandboxAttempt<'a> {
|
||||
command: SandboxCommand,
|
||||
options: ExecOptions,
|
||||
network: Option<&NetworkProxy>,
|
||||
) -> Result<crate::sandboxing::ExecRequest, SandboxTransformError> {
|
||||
self.manager
|
||||
) -> Result<crate::sandboxing::ExecRequest, CodexErr> {
|
||||
let request = self
|
||||
.manager
|
||||
.transform(SandboxTransformRequest {
|
||||
command,
|
||||
permissions: self.permissions,
|
||||
@@ -442,19 +443,12 @@ impl<'a> SandboxAttempt<'a> {
|
||||
windows_sandbox_level: self.windows_sandbox_level,
|
||||
windows_sandbox_private_desktop: self.windows_sandbox_private_desktop,
|
||||
})
|
||||
.map(|request| {
|
||||
let windows_sandbox_policy_cwd =
|
||||
codex_utils_absolute_path::AbsolutePathBuf::try_from(
|
||||
self.sandbox_cwd.to_path_buf(),
|
||||
)
|
||||
.unwrap_or_else(|_| request.cwd.clone());
|
||||
crate::sandboxing::ExecRequest::from_sandbox_exec_request(
|
||||
request,
|
||||
options,
|
||||
windows_sandbox_policy_cwd,
|
||||
self.workspace_roots.to_vec(),
|
||||
)
|
||||
})
|
||||
.map_err(CodexErr::from)?;
|
||||
Ok(crate::sandboxing::ExecRequest::from_sandbox_exec_request(
|
||||
request,
|
||||
options,
|
||||
self.workspace_roots.to_vec(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -643,9 +643,12 @@ fn add_core_utility_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mut
|
||||
planned_tools.add(PlanHandler);
|
||||
|
||||
if turn_context.config.experimental_request_user_input_enabled {
|
||||
planned_tools.add(RequestUserInputHandler {
|
||||
available_modes: request_user_input_available_modes(features),
|
||||
});
|
||||
planned_tools.add_with_exposure(
|
||||
RequestUserInputHandler {
|
||||
available_modes: request_user_input_available_modes(features),
|
||||
},
|
||||
ToolExposure::DirectModelOnly,
|
||||
);
|
||||
}
|
||||
|
||||
if features.enabled(Feature::RequestPermissionsTool) {
|
||||
@@ -654,7 +657,7 @@ fn add_core_utility_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mut
|
||||
|
||||
if features.enabled(Feature::TokenBudget) {
|
||||
planned_tools.add_with_exposure(NewContextWindowHandler, ToolExposure::DirectModelOnly);
|
||||
planned_tools.add_with_exposure(GetContextRemainingHandler, ToolExposure::DirectModelOnly);
|
||||
planned_tools.add(GetContextRemainingHandler);
|
||||
}
|
||||
|
||||
if tool_suggest_enabled(turn_context)
|
||||
|
||||
@@ -431,6 +431,10 @@ async fn request_user_input_tool_respects_experimental_config_gate() {
|
||||
let enabled = probe(|_| {}).await;
|
||||
enabled.assert_visible_contains(&["request_user_input"]);
|
||||
enabled.assert_registered_contains(&["request_user_input"]);
|
||||
assert_eq!(
|
||||
enabled.exposure("request_user_input"),
|
||||
ToolExposure::DirectModelOnly
|
||||
);
|
||||
|
||||
let disabled = probe(|turn| {
|
||||
update_config(turn, |config| {
|
||||
@@ -442,6 +446,30 @@ async fn request_user_input_tool_respects_experimental_config_gate() {
|
||||
disabled.assert_registered_lacks(&["request_user_input"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_user_input_stays_direct_in_code_mode_only() {
|
||||
let plan = probe(|turn| {
|
||||
set_features(turn, &[Feature::CodeMode, Feature::CodeModeOnly]);
|
||||
})
|
||||
.await;
|
||||
|
||||
plan.assert_visible_contains(&[
|
||||
"request_user_input",
|
||||
codex_code_mode::PUBLIC_TOOL_NAME,
|
||||
codex_code_mode::WAIT_TOOL_NAME,
|
||||
]);
|
||||
plan.assert_registered_contains(&["request_user_input"]);
|
||||
assert_eq!(
|
||||
plan.exposure("request_user_input"),
|
||||
ToolExposure::DirectModelOnly
|
||||
);
|
||||
|
||||
let ToolSpec::Freeform(exec) = plan.visible_spec(codex_code_mode::PUBLIC_TOOL_NAME) else {
|
||||
panic!("expected code mode exec tool");
|
||||
};
|
||||
assert!(!exec.description.contains("request_user_input"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shell_family_registers_visible_unified_exec_and_hidden_legacy_shell() {
|
||||
let plan = probe(|turn| {
|
||||
@@ -545,21 +573,21 @@ async fn zsh_fork_unified_exec_keeps_shell_parameter_when_remote_environment_ava
|
||||
.environments
|
||||
.primary()
|
||||
.expect("primary environment")
|
||||
.cwd
|
||||
.cwd()
|
||||
.clone();
|
||||
turn.environments
|
||||
.turn_environments
|
||||
.push(crate::session::turn_context::TurnEnvironment {
|
||||
environment_id: "remote".to_string(),
|
||||
environment: Arc::new(
|
||||
turn.environments.turn_environments.push(
|
||||
crate::session::turn_context::TurnEnvironment::new(
|
||||
"remote".to_string(),
|
||||
Arc::new(
|
||||
codex_exec_server::Environment::create_for_tests(Some(
|
||||
"ws://127.0.0.1:1/remote-exec-server".to_string(),
|
||||
))
|
||||
.expect("remote test environment"),
|
||||
),
|
||||
cwd: remote_cwd,
|
||||
shell: None,
|
||||
});
|
||||
remote_cwd,
|
||||
/*shell*/ None,
|
||||
),
|
||||
);
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1224,6 +1252,7 @@ async fn code_mode_only_can_expose_namespaced_multi_agent_v2_as_normal_tools() {
|
||||
vec![
|
||||
"exec",
|
||||
"wait",
|
||||
"request_user_input",
|
||||
"agents",
|
||||
// Hosted Responses tools.
|
||||
"web_search",
|
||||
@@ -1309,6 +1338,7 @@ async fn hosted_tools_follow_provider_auth_model_and_config_gates() {
|
||||
// Code-mode entrypoints.
|
||||
codex_code_mode::PUBLIC_TOOL_NAME,
|
||||
codex_code_mode::WAIT_TOOL_NAME,
|
||||
"request_user_input",
|
||||
// Multi-agent v2 tools.
|
||||
"spawn_agent",
|
||||
"send_message",
|
||||
|
||||
+124
-302
@@ -6,16 +6,15 @@ use std::sync::RwLock;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_analytics::CompactionImplementation;
|
||||
use codex_analytics::CompactionPhase;
|
||||
use codex_analytics::CompactionReason;
|
||||
use codex_analytics::CompactionStrategy;
|
||||
use codex_analytics::CompactionTrigger;
|
||||
use codex_utils_string::to_ascii_json_string;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use crate::responses_metadata::CodexResponsesMetadata;
|
||||
use crate::responses_metadata::CodexResponsesRequestKind;
|
||||
use crate::responses_metadata::TurnMetadataWorkspace;
|
||||
use crate::responses_metadata::filter_extra_metadata;
|
||||
use crate::responses_metadata::subagent_header_value;
|
||||
use crate::responses_metadata::subagent_metadata_kind;
|
||||
use crate::sandbox_tags::permission_profile_sandbox_tag;
|
||||
use codex_git_utils::get_git_remote_urls_assume_git_repo;
|
||||
use codex_git_utils::get_git_repo_root;
|
||||
@@ -26,62 +25,18 @@ use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadSource;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
const MODEL_KEY: &str = "model";
|
||||
const REASONING_EFFORT_KEY: &str = "reasoning_effort";
|
||||
const TURN_STARTED_AT_UNIX_MS_KEY: &str = "turn_started_at_unix_ms";
|
||||
const USER_INPUT_REQUESTED_DURING_TURN_KEY: &str = "user_input_requested_during_turn";
|
||||
const WORKSPACE_KIND_KEY: &str = "workspace_kind";
|
||||
const REQUEST_KIND_KEY: &str = "request_kind";
|
||||
const COMPACTION_KEY: &str = "compaction";
|
||||
const WINDOW_ID_KEY: &str = "window_id";
|
||||
|
||||
pub(crate) struct McpTurnMetadataContext<'a> {
|
||||
pub(crate) model: &'a str,
|
||||
pub(crate) reasoning_effort: Option<ReasoningEffortConfig>,
|
||||
}
|
||||
|
||||
/// Metadata present only on outbound model requests that perform compaction.
|
||||
///
|
||||
/// These fields describe the operation at dispatch time. Post-response outcomes such as status,
|
||||
/// error, duration, and token deltas remain in compaction analytics events.
|
||||
#[derive(Clone, Copy, Debug, Serialize)]
|
||||
pub(crate) struct CompactionTurnMetadata {
|
||||
trigger: CompactionTrigger,
|
||||
reason: CompactionReason,
|
||||
implementation: CompactionImplementation,
|
||||
phase: CompactionPhase,
|
||||
strategy: CompactionStrategy,
|
||||
}
|
||||
|
||||
impl CompactionTurnMetadata {
|
||||
pub(crate) fn new(
|
||||
trigger: CompactionTrigger,
|
||||
reason: CompactionReason,
|
||||
implementation: CompactionImplementation,
|
||||
phase: CompactionPhase,
|
||||
) -> Self {
|
||||
Self {
|
||||
trigger,
|
||||
reason,
|
||||
implementation,
|
||||
phase,
|
||||
strategy: CompactionStrategy::Memento,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum TurnMetadataRequestKind {
|
||||
Turn,
|
||||
Prewarm,
|
||||
Compaction,
|
||||
Memory,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct WorkspaceGitMetadata {
|
||||
associated_remote_urls: Option<BTreeMap<String, String>>,
|
||||
@@ -97,16 +52,6 @@ impl WorkspaceGitMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Default)]
|
||||
struct TurnMetadataWorkspace {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
associated_remote_urls: Option<BTreeMap<String, String>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
latest_git_commit_hash: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
has_changes: Option<bool>,
|
||||
}
|
||||
|
||||
impl From<WorkspaceGitMetadata> for TurnMetadataWorkspace {
|
||||
fn from(value: WorkspaceGitMetadata) -> Self {
|
||||
Self {
|
||||
@@ -117,141 +62,40 @@ impl From<WorkspaceGitMetadata> for TurnMetadataWorkspace {
|
||||
}
|
||||
}
|
||||
|
||||
/// Base payload for the outbound model request `x-codex-turn-metadata` header.
|
||||
///
|
||||
/// Turn-owned state populates identity fields, including optional fork and subagent lineage. A
|
||||
/// concrete request kind is added at outbound model dispatch so turns, startup prewarm, and
|
||||
/// compaction remain distinguishable. Detached memory requests are constructed as `memory`
|
||||
/// directly.
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct TurnMetadataBag {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
request_kind: Option<TurnMetadataRequestKind>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
session_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
thread_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
forked_from_thread_id: Option<ThreadId>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
parent_thread_id: Option<ThreadId>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
subagent_kind: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
thread_source: Option<ThreadSource>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
turn_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
workspaces: BTreeMap<String, TurnMetadataWorkspace>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
sandbox: Option<String>,
|
||||
}
|
||||
|
||||
impl TurnMetadataBag {
|
||||
fn with_workspace_git_metadata(
|
||||
mut self,
|
||||
repo_root: Option<String>,
|
||||
workspace_git_metadata: Option<WorkspaceGitMetadata>,
|
||||
) -> Self {
|
||||
if let (Some(repo_root), Some(workspace_git_metadata)) = (repo_root, workspace_git_metadata)
|
||||
&& !workspace_git_metadata.is_empty()
|
||||
{
|
||||
self.workspaces
|
||||
.insert(repo_root, workspace_git_metadata.into());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
fn to_header_value(&self) -> Option<String> {
|
||||
to_ascii_json_string(self).ok()
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_turn_metadata(
|
||||
header: &str,
|
||||
turn_started_at_unix_ms: Option<i64>,
|
||||
responsesapi_client_metadata: Option<&HashMap<String, String>>,
|
||||
) -> Option<String> {
|
||||
if turn_started_at_unix_ms.is_none() && responsesapi_client_metadata.is_none() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut metadata = serde_json::from_str::<serde_json::Map<String, Value>>(header).ok()?;
|
||||
if let Some(turn_started_at_unix_ms) = turn_started_at_unix_ms {
|
||||
metadata.insert(
|
||||
TURN_STARTED_AT_UNIX_MS_KEY.to_string(),
|
||||
Value::Number(turn_started_at_unix_ms.into()),
|
||||
);
|
||||
}
|
||||
if let Some(responsesapi_client_metadata) = responsesapi_client_metadata {
|
||||
for (key, value) in responsesapi_client_metadata {
|
||||
if matches!(
|
||||
key.as_str(),
|
||||
"session_id"
|
||||
| "thread_id"
|
||||
| "turn_id"
|
||||
| TURN_STARTED_AT_UNIX_MS_KEY
|
||||
| "forked_from_thread_id"
|
||||
| "parent_thread_id"
|
||||
| "subagent_kind"
|
||||
| REQUEST_KIND_KEY
|
||||
| COMPACTION_KEY
|
||||
| WINDOW_ID_KEY
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
metadata
|
||||
.entry(key.clone())
|
||||
.or_insert_with(|| Value::String(value.clone()));
|
||||
}
|
||||
}
|
||||
to_ascii_json_string(&metadata).ok()
|
||||
}
|
||||
|
||||
pub async fn build_turn_metadata_header(
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn detached_memory_responses_metadata(
|
||||
installation_id: String,
|
||||
session_id: String,
|
||||
thread_id: String,
|
||||
window_id: String,
|
||||
session_source: &SessionSource,
|
||||
cwd: &AbsolutePathBuf,
|
||||
sandbox: Option<&str>,
|
||||
) -> Option<String> {
|
||||
let repo_root = get_git_repo_root(cwd).map(|root| root.to_string_lossy().into_owned());
|
||||
|
||||
let (head_commit_hash, associated_remote_urls, has_changes) = tokio::join!(
|
||||
get_head_commit_hash(cwd),
|
||||
get_git_remote_urls_assume_git_repo(cwd),
|
||||
get_has_changes(cwd),
|
||||
);
|
||||
let latest_git_commit_hash = head_commit_hash.map(|sha| sha.0);
|
||||
TurnMetadataBag {
|
||||
request_kind: Some(TurnMetadataRequestKind::Memory),
|
||||
session_id: None,
|
||||
thread_id: None,
|
||||
forked_from_thread_id: None,
|
||||
parent_thread_id: None,
|
||||
subagent_kind: None,
|
||||
thread_source: None,
|
||||
turn_id: None,
|
||||
workspaces: BTreeMap::new(),
|
||||
) -> CodexResponsesMetadata {
|
||||
CodexResponsesMetadata {
|
||||
request_kind: Some(CodexResponsesRequestKind::Memory),
|
||||
subagent_header: subagent_header_value(session_source),
|
||||
sandbox: sandbox.map(ToString::to_string),
|
||||
workspaces: memory_workspaces(cwd).await,
|
||||
..CodexResponsesMetadata::new(installation_id, session_id, thread_id, window_id)
|
||||
}
|
||||
.with_workspace_git_metadata(
|
||||
repo_root,
|
||||
Some(WorkspaceGitMetadata {
|
||||
associated_remote_urls,
|
||||
latest_git_commit_hash,
|
||||
has_changes,
|
||||
}),
|
||||
)
|
||||
.to_header_value()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct TurnMetadataState {
|
||||
cwd: AbsolutePathBuf,
|
||||
repo_root: Option<String>,
|
||||
base_metadata: TurnMetadataBag,
|
||||
base_header: Option<String>,
|
||||
enriched_header: Arc<RwLock<Option<String>>>,
|
||||
session_id: String,
|
||||
thread_id: String,
|
||||
forked_from_thread_id: Option<ThreadId>,
|
||||
parent_thread_id: Option<ThreadId>,
|
||||
subagent_header: Option<String>,
|
||||
subagent_kind: Option<String>,
|
||||
turn_id: String,
|
||||
sandbox: Option<String>,
|
||||
enriched_workspaces: Arc<RwLock<Option<BTreeMap<String, TurnMetadataWorkspace>>>>,
|
||||
turn_started_at_unix_ms: Arc<RwLock<Option<i64>>>,
|
||||
responsesapi_client_metadata: Arc<RwLock<Option<HashMap<String, String>>>>,
|
||||
responsesapi_client_metadata: Arc<RwLock<BTreeMap<String, String>>>,
|
||||
user_input_requested_during_turn: Arc<AtomicBool>,
|
||||
enrichment_task: Arc<Mutex<Option<JoinHandle<()>>>>,
|
||||
}
|
||||
@@ -264,7 +108,6 @@ impl TurnMetadataState {
|
||||
forked_from_thread_id: Option<ThreadId>,
|
||||
parent_thread_id: Option<ThreadId>,
|
||||
session_source: &SessionSource,
|
||||
thread_source: Option<ThreadSource>,
|
||||
turn_id: String,
|
||||
cwd: AbsolutePathBuf,
|
||||
permission_profile: &PermissionProfile,
|
||||
@@ -280,79 +123,34 @@ impl TurnMetadataState {
|
||||
)
|
||||
.to_string(),
|
||||
);
|
||||
let subagent_kind = match session_source {
|
||||
SessionSource::SubAgent(subagent_source) => Some(subagent_source.kind().to_string()),
|
||||
SessionSource::Cli
|
||||
| SessionSource::VSCode
|
||||
| SessionSource::Exec
|
||||
| SessionSource::Mcp
|
||||
| SessionSource::Custom(_)
|
||||
| SessionSource::Internal(_)
|
||||
| SessionSource::Unknown => None,
|
||||
};
|
||||
let base_metadata = TurnMetadataBag {
|
||||
request_kind: None,
|
||||
session_id: Some(session_id),
|
||||
thread_id: Some(thread_id),
|
||||
forked_from_thread_id,
|
||||
parent_thread_id,
|
||||
subagent_kind,
|
||||
thread_source,
|
||||
turn_id: Some(turn_id),
|
||||
workspaces: BTreeMap::new(),
|
||||
sandbox,
|
||||
};
|
||||
let base_header = base_metadata.to_header_value();
|
||||
|
||||
Self {
|
||||
cwd,
|
||||
repo_root,
|
||||
base_metadata,
|
||||
base_header,
|
||||
enriched_header: Arc::new(RwLock::new(None)),
|
||||
session_id,
|
||||
thread_id,
|
||||
forked_from_thread_id,
|
||||
parent_thread_id,
|
||||
subagent_header: subagent_header_value(session_source),
|
||||
subagent_kind: subagent_metadata_kind(session_source),
|
||||
turn_id,
|
||||
sandbox,
|
||||
enriched_workspaces: Arc::new(RwLock::new(None)),
|
||||
turn_started_at_unix_ms: Arc::new(RwLock::new(None)),
|
||||
responsesapi_client_metadata: Arc::new(RwLock::new(None)),
|
||||
responsesapi_client_metadata: Arc::new(RwLock::new(BTreeMap::new())),
|
||||
user_input_requested_during_turn: Arc::new(AtomicBool::new(false)),
|
||||
enrichment_task: Arc::new(Mutex::new(None)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn current_header_value(&self) -> Option<String> {
|
||||
let header = if let Some(header) = self
|
||||
.enriched_header
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.as_ref()
|
||||
.cloned()
|
||||
{
|
||||
header
|
||||
} else {
|
||||
self.base_header.clone()?
|
||||
};
|
||||
let turn_started_at_unix_ms = *self
|
||||
.turn_started_at_unix_ms
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let responsesapi_client_metadata = self
|
||||
.responsesapi_client_metadata
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone();
|
||||
merge_turn_metadata(
|
||||
&header,
|
||||
turn_started_at_unix_ms,
|
||||
responsesapi_client_metadata.as_ref(),
|
||||
)
|
||||
.or(Some(header))
|
||||
}
|
||||
|
||||
pub(crate) fn current_meta_value_for_mcp_request(
|
||||
&self,
|
||||
context: McpTurnMetadataContext<'_>,
|
||||
) -> Option<serde_json::Value> {
|
||||
let header = self.current_header_value()?;
|
||||
let mut metadata = serde_json::from_str::<serde_json::Map<String, Value>>(&header).ok()?;
|
||||
metadata.remove(REQUEST_KIND_KEY);
|
||||
let Value::Object(mut metadata) =
|
||||
self.responses_metadata_template().turn_metadata_value()?
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
metadata.insert(
|
||||
MODEL_KEY.to_string(),
|
||||
Value::String(context.model.to_string()),
|
||||
@@ -382,50 +180,18 @@ impl TurnMetadataState {
|
||||
Some(Value::Object(metadata))
|
||||
}
|
||||
|
||||
fn current_header_value_for_model_request_kind(
|
||||
pub(crate) fn to_responses_metadata(
|
||||
&self,
|
||||
window_id: &str,
|
||||
request_kind: TurnMetadataRequestKind,
|
||||
) -> Option<String> {
|
||||
let header = self.current_header_value()?;
|
||||
let mut metadata = serde_json::from_str::<serde_json::Map<String, Value>>(&header).ok()?;
|
||||
metadata.insert(
|
||||
REQUEST_KIND_KEY.to_string(),
|
||||
serde_json::to_value(request_kind).ok()?,
|
||||
);
|
||||
metadata.insert(
|
||||
WINDOW_ID_KEY.to_string(),
|
||||
Value::String(window_id.to_string()),
|
||||
);
|
||||
to_ascii_json_string(&metadata).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn current_header_value_for_model_request(&self, window_id: &str) -> Option<String> {
|
||||
self.current_header_value_for_model_request_kind(window_id, TurnMetadataRequestKind::Turn)
|
||||
}
|
||||
|
||||
pub(crate) fn current_header_value_for_prewarm(&self, window_id: &str) -> Option<String> {
|
||||
self.current_header_value_for_model_request_kind(
|
||||
installation_id: String,
|
||||
window_id: String,
|
||||
request_kind: CodexResponsesRequestKind,
|
||||
) -> CodexResponsesMetadata {
|
||||
CodexResponsesMetadata {
|
||||
installation_id,
|
||||
window_id,
|
||||
TurnMetadataRequestKind::Prewarm,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn current_header_value_for_compaction(
|
||||
&self,
|
||||
window_id: &str,
|
||||
compaction: CompactionTurnMetadata,
|
||||
) -> Option<String> {
|
||||
let header = self.current_header_value_for_model_request_kind(
|
||||
window_id,
|
||||
TurnMetadataRequestKind::Compaction,
|
||||
)?;
|
||||
let mut metadata = serde_json::from_str::<serde_json::Map<String, Value>>(&header).ok()?;
|
||||
metadata.insert(
|
||||
COMPACTION_KEY.to_string(),
|
||||
serde_json::to_value(compaction).ok()?,
|
||||
);
|
||||
to_ascii_json_string(&metadata).ok()
|
||||
request_kind: Some(request_kind),
|
||||
..self.responses_metadata_template()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mark_user_input_requested_during_turn(&self) {
|
||||
@@ -441,15 +207,54 @@ impl TurnMetadataState {
|
||||
.responsesapi_client_metadata
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) =
|
||||
Some(responsesapi_client_metadata);
|
||||
filter_extra_metadata(responsesapi_client_metadata);
|
||||
}
|
||||
|
||||
pub(crate) fn workspace_kind(&self) -> Option<String> {
|
||||
self.responsesapi_client_metadata
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.as_ref()
|
||||
.and_then(|metadata| metadata.get(WORKSPACE_KIND_KEY).cloned())
|
||||
.get(WORKSPACE_KIND_KEY)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn responses_metadata_template(&self) -> CodexResponsesMetadata {
|
||||
CodexResponsesMetadata {
|
||||
turn_id: Some(self.turn_id.clone()),
|
||||
forked_from_thread_id: self.forked_from_thread_id,
|
||||
parent_thread_id: self.parent_thread_id,
|
||||
subagent_header: self.subagent_header.clone(),
|
||||
subagent_kind: self.subagent_kind.clone(),
|
||||
sandbox: self.sandbox.clone(),
|
||||
workspaces: self.current_workspaces(),
|
||||
turn_started_at_unix_ms: self.current_turn_started_at_unix_ms(),
|
||||
extra: self
|
||||
.responsesapi_client_metadata
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone(),
|
||||
..CodexResponsesMetadata::new(
|
||||
String::new(),
|
||||
self.session_id.clone(),
|
||||
self.thread_id.clone(),
|
||||
String::new(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn current_workspaces(&self) -> BTreeMap<String, TurnMetadataWorkspace> {
|
||||
self.enriched_workspaces
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn current_turn_started_at_unix_ms(&self) -> Option<i64> {
|
||||
*self
|
||||
.turn_started_at_unix_ms
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
pub(crate) fn set_turn_started_at_unix_ms(&self, turn_started_at_unix_ms: i64) {
|
||||
@@ -479,20 +284,16 @@ impl TurnMetadataState {
|
||||
return;
|
||||
};
|
||||
|
||||
let enriched_metadata = state
|
||||
.base_metadata
|
||||
.clone()
|
||||
.with_workspace_git_metadata(Some(repo_root), Some(workspace_git_metadata));
|
||||
if enriched_metadata.workspaces.is_empty() {
|
||||
if workspace_git_metadata.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(header_value) = enriched_metadata.to_header_value() {
|
||||
*state
|
||||
.enriched_header
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(header_value);
|
||||
}
|
||||
let mut workspaces = BTreeMap::new();
|
||||
workspaces.insert(repo_root, workspace_git_metadata.into());
|
||||
*state
|
||||
.enriched_workspaces
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(workspaces);
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -522,6 +323,27 @@ impl TurnMetadataState {
|
||||
}
|
||||
}
|
||||
|
||||
async fn memory_workspaces(cwd: &AbsolutePathBuf) -> BTreeMap<String, TurnMetadataWorkspace> {
|
||||
let repo_root = get_git_repo_root(cwd).map(|root| root.to_string_lossy().into_owned());
|
||||
let (head_commit_hash, associated_remote_urls, has_changes) = tokio::join!(
|
||||
get_head_commit_hash(cwd),
|
||||
get_git_remote_urls_assume_git_repo(cwd),
|
||||
get_has_changes(cwd),
|
||||
);
|
||||
let workspace_git_metadata = WorkspaceGitMetadata {
|
||||
associated_remote_urls,
|
||||
latest_git_commit_hash: head_commit_hash.map(|sha| sha.0),
|
||||
has_changes,
|
||||
};
|
||||
let mut workspaces = BTreeMap::new();
|
||||
if let Some(repo_root) = repo_root
|
||||
&& !workspace_git_metadata.is_empty()
|
||||
{
|
||||
workspaces.insert(repo_root, workspace_git_metadata.into());
|
||||
}
|
||||
workspaces
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "turn_metadata_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
use super::*;
|
||||
|
||||
use crate::responses_metadata::CodexResponsesRequestKind;
|
||||
use crate::responses_metadata::CompactionTurnMetadata;
|
||||
use crate::responses_metadata::INSTALLATION_ID_KEY;
|
||||
use crate::responses_metadata::WINDOW_ID_KEY;
|
||||
use crate::sandbox_tags::permission_profile_sandbox_tag;
|
||||
use codex_analytics::CompactionImplementation;
|
||||
use codex_analytics::CompactionPhase;
|
||||
use codex_analytics::CompactionReason;
|
||||
use codex_analytics::CompactionTrigger;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_protocol::protocol::ThreadSource;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use core_test_support::PathBufExt;
|
||||
use core_test_support::PathExt;
|
||||
@@ -23,6 +30,44 @@ fn test_mcp_turn_metadata_context() -> McpTurnMetadataContext<'static> {
|
||||
}
|
||||
}
|
||||
|
||||
fn test_responses_metadata_json(
|
||||
state: &TurnMetadataState,
|
||||
window_id: &str,
|
||||
request_kind: CodexResponsesRequestKind,
|
||||
) -> String {
|
||||
state
|
||||
.to_responses_metadata(
|
||||
"installation-a".to_string(),
|
||||
window_id.to_string(),
|
||||
request_kind,
|
||||
)
|
||||
.turn_metadata_json()
|
||||
.expect("turn metadata json")
|
||||
}
|
||||
|
||||
fn test_turn_responses_metadata_json(state: &TurnMetadataState, window_id: &str) -> String {
|
||||
test_responses_metadata_json(state, window_id, CodexResponsesRequestKind::Turn)
|
||||
}
|
||||
|
||||
fn test_compaction_responses_metadata_json(
|
||||
state: &TurnMetadataState,
|
||||
window_id: &str,
|
||||
compaction: CompactionTurnMetadata,
|
||||
) -> String {
|
||||
test_responses_metadata_json(
|
||||
state,
|
||||
window_id,
|
||||
CodexResponsesRequestKind::Compaction(compaction),
|
||||
)
|
||||
}
|
||||
|
||||
fn test_turn_metadata_header(state: &TurnMetadataState) -> String {
|
||||
state
|
||||
.responses_metadata_template()
|
||||
.turn_metadata_json()
|
||||
.expect("header")
|
||||
}
|
||||
|
||||
async fn create_clean_git_repo(repo_name: &str) -> (TempDir, AbsolutePathBuf) {
|
||||
let temp_dir = TempDir::new().expect("temp dir");
|
||||
let repo_path = temp_dir.path().join(repo_name).abs();
|
||||
@@ -64,12 +109,21 @@ async fn create_clean_git_repo(repo_name: &str) -> (TempDir, AbsolutePathBuf) {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_turn_metadata_header_marks_detached_memory_without_turn_identity() {
|
||||
async fn detached_memory_responses_metadata_omits_turn_identity() {
|
||||
let (_temp_dir, repo_path) = create_clean_git_repo("repo-東京").await;
|
||||
|
||||
let header = build_turn_metadata_header(&repo_path, Some("none"))
|
||||
.await
|
||||
.expect("header");
|
||||
let header = detached_memory_responses_metadata(
|
||||
String::new(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
&SessionSource::Unknown,
|
||||
&repo_path,
|
||||
Some("none"),
|
||||
)
|
||||
.await
|
||||
.turn_metadata_json()
|
||||
.expect("header");
|
||||
assert!(header.is_ascii());
|
||||
assert!(!header.contains("東京"));
|
||||
let parsed: Value = serde_json::from_str(&header).expect("valid json");
|
||||
@@ -100,13 +154,22 @@ async fn build_turn_metadata_header_marks_detached_memory_without_turn_identity(
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_turn_metadata_header_marks_memory_without_workspace_metadata() {
|
||||
async fn detached_memory_responses_metadata_omits_empty_workspace_metadata() {
|
||||
let temp_dir = TempDir::new().expect("temp dir");
|
||||
let cwd = temp_dir.path().abs();
|
||||
|
||||
let header = build_turn_metadata_header(&cwd, /*sandbox*/ None)
|
||||
.await
|
||||
.expect("detached memory should emit its request kind");
|
||||
let header = detached_memory_responses_metadata(
|
||||
String::new(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
&SessionSource::Unknown,
|
||||
&cwd,
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.turn_metadata_json()
|
||||
.expect("detached memory should emit its request kind");
|
||||
let parsed: Value = serde_json::from_str(&header).expect("valid json");
|
||||
|
||||
assert_eq!(parsed, serde_json::json!({"request_kind": "memory"}));
|
||||
@@ -124,7 +187,6 @@ fn turn_metadata_state_uses_platform_sandbox_tag() {
|
||||
/*forked_from_thread_id*/ None,
|
||||
/*parent_thread_id*/ None,
|
||||
&SessionSource::Exec,
|
||||
Some(ThreadSource::User),
|
||||
"turn-a".to_string(),
|
||||
cwd,
|
||||
&permission_profile,
|
||||
@@ -132,12 +194,11 @@ fn turn_metadata_state_uses_platform_sandbox_tag() {
|
||||
/*enforce_managed_network*/ false,
|
||||
);
|
||||
|
||||
let header = state.current_header_value().expect("header");
|
||||
let header = test_turn_metadata_header(&state);
|
||||
let json: Value = serde_json::from_str(&header).expect("json");
|
||||
let sandbox_name = json.get("sandbox").and_then(Value::as_str);
|
||||
let session_id = json.get("session_id").and_then(Value::as_str);
|
||||
let thread_id = json.get("thread_id").and_then(Value::as_str);
|
||||
let thread_source = json.get("thread_source").and_then(Value::as_str);
|
||||
|
||||
assert!(json.get("request_kind").is_none());
|
||||
let expected_sandbox = permission_profile_sandbox_tag(
|
||||
@@ -148,39 +209,12 @@ fn turn_metadata_state_uses_platform_sandbox_tag() {
|
||||
assert_eq!(sandbox_name, Some(expected_sandbox));
|
||||
assert_eq!(session_id, Some("session-a"));
|
||||
assert_eq!(thread_id, Some("thread-a"));
|
||||
assert_eq!(thread_source, Some("user"));
|
||||
assert!(json.get("forked_from_thread_id").is_none());
|
||||
assert!(json.get("parent_thread_id").is_none());
|
||||
assert!(json.get("subagent_kind").is_none());
|
||||
assert!(json.get("session_source").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_metadata_state_uses_explicit_subagent_thread_source() {
|
||||
let temp_dir = TempDir::new().expect("temp dir");
|
||||
let cwd = temp_dir.path().abs();
|
||||
let permission_profile = PermissionProfile::read_only();
|
||||
let state = TurnMetadataState::new(
|
||||
"session-a".to_string(),
|
||||
"thread-a".to_string(),
|
||||
/*forked_from_thread_id*/ None,
|
||||
/*parent_thread_id*/ None,
|
||||
&SessionSource::Exec,
|
||||
Some(ThreadSource::Subagent),
|
||||
"turn-a".to_string(),
|
||||
cwd,
|
||||
&permission_profile,
|
||||
WindowsSandboxLevel::Disabled,
|
||||
/*enforce_managed_network*/ false,
|
||||
);
|
||||
|
||||
let header = state.current_header_value().expect("header");
|
||||
let json: Value = serde_json::from_str(&header).expect("json");
|
||||
|
||||
assert_eq!(json["thread_source"].as_str(), Some("subagent"));
|
||||
assert!(json.get("session_source").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_metadata_state_includes_root_fork_lineage() {
|
||||
let temp_dir = TempDir::new().expect("temp dir");
|
||||
@@ -195,7 +229,6 @@ fn turn_metadata_state_includes_root_fork_lineage() {
|
||||
Some(source_thread_id),
|
||||
/*parent_thread_id*/ None,
|
||||
&SessionSource::Exec,
|
||||
Some(ThreadSource::User),
|
||||
"turn-a".to_string(),
|
||||
cwd,
|
||||
&permission_profile,
|
||||
@@ -203,7 +236,7 @@ fn turn_metadata_state_includes_root_fork_lineage() {
|
||||
/*enforce_managed_network*/ false,
|
||||
);
|
||||
|
||||
let header = state.current_header_value().expect("header");
|
||||
let header = test_turn_metadata_header(&state);
|
||||
let json: Value = serde_json::from_str(&header).expect("json");
|
||||
|
||||
assert_eq!(
|
||||
@@ -234,7 +267,6 @@ fn turn_metadata_state_includes_thread_spawn_subagent_parent_without_fork() {
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
}),
|
||||
Some(ThreadSource::Subagent),
|
||||
"turn-a".to_string(),
|
||||
cwd,
|
||||
&permission_profile,
|
||||
@@ -242,7 +274,7 @@ fn turn_metadata_state_includes_thread_spawn_subagent_parent_without_fork() {
|
||||
/*enforce_managed_network*/ false,
|
||||
);
|
||||
|
||||
let header = state.current_header_value().expect("header");
|
||||
let header = test_turn_metadata_header(&state);
|
||||
let json: Value = serde_json::from_str(&header).expect("json");
|
||||
|
||||
assert!(json.get("forked_from_thread_id").is_none());
|
||||
@@ -273,7 +305,6 @@ fn turn_metadata_state_includes_forked_thread_spawn_subagent_lineage() {
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
}),
|
||||
Some(ThreadSource::Subagent),
|
||||
"turn-a".to_string(),
|
||||
cwd,
|
||||
&permission_profile,
|
||||
@@ -281,7 +312,7 @@ fn turn_metadata_state_includes_forked_thread_spawn_subagent_lineage() {
|
||||
/*enforce_managed_network*/ false,
|
||||
);
|
||||
|
||||
let header = state.current_header_value().expect("header");
|
||||
let header = test_turn_metadata_header(&state);
|
||||
let json: Value = serde_json::from_str(&header).expect("json");
|
||||
|
||||
assert_eq!(
|
||||
@@ -318,7 +349,6 @@ fn turn_metadata_state_includes_known_parent_for_non_thread_spawn_subagents_with
|
||||
/*forked_from_thread_id*/ None,
|
||||
Some(parent_thread_id),
|
||||
&SessionSource::SubAgent(subagent_source),
|
||||
Some(ThreadSource::Subagent),
|
||||
"turn-a".to_string(),
|
||||
cwd.clone(),
|
||||
&permission_profile,
|
||||
@@ -326,7 +356,7 @@ fn turn_metadata_state_includes_known_parent_for_non_thread_spawn_subagents_with
|
||||
/*enforce_managed_network*/ false,
|
||||
);
|
||||
|
||||
let header = state.current_header_value().expect("header");
|
||||
let header = test_turn_metadata_header(&state);
|
||||
let json: Value = serde_json::from_str(&header).expect("json");
|
||||
|
||||
assert!(json.get("forked_from_thread_id").is_none());
|
||||
@@ -350,7 +380,6 @@ fn turn_metadata_state_includes_turn_started_at_unix_ms_after_start() {
|
||||
/*forked_from_thread_id*/ None,
|
||||
/*parent_thread_id*/ None,
|
||||
&SessionSource::Exec,
|
||||
Some(ThreadSource::User),
|
||||
"turn-a".to_string(),
|
||||
cwd,
|
||||
&permission_profile,
|
||||
@@ -359,7 +388,7 @@ fn turn_metadata_state_includes_turn_started_at_unix_ms_after_start() {
|
||||
);
|
||||
state.set_turn_started_at_unix_ms(/*turn_started_at_unix_ms*/ 1_700_000_000_123);
|
||||
|
||||
let header = state.current_header_value().expect("header");
|
||||
let header = test_turn_metadata_header(&state);
|
||||
let json: Value = serde_json::from_str(&header).expect("json");
|
||||
|
||||
assert_eq!(
|
||||
@@ -380,7 +409,6 @@ fn turn_metadata_state_includes_model_and_reasoning_effort_only_in_request_meta(
|
||||
/*forked_from_thread_id*/ None,
|
||||
/*parent_thread_id*/ None,
|
||||
&SessionSource::Exec,
|
||||
/*thread_source*/ None,
|
||||
"turn-a".to_string(),
|
||||
cwd,
|
||||
&permission_profile,
|
||||
@@ -388,7 +416,7 @@ fn turn_metadata_state_includes_model_and_reasoning_effort_only_in_request_meta(
|
||||
/*enforce_managed_network*/ false,
|
||||
);
|
||||
|
||||
let header = state.current_header_value().expect("header");
|
||||
let header = test_turn_metadata_header(&state);
|
||||
let header_json: Value = serde_json::from_str(&header).expect("json");
|
||||
assert!(header_json.get("model").is_none());
|
||||
assert!(header_json.get("reasoning_effort").is_none());
|
||||
@@ -429,7 +457,6 @@ fn turn_metadata_state_marks_user_input_requested_during_turn_only_for_mcp_reque
|
||||
/*forked_from_thread_id*/ None,
|
||||
/*parent_thread_id*/ None,
|
||||
&SessionSource::Exec,
|
||||
/*thread_source*/ None,
|
||||
"turn-a".to_string(),
|
||||
cwd,
|
||||
&permission_profile,
|
||||
@@ -437,7 +464,7 @@ fn turn_metadata_state_marks_user_input_requested_during_turn_only_for_mcp_reque
|
||||
/*enforce_managed_network*/ false,
|
||||
);
|
||||
|
||||
let header = state.current_header_value().expect("header");
|
||||
let header = test_turn_metadata_header(&state);
|
||||
let header_json: Value = serde_json::from_str(&header).expect("json");
|
||||
assert!(
|
||||
header_json
|
||||
@@ -452,7 +479,7 @@ fn turn_metadata_state_marks_user_input_requested_during_turn_only_for_mcp_reque
|
||||
|
||||
state.mark_user_input_requested_during_turn();
|
||||
|
||||
let header = state.current_header_value().expect("header");
|
||||
let header = test_turn_metadata_header(&state);
|
||||
let header_json: Value = serde_json::from_str(&header).expect("json");
|
||||
assert!(
|
||||
header_json
|
||||
@@ -482,7 +509,6 @@ fn turn_metadata_state_ignores_client_reserved_metadata_before_start() {
|
||||
/*forked_from_thread_id*/ None,
|
||||
/*parent_thread_id*/ None,
|
||||
&SessionSource::Exec,
|
||||
Some(ThreadSource::User),
|
||||
"turn-a".to_string(),
|
||||
cwd,
|
||||
&permission_profile,
|
||||
@@ -505,7 +531,7 @@ fn turn_metadata_state_ignores_client_reserved_metadata_before_start() {
|
||||
("subagent_kind".to_string(), "client-supplied".to_string()),
|
||||
]));
|
||||
|
||||
let header = state.current_header_value().expect("header");
|
||||
let header = test_turn_metadata_header(&state);
|
||||
let json: Value = serde_json::from_str(&header).expect("json");
|
||||
|
||||
assert!(json.get("turn_started_at_unix_ms").is_none());
|
||||
@@ -536,7 +562,6 @@ fn turn_metadata_state_merges_client_metadata_without_replacing_reserved_fields(
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
}),
|
||||
Some(ThreadSource::User),
|
||||
"turn-a".to_string(),
|
||||
cwd,
|
||||
&permission_profile,
|
||||
@@ -554,6 +579,19 @@ fn turn_metadata_state_merges_client_metadata_without_replacing_reserved_fields(
|
||||
),
|
||||
("session_id".to_string(), "client-supplied".to_string()),
|
||||
("thread_id".to_string(), "client-supplied".to_string()),
|
||||
("installation_id".to_string(), "client-supplied".to_string()),
|
||||
(
|
||||
"x-codex-installation-id".to_string(),
|
||||
"client-supplied".to_string(),
|
||||
),
|
||||
(
|
||||
"x-codex-parent-thread-id".to_string(),
|
||||
"client-supplied".to_string(),
|
||||
),
|
||||
(
|
||||
"x-openai-subagent".to_string(),
|
||||
"client-supplied".to_string(),
|
||||
),
|
||||
(
|
||||
"forked_from_thread_id".to_string(),
|
||||
"client-supplied".to_string(),
|
||||
@@ -574,7 +612,7 @@ fn turn_metadata_state_merges_client_metadata_without_replacing_reserved_fields(
|
||||
]));
|
||||
state.set_turn_started_at_unix_ms(/*turn_started_at_unix_ms*/ 1_700_000_000_123);
|
||||
|
||||
let header = state.current_header_value().expect("header");
|
||||
let header = test_turn_metadata_header(&state);
|
||||
assert!(header.is_ascii());
|
||||
assert!(!header.contains("東京"));
|
||||
let json: Value = serde_json::from_str(&header).expect("json");
|
||||
@@ -586,6 +624,10 @@ fn turn_metadata_state_merges_client_metadata_without_replacing_reserved_fields(
|
||||
assert_eq!(json["reasoning_effort"].as_str(), Some("client-supplied"));
|
||||
assert_eq!(json["session_id"].as_str(), Some("session-a"));
|
||||
assert_eq!(json["thread_id"].as_str(), Some("thread-a"));
|
||||
assert!(json.get(INSTALLATION_ID_KEY).is_none());
|
||||
assert!(json.get("x-codex-installation-id").is_none());
|
||||
assert!(json.get("x-codex-parent-thread-id").is_none());
|
||||
assert!(json.get("x-openai-subagent").is_none());
|
||||
assert_eq!(
|
||||
json["forked_from_thread_id"].as_str(),
|
||||
Some("44444444-4444-4444-8444-444444444444")
|
||||
@@ -595,7 +637,7 @@ fn turn_metadata_state_merges_client_metadata_without_replacing_reserved_fields(
|
||||
Some("55555555-5555-4555-8555-555555555555")
|
||||
);
|
||||
assert_eq!(json["subagent_kind"].as_str(), Some("thread_spawn"));
|
||||
assert_eq!(json["thread_source"].as_str(), Some("user"));
|
||||
assert_eq!(json["thread_source"].as_str(), Some("client-supplied"));
|
||||
assert_eq!(json["turn_id"].as_str(), Some("turn-a"));
|
||||
assert!(json.get("request_kind").is_none());
|
||||
assert!(json.get(WINDOW_ID_KEY).is_none());
|
||||
@@ -604,12 +646,14 @@ fn turn_metadata_state_merges_client_metadata_without_replacing_reserved_fields(
|
||||
Some(1_700_000_000_123)
|
||||
);
|
||||
|
||||
let model_request_header = state
|
||||
.current_header_value_for_model_request("thread-a:1")
|
||||
.expect("model request header");
|
||||
let model_request_header = test_turn_responses_metadata_json(&state, "thread-a:1");
|
||||
let model_request_json: Value =
|
||||
serde_json::from_str(&model_request_header).expect("model request json");
|
||||
assert_eq!(model_request_json["request_kind"].as_str(), Some("turn"));
|
||||
assert_eq!(
|
||||
model_request_json[INSTALLATION_ID_KEY].as_str(),
|
||||
Some("installation-a")
|
||||
);
|
||||
assert_eq!(
|
||||
model_request_json[WINDOW_ID_KEY].as_str(),
|
||||
Some("thread-a:1")
|
||||
@@ -635,7 +679,6 @@ fn turn_metadata_state_overlays_compaction_only_on_compaction_requests() {
|
||||
/*forked_from_thread_id*/ None,
|
||||
/*parent_thread_id*/ None,
|
||||
&SessionSource::Exec,
|
||||
Some(ThreadSource::User),
|
||||
"turn-a".to_string(),
|
||||
cwd,
|
||||
&permission_profile,
|
||||
@@ -647,17 +690,16 @@ fn turn_metadata_state_overlays_compaction_only_on_compaction_requests() {
|
||||
"client-supplied".to_string(),
|
||||
)]));
|
||||
|
||||
let compact_header = state
|
||||
.current_header_value_for_compaction(
|
||||
"thread-a:2",
|
||||
CompactionTurnMetadata::new(
|
||||
CompactionTrigger::Auto,
|
||||
CompactionReason::ContextLimit,
|
||||
CompactionImplementation::ResponsesCompactionV2,
|
||||
CompactionPhase::MidTurn,
|
||||
),
|
||||
)
|
||||
.expect("compact header");
|
||||
let compact_header = test_compaction_responses_metadata_json(
|
||||
&state,
|
||||
"thread-a:2",
|
||||
CompactionTurnMetadata::new(
|
||||
CompactionTrigger::Auto,
|
||||
CompactionReason::ContextLimit,
|
||||
CompactionImplementation::ResponsesCompactionV2,
|
||||
CompactionPhase::MidTurn,
|
||||
),
|
||||
);
|
||||
let compact_json: Value = serde_json::from_str(&compact_header).expect("json");
|
||||
assert_eq!(compact_json["request_kind"].as_str(), Some("compaction"));
|
||||
assert_eq!(compact_json["turn_id"].as_str(), Some("turn-a"));
|
||||
@@ -673,9 +715,7 @@ fn turn_metadata_state_overlays_compaction_only_on_compaction_requests() {
|
||||
})
|
||||
);
|
||||
|
||||
let regular_header = state
|
||||
.current_header_value_for_model_request("thread-a:3")
|
||||
.expect("regular header");
|
||||
let regular_header = test_turn_responses_metadata_json(&state, "thread-a:3");
|
||||
let regular_json: Value = serde_json::from_str(®ular_header).expect("json");
|
||||
assert_eq!(regular_json["request_kind"].as_str(), Some("turn"));
|
||||
assert_eq!(regular_json[WINDOW_ID_KEY].as_str(), Some("thread-a:3"));
|
||||
@@ -701,7 +741,6 @@ async fn turn_metadata_state_preserves_lineage_after_git_enrichment() {
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
}),
|
||||
Some(ThreadSource::Subagent),
|
||||
"turn-a".to_string(),
|
||||
repo_path,
|
||||
&permission_profile,
|
||||
@@ -713,7 +752,7 @@ async fn turn_metadata_state_preserves_lineage_after_git_enrichment() {
|
||||
|
||||
let json = tokio::time::timeout(Duration::from_secs(2), async {
|
||||
loop {
|
||||
let header = state.current_header_value().expect("header");
|
||||
let header = test_turn_metadata_header(&state);
|
||||
let json: Value = serde_json::from_str(&header).expect("json");
|
||||
if json
|
||||
.get("workspaces")
|
||||
|
||||
@@ -10,10 +10,9 @@ use crate::session::turn_context::TurnContext;
|
||||
use crate::tools::context::ExecCommandToolOutput;
|
||||
use crate::unified_exec::WriteStdinRequest;
|
||||
use crate::unified_exec::process::OutputHandles;
|
||||
use async_trait::async_trait;
|
||||
use codex_exec_server::ExecProcess;
|
||||
use codex_exec_server::ExecProcessEventReceiver;
|
||||
use codex_exec_server::ExecServerError;
|
||||
use codex_exec_server::ExecProcessFuture;
|
||||
use codex_exec_server::ProcessId;
|
||||
use codex_exec_server::ProcessSignal;
|
||||
use codex_exec_server::ReadResponse;
|
||||
@@ -218,7 +217,31 @@ struct BlockingTerminateExecProcess {
|
||||
wake_tx: watch::Sender<u64>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BlockingTerminateExecProcess {
|
||||
async fn read(&self) -> Result<ReadResponse, codex_exec_server::ExecServerError> {
|
||||
Ok(ReadResponse {
|
||||
chunks: Vec::new(),
|
||||
next_seq: 1,
|
||||
exited: false,
|
||||
exit_code: None,
|
||||
closed: false,
|
||||
failure: None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn write(&self) -> Result<WriteResponse, codex_exec_server::ExecServerError> {
|
||||
Ok(WriteResponse {
|
||||
status: WriteStatus::Accepted,
|
||||
})
|
||||
}
|
||||
|
||||
async fn terminate(&self) -> Result<(), codex_exec_server::ExecServerError> {
|
||||
let _ = self.terminate_started.send(true);
|
||||
self.allow_terminate.notified().await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecProcess for BlockingTerminateExecProcess {
|
||||
fn process_id(&self) -> &ProcessId {
|
||||
&self.process_id
|
||||
@@ -232,36 +255,25 @@ impl ExecProcess for BlockingTerminateExecProcess {
|
||||
ExecProcessEventReceiver::empty()
|
||||
}
|
||||
|
||||
async fn read(
|
||||
fn read(
|
||||
&self,
|
||||
_after_seq: Option<u64>,
|
||||
_max_bytes: Option<usize>,
|
||||
_wait_ms: Option<u64>,
|
||||
) -> Result<ReadResponse, ExecServerError> {
|
||||
Ok(ReadResponse {
|
||||
chunks: Vec::new(),
|
||||
next_seq: 1,
|
||||
exited: false,
|
||||
exit_code: None,
|
||||
closed: false,
|
||||
failure: None,
|
||||
})
|
||||
) -> ExecProcessFuture<'_, ReadResponse> {
|
||||
Box::pin(BlockingTerminateExecProcess::read(self))
|
||||
}
|
||||
|
||||
async fn write(&self, _chunk: Vec<u8>) -> Result<WriteResponse, ExecServerError> {
|
||||
Ok(WriteResponse {
|
||||
status: WriteStatus::Accepted,
|
||||
})
|
||||
fn write(&self, _chunk: Vec<u8>) -> ExecProcessFuture<'_, WriteResponse> {
|
||||
Box::pin(BlockingTerminateExecProcess::write(self))
|
||||
}
|
||||
|
||||
async fn signal(&self, _signal: ProcessSignal) -> Result<(), ExecServerError> {
|
||||
Ok(())
|
||||
fn signal(&self, _signal: ProcessSignal) -> ExecProcessFuture<'_, ()> {
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
|
||||
async fn terminate(&self) -> Result<(), ExecServerError> {
|
||||
let _ = self.terminate_started.send(true);
|
||||
self.allow_terminate.notified().await;
|
||||
Ok(())
|
||||
fn terminate(&self) -> ExecProcessFuture<'_, ()> {
|
||||
Box::pin(BlockingTerminateExecProcess::terminate(self))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -57,6 +57,7 @@ use codex_protocol::protocol::ExecCommandSource;
|
||||
use codex_tools::ToolName;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_output_truncation::approx_token_count;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
|
||||
const UNIFIED_EXEC_ENV: [(&str, &str); 10] = [
|
||||
("NO_COLOR", "1"),
|
||||
@@ -156,7 +157,7 @@ fn exec_server_params_for_request(
|
||||
codex_exec_server::ExecParams {
|
||||
process_id: exec_server_process_id(process_id).into(),
|
||||
argv: request.command.clone(),
|
||||
cwd: request.cwd.to_path_buf(),
|
||||
cwd: PathUri::from_abs_path(&request.cwd),
|
||||
env_policy,
|
||||
env,
|
||||
tty,
|
||||
|
||||
@@ -66,7 +66,7 @@ fn env_overlay_for_exec_server_keeps_runtime_changes_only() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_server_params_use_env_policy_overlay_contract() {
|
||||
fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() {
|
||||
let cwd: codex_utils_absolute_path::AbsolutePathBuf = std::env::current_dir()
|
||||
.expect("current dir")
|
||||
.try_into()
|
||||
@@ -115,6 +115,7 @@ fn exec_server_params_use_env_policy_overlay_contract() {
|
||||
exec_server_params_for_request(/*process_id*/ 123, &request, /*tty*/ true);
|
||||
|
||||
assert_eq!(params.process_id.as_str(), "123");
|
||||
assert_eq!(params.cwd, PathUri::from_abs_path(&request.cwd));
|
||||
assert!(params.env_policy.is_some());
|
||||
assert_eq!(
|
||||
params.env,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::process::UnifiedExecProcess;
|
||||
use crate::unified_exec::UnifiedExecError;
|
||||
use async_trait::async_trait;
|
||||
use codex_exec_server::ExecProcess;
|
||||
use codex_exec_server::ExecProcessEventReceiver;
|
||||
use codex_exec_server::ExecProcessFuture;
|
||||
use codex_exec_server::ExecServerError;
|
||||
use codex_exec_server::ProcessId;
|
||||
use codex_exec_server::ProcessSignal;
|
||||
@@ -26,26 +26,8 @@ struct MockExecProcess {
|
||||
wake_tx: watch::Sender<u64>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ExecProcess for MockExecProcess {
|
||||
fn process_id(&self) -> &ProcessId {
|
||||
&self.process_id
|
||||
}
|
||||
|
||||
fn subscribe_wake(&self) -> watch::Receiver<u64> {
|
||||
self.wake_tx.subscribe()
|
||||
}
|
||||
|
||||
fn subscribe_events(&self) -> ExecProcessEventReceiver {
|
||||
ExecProcessEventReceiver::empty()
|
||||
}
|
||||
|
||||
async fn read(
|
||||
&self,
|
||||
_after_seq: Option<u64>,
|
||||
_max_bytes: Option<usize>,
|
||||
_wait_ms: Option<u64>,
|
||||
) -> Result<ReadResponse, ExecServerError> {
|
||||
impl MockExecProcess {
|
||||
async fn read(&self) -> Result<ReadResponse, ExecServerError> {
|
||||
Ok(self
|
||||
.read_responses
|
||||
.lock()
|
||||
@@ -61,14 +43,6 @@ impl ExecProcess for MockExecProcess {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn write(&self, _chunk: Vec<u8>) -> Result<WriteResponse, ExecServerError> {
|
||||
Ok(self.write_response.clone())
|
||||
}
|
||||
|
||||
async fn signal(&self, _signal: ProcessSignal) -> Result<(), ExecServerError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn terminate(&self) -> Result<(), ExecServerError> {
|
||||
if let Some(message) = &self.terminate_error {
|
||||
return Err(ExecServerError::Protocol(message.clone()));
|
||||
@@ -77,6 +51,41 @@ impl ExecProcess for MockExecProcess {
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecProcess for MockExecProcess {
|
||||
fn process_id(&self) -> &ProcessId {
|
||||
&self.process_id
|
||||
}
|
||||
|
||||
fn subscribe_wake(&self) -> watch::Receiver<u64> {
|
||||
self.wake_tx.subscribe()
|
||||
}
|
||||
|
||||
fn subscribe_events(&self) -> ExecProcessEventReceiver {
|
||||
ExecProcessEventReceiver::empty()
|
||||
}
|
||||
|
||||
fn read(
|
||||
&self,
|
||||
_after_seq: Option<u64>,
|
||||
_max_bytes: Option<usize>,
|
||||
_wait_ms: Option<u64>,
|
||||
) -> ExecProcessFuture<'_, ReadResponse> {
|
||||
Box::pin(MockExecProcess::read(self))
|
||||
}
|
||||
|
||||
fn write(&self, _chunk: Vec<u8>) -> ExecProcessFuture<'_, WriteResponse> {
|
||||
Box::pin(async { Ok(self.write_response.clone()) })
|
||||
}
|
||||
|
||||
fn signal(&self, _signal: ProcessSignal) -> ExecProcessFuture<'_, ()> {
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
|
||||
fn terminate(&self) -> ExecProcessFuture<'_, ()> {
|
||||
Box::pin(MockExecProcess::terminate(self))
|
||||
}
|
||||
}
|
||||
|
||||
async fn remote_process(
|
||||
write_status: WriteStatus,
|
||||
terminate_error: Option<String>,
|
||||
|
||||
Reference in New Issue
Block a user