Propagate goal permission context

This commit is contained in:
David Wiesen
2026-06-23 13:39:25 -07:00
parent 4cc6a4bab5
commit 98575744db
12 changed files with 434 additions and 8 deletions
+37 -1
View File
@@ -3679,12 +3679,48 @@
},
"ThreadGoalSetParams": {
"properties": {
"approvalPolicy": {
"anyOf": [
{
"$ref": "#/definitions/AskForApproval"
},
{
"type": "null"
}
]
},
"approvalsReviewer": {
"anyOf": [
{
"$ref": "#/definitions/ApprovalsReviewer"
},
{
"type": "null"
}
]
},
"objective": {
"type": [
"string",
"null"
]
},
"permissions": {
"type": [
"string",
"null"
]
},
"sandboxPolicy": {
"anyOf": [
{
"$ref": "#/definitions/SandboxPolicy"
},
{
"type": "null"
}
]
},
"status": {
"anyOf": [
{
@@ -6833,4 +6869,4 @@
}
],
"title": "ClientRequest"
}
}
@@ -17348,12 +17348,48 @@
"ThreadGoalSetParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"approvalPolicy": {
"anyOf": [
{
"$ref": "#/definitions/v2/AskForApproval"
},
{
"type": "null"
}
]
},
"approvalsReviewer": {
"anyOf": [
{
"$ref": "#/definitions/v2/ApprovalsReviewer"
},
{
"type": "null"
}
]
},
"objective": {
"type": [
"string",
"null"
]
},
"permissions": {
"type": [
"string",
"null"
]
},
"sandboxPolicy": {
"anyOf": [
{
"$ref": "#/definitions/v2/SandboxPolicy"
},
{
"type": "null"
}
]
},
"status": {
"anyOf": [
{
@@ -20689,4 +20725,4 @@
},
"title": "CodexAppServerProtocol",
"type": "object"
}
}
@@ -15127,12 +15127,48 @@
"ThreadGoalSetParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"approvalPolicy": {
"anyOf": [
{
"$ref": "#/definitions/AskForApproval"
},
{
"type": "null"
}
]
},
"approvalsReviewer": {
"anyOf": [
{
"$ref": "#/definitions/ApprovalsReviewer"
},
{
"type": "null"
}
]
},
"objective": {
"type": [
"string",
"null"
]
},
"permissions": {
"type": [
"string",
"null"
]
},
"sandboxPolicy": {
"anyOf": [
{
"$ref": "#/definitions/SandboxPolicy"
},
{
"type": "null"
}
]
},
"status": {
"anyOf": [
{
@@ -18467,4 +18503,4 @@
},
"title": "CodexAppServerProtocolV2",
"type": "object"
}
}
@@ -1,6 +1,9 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ApprovalsReviewer } from "./ApprovalsReviewer";
import type { AskForApproval } from "./AskForApproval";
import type { SandboxPolicy } from "./SandboxPolicy";
import type { ThreadGoalStatus } from "./ThreadGoalStatus";
export type ThreadGoalSetParams = { threadId: string, objective?: string | null, status?: ThreadGoalStatus | null, tokenBudget?: number | null, };
export type ThreadGoalSetParams = { threadId: string, objective?: string | null, status?: ThreadGoalStatus | null, approvalPolicy?: AskForApproval | null, approvalsReviewer?: ApprovalsReviewer | null, sandboxPolicy?: SandboxPolicy | null, permissions?: string | null, tokenBudget?: number | null, };
@@ -1968,6 +1968,10 @@ mod tests {
thread_id: "goal-thread".to_string(),
objective: Some("ship it".to_string()),
status: None,
approval_policy: None,
approvals_reviewer: None,
sandbox_policy: None,
permissions: None,
token_budget: None,
},
};
@@ -3534,6 +3538,10 @@ mod tests {
thread_id: "thr_123".to_string(),
objective: Some("ship goal mode".to_string()),
status: Some(v2::ThreadGoalStatus::Active),
approval_policy: None,
approvals_reviewer: None,
sandbox_policy: None,
permissions: None,
token_budget: Some(Some(10_000)),
},
};
@@ -769,6 +769,22 @@ pub struct ThreadGoalSetParams {
pub objective: Option<String>,
#[ts(optional = nullable)]
pub status: Option<ThreadGoalStatus>,
/// Override the approval policy before any goal runtime effects resume work.
#[experimental(nested)]
#[ts(optional = nullable)]
pub approval_policy: Option<AskForApproval>,
/// Override where approval requests are routed before any goal runtime
/// effects resume work.
#[ts(optional = nullable)]
pub approvals_reviewer: Option<ApprovalsReviewer>,
/// Override the sandbox policy before any goal runtime effects resume work.
#[ts(optional = nullable)]
pub sandbox_policy: Option<SandboxPolicy>,
/// Select a named permissions profile id before any goal runtime effects
/// resume work. Cannot be combined with `sandboxPolicy`.
#[experimental("thread/goal/set.permissions")]
#[ts(optional = nullable)]
pub permissions: Option<String>,
#[serde(
default,
deserialize_with = "crate::protocol::serde_helpers::deserialize_double_option",
@@ -474,7 +474,9 @@ impl MessageProcessor {
let thread_goal_processor = ThreadGoalRequestProcessor::new(
Arc::clone(&thread_manager),
outgoing.clone(),
arg0_paths.clone(),
Arc::clone(&config),
config_manager.clone(),
thread_state_manager.clone(),
state_db.clone(),
Arc::clone(&goal_service),
@@ -9,7 +9,9 @@ use codex_goal_extension::GoalTokenBudgetUpdate;
pub(crate) struct ThreadGoalRequestProcessor {
thread_manager: Arc<ThreadManager>,
outgoing: Arc<OutgoingMessageSender>,
arg0_paths: Arg0DispatchPaths,
config: Arc<Config>,
config_manager: ConfigManager,
thread_state_manager: ThreadStateManager,
state_db: Option<StateDbHandle>,
goal_service: Arc<GoalService>,
@@ -19,7 +21,9 @@ impl ThreadGoalRequestProcessor {
pub(crate) fn new(
thread_manager: Arc<ThreadManager>,
outgoing: Arc<OutgoingMessageSender>,
arg0_paths: Arg0DispatchPaths,
config: Arc<Config>,
config_manager: ConfigManager,
thread_state_manager: ThreadStateManager,
state_db: Option<StateDbHandle>,
goal_service: Arc<GoalService>,
@@ -27,7 +31,9 @@ impl ThreadGoalRequestProcessor {
Self {
thread_manager,
outgoing,
arg0_paths,
config,
config_manager,
thread_state_manager,
state_db,
goal_service,
@@ -115,6 +121,12 @@ impl ThreadGoalRequestProcessor {
};
let status = params.status.map(ThreadGoalStatus::to_core);
let objective = params.objective.as_deref();
let live_thread = self.thread_manager.get_thread(thread_id).await.ok();
if let Some(thread) = live_thread.as_ref() {
self.apply_goal_thread_settings(thread.as_ref(), &params)
.await?;
}
let outcome = self
.goal_service
@@ -136,15 +148,15 @@ impl ThreadGoalRequestProcessor {
.map_err(goal_service_error)?;
let goal = ThreadGoal::from(outcome.goal.clone());
let persist_result = match self.thread_manager.get_thread(thread_id).await {
Ok(thread) => {
let persist_result = match live_thread {
Some(thread) => {
// Live goal-first threads can be listed before any user turn is written.
// Use the live path so JSONL and SQLite preview metadata stay in sync.
thread
.append_rollout_items(&[outcome.thread_goal_updated_item()])
.await
}
Err(_) => Ok(()),
None => Ok(()),
};
if let Err(err) = persist_result {
warn!("failed to persist goal update for live thread {thread_id}: {err}");
@@ -216,6 +228,92 @@ impl ThreadGoalRequestProcessor {
Ok(())
}
async fn apply_goal_thread_settings(
&self,
thread: &CodexThread,
params: &ThreadGoalSetParams,
) -> Result<(), JSONRPCErrorError> {
if params.sandbox_policy.is_some() && params.permissions.is_some() {
return Err(invalid_request(
"`permissions` cannot be combined with `sandboxPolicy`",
));
}
let approval_policy = params
.approval_policy
.clone()
.map(codex_app_server_protocol::AskForApproval::to_core);
let approvals_reviewer = params
.approvals_reviewer
.clone()
.map(codex_app_server_protocol::ApprovalsReviewer::to_core);
let sandbox_policy = params.sandbox_policy.clone().map(|policy| policy.to_core());
let has_any_overrides = approval_policy.is_some()
|| approvals_reviewer.is_some()
|| sandbox_policy.is_some()
|| params.permissions.is_some();
if !has_any_overrides {
return Ok(());
}
let (permission_profile, active_permission_profile, profile_workspace_roots) =
if let Some(permissions) = params.permissions.clone() {
let snapshot = thread.config_snapshot().await;
let overrides = ConfigOverrides {
workspace_roots: Some(snapshot.workspace_roots.clone()),
default_permissions: Some(permissions),
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()
};
let config = self
.config_manager
.load_for_cwd(
/*request_overrides*/ None,
overrides,
Some(snapshot.cwd().to_path_buf()),
)
.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 goal permission context: {warning}"
)));
}
(
Some(config.permissions.permission_profile().clone()),
config.permissions.active_permission_profile(),
Some(config.permissions.profile_workspace_roots().to_vec()),
)
} else {
(None, None, None)
};
thread
.apply_thread_settings_overrides(CodexThreadSettingsOverrides {
environments: None,
workspace_roots: None,
approval_policy,
approvals_reviewer,
sandbox_policy,
permission_profile,
active_permission_profile,
profile_workspace_roots,
windows_sandbox_level: None,
model: None,
effort: None,
summary: None,
service_tier: None,
collaboration_mode: None,
multi_agent_mode: None,
personality: None,
})
.await
.map_err(|err| invalid_request(format!("invalid goal permission context: {err}")))
}
async fn state_db_for_materialized_thread(
&self,
thread_id: ThreadId,
@@ -22,6 +22,7 @@ use codex_app_server_protocol::FileChangeApprovalDecision;
use codex_app_server_protocol::FileChangeRequestApprovalResponse;
use codex_app_server_protocol::ItemStartedNotification;
use codex_app_server_protocol::JSONRPCError;
use codex_app_server_protocol::JSONRPCNotification;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::McpToolCallAppContext;
use codex_app_server_protocol::PatchApplyStatus;
@@ -46,7 +47,9 @@ use codex_app_server_protocol::ThreadSource;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::ThreadStatus;
use codex_app_server_protocol::ThreadSettingsUpdatedNotification;
use codex_app_server_protocol::ThreadUnsubscribeParams;
use codex_app_server_protocol::ThreadUnsubscribeResponse;
use codex_app_server_protocol::TurnItemsView;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
@@ -59,6 +62,7 @@ use codex_protocol::ThreadId;
use codex_protocol::config_types::Personality;
use codex_protocol::mcp::CallToolResult;
use codex_protocol::models::ContentItem;
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::AgentMessageEvent;
use codex_protocol::protocol::EventMsg;
@@ -1431,6 +1435,130 @@ async fn thread_goal_set_edits_objective_without_resetting_usage() -> Result<()>
Ok(())
}
#[tokio::test]
async fn thread_goal_set_applies_permission_context_before_resume() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let mut mcp = TestAppServer::new(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
..Default::default()
})
.await?;
let start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(start_id)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(start_resp)?;
let turn_id = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
client_user_message_id: None,
input: vec![UserInput::Text {
text: "materialize this thread".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let _turn_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(turn_id)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
let goal_id = mcp
.send_raw_request(
"thread/goal/set",
Some(json!({
"threadId": thread.id,
"objective": "resume with current permissions",
"approvalPolicy": "on-request",
"permissions": BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS,
})),
)
.await?;
let goal_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(goal_id)),
)
.await??;
let _goal: ThreadGoalSetResponse = to_response(goal_resp)?;
let settings_notification: JSONRPCNotification = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("thread/settings/updated"),
)
.await??;
let settings_params = settings_notification
.params
.context("thread/settings/updated should include params")?;
let updated: ThreadSettingsUpdatedNotification = serde_json::from_value(settings_params)?;
assert_eq!(updated.thread_id, thread.id);
assert_eq!(updated.thread_settings.approval_policy, AskForApproval::OnRequest);
assert_eq!(
updated
.thread_settings
.active_permission_profile
.as_ref()
.map(|profile| profile.id.as_str()),
Some(BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS)
);
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("thread/goal/updated"),
)
.await??;
let unsubscribe_id = mcp
.send_thread_unsubscribe_request(ThreadUnsubscribeParams {
thread_id: thread.id.clone(),
})
.await?;
let unsubscribe_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(unsubscribe_id)),
)
.await??;
let _unsubscribe: ThreadUnsubscribeResponse = to_response(unsubscribe_resp)?;
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread.id.clone(),
..Default::default()
})
.await?;
let resume_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(resume_id)),
)
.await??;
let resumed: ThreadResumeResponse = to_response(resume_resp)?;
assert_eq!(resumed.approval_policy, AskForApproval::OnRequest);
assert_eq!(
resumed
.active_permission_profile
.as_ref()
.map(|profile| profile.id.as_str()),
Some(BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS)
);
Ok(())
}
#[tokio::test]
async fn thread_goal_lifecycle_emits_analytics_and_clear_deletes_goal() -> Result<()> {
let server = create_mock_responses_server_sequence_unchecked(vec![
+43
View File
@@ -23,6 +23,7 @@ use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::AdditionalContextEntry;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::RolloutItem;
@@ -30,6 +31,8 @@ use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::protocol::SessionConfiguredEvent;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::Submission;
use codex_protocol::protocol::ThreadSettingsAppliedEvent;
use codex_protocol::protocol::ThreadSettingsSnapshot;
use codex_protocol::protocol::ThreadMemoryMode;
use codex_protocol::protocol::ThreadSource;
use codex_protocol::protocol::TokenUsageInfo;
@@ -52,6 +55,7 @@ use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::sync::watch;
use uuid::Uuid;
use codex_rollout::state_db::StateDbHandle;
@@ -355,6 +359,45 @@ impl CodexThread {
self.codex.session.preview_settings(&updates).await
}
/// Apply persistent thread settings overrides immediately and emit the same
/// settings-applied event that queued `thread/settings/update` uses.
pub async fn apply_thread_settings_overrides(
&self,
overrides: CodexThreadSettingsOverrides,
) -> ConstraintResult<()> {
let updates = self.thread_settings_update(overrides).await;
self.codex.session.update_settings(updates).await?;
let snapshot = {
let state = self.codex.session.state.lock().await;
state.session_configuration.thread_config_snapshot()
};
let cwd = snapshot.cwd().clone();
self.codex
.session
.send_event_raw(Event {
id: Uuid::now_v7().to_string(),
msg: EventMsg::ThreadSettingsApplied(ThreadSettingsAppliedEvent {
thread_settings: ThreadSettingsSnapshot {
model: snapshot.model,
model_provider_id: snapshot.model_provider_id,
service_tier: snapshot.service_tier,
approval_policy: snapshot.approval_policy,
approvals_reviewer: snapshot.approvals_reviewer,
permission_profile: snapshot.permission_profile,
active_permission_profile: snapshot.active_permission_profile,
cwd,
reasoning_effort: snapshot.reasoning_effort,
reasoning_summary: snapshot.reasoning_summary,
personality: snapshot.personality,
collaboration_mode: snapshot.collaboration_mode,
multi_agent_mode: snapshot.multi_agent_mode,
},
}),
})
.await;
Ok(())
}
async fn thread_settings_update(
&self,
overrides: CodexThreadSettingsOverrides,
+2 -1
View File
@@ -200,7 +200,7 @@ impl App {
};
let result = app_server
.thread_goal_set(thread_id, Some(objective), Some(status), token_budget)
.thread_goal_set(&self.config, thread_id, Some(objective), Some(status), token_budget)
.await;
match result {
@@ -234,6 +234,7 @@ impl App {
) {
let result = app_server
.thread_goal_set(
&self.config,
thread_id,
/*objective*/ None,
Some(status),
+19
View File
@@ -915,11 +915,26 @@ impl AppServerSession {
pub(crate) async fn thread_goal_set(
&mut self,
config: &Config,
thread_id: ThreadId,
objective: Option<String>,
status: Option<ThreadGoalStatus>,
token_budget: Option<Option<i64>>,
) -> Result<ThreadGoalSetResponse> {
let permissions = permissions_selection_from_config(config, self.thread_params_mode);
let sandbox_policy = permissions.is_none().then(|| {
legacy_compatible_permission_profile(
&config.permissions.effective_permission_profile(),
config.cwd.as_path(),
)
.to_legacy_sandbox_policy(config.cwd.as_path())
.unwrap_or_else(|err| {
unreachable!(
"legacy-compatible permissions must project to legacy policy: {err}"
)
})
.into()
});
let request_id = self.next_request_id();
self.client
.request_typed(ClientRequest::ThreadGoalSet {
@@ -928,6 +943,10 @@ impl AppServerSession {
thread_id: thread_id.to_string(),
objective,
status,
approval_policy: Some(config.permissions.approval_policy.value().into()),
approvals_reviewer: approvals_reviewer_override_from_config(config),
sandbox_policy,
permissions,
token_budget,
},
})