mirror of
https://github.com/openai/codex.git
synced 2026-11-07 20:30:33 +00:00
app-server: select permission profiles by id
This commit is contained in:
@@ -194,18 +194,24 @@ pub struct InProcessClientSender {
|
||||
}
|
||||
|
||||
impl InProcessClientSender {
|
||||
pub async fn request(&self, request: ClientRequest) -> IoResult<PendingClientRequestResponse> {
|
||||
pub fn request(
|
||||
&self,
|
||||
request: ClientRequest,
|
||||
) -> impl std::future::Future<Output = IoResult<PendingClientRequestResponse>> + '_ {
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
self.try_send_client_message(InProcessClientMessage::Request {
|
||||
let send_result = self.try_send_client_message(InProcessClientMessage::Request {
|
||||
request: Box::new(request),
|
||||
response_tx,
|
||||
})?;
|
||||
response_rx.await.map_err(|err| {
|
||||
IoError::new(
|
||||
ErrorKind::BrokenPipe,
|
||||
format!("in-process request response channel closed: {err}"),
|
||||
)
|
||||
})
|
||||
});
|
||||
async move {
|
||||
send_result?;
|
||||
response_rx.await.map_err(|err| {
|
||||
IoError::new(
|
||||
ErrorKind::BrokenPipe,
|
||||
format!("in-process request response channel closed: {err}"),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn notify(&self, notification: ClientNotification) -> IoResult<()> {
|
||||
@@ -266,8 +272,11 @@ impl InProcessClientHandle {
|
||||
/// request IDs unique among concurrent requests; reusing an in-flight ID
|
||||
/// produces an `INVALID_REQUEST` response and can make request routing
|
||||
/// ambiguous in the caller.
|
||||
pub async fn request(&self, request: ClientRequest) -> IoResult<PendingClientRequestResponse> {
|
||||
self.client.request(request).await
|
||||
pub fn request(
|
||||
&self,
|
||||
request: ClientRequest,
|
||||
) -> impl std::future::Future<Output = IoResult<PendingClientRequestResponse>> + '_ {
|
||||
self.client.request(request)
|
||||
}
|
||||
|
||||
/// Sends a typed client notification into the in-process runtime.
|
||||
@@ -443,14 +452,13 @@ async fn start_uninitialized(args: InProcessStartArgs) -> IoResult<InProcessClie
|
||||
match command {
|
||||
Some(ProcessorCommand::Request(request)) => {
|
||||
let was_initialized = session.initialized();
|
||||
processor
|
||||
.process_client_request(
|
||||
Box::pin(processor.process_client_request(
|
||||
IN_PROCESS_CONNECTION_ID,
|
||||
*request,
|
||||
request,
|
||||
Arc::clone(&session),
|
||||
&outbound_initialized,
|
||||
)
|
||||
.await;
|
||||
))
|
||||
.await;
|
||||
let opted_out_notification_methods_snapshot =
|
||||
session.opted_out_notification_methods();
|
||||
let experimental_api_enabled =
|
||||
@@ -521,7 +529,6 @@ async fn start_uninitialized(args: InProcessStartArgs) -> IoResult<InProcessClie
|
||||
message = client_rx.recv() => {
|
||||
match message {
|
||||
Some(InProcessClientMessage::Request { request, response_tx }) => {
|
||||
let request = *request;
|
||||
let request_id = request.id().clone();
|
||||
match pending_request_responses.entry(request_id.clone()) {
|
||||
Entry::Vacant(entry) => {
|
||||
@@ -535,7 +542,7 @@ async fn start_uninitialized(args: InProcessStartArgs) -> IoResult<InProcessClie
|
||||
}
|
||||
}
|
||||
|
||||
match processor_tx.try_send(ProcessorCommand::Request(Box::new(request))) {
|
||||
match processor_tx.try_send(ProcessorCommand::Request(request)) {
|
||||
Ok(()) => {}
|
||||
Err(mpsc::error::TrySendError::Full(_)) => {
|
||||
if let Some(response_tx) =
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::collections::HashSet;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
@@ -528,7 +529,7 @@ impl MessageProcessor {
|
||||
Self::run_request_with_context(
|
||||
Arc::clone(&self.outgoing),
|
||||
request_context.clone(),
|
||||
async {
|
||||
Box::pin(async {
|
||||
let codex_request = serde_json::to_value(&request)
|
||||
.map_err(|err| invalid_request(format!("Invalid request: {err}")))
|
||||
.and_then(|request_json| {
|
||||
@@ -541,13 +542,13 @@ impl MessageProcessor {
|
||||
// session state into outbound state and sending initialize notifications to
|
||||
// this specific connection. Passing `None` avoids marking the connection
|
||||
// ready too early from inside the shared request handler.
|
||||
self.handle_client_request(
|
||||
Box::pin(self.handle_client_request(
|
||||
request_id.clone(),
|
||||
codex_request,
|
||||
Arc::clone(&session),
|
||||
/*outbound_initialized*/ None,
|
||||
request_context.clone(),
|
||||
)
|
||||
))
|
||||
.await
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
@@ -555,7 +556,7 @@ impl MessageProcessor {
|
||||
if let Err(error) = result {
|
||||
self.outgoing.send_error(request_id.clone(), error).await;
|
||||
}
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -567,7 +568,7 @@ impl MessageProcessor {
|
||||
pub(crate) async fn process_client_request(
|
||||
self: &Arc<Self>,
|
||||
connection_id: ConnectionId,
|
||||
request: ClientRequest,
|
||||
request: Box<ClientRequest>,
|
||||
session: Arc<ConnectionSessionState>,
|
||||
outbound_initialized: &AtomicBool,
|
||||
) {
|
||||
@@ -575,8 +576,11 @@ impl MessageProcessor {
|
||||
connection_id,
|
||||
request_id: request.id().clone(),
|
||||
};
|
||||
let request_span =
|
||||
crate::app_server_tracing::typed_request_span(&request, connection_id, &session);
|
||||
let request_span = crate::app_server_tracing::typed_request_span(
|
||||
request.as_ref(),
|
||||
connection_id,
|
||||
&session,
|
||||
);
|
||||
let request_context =
|
||||
RequestContext::new(request_id.clone(), request_span, /*parent_trace*/ None);
|
||||
tracing::trace!(
|
||||
@@ -587,23 +591,22 @@ impl MessageProcessor {
|
||||
Self::run_request_with_context(
|
||||
Arc::clone(&self.outgoing),
|
||||
request_context.clone(),
|
||||
async {
|
||||
Box::pin(async {
|
||||
// In-process clients do not have the websocket transport loop that performs
|
||||
// post-initialize bookkeeping, so they still finalize outbound readiness in
|
||||
// the shared request handler.
|
||||
let result = self
|
||||
.handle_client_request(
|
||||
request_id.clone(),
|
||||
request,
|
||||
Arc::clone(&session),
|
||||
Some(outbound_initialized),
|
||||
request_context.clone(),
|
||||
)
|
||||
.await;
|
||||
let result = Box::pin(self.handle_client_request(
|
||||
request_id.clone(),
|
||||
*request,
|
||||
Arc::clone(&session),
|
||||
Some(outbound_initialized),
|
||||
request_context.clone(),
|
||||
))
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
self.outgoing.send_error(request_id.clone(), error).await;
|
||||
}
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -621,13 +624,11 @@ impl MessageProcessor {
|
||||
tracing::info!("<- typed notification: {:?}", notification);
|
||||
}
|
||||
|
||||
async fn run_request_with_context<F>(
|
||||
async fn run_request_with_context(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
request_context: RequestContext,
|
||||
request_fut: F,
|
||||
) where
|
||||
F: Future<Output = ()>,
|
||||
{
|
||||
request_fut: Pin<Box<dyn Future<Output = ()> + Send + '_>>,
|
||||
) {
|
||||
outgoing
|
||||
.register_request_context(request_context.clone())
|
||||
.await;
|
||||
@@ -765,12 +766,12 @@ impl MessageProcessor {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.dispatch_initialized_client_request(
|
||||
Box::pin(self.dispatch_initialized_client_request(
|
||||
connection_request_id,
|
||||
codex_request,
|
||||
session,
|
||||
request_context,
|
||||
)
|
||||
))
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -808,15 +809,14 @@ impl MessageProcessor {
|
||||
rpc_gate,
|
||||
async move {
|
||||
let processor_for_request = Arc::clone(&processor);
|
||||
let result = processor_for_request
|
||||
.handle_initialized_client_request(
|
||||
connection_request_id,
|
||||
codex_request,
|
||||
request_context,
|
||||
app_server_client_name,
|
||||
client_version,
|
||||
)
|
||||
.await;
|
||||
let result = Box::pin(processor_for_request.handle_initialized_client_request(
|
||||
connection_request_id,
|
||||
codex_request,
|
||||
request_context,
|
||||
app_server_client_name,
|
||||
client_version,
|
||||
))
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
processor.outgoing.send_error(error_request_id, error).await;
|
||||
}
|
||||
|
||||
@@ -658,6 +658,7 @@ async fn turn_start_jsonrpc_span_parents_core_turn_spans() -> Result<()> {
|
||||
}],
|
||||
responsesapi_client_metadata: None,
|
||||
cwd: None,
|
||||
workspace_roots: None,
|
||||
approval_policy: None,
|
||||
sandbox_policy: None,
|
||||
permissions: None,
|
||||
|
||||
@@ -103,8 +103,6 @@ use codex_app_server_protocol::MockExperimentalMethodParams;
|
||||
use codex_app_server_protocol::MockExperimentalMethodResponse;
|
||||
use codex_app_server_protocol::ModelListParams;
|
||||
use codex_app_server_protocol::ModelListResponse;
|
||||
use codex_app_server_protocol::PermissionProfileModificationParams;
|
||||
use codex_app_server_protocol::PermissionProfileSelectionParams;
|
||||
use codex_app_server_protocol::PluginDetail;
|
||||
use codex_app_server_protocol::PluginInstallParams;
|
||||
use codex_app_server_protocol::PluginInstallResponse;
|
||||
@@ -354,6 +352,8 @@ use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use codex_protocol::protocol::AgentStatus;
|
||||
@@ -431,6 +431,11 @@ use uuid::Uuid;
|
||||
#[cfg(test)]
|
||||
use codex_app_server_protocol::ServerRequest;
|
||||
|
||||
struct ResolvedPermissionProfileSelection {
|
||||
permission_profile: PermissionProfile,
|
||||
active_permission_profile: ActivePermissionProfile,
|
||||
}
|
||||
|
||||
mod account_processor;
|
||||
mod apps_processor;
|
||||
mod catalog_processor;
|
||||
@@ -442,6 +447,7 @@ mod feedback_processor;
|
||||
mod fs_processor;
|
||||
mod git_processor;
|
||||
mod initialize_processor;
|
||||
mod legacy_sandbox_compat;
|
||||
mod marketplace_processor;
|
||||
mod mcp_processor;
|
||||
mod plugins;
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
use super::*;
|
||||
|
||||
const WORKSPACE_PERMISSION_PROFILE_ID: &str = ":workspace";
|
||||
const READ_ONLY_PERMISSION_PROFILE_ID: &str = ":read-only";
|
||||
const DANGER_NO_SANDBOX_PERMISSION_PROFILE_ID: &str = ":danger-no-sandbox";
|
||||
|
||||
pub(super) struct CurrentPermissionProfile<'a> {
|
||||
pub(super) permission_profile: &'a PermissionProfile,
|
||||
pub(super) workspace_roots: &'a [AbsolutePathBuf],
|
||||
}
|
||||
|
||||
pub(super) struct LegacySandboxProfileSelection {
|
||||
pub(super) permissions: String,
|
||||
pub(super) workspace_roots: Option<Vec<AbsolutePathBuf>>,
|
||||
expected_enforcement: codex_protocol::models::SandboxEnforcement,
|
||||
expected_network: codex_protocol::permissions::NetworkSandboxPolicy,
|
||||
}
|
||||
|
||||
pub(super) enum LegacySandboxResolution {
|
||||
Noop {
|
||||
workspace_roots: Option<Vec<AbsolutePathBuf>>,
|
||||
},
|
||||
Selection(LegacySandboxProfileSelection),
|
||||
}
|
||||
|
||||
pub(super) fn resolve_legacy_sandbox_profile_selection(
|
||||
sandbox_policy: &codex_app_server_protocol::SandboxPolicy,
|
||||
current: Option<CurrentPermissionProfile<'_>>,
|
||||
cwd: &AbsolutePathBuf,
|
||||
explicit_workspace_roots: Option<&[AbsolutePathBuf]>,
|
||||
field_name: &str,
|
||||
) -> Result<LegacySandboxResolution, JSONRPCErrorError> {
|
||||
let legacy_workspace_roots =
|
||||
workspace_roots_from_implicit_legacy_sandbox(cwd, sandbox_policy, explicit_workspace_roots);
|
||||
if let Some(current_match) = legacy_sandbox_current_match(
|
||||
sandbox_policy,
|
||||
current,
|
||||
cwd,
|
||||
explicit_workspace_roots,
|
||||
legacy_workspace_roots.as_deref(),
|
||||
) {
|
||||
return Ok(LegacySandboxResolution::Noop {
|
||||
workspace_roots: current_match.workspace_roots,
|
||||
});
|
||||
}
|
||||
|
||||
let expected_network =
|
||||
codex_protocol::permissions::NetworkSandboxPolicy::from(&sandbox_policy.to_core());
|
||||
match sandbox_policy {
|
||||
codex_app_server_protocol::SandboxPolicy::DangerFullAccess => Ok(
|
||||
LegacySandboxResolution::Selection(LegacySandboxProfileSelection {
|
||||
permissions: DANGER_NO_SANDBOX_PERMISSION_PROFILE_ID.to_string(),
|
||||
workspace_roots: None,
|
||||
expected_enforcement: codex_protocol::models::SandboxEnforcement::Disabled,
|
||||
expected_network,
|
||||
}),
|
||||
),
|
||||
codex_app_server_protocol::SandboxPolicy::ReadOnly { network_access: _ } => Ok(
|
||||
LegacySandboxResolution::Selection(LegacySandboxProfileSelection {
|
||||
permissions: READ_ONLY_PERMISSION_PROFILE_ID.to_string(),
|
||||
workspace_roots: None,
|
||||
expected_enforcement: codex_protocol::models::SandboxEnforcement::Managed,
|
||||
expected_network,
|
||||
}),
|
||||
),
|
||||
codex_app_server_protocol::SandboxPolicy::WorkspaceWrite { .. } => Ok(
|
||||
LegacySandboxResolution::Selection(LegacySandboxProfileSelection {
|
||||
permissions: WORKSPACE_PERMISSION_PROFILE_ID.to_string(),
|
||||
workspace_roots: legacy_workspace_roots,
|
||||
expected_enforcement: codex_protocol::models::SandboxEnforcement::Managed,
|
||||
expected_network,
|
||||
}),
|
||||
),
|
||||
codex_app_server_protocol::SandboxPolicy::ExternalSandbox { .. } => {
|
||||
Err(invalid_request(format!(
|
||||
"`{field_name}` externalSandbox cannot be mapped to a named permissions profile"
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn sandbox_policy_from_legacy_mode(
|
||||
sandbox_mode: SandboxMode,
|
||||
) -> codex_app_server_protocol::SandboxPolicy {
|
||||
match sandbox_mode {
|
||||
SandboxMode::ReadOnly => codex_protocol::protocol::SandboxPolicy::new_read_only_policy(),
|
||||
SandboxMode::WorkspaceWrite => {
|
||||
codex_protocol::protocol::SandboxPolicy::new_workspace_write_policy()
|
||||
}
|
||||
SandboxMode::DangerFullAccess => codex_protocol::protocol::SandboxPolicy::DangerFullAccess,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
pub(super) fn validate_legacy_sandbox_profile_selection(
|
||||
legacy_selection: &LegacySandboxProfileSelection,
|
||||
resolved_selection: &ResolvedPermissionProfileSelection,
|
||||
field_name: &str,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let permission_profile = &resolved_selection.permission_profile;
|
||||
if permission_profile.enforcement() != legacy_selection.expected_enforcement {
|
||||
return Err(invalid_request(format!(
|
||||
"`{field_name}` does not match permissions profile `{}`",
|
||||
legacy_selection.permissions
|
||||
)));
|
||||
}
|
||||
if permission_profile.network_sandbox_policy() != legacy_selection.expected_network {
|
||||
return Err(invalid_request(format!(
|
||||
"`{field_name}` network access does not match permissions profile `{}`",
|
||||
legacy_selection.permissions
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn resolve_cwd_against_fallback(
|
||||
cwd: Option<&Path>,
|
||||
fallback_cwd: &AbsolutePathBuf,
|
||||
) -> AbsolutePathBuf {
|
||||
match cwd {
|
||||
Some(cwd) => {
|
||||
if let Ok(path) = AbsolutePathBuf::try_from(cwd) {
|
||||
path
|
||||
} else {
|
||||
AbsolutePathBuf::resolve_path_against_base(cwd, fallback_cwd.as_path())
|
||||
}
|
||||
}
|
||||
None => fallback_cwd.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
struct LegacySandboxCurrentMatch {
|
||||
workspace_roots: Option<Vec<AbsolutePathBuf>>,
|
||||
}
|
||||
|
||||
fn legacy_sandbox_current_match(
|
||||
sandbox_policy: &codex_app_server_protocol::SandboxPolicy,
|
||||
current: Option<CurrentPermissionProfile<'_>>,
|
||||
cwd: &AbsolutePathBuf,
|
||||
explicit_workspace_roots: Option<&[AbsolutePathBuf]>,
|
||||
legacy_workspace_roots: Option<&[AbsolutePathBuf]>,
|
||||
) -> Option<LegacySandboxCurrentMatch> {
|
||||
let current = current?;
|
||||
|
||||
let projection_workspace_roots = explicit_workspace_roots
|
||||
.or(legacy_workspace_roots)
|
||||
.unwrap_or(current.workspace_roots);
|
||||
let materialized_profile = current
|
||||
.permission_profile
|
||||
.materialize_project_roots_with_workspace_roots(projection_workspace_roots);
|
||||
let file_system_policy = materialized_profile.file_system_sandbox_policy();
|
||||
let active_sandbox = codex_sandboxing::compatibility_sandbox_policy_for_permission_profile(
|
||||
&materialized_profile,
|
||||
&file_system_policy,
|
||||
materialized_profile.network_sandbox_policy(),
|
||||
cwd.as_path(),
|
||||
);
|
||||
if active_sandbox != sandbox_policy.to_core() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let workspace_roots = legacy_workspace_roots
|
||||
.filter(|roots| *roots != current.workspace_roots)
|
||||
.map(<[AbsolutePathBuf]>::to_vec);
|
||||
|
||||
Some(LegacySandboxCurrentMatch { workspace_roots })
|
||||
}
|
||||
|
||||
fn workspace_roots_from_implicit_legacy_sandbox(
|
||||
cwd: &AbsolutePathBuf,
|
||||
sandbox_policy: &codex_app_server_protocol::SandboxPolicy,
|
||||
explicit_workspace_roots: Option<&[AbsolutePathBuf]>,
|
||||
) -> Option<Vec<AbsolutePathBuf>> {
|
||||
if explicit_workspace_roots.is_some()
|
||||
|| !matches!(
|
||||
sandbox_policy,
|
||||
codex_app_server_protocol::SandboxPolicy::WorkspaceWrite { .. }
|
||||
)
|
||||
{
|
||||
None
|
||||
} else {
|
||||
Some(workspace_roots_from_legacy_sandbox(cwd, sandbox_policy))
|
||||
}
|
||||
}
|
||||
|
||||
fn workspace_roots_from_legacy_sandbox(
|
||||
cwd: &AbsolutePathBuf,
|
||||
sandbox_policy: &codex_app_server_protocol::SandboxPolicy,
|
||||
) -> Vec<AbsolutePathBuf> {
|
||||
let mut roots = Vec::with_capacity(1 + sandbox_policy.legacy_writable_roots().len());
|
||||
push_unique_root(&mut roots, cwd.clone());
|
||||
for root in sandbox_policy.legacy_writable_roots() {
|
||||
push_unique_root(&mut roots, root.clone());
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn push_unique_root(roots: &mut Vec<AbsolutePathBuf>, root: AbsolutePathBuf) {
|
||||
if !roots.iter().any(|existing| existing == &root) {
|
||||
roots.push(root);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn abs_test_path(name: &str) -> AbsolutePathBuf {
|
||||
AbsolutePathBuf::from_absolute_path(std::env::temp_dir().join(name))
|
||||
.expect("temp dir path should be absolute")
|
||||
}
|
||||
|
||||
fn workspace_write_policy() -> codex_app_server_protocol::SandboxPolicy {
|
||||
codex_app_server_protocol::SandboxPolicy::WorkspaceWrite {
|
||||
network_access: false,
|
||||
exclude_tmpdir_env_var: false,
|
||||
exclude_slash_tmp: false,
|
||||
legacy_writable_roots: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_workspace_sandbox_updates_roots_when_current_profile_matches_new_cwd() {
|
||||
let old_root = abs_test_path("codex-old-workspace-root");
|
||||
let cwd = abs_test_path("codex-new-workspace-root");
|
||||
let policy = workspace_write_policy();
|
||||
|
||||
let resolution = resolve_legacy_sandbox_profile_selection(
|
||||
&policy,
|
||||
Some(CurrentPermissionProfile {
|
||||
permission_profile: &PermissionProfile::workspace_write(),
|
||||
workspace_roots: std::slice::from_ref(&old_root),
|
||||
}),
|
||||
&cwd,
|
||||
/*explicit_workspace_roots*/ None,
|
||||
"sandboxPolicy",
|
||||
)
|
||||
.expect("legacy sandbox should resolve");
|
||||
|
||||
match resolution {
|
||||
LegacySandboxResolution::Noop {
|
||||
workspace_roots: Some(workspace_roots),
|
||||
} => assert_eq!(workspace_roots, vec![cwd]),
|
||||
_ => panic!("expected workspace-roots-only resolution, got unexpected selection"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_workspace_sandbox_is_noop_when_current_workspace_roots_match() {
|
||||
let cwd = abs_test_path("codex-current-workspace-root");
|
||||
let policy = workspace_write_policy();
|
||||
|
||||
let resolution = resolve_legacy_sandbox_profile_selection(
|
||||
&policy,
|
||||
Some(CurrentPermissionProfile {
|
||||
permission_profile: &PermissionProfile::workspace_write(),
|
||||
workspace_roots: std::slice::from_ref(&cwd),
|
||||
}),
|
||||
&cwd,
|
||||
/*explicit_workspace_roots*/ None,
|
||||
"sandboxPolicy",
|
||||
)
|
||||
.expect("legacy sandbox should resolve");
|
||||
|
||||
match resolution {
|
||||
LegacySandboxResolution::Noop {
|
||||
workspace_roots: None,
|
||||
} => {}
|
||||
_ => panic!("expected no-op resolution, got unexpected workspace roots or selection"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -604,11 +604,13 @@ pub(super) async fn handle_pending_thread_resume_request(
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
cwd,
|
||||
workspace_roots,
|
||||
reasoning_effort,
|
||||
..
|
||||
} = pending.config_snapshot;
|
||||
let instruction_sources = pending.instruction_sources;
|
||||
let sandbox = thread_response_sandbox_policy(&permission_profile, cwd.as_path());
|
||||
let sandbox =
|
||||
thread_response_sandbox_policy(&permission_profile, &workspace_roots, cwd.as_path());
|
||||
let active_permission_profile =
|
||||
thread_response_active_permission_profile(active_permission_profile);
|
||||
let session_id = conversation.session_configured().session_id.to_string();
|
||||
@@ -624,7 +626,7 @@ pub(super) async fn handle_pending_thread_resume_request(
|
||||
approval_policy: approval_policy.into(),
|
||||
approvals_reviewer: approvals_reviewer.into(),
|
||||
sandbox,
|
||||
permission_profile: Some(permission_profile.into()),
|
||||
workspace_roots,
|
||||
active_permission_profile,
|
||||
reasoning_effort,
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::legacy_sandbox_compat::*;
|
||||
use super::*;
|
||||
use crate::error_code::method_not_found;
|
||||
|
||||
@@ -17,6 +18,119 @@ struct ThreadListFilters {
|
||||
use_state_db_only: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PersistedThreadPermissionState {
|
||||
permission_profile: PermissionProfile,
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
workspace_roots: Vec<AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
fn absolute_path_from_history_path(
|
||||
path: &Path,
|
||||
base: Option<&AbsolutePathBuf>,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
if let Ok(path) = AbsolutePathBuf::try_from(path) {
|
||||
Some(path)
|
||||
} else if let Some(base) = base {
|
||||
Some(AbsolutePathBuf::resolve_path_against_base(
|
||||
path,
|
||||
base.as_path(),
|
||||
))
|
||||
} else {
|
||||
AbsolutePathBuf::relative_to_current_dir(path).ok()
|
||||
}
|
||||
}
|
||||
|
||||
fn roots_or_cwd(
|
||||
roots: Vec<AbsolutePathBuf>,
|
||||
cwd: Option<&AbsolutePathBuf>,
|
||||
) -> Vec<AbsolutePathBuf> {
|
||||
if roots.is_empty() {
|
||||
cwd.cloned().into_iter().collect()
|
||||
} else {
|
||||
roots
|
||||
}
|
||||
}
|
||||
|
||||
fn effective_cwd_for_legacy_sandbox(
|
||||
request_cwd: Option<&str>,
|
||||
history_cwd: Option<&Path>,
|
||||
persisted_permission_state: Option<&PersistedThreadPermissionState>,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
let history_cwd =
|
||||
history_cwd.and_then(|cwd| absolute_path_from_history_path(cwd, /*base*/ None));
|
||||
request_cwd
|
||||
.and_then(|cwd| absolute_path_from_history_path(Path::new(cwd), history_cwd.as_ref()))
|
||||
.or_else(|| history_cwd.clone())
|
||||
.or_else(|| {
|
||||
persisted_permission_state
|
||||
.and_then(|state| state.workspace_roots.first())
|
||||
.cloned()
|
||||
})
|
||||
}
|
||||
|
||||
fn persisted_thread_permission_state(
|
||||
history: &InitialHistory,
|
||||
fallback_cwd: Option<&Path>,
|
||||
fallback_sandbox_policy: Option<&codex_protocol::protocol::SandboxPolicy>,
|
||||
) -> Option<PersistedThreadPermissionState> {
|
||||
let mut cwd =
|
||||
fallback_cwd.and_then(|cwd| absolute_path_from_history_path(cwd, /*base*/ None));
|
||||
let mut workspace_roots = None;
|
||||
let mut permission_profile = None;
|
||||
let mut active_permission_profile = None;
|
||||
|
||||
for item in history.get_rollout_items() {
|
||||
match item {
|
||||
RolloutItem::SessionMeta(meta_line) => {
|
||||
cwd = absolute_path_from_history_path(meta_line.meta.cwd.as_path(), cwd.as_ref())
|
||||
.or(cwd);
|
||||
workspace_roots = Some(roots_or_cwd(meta_line.meta.workspace_roots, cwd.as_ref()));
|
||||
}
|
||||
RolloutItem::TurnContext(context) => {
|
||||
cwd = absolute_path_from_history_path(context.cwd.as_path(), cwd.as_ref()).or(cwd);
|
||||
workspace_roots = Some(context.workspace_roots);
|
||||
let context_cwd = cwd
|
||||
.as_ref()
|
||||
.map(AbsolutePathBuf::as_path)
|
||||
.unwrap_or(context.cwd.as_path());
|
||||
permission_profile = Some(context.permission_profile.unwrap_or_else(|| {
|
||||
PermissionProfile::from_legacy_sandbox_policy_for_cwd(
|
||||
&context.sandbox_policy,
|
||||
context_cwd,
|
||||
)
|
||||
}));
|
||||
if context.active_permission_profile.is_some() {
|
||||
active_permission_profile = context.active_permission_profile;
|
||||
}
|
||||
}
|
||||
RolloutItem::EventMsg(EventMsg::SessionConfigured(event)) => {
|
||||
cwd = Some(event.cwd.clone());
|
||||
workspace_roots = Some(event.workspace_roots);
|
||||
permission_profile = Some(event.permission_profile);
|
||||
active_permission_profile = event.active_permission_profile;
|
||||
}
|
||||
RolloutItem::ResponseItem(_) | RolloutItem::Compacted(_) | RolloutItem::EventMsg(_) => {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if permission_profile.is_none() {
|
||||
let cwd = cwd.as_ref()?;
|
||||
let fallback_sandbox_policy = fallback_sandbox_policy?;
|
||||
permission_profile = Some(PermissionProfile::from_legacy_sandbox_policy_for_cwd(
|
||||
fallback_sandbox_policy,
|
||||
cwd.as_path(),
|
||||
));
|
||||
}
|
||||
|
||||
Some(PersistedThreadPermissionState {
|
||||
permission_profile: permission_profile?,
|
||||
active_permission_profile,
|
||||
workspace_roots: workspace_roots.unwrap_or_else(|| cwd.into_iter().collect()),
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_resume_override_mismatches(
|
||||
request: &ThreadResumeParams,
|
||||
config_snapshot: &ThreadConfigSnapshot,
|
||||
@@ -98,12 +212,6 @@ fn collect_resume_override_mismatches(
|
||||
));
|
||||
}
|
||||
}
|
||||
if request.permissions.is_some() {
|
||||
mismatch_details.push(format!(
|
||||
"permissions override was provided and ignored while running; active={:?}",
|
||||
config_snapshot.active_permission_profile
|
||||
));
|
||||
}
|
||||
if let Some(requested_personality) = request.personality.as_ref()
|
||||
&& config_snapshot.personality.as_ref() != Some(requested_personality)
|
||||
{
|
||||
@@ -802,6 +910,7 @@ impl ThreadRequestProcessor {
|
||||
model_provider,
|
||||
service_tier,
|
||||
cwd,
|
||||
workspace_roots,
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
sandbox,
|
||||
@@ -835,6 +944,7 @@ impl ThreadRequestProcessor {
|
||||
model_provider,
|
||||
service_tier,
|
||||
cwd,
|
||||
workspace_roots,
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
sandbox,
|
||||
@@ -975,7 +1085,7 @@ impl ThreadRequestProcessor {
|
||||
let requested_permissions_trust_project =
|
||||
requested_permissions_trust_project(&typesafe_overrides, config.cwd.as_path());
|
||||
let effective_permissions_trust_project = permission_profile_trusts_project(
|
||||
&config.permissions.permission_profile(),
|
||||
config.permissions.permission_profile_ref(),
|
||||
config.cwd.as_path(),
|
||||
);
|
||||
|
||||
@@ -1160,6 +1270,7 @@ impl ThreadRequestProcessor {
|
||||
|
||||
let sandbox = thread_response_sandbox_policy(
|
||||
&config_snapshot.permission_profile,
|
||||
&config_snapshot.workspace_roots,
|
||||
config_snapshot.cwd.as_path(),
|
||||
);
|
||||
let active_permission_profile =
|
||||
@@ -1175,7 +1286,7 @@ impl ThreadRequestProcessor {
|
||||
approval_policy: config_snapshot.approval_policy.into(),
|
||||
approvals_reviewer: config_snapshot.approvals_reviewer.into(),
|
||||
sandbox,
|
||||
permission_profile: Some(config_snapshot.permission_profile.into()),
|
||||
workspace_roots: config_snapshot.workspace_roots,
|
||||
active_permission_profile,
|
||||
reasoning_effort: config_snapshot.reasoning_effort,
|
||||
};
|
||||
@@ -1212,10 +1323,11 @@ impl ThreadRequestProcessor {
|
||||
model_provider: Option<String>,
|
||||
service_tier: Option<Option<String>>,
|
||||
cwd: Option<String>,
|
||||
workspace_roots: Option<Vec<AbsolutePathBuf>>,
|
||||
approval_policy: Option<codex_app_server_protocol::AskForApproval>,
|
||||
approvals_reviewer: Option<codex_app_server_protocol::ApprovalsReviewer>,
|
||||
sandbox: Option<SandboxMode>,
|
||||
permissions: Option<PermissionProfileSelectionParams>,
|
||||
permissions: Option<String>,
|
||||
base_instructions: Option<String>,
|
||||
developer_instructions: Option<String>,
|
||||
personality: Option<Personality>,
|
||||
@@ -1225,6 +1337,8 @@ impl ThreadRequestProcessor {
|
||||
model_provider,
|
||||
service_tier,
|
||||
cwd: cwd.map(PathBuf::from),
|
||||
workspace_roots: workspace_roots
|
||||
.map(|roots| roots.into_iter().map(|root| root.to_path_buf()).collect()),
|
||||
approval_policy: approval_policy
|
||||
.map(codex_app_server_protocol::AskForApproval::to_core),
|
||||
approvals_reviewer: approvals_reviewer
|
||||
@@ -1241,6 +1355,47 @@ impl ThreadRequestProcessor {
|
||||
overrides
|
||||
}
|
||||
|
||||
async fn validate_active_permission_profile_selection(
|
||||
&self,
|
||||
permissions: String,
|
||||
request_overrides: Option<HashMap<String, serde_json::Value>>,
|
||||
cwd: Option<PathBuf>,
|
||||
fallback_cwd: Option<PathBuf>,
|
||||
) -> Result<ResolvedPermissionProfileSelection, JSONRPCErrorError> {
|
||||
let mut overrides = ConfigOverrides {
|
||||
cwd,
|
||||
codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(),
|
||||
main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
apply_permission_profile_selection_to_config_overrides(&mut overrides, Some(permissions));
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_for_cwd(request_overrides, overrides, fallback_cwd)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
if let Some(warning) = config.startup_warnings.iter().find(|warning| {
|
||||
warning.contains("Configured value for `permission_profile` is disallowed")
|
||||
}) {
|
||||
return Err(invalid_request(format!(
|
||||
"invalid permission profile selection: {warning}"
|
||||
)));
|
||||
}
|
||||
let active_permission_profile =
|
||||
config
|
||||
.permissions
|
||||
.active_permission_profile()
|
||||
.ok_or_else(|| {
|
||||
invalid_request(
|
||||
"permission profile selection did not resolve to a named profile",
|
||||
)
|
||||
})?;
|
||||
Ok(ResolvedPermissionProfileSelection {
|
||||
permission_profile: config.permissions.permission_profile(),
|
||||
active_permission_profile,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_environment_selections(
|
||||
&self,
|
||||
environments: Option<Vec<TurnEnvironmentParams>>,
|
||||
@@ -2381,6 +2536,7 @@ impl ThreadRequestProcessor {
|
||||
model_provider,
|
||||
service_tier,
|
||||
cwd,
|
||||
workspace_roots,
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
sandbox,
|
||||
@@ -2393,6 +2549,7 @@ impl ThreadRequestProcessor {
|
||||
persist_extended_history: _persist_extended_history,
|
||||
} = params;
|
||||
let include_turns = !exclude_turns;
|
||||
let mut workspace_roots = workspace_roots;
|
||||
|
||||
let (thread_history, resume_source_thread) = match if let Some(history) = history {
|
||||
self.resume_thread_from_history(history.as_slice())
|
||||
@@ -2411,19 +2568,147 @@ impl ThreadRequestProcessor {
|
||||
};
|
||||
|
||||
let history_cwd = thread_history.session_cwd();
|
||||
let persisted_permission_state = persisted_thread_permission_state(
|
||||
&thread_history,
|
||||
history_cwd.as_deref(),
|
||||
resume_source_thread
|
||||
.as_ref()
|
||||
.map(|thread| &thread.sandbox_policy),
|
||||
);
|
||||
let permission_profile_selection = if let Some(permissions) = permissions {
|
||||
match self
|
||||
.validate_active_permission_profile_selection(
|
||||
permissions,
|
||||
request_overrides.clone(),
|
||||
cwd.clone().map(PathBuf::from),
|
||||
history_cwd.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(selection) => Some(selection),
|
||||
Err(error) => {
|
||||
self.outgoing.send_error(request_id, error).await;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
} else if let Some(sandbox_mode) = sandbox {
|
||||
let sandbox_policy = sandbox_policy_from_legacy_mode(sandbox_mode);
|
||||
let Some(effective_cwd) = effective_cwd_for_legacy_sandbox(
|
||||
cwd.as_deref(),
|
||||
history_cwd.as_deref(),
|
||||
persisted_permission_state.as_ref(),
|
||||
) else {
|
||||
self.outgoing
|
||||
.send_error(
|
||||
request_id,
|
||||
invalid_request("`sandbox` requires a cwd to resolve legacy permissions"),
|
||||
)
|
||||
.await;
|
||||
return Ok(());
|
||||
};
|
||||
match resolve_legacy_sandbox_profile_selection(
|
||||
&sandbox_policy,
|
||||
persisted_permission_state
|
||||
.as_ref()
|
||||
.map(|state| CurrentPermissionProfile {
|
||||
permission_profile: &state.permission_profile,
|
||||
workspace_roots: &state.workspace_roots,
|
||||
}),
|
||||
&effective_cwd,
|
||||
workspace_roots.as_deref(),
|
||||
"sandbox",
|
||||
) {
|
||||
Ok(LegacySandboxResolution::Noop {
|
||||
workspace_roots: legacy_workspace_roots,
|
||||
}) => {
|
||||
if workspace_roots.is_none() {
|
||||
workspace_roots = legacy_workspace_roots;
|
||||
}
|
||||
None
|
||||
}
|
||||
Ok(LegacySandboxResolution::Selection(legacy_selection)) => {
|
||||
if workspace_roots.is_none() {
|
||||
workspace_roots = legacy_selection.workspace_roots.clone();
|
||||
}
|
||||
match self
|
||||
.validate_active_permission_profile_selection(
|
||||
legacy_selection.permissions.clone(),
|
||||
request_overrides.clone(),
|
||||
cwd.clone().map(PathBuf::from),
|
||||
history_cwd.clone(),
|
||||
)
|
||||
.await
|
||||
.and_then(|selection| {
|
||||
validate_legacy_sandbox_profile_selection(
|
||||
&legacy_selection,
|
||||
&selection,
|
||||
"sandbox",
|
||||
)
|
||||
.map(|()| selection)
|
||||
}) {
|
||||
Ok(selection) => Some(selection),
|
||||
Err(error) => {
|
||||
self.outgoing.send_error(request_id, error).await;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
self.outgoing.send_error(request_id, error).await;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let active_permission_profile = permission_profile_selection
|
||||
.as_ref()
|
||||
.map(|selection| selection.active_permission_profile.clone())
|
||||
.or_else(|| {
|
||||
persisted_permission_state
|
||||
.as_ref()
|
||||
.and_then(|state| state.active_permission_profile.clone())
|
||||
});
|
||||
let expected_active_permission_profile_source = permission_profile_selection
|
||||
.as_ref()
|
||||
.map(|selection| selection.permission_profile.clone())
|
||||
.or_else(|| {
|
||||
persisted_permission_state
|
||||
.as_ref()
|
||||
.map(|state| state.permission_profile.clone())
|
||||
});
|
||||
let workspace_roots_were_explicit = workspace_roots.is_some();
|
||||
let mut typesafe_overrides = self.build_thread_config_overrides(
|
||||
model,
|
||||
model_provider,
|
||||
service_tier,
|
||||
cwd,
|
||||
workspace_roots,
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
sandbox,
|
||||
permissions,
|
||||
/*sandbox*/ None,
|
||||
/*permissions*/ None,
|
||||
base_instructions,
|
||||
developer_instructions,
|
||||
personality,
|
||||
);
|
||||
typesafe_overrides.permission_profile = expected_active_permission_profile_source.clone();
|
||||
if !workspace_roots_were_explicit {
|
||||
if let Some(persisted_permission_state) = persisted_permission_state.as_ref() {
|
||||
typesafe_overrides.workspace_roots = Some(
|
||||
persisted_permission_state
|
||||
.workspace_roots
|
||||
.iter()
|
||||
.map(codex_utils_absolute_path::AbsolutePathBuf::to_path_buf)
|
||||
.collect(),
|
||||
);
|
||||
} else if let Some(root) = history_cwd
|
||||
.as_deref()
|
||||
.and_then(|cwd| absolute_path_from_history_path(cwd, /*base*/ None))
|
||||
{
|
||||
typesafe_overrides.workspace_roots = Some(vec![root.to_path_buf()]);
|
||||
}
|
||||
}
|
||||
self.load_and_apply_persisted_resume_metadata(
|
||||
&thread_history,
|
||||
&mut request_overrides,
|
||||
@@ -2432,7 +2717,7 @@ impl ThreadRequestProcessor {
|
||||
.await;
|
||||
|
||||
// Derive a Config using the same logic as new conversation, honoring overrides if provided.
|
||||
let config = match self
|
||||
let mut config = match self
|
||||
.config_manager
|
||||
.load_for_cwd(request_overrides, typesafe_overrides, history_cwd)
|
||||
.await
|
||||
@@ -2444,6 +2729,12 @@ impl ThreadRequestProcessor {
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
config
|
||||
.permissions
|
||||
.set_active_permission_profile_for_current_profile(
|
||||
active_permission_profile,
|
||||
expected_active_permission_profile_source.as_ref(),
|
||||
);
|
||||
|
||||
let instruction_sources = Self::instruction_sources_from_config(&config).await;
|
||||
let response_history = thread_history.clone();
|
||||
@@ -2537,6 +2828,7 @@ impl ThreadRequestProcessor {
|
||||
let config_snapshot = codex_thread.config_snapshot().await;
|
||||
let sandbox = thread_response_sandbox_policy(
|
||||
&config_snapshot.permission_profile,
|
||||
&config_snapshot.workspace_roots,
|
||||
config_snapshot.cwd.as_path(),
|
||||
);
|
||||
let active_permission_profile = thread_response_active_permission_profile(
|
||||
@@ -2557,7 +2849,7 @@ impl ThreadRequestProcessor {
|
||||
approval_policy: session_configured.approval_policy.into(),
|
||||
approvals_reviewer: session_configured.approvals_reviewer.into(),
|
||||
sandbox,
|
||||
permission_profile: Some(config_snapshot.permission_profile.into()),
|
||||
workspace_roots: config_snapshot.workspace_roots,
|
||||
active_permission_profile,
|
||||
reasoning_effort: session_configured.reasoning_effort,
|
||||
};
|
||||
@@ -2711,6 +3003,94 @@ impl ThreadRequestProcessor {
|
||||
)
|
||||
.await?;
|
||||
|
||||
let config_snapshot = existing_thread.config_snapshot().await;
|
||||
let mut workspace_roots = params.workspace_roots.clone();
|
||||
let permission_profile_selection = if let Some(permissions) = params.permissions.clone()
|
||||
{
|
||||
Some(
|
||||
self.validate_active_permission_profile_selection(
|
||||
permissions,
|
||||
/*request_overrides*/ None,
|
||||
/*cwd*/ None,
|
||||
Some(config_snapshot.cwd.to_path_buf()),
|
||||
)
|
||||
.await?,
|
||||
)
|
||||
} else if let Some(sandbox_mode) = params.sandbox {
|
||||
let sandbox_policy = sandbox_policy_from_legacy_mode(sandbox_mode);
|
||||
match resolve_legacy_sandbox_profile_selection(
|
||||
&sandbox_policy,
|
||||
Some(CurrentPermissionProfile {
|
||||
permission_profile: &config_snapshot.permission_profile,
|
||||
workspace_roots: &config_snapshot.workspace_roots,
|
||||
}),
|
||||
&config_snapshot.cwd,
|
||||
workspace_roots.as_deref(),
|
||||
"sandbox",
|
||||
)? {
|
||||
LegacySandboxResolution::Noop {
|
||||
workspace_roots: legacy_workspace_roots,
|
||||
} => {
|
||||
if workspace_roots.is_none() {
|
||||
workspace_roots = legacy_workspace_roots;
|
||||
}
|
||||
None
|
||||
}
|
||||
LegacySandboxResolution::Selection(legacy_selection) => {
|
||||
if workspace_roots.is_none() {
|
||||
workspace_roots = legacy_selection.workspace_roots.clone();
|
||||
}
|
||||
let selection = self
|
||||
.validate_active_permission_profile_selection(
|
||||
legacy_selection.permissions.clone(),
|
||||
/*request_overrides*/ None,
|
||||
/*cwd*/ None,
|
||||
Some(config_snapshot.cwd.to_path_buf()),
|
||||
)
|
||||
.await?;
|
||||
validate_legacy_sandbox_profile_selection(
|
||||
&legacy_selection,
|
||||
&selection,
|
||||
"sandbox",
|
||||
)?;
|
||||
Some(selection)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if workspace_roots.is_some() || permission_profile_selection.is_some() {
|
||||
existing_thread
|
||||
.update_turn_context_overrides(CodexThreadTurnContextOverrides {
|
||||
cwd: None,
|
||||
workspace_roots: workspace_roots.map(|roots| {
|
||||
roots
|
||||
.into_iter()
|
||||
.map(AbsolutePathBuf::into_path_buf)
|
||||
.collect()
|
||||
}),
|
||||
approval_policy: None,
|
||||
approvals_reviewer: None,
|
||||
sandbox_policy: None,
|
||||
permission_profile: permission_profile_selection
|
||||
.as_ref()
|
||||
.map(|selection| selection.permission_profile.clone()),
|
||||
active_permission_profile: permission_profile_selection
|
||||
.map(|selection| selection.active_permission_profile),
|
||||
windows_sandbox_level: None,
|
||||
model: None,
|
||||
effort: None,
|
||||
summary: None,
|
||||
service_tier: None,
|
||||
collaboration_mode: None,
|
||||
personality: None,
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
invalid_request(format!("invalid thread resume override: {err}"))
|
||||
})?;
|
||||
}
|
||||
|
||||
let config_snapshot = existing_thread.config_snapshot().await;
|
||||
let mismatch_details = collect_resume_override_mismatches(params, &config_snapshot);
|
||||
if !mismatch_details.is_empty() {
|
||||
@@ -3017,6 +3397,7 @@ impl ThreadRequestProcessor {
|
||||
model_provider,
|
||||
service_tier,
|
||||
cwd,
|
||||
workspace_roots,
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
sandbox,
|
||||
@@ -3077,26 +3458,123 @@ impl ThreadRequestProcessor {
|
||||
} else {
|
||||
Some(cli_overrides)
|
||||
};
|
||||
let fork_history = InitialHistory::Forked(history_items.clone());
|
||||
let persisted_permission_state = persisted_thread_permission_state(
|
||||
&fork_history,
|
||||
history_cwd.as_deref(),
|
||||
Some(&source_thread.sandbox_policy),
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
invalid_request("thread history is missing persisted permission configuration")
|
||||
})?;
|
||||
let mut workspace_roots = workspace_roots;
|
||||
let permission_profile_selection = if let Some(permissions) = permissions {
|
||||
Some(
|
||||
self.validate_active_permission_profile_selection(
|
||||
permissions,
|
||||
request_overrides.clone(),
|
||||
cwd.clone().map(PathBuf::from),
|
||||
history_cwd.clone(),
|
||||
)
|
||||
.await?,
|
||||
)
|
||||
} else if let Some(sandbox_mode) = sandbox {
|
||||
let sandbox_policy = sandbox_policy_from_legacy_mode(sandbox_mode);
|
||||
let effective_cwd = effective_cwd_for_legacy_sandbox(
|
||||
cwd.as_deref(),
|
||||
history_cwd.as_deref(),
|
||||
Some(&persisted_permission_state),
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
invalid_request("`sandbox` requires a cwd to resolve legacy permissions")
|
||||
})?;
|
||||
match resolve_legacy_sandbox_profile_selection(
|
||||
&sandbox_policy,
|
||||
Some(CurrentPermissionProfile {
|
||||
permission_profile: &persisted_permission_state.permission_profile,
|
||||
workspace_roots: &persisted_permission_state.workspace_roots,
|
||||
}),
|
||||
&effective_cwd,
|
||||
workspace_roots.as_deref(),
|
||||
"sandbox",
|
||||
)? {
|
||||
LegacySandboxResolution::Noop {
|
||||
workspace_roots: legacy_workspace_roots,
|
||||
} => {
|
||||
if workspace_roots.is_none() {
|
||||
workspace_roots = legacy_workspace_roots;
|
||||
}
|
||||
None
|
||||
}
|
||||
LegacySandboxResolution::Selection(legacy_selection) => {
|
||||
if workspace_roots.is_none() {
|
||||
workspace_roots = legacy_selection.workspace_roots.clone();
|
||||
}
|
||||
let selection = self
|
||||
.validate_active_permission_profile_selection(
|
||||
legacy_selection.permissions.clone(),
|
||||
request_overrides.clone(),
|
||||
cwd.clone().map(PathBuf::from),
|
||||
history_cwd.clone(),
|
||||
)
|
||||
.await?;
|
||||
validate_legacy_sandbox_profile_selection(
|
||||
&legacy_selection,
|
||||
&selection,
|
||||
"sandbox",
|
||||
)?;
|
||||
Some(selection)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let active_permission_profile = permission_profile_selection
|
||||
.as_ref()
|
||||
.map(|selection| selection.active_permission_profile.clone())
|
||||
.or_else(|| persisted_permission_state.active_permission_profile.clone());
|
||||
let expected_active_permission_profile_source = permission_profile_selection
|
||||
.as_ref()
|
||||
.map(|selection| selection.permission_profile.clone())
|
||||
.or_else(|| Some(persisted_permission_state.permission_profile.clone()));
|
||||
let workspace_roots_were_explicit = workspace_roots.is_some();
|
||||
let mut typesafe_overrides = self.build_thread_config_overrides(
|
||||
model,
|
||||
model_provider,
|
||||
service_tier,
|
||||
cwd,
|
||||
workspace_roots,
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
sandbox,
|
||||
permissions,
|
||||
/*sandbox*/ None,
|
||||
/*permissions*/ None,
|
||||
base_instructions,
|
||||
developer_instructions,
|
||||
/*personality*/ None,
|
||||
);
|
||||
typesafe_overrides.permission_profile = expected_active_permission_profile_source.clone();
|
||||
if !workspace_roots_were_explicit {
|
||||
typesafe_overrides.workspace_roots = Some(
|
||||
persisted_permission_state
|
||||
.workspace_roots
|
||||
.iter()
|
||||
.map(codex_utils_absolute_path::AbsolutePathBuf::to_path_buf)
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
typesafe_overrides.ephemeral = ephemeral.then_some(true);
|
||||
// Derive a Config using the same logic as new conversation, honoring overrides if provided.
|
||||
let config = self
|
||||
let mut config = self
|
||||
.config_manager
|
||||
.load_for_cwd(request_overrides, typesafe_overrides, history_cwd)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
config
|
||||
.permissions
|
||||
.set_active_permission_profile_for_current_profile(
|
||||
active_permission_profile,
|
||||
expected_active_permission_profile_source.as_ref(),
|
||||
);
|
||||
|
||||
let fallback_model_provider = config.model_provider_id.clone();
|
||||
let instruction_sources = Self::instruction_sources_from_config(&config).await;
|
||||
@@ -3200,6 +3678,7 @@ impl ThreadRequestProcessor {
|
||||
let config_snapshot = forked_thread.config_snapshot().await;
|
||||
let sandbox = thread_response_sandbox_policy(
|
||||
&config_snapshot.permission_profile,
|
||||
&config_snapshot.workspace_roots,
|
||||
config_snapshot.cwd.as_path(),
|
||||
);
|
||||
let active_permission_profile =
|
||||
@@ -3215,7 +3694,7 @@ impl ThreadRequestProcessor {
|
||||
approval_policy: session_configured.approval_policy.into(),
|
||||
approvals_reviewer: session_configured.approvals_reviewer.into(),
|
||||
sandbox,
|
||||
permission_profile: Some(config_snapshot.permission_profile.into()),
|
||||
workspace_roots: config_snapshot.workspace_roots,
|
||||
active_permission_profile,
|
||||
reasoning_effort: session_configured.reasoning_effort,
|
||||
};
|
||||
|
||||
@@ -495,6 +495,101 @@ mod thread_processor_behavior_tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persisted_thread_permission_state_uses_latest_turn_active_profile() {
|
||||
let cwd = test_path_buf("/tmp/project").abs();
|
||||
let workspace_root = test_path_buf("/tmp/workspace").abs();
|
||||
let active_permission_profile =
|
||||
codex_protocol::models::ActivePermissionProfile::new(":workspace");
|
||||
let permission_profile = codex_protocol::models::PermissionProfile::workspace_write();
|
||||
|
||||
let history = codex_protocol::protocol::InitialHistory::Forked(vec![
|
||||
codex_protocol::protocol::RolloutItem::TurnContext(
|
||||
codex_protocol::protocol::TurnContextItem {
|
||||
turn_id: Some("turn-1".to_string()),
|
||||
trace_id: None,
|
||||
cwd: cwd.to_path_buf(),
|
||||
workspace_roots: vec![workspace_root.clone()],
|
||||
current_date: None,
|
||||
timezone: None,
|
||||
approval_policy: AskForApproval::Never,
|
||||
sandbox_policy: SandboxPolicy::new_workspace_write_policy(),
|
||||
permission_profile: Some(permission_profile.clone()),
|
||||
active_permission_profile: Some(active_permission_profile.clone()),
|
||||
network: None,
|
||||
file_system_sandbox_policy: None,
|
||||
model: "gpt-5".to_string(),
|
||||
personality: None,
|
||||
collaboration_mode: None,
|
||||
realtime_active: None,
|
||||
effort: None,
|
||||
summary: codex_protocol::config_types::ReasoningSummary::Auto,
|
||||
user_instructions: None,
|
||||
developer_instructions: None,
|
||||
final_output_json_schema: None,
|
||||
truncation_policy: None,
|
||||
},
|
||||
),
|
||||
]);
|
||||
|
||||
let persisted = persisted_thread_permission_state(
|
||||
&history,
|
||||
Some(cwd.as_path()),
|
||||
/*fallback_sandbox_policy*/ None,
|
||||
)
|
||||
.expect("permission state should be reconstructed");
|
||||
|
||||
assert_eq!(persisted.permission_profile, permission_profile);
|
||||
assert_eq!(
|
||||
persisted.active_permission_profile,
|
||||
Some(active_permission_profile)
|
||||
);
|
||||
assert_eq!(persisted.workspace_roots, vec![workspace_root]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persisted_thread_permission_state_preserves_empty_workspace_roots_from_event_roundtrip() {
|
||||
let cwd = test_path_buf("/tmp/project").abs();
|
||||
let thread_id = ThreadId::from_string("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap();
|
||||
let permission_profile = codex_protocol::models::PermissionProfile::workspace_write();
|
||||
let event = codex_protocol::protocol::EventMsg::SessionConfigured(
|
||||
codex_protocol::protocol::SessionConfiguredEvent {
|
||||
session_id: thread_id.into(),
|
||||
thread_id,
|
||||
forked_from_id: None,
|
||||
thread_source: None,
|
||||
thread_name: None,
|
||||
model: "gpt-5".to_string(),
|
||||
model_provider_id: "mock_provider".to_string(),
|
||||
service_tier: None,
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer::User,
|
||||
permission_profile: permission_profile.clone(),
|
||||
active_permission_profile: None,
|
||||
cwd: cwd.clone(),
|
||||
workspace_roots: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
initial_messages: None,
|
||||
network_proxy: None,
|
||||
rollout_path: None,
|
||||
},
|
||||
);
|
||||
let event = serde_json::from_value(serde_json::to_value(event).unwrap()).unwrap();
|
||||
let history = codex_protocol::protocol::InitialHistory::Forked(vec![
|
||||
codex_protocol::protocol::RolloutItem::EventMsg(event),
|
||||
]);
|
||||
|
||||
let persisted = persisted_thread_permission_state(
|
||||
&history,
|
||||
Some(cwd.as_path()),
|
||||
/*fallback_sandbox_policy*/ None,
|
||||
)
|
||||
.expect("permission state should be reconstructed");
|
||||
|
||||
assert_eq!(persisted.permission_profile, permission_profile);
|
||||
assert_eq!(persisted.workspace_roots, Vec::<AbsolutePathBuf>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_load_error_marks_cloud_requirements_failures_for_relogin() {
|
||||
let err = std::io::Error::other(CloudRequirementsLoadError::new(
|
||||
@@ -630,6 +725,7 @@ mod thread_processor_behavior_tests {
|
||||
model_provider: None,
|
||||
service_tier: Some(Some("priority".to_string())),
|
||||
cwd: None,
|
||||
workspace_roots: None,
|
||||
approval_policy: None,
|
||||
approvals_reviewer: None,
|
||||
sandbox: None,
|
||||
@@ -650,6 +746,7 @@ mod thread_processor_behavior_tests {
|
||||
permission_profile: codex_protocol::models::PermissionProfile::Disabled,
|
||||
active_permission_profile: None,
|
||||
cwd,
|
||||
workspace_roots: Vec::new(),
|
||||
ephemeral: false,
|
||||
reasoning_effort: None,
|
||||
personality: None,
|
||||
|
||||
@@ -177,32 +177,26 @@ pub(super) fn thread_response_active_permission_profile(
|
||||
|
||||
pub(super) fn apply_permission_profile_selection_to_config_overrides(
|
||||
overrides: &mut ConfigOverrides,
|
||||
permissions: Option<PermissionProfileSelectionParams>,
|
||||
permissions: Option<String>,
|
||||
) {
|
||||
let Some(PermissionProfileSelectionParams::Profile { id, modifications }) = permissions else {
|
||||
let Some(id) = permissions else {
|
||||
return;
|
||||
};
|
||||
overrides.default_permissions = Some(id);
|
||||
overrides
|
||||
.additional_writable_roots
|
||||
.extend(modifications.unwrap_or_default().into_iter().map(
|
||||
|modification| match modification {
|
||||
PermissionProfileModificationParams::AdditionalWritableRoot { path } => {
|
||||
path.to_path_buf()
|
||||
}
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
pub(super) fn thread_response_sandbox_policy(
|
||||
permission_profile: &codex_protocol::models::PermissionProfile,
|
||||
workspace_roots: &[AbsolutePathBuf],
|
||||
cwd: &Path,
|
||||
) -> codex_app_server_protocol::SandboxPolicy {
|
||||
let file_system_policy = permission_profile.file_system_sandbox_policy();
|
||||
let materialized_permission_profile =
|
||||
permission_profile.materialize_project_roots_with_workspace_roots(workspace_roots);
|
||||
let file_system_policy = materialized_permission_profile.file_system_sandbox_policy();
|
||||
let sandbox_policy = codex_sandboxing::compatibility_sandbox_policy_for_permission_profile(
|
||||
permission_profile,
|
||||
&materialized_permission_profile,
|
||||
&file_system_policy,
|
||||
permission_profile.network_sandbox_policy(),
|
||||
materialized_permission_profile.network_sandbox_policy(),
|
||||
cwd,
|
||||
);
|
||||
sandbox_policy.into()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::legacy_sandbox_compat::*;
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -357,6 +358,7 @@ impl TurnRequestProcessor {
|
||||
let turn_has_input = !mapped_items.is_empty();
|
||||
|
||||
let has_any_overrides = params.cwd.is_some()
|
||||
|| params.workspace_roots.is_some()
|
||||
|| params.approval_policy.is_some()
|
||||
|| params.approvals_reviewer.is_some()
|
||||
|| params.sandbox_policy.is_some()
|
||||
@@ -375,47 +377,70 @@ impl TurnRequestProcessor {
|
||||
}
|
||||
|
||||
let cwd = params.cwd;
|
||||
let mut workspace_roots = params.workspace_roots;
|
||||
let approval_policy = params.approval_policy.map(AskForApproval::to_core);
|
||||
let approvals_reviewer = params
|
||||
.approvals_reviewer
|
||||
.map(codex_app_server_protocol::ApprovalsReviewer::to_core);
|
||||
let sandbox_policy = params.sandbox_policy.map(|p| p.to_core());
|
||||
let legacy_sandbox_policy = params.sandbox_policy;
|
||||
let sandbox_policy = None;
|
||||
let (permission_profile, active_permission_profile) =
|
||||
if let Some(permissions) = params.permissions {
|
||||
let snapshot = thread.config_snapshot().await;
|
||||
let mut overrides = ConfigOverrides {
|
||||
cwd: cwd.clone(),
|
||||
codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(),
|
||||
main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
apply_permission_profile_selection_to_config_overrides(
|
||||
&mut overrides,
|
||||
Some(permissions),
|
||||
);
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_for_cwd(
|
||||
/*request_overrides*/ None,
|
||||
overrides,
|
||||
let selection = self
|
||||
.validate_active_permission_profile_selection(
|
||||
permissions,
|
||||
cwd.clone(),
|
||||
Some(snapshot.cwd.to_path_buf()),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
// Startup config is allowed to fall back when requirements
|
||||
// disallow a configured profile. An explicit turn request
|
||||
// is different: reject it before accepting user input.
|
||||
if let Some(warning) = config.startup_warnings.iter().find(|warning| {
|
||||
warning.contains("Configured value for `permission_profile` is disallowed")
|
||||
}) {
|
||||
return Err(invalid_request(format!(
|
||||
"invalid turn context override: {warning}"
|
||||
)));
|
||||
}
|
||||
.await?;
|
||||
(
|
||||
Some(config.permissions.permission_profile()),
|
||||
config.permissions.active_permission_profile(),
|
||||
Some(selection.permission_profile),
|
||||
Some(selection.active_permission_profile),
|
||||
)
|
||||
} else if let Some(legacy_sandbox_policy) = legacy_sandbox_policy.as_ref() {
|
||||
let snapshot = thread.config_snapshot().await;
|
||||
let effective_cwd = resolve_cwd_against_fallback(cwd.as_deref(), &snapshot.cwd);
|
||||
match resolve_legacy_sandbox_profile_selection(
|
||||
legacy_sandbox_policy,
|
||||
Some(CurrentPermissionProfile {
|
||||
permission_profile: &snapshot.permission_profile,
|
||||
workspace_roots: &snapshot.workspace_roots,
|
||||
}),
|
||||
&effective_cwd,
|
||||
workspace_roots.as_deref(),
|
||||
"sandboxPolicy",
|
||||
)? {
|
||||
LegacySandboxResolution::Noop {
|
||||
workspace_roots: legacy_workspace_roots,
|
||||
} => {
|
||||
if workspace_roots.is_none() {
|
||||
workspace_roots = legacy_workspace_roots;
|
||||
}
|
||||
(None, None)
|
||||
}
|
||||
LegacySandboxResolution::Selection(legacy_selection) => {
|
||||
if workspace_roots.is_none() {
|
||||
workspace_roots = legacy_selection.workspace_roots.clone();
|
||||
}
|
||||
let selection = self
|
||||
.validate_active_permission_profile_selection(
|
||||
legacy_selection.permissions.clone(),
|
||||
cwd.clone(),
|
||||
Some(snapshot.cwd.to_path_buf()),
|
||||
)
|
||||
.await?;
|
||||
validate_legacy_sandbox_profile_selection(
|
||||
&legacy_selection,
|
||||
&selection,
|
||||
"sandboxPolicy",
|
||||
)?;
|
||||
(
|
||||
Some(selection.permission_profile),
|
||||
Some(selection.active_permission_profile),
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
@@ -432,6 +457,9 @@ impl TurnRequestProcessor {
|
||||
thread
|
||||
.validate_turn_context_overrides(CodexThreadTurnContextOverrides {
|
||||
cwd: cwd.clone(),
|
||||
workspace_roots: workspace_roots
|
||||
.clone()
|
||||
.map(|roots| roots.into_iter().map(|root| root.to_path_buf()).collect()),
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
sandbox_policy: sandbox_policy.clone(),
|
||||
@@ -457,6 +485,7 @@ impl TurnRequestProcessor {
|
||||
final_output_json_schema: params.output_schema,
|
||||
responsesapi_client_metadata: params.responsesapi_client_metadata,
|
||||
cwd,
|
||||
workspace_roots,
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
sandbox_policy,
|
||||
@@ -516,6 +545,49 @@ impl TurnRequestProcessor {
|
||||
Ok(TurnStartResponse { turn })
|
||||
}
|
||||
|
||||
async fn validate_active_permission_profile_selection(
|
||||
&self,
|
||||
permissions: String,
|
||||
cwd: Option<PathBuf>,
|
||||
fallback_cwd: Option<PathBuf>,
|
||||
) -> Result<ResolvedPermissionProfileSelection, JSONRPCErrorError> {
|
||||
let mut overrides = ConfigOverrides {
|
||||
cwd,
|
||||
codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(),
|
||||
main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
apply_permission_profile_selection_to_config_overrides(&mut overrides, Some(permissions));
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_for_cwd(/*request_overrides*/ None, overrides, fallback_cwd)
|
||||
.await
|
||||
.map_err(|err| config_load_error(&err))?;
|
||||
// Startup config is allowed to fall back when requirements disallow a
|
||||
// configured profile. An explicit turn request is different: reject it
|
||||
// before accepting user input.
|
||||
if let Some(warning) = config.startup_warnings.iter().find(|warning| {
|
||||
warning.contains("Configured value for `permission_profile` is disallowed")
|
||||
}) {
|
||||
return Err(invalid_request(format!(
|
||||
"invalid turn context override: {warning}"
|
||||
)));
|
||||
}
|
||||
let active_permission_profile =
|
||||
config
|
||||
.permissions
|
||||
.active_permission_profile()
|
||||
.ok_or_else(|| {
|
||||
invalid_request(
|
||||
"permission profile selection did not resolve to a named profile",
|
||||
)
|
||||
})?;
|
||||
Ok(ResolvedPermissionProfileSelection {
|
||||
permission_profile: config.permissions.permission_profile(),
|
||||
active_permission_profile,
|
||||
})
|
||||
}
|
||||
|
||||
async fn thread_inject_items_response_inner(
|
||||
&self,
|
||||
params: ThreadInjectItemsParams,
|
||||
|
||||
Reference in New Issue
Block a user