mirror of
https://github.com/openai/codex.git
synced 2026-11-16 22:00:36 +00:00
Merge bdeb884bf3 into sapling-pr-archive-bolinfest
This commit is contained in:
Generated
+2
@@ -2780,6 +2780,7 @@ dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"codex-config",
|
||||
"codex-plugin",
|
||||
"codex-protocol",
|
||||
"codex-utils-absolute-path",
|
||||
"futures",
|
||||
@@ -3151,6 +3152,7 @@ dependencies = [
|
||||
name = "codex-plugin"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"codex-config",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-plugins",
|
||||
"thiserror 2.0.18",
|
||||
|
||||
@@ -684,6 +684,7 @@ fn analytics_hook_source(source: HookSource) -> &'static str {
|
||||
HookSource::Project => "project",
|
||||
HookSource::Mdm => "mdm",
|
||||
HookSource::SessionFlags => "session_flags",
|
||||
HookSource::Plugin => "plugin",
|
||||
HookSource::LegacyManagedConfigFile => "legacy_managed_config_file",
|
||||
HookSource::LegacyManagedConfigMdm => "legacy_managed_config_mdm",
|
||||
HookSource::Unknown => "unknown",
|
||||
|
||||
@@ -1900,6 +1900,7 @@
|
||||
"project",
|
||||
"mdm",
|
||||
"sessionFlags",
|
||||
"plugin",
|
||||
"legacyManagedConfigFile",
|
||||
"legacyManagedConfigMdm",
|
||||
"unknown"
|
||||
|
||||
+21
@@ -5345,6 +5345,26 @@
|
||||
"title": "AccountUpdatedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
"ActivePermissionProfile": {
|
||||
"properties": {
|
||||
"extends": {
|
||||
"default": null,
|
||||
"description": "Parent profile identifier once permissions profiles support inheritance. This is currently always `null`.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"id": {
|
||||
"description": "Identifier from `default_permissions`, such as a built-in `:workspace` profile or a user-defined `[permissions.<id>]` profile.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"AddCreditsNudgeCreditType": {
|
||||
"enum": [
|
||||
"credits",
|
||||
@@ -9680,6 +9700,7 @@
|
||||
"project",
|
||||
"mdm",
|
||||
"sessionFlags",
|
||||
"plugin",
|
||||
"legacyManagedConfigFile",
|
||||
"legacyManagedConfigMdm",
|
||||
"unknown"
|
||||
|
||||
+21
@@ -130,6 +130,26 @@
|
||||
"title": "AccountUpdatedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
"ActivePermissionProfile": {
|
||||
"properties": {
|
||||
"extends": {
|
||||
"default": null,
|
||||
"description": "Parent profile identifier once permissions profiles support inheritance. This is currently always `null`.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"id": {
|
||||
"description": "Identifier from `default_permissions`, such as a built-in `:workspace` profile or a user-defined `[permissions.<id>]` profile.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"AddCreditsNudgeCreditType": {
|
||||
"enum": [
|
||||
"credits",
|
||||
@@ -6310,6 +6330,7 @@
|
||||
"project",
|
||||
"mdm",
|
||||
"sessionFlags",
|
||||
"plugin",
|
||||
"legacyManagedConfigFile",
|
||||
"legacyManagedConfigMdm",
|
||||
"unknown"
|
||||
|
||||
@@ -160,6 +160,7 @@
|
||||
"project",
|
||||
"mdm",
|
||||
"sessionFlags",
|
||||
"plugin",
|
||||
"legacyManagedConfigFile",
|
||||
"legacyManagedConfigMdm",
|
||||
"unknown"
|
||||
|
||||
@@ -160,6 +160,7 @@
|
||||
"project",
|
||||
"mdm",
|
||||
"sessionFlags",
|
||||
"plugin",
|
||||
"legacyManagedConfigFile",
|
||||
"legacyManagedConfigMdm",
|
||||
"unknown"
|
||||
|
||||
@@ -5,6 +5,26 @@
|
||||
"description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.",
|
||||
"type": "string"
|
||||
},
|
||||
"ActivePermissionProfile": {
|
||||
"properties": {
|
||||
"extends": {
|
||||
"default": null,
|
||||
"description": "Parent profile identifier once permissions profiles support inheritance. This is currently always `null`.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"id": {
|
||||
"description": "Identifier from `default_permissions`, such as a built-in `:workspace` profile or a user-defined `[permissions.<id>]` profile.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"AgentPath": {
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -5,6 +5,26 @@
|
||||
"description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.",
|
||||
"type": "string"
|
||||
},
|
||||
"ActivePermissionProfile": {
|
||||
"properties": {
|
||||
"extends": {
|
||||
"default": null,
|
||||
"description": "Parent profile identifier once permissions profiles support inheritance. This is currently always `null`.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"id": {
|
||||
"description": "Identifier from `default_permissions`, such as a built-in `:workspace` profile or a user-defined `[permissions.<id>]` profile.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"AgentPath": {
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -5,6 +5,26 @@
|
||||
"description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.",
|
||||
"type": "string"
|
||||
},
|
||||
"ActivePermissionProfile": {
|
||||
"properties": {
|
||||
"extends": {
|
||||
"default": null,
|
||||
"description": "Parent profile identifier once permissions profiles support inheritance. This is currently always `null`.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"id": {
|
||||
"description": "Identifier from `default_permissions`, such as a built-in `:workspace` profile or a user-defined `[permissions.<id>]` profile.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"AgentPath": {
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
// 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.
|
||||
|
||||
export type ActivePermissionProfile = {
|
||||
/**
|
||||
* Identifier from `default_permissions`, such as a built-in `:workspace`
|
||||
* profile or a user-defined `[permissions.<id>]` profile.
|
||||
*/
|
||||
id: string,
|
||||
/**
|
||||
* Parent profile identifier once permissions profiles support
|
||||
* inheritance. This is currently always `null`.
|
||||
*/
|
||||
extends: string | null, };
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type HookSource = "system" | "user" | "project" | "mdm" | "sessionFlags" | "legacyManagedConfigFile" | "legacyManagedConfigMdm" | "unknown";
|
||||
export type HookSource = "system" | "user" | "project" | "mdm" | "sessionFlags" | "plugin" | "legacyManagedConfigFile" | "legacyManagedConfigMdm" | "unknown";
|
||||
|
||||
@@ -4,6 +4,7 @@ export type { Account } from "./Account";
|
||||
export type { AccountLoginCompletedNotification } from "./AccountLoginCompletedNotification";
|
||||
export type { AccountRateLimitsUpdatedNotification } from "./AccountRateLimitsUpdatedNotification";
|
||||
export type { AccountUpdatedNotification } from "./AccountUpdatedNotification";
|
||||
export type { ActivePermissionProfile } from "./ActivePermissionProfile";
|
||||
export type { AddCreditsNudgeCreditType } from "./AddCreditsNudgeCreditType";
|
||||
export type { AddCreditsNudgeEmailStatus } from "./AddCreditsNudgeEmailStatus";
|
||||
export type { AdditionalFileSystemPermissions } from "./AdditionalFileSystemPermissions";
|
||||
|
||||
@@ -2003,6 +2003,7 @@ mod tests {
|
||||
)
|
||||
.into(),
|
||||
),
|
||||
active_permission_profile: None,
|
||||
reasoning_effort: None,
|
||||
},
|
||||
};
|
||||
@@ -2048,6 +2049,7 @@ mod tests {
|
||||
"permissionProfile": {
|
||||
"type": "disabled"
|
||||
},
|
||||
"activePermissionProfile": null,
|
||||
"reasoningEffort": null
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -38,6 +38,7 @@ use codex_protocol::mcp::ResourceTemplate as McpResourceTemplate;
|
||||
use codex_protocol::mcp::Tool as McpTool;
|
||||
use codex_protocol::memory_citation::MemoryCitation as CoreMemoryCitation;
|
||||
use codex_protocol::memory_citation::MemoryCitationEntry as CoreMemoryCitationEntry;
|
||||
use codex_protocol::models::ActivePermissionProfile as CoreActivePermissionProfile;
|
||||
use codex_protocol::models::AdditionalPermissionProfile as CoreAdditionalPermissionProfile;
|
||||
use codex_protocol::models::FileSystemPermissions as CoreFileSystemPermissions;
|
||||
use codex_protocol::models::ManagedFileSystemPermissions as CoreManagedFileSystemPermissions;
|
||||
@@ -469,6 +470,7 @@ v2_enum_from_core!(
|
||||
Project,
|
||||
Mdm,
|
||||
SessionFlags,
|
||||
Plugin,
|
||||
LegacyManagedConfigFile,
|
||||
LegacyManagedConfigMdm,
|
||||
Unknown,
|
||||
@@ -1657,6 +1659,37 @@ impl From<PermissionProfile> for CorePermissionProfile {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct ActivePermissionProfile {
|
||||
/// Identifier from `default_permissions`, such as a built-in `:workspace`
|
||||
/// profile or a user-defined `[permissions.<id>]` profile.
|
||||
pub id: String,
|
||||
/// Parent profile identifier once permissions profiles support
|
||||
/// inheritance. This is currently always `null`.
|
||||
#[serde(default)]
|
||||
pub extends: Option<String>,
|
||||
}
|
||||
|
||||
impl From<CoreActivePermissionProfile> for ActivePermissionProfile {
|
||||
fn from(value: CoreActivePermissionProfile) -> Self {
|
||||
Self {
|
||||
id: value.id,
|
||||
extends: value.extends,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ActivePermissionProfile> for CoreActivePermissionProfile {
|
||||
fn from(value: ActivePermissionProfile) -> Self {
|
||||
Self {
|
||||
id: value.id,
|
||||
extends: value.extends,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
@@ -3469,6 +3502,11 @@ pub struct ThreadStartResponse {
|
||||
#[experimental("thread/start.permissionProfile")]
|
||||
#[serde(default)]
|
||||
pub permission_profile: Option<PermissionProfile>,
|
||||
/// Named profile that produced `permissionProfile`, when the active
|
||||
/// permissions came from `default_permissions`.
|
||||
#[experimental("thread/start.activePermissionProfile")]
|
||||
#[serde(default)]
|
||||
pub active_permission_profile: Option<ActivePermissionProfile>,
|
||||
pub reasoning_effort: Option<ReasoningEffort>,
|
||||
}
|
||||
|
||||
@@ -3575,6 +3613,11 @@ pub struct ThreadResumeResponse {
|
||||
#[experimental("thread/resume.permissionProfile")]
|
||||
#[serde(default)]
|
||||
pub permission_profile: Option<PermissionProfile>,
|
||||
/// Named profile that produced `permissionProfile`, when the active
|
||||
/// permissions came from `default_permissions`.
|
||||
#[experimental("thread/resume.activePermissionProfile")]
|
||||
#[serde(default)]
|
||||
pub active_permission_profile: Option<ActivePermissionProfile>,
|
||||
pub reasoning_effort: Option<ReasoningEffort>,
|
||||
}
|
||||
|
||||
@@ -3672,6 +3715,11 @@ pub struct ThreadForkResponse {
|
||||
#[experimental("thread/fork.permissionProfile")]
|
||||
#[serde(default)]
|
||||
pub permission_profile: Option<PermissionProfile>,
|
||||
/// Named profile that produced `permissionProfile`, when the active
|
||||
/// permissions came from `default_permissions`.
|
||||
#[experimental("thread/fork.activePermissionProfile")]
|
||||
#[serde(default)]
|
||||
pub active_permission_profile: Option<ActivePermissionProfile>,
|
||||
pub reasoning_effort: Option<ReasoningEffort>,
|
||||
}
|
||||
|
||||
@@ -10658,6 +10706,9 @@ mod tests {
|
||||
assert_eq!(start.permission_profile, None);
|
||||
assert_eq!(resume.permission_profile, None);
|
||||
assert_eq!(fork.permission_profile, None);
|
||||
assert_eq!(start.active_permission_profile, None);
|
||||
assert_eq!(resume.active_permission_profile, None);
|
||||
assert_eq!(fork.active_permission_profile, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2798,6 +2798,9 @@ impl CodexMessageProcessor {
|
||||
);
|
||||
let permission_profile =
|
||||
thread_response_permission_profile(config_snapshot.permission_profile);
|
||||
let active_permission_profile = thread_response_active_permission_profile(
|
||||
config_snapshot.active_permission_profile,
|
||||
);
|
||||
|
||||
let response = ThreadStartResponse {
|
||||
thread: thread.clone(),
|
||||
@@ -2810,6 +2813,7 @@ impl CodexMessageProcessor {
|
||||
approvals_reviewer: config_snapshot.approvals_reviewer.into(),
|
||||
sandbox,
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
reasoning_effort: config_snapshot.reasoning_effort,
|
||||
};
|
||||
Ok::<_, JSONRPCErrorError>((response, thread_started_notification(thread)))
|
||||
@@ -4348,7 +4352,10 @@ impl CodexMessageProcessor {
|
||||
config_snapshot.cwd.as_path(),
|
||||
);
|
||||
let permission_profile =
|
||||
thread_response_permission_profile(config_snapshot.permission_profile.clone());
|
||||
thread_response_permission_profile(config_snapshot.permission_profile);
|
||||
let active_permission_profile = thread_response_active_permission_profile(
|
||||
config_snapshot.active_permission_profile,
|
||||
);
|
||||
|
||||
let response = ThreadResumeResponse {
|
||||
thread,
|
||||
@@ -4361,6 +4368,7 @@ impl CodexMessageProcessor {
|
||||
approvals_reviewer: session_configured.approvals_reviewer.into(),
|
||||
sandbox,
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
reasoning_effort: session_configured.reasoning_effort,
|
||||
};
|
||||
self.analytics_events_client.track_response(
|
||||
@@ -4949,6 +4957,9 @@ impl CodexMessageProcessor {
|
||||
);
|
||||
let permission_profile =
|
||||
thread_response_permission_profile(config_snapshot.permission_profile);
|
||||
let active_permission_profile = thread_response_active_permission_profile(
|
||||
config_snapshot.active_permission_profile,
|
||||
);
|
||||
|
||||
let response = ThreadForkResponse {
|
||||
thread: thread.clone(),
|
||||
@@ -4961,6 +4972,7 @@ impl CodexMessageProcessor {
|
||||
approvals_reviewer: session_configured.approvals_reviewer.into(),
|
||||
sandbox,
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
reasoning_effort: session_configured.reasoning_effort,
|
||||
};
|
||||
|
||||
@@ -8223,6 +8235,7 @@ async fn handle_pending_thread_resume_request(
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
cwd,
|
||||
reasoning_effort,
|
||||
..
|
||||
@@ -8230,6 +8243,8 @@ async fn handle_pending_thread_resume_request(
|
||||
let instruction_sources = pending.instruction_sources;
|
||||
let sandbox = thread_response_sandbox_policy(&permission_profile, cwd.as_path());
|
||||
let permission_profile = thread_response_permission_profile(permission_profile);
|
||||
let active_permission_profile =
|
||||
thread_response_active_permission_profile(active_permission_profile);
|
||||
|
||||
let response = ThreadResumeResponse {
|
||||
thread,
|
||||
@@ -8242,6 +8257,7 @@ async fn handle_pending_thread_resume_request(
|
||||
approvals_reviewer: approvals_reviewer.into(),
|
||||
sandbox,
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
reasoning_effort,
|
||||
};
|
||||
let token_usage_thread = pending.include_turns.then(|| response.thread.clone());
|
||||
@@ -9371,6 +9387,12 @@ fn thread_response_permission_profile(
|
||||
Some(permission_profile.into())
|
||||
}
|
||||
|
||||
fn thread_response_active_permission_profile(
|
||||
active_permission_profile: Option<codex_protocol::models::ActivePermissionProfile>,
|
||||
) -> Option<codex_app_server_protocol::ActivePermissionProfile> {
|
||||
active_permission_profile.map(Into::into)
|
||||
}
|
||||
|
||||
fn thread_response_sandbox_policy(
|
||||
permission_profile: &codex_protocol::models::PermissionProfile,
|
||||
cwd: &Path,
|
||||
@@ -10165,6 +10187,7 @@ mod tests {
|
||||
approval_policy: codex_protocol::protocol::AskForApproval::OnRequest,
|
||||
approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer::User,
|
||||
permission_profile: codex_protocol::models::PermissionProfile::Disabled,
|
||||
active_permission_profile: None,
|
||||
cwd,
|
||||
ephemeral: false,
|
||||
reasoning_effort: None,
|
||||
|
||||
@@ -564,12 +564,13 @@ pub async fn run_main_with_transport_options(
|
||||
|
||||
let feedback_layer = feedback.logger_layer();
|
||||
let feedback_metadata_layer = feedback.metadata_layer();
|
||||
let state_db = codex_state::StateRuntime::init(
|
||||
let state_db_result = codex_state::StateRuntime::init(
|
||||
config.sqlite_home.clone(),
|
||||
config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.ok();
|
||||
.await;
|
||||
let state_db_init_error = state_db_result.as_ref().err().map(ToString::to_string);
|
||||
let state_db = state_db_result.ok();
|
||||
let log_db = state_db.clone().map(log_db::start);
|
||||
let log_db_layer = log_db
|
||||
.clone()
|
||||
@@ -590,6 +591,9 @@ pub async fn run_main_with_transport_options(
|
||||
None => error!("{}", warning.summary),
|
||||
}
|
||||
}
|
||||
if let Some(err) = &state_db_init_error {
|
||||
error!("failed to initialize sqlite state db: {err}");
|
||||
}
|
||||
|
||||
let transport_shutdown_token = CancellationToken::new();
|
||||
let mut transport_accept_handles = Vec::<JoinHandle<()>>::new();
|
||||
@@ -635,11 +639,19 @@ pub async fn run_main_with_transport_options(
|
||||
let auth_manager =
|
||||
AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await;
|
||||
|
||||
let remote_control_enabled = config.features.enabled(Feature::RemoteControl);
|
||||
let remote_control_config_enabled = config.features.enabled(Feature::RemoteControl);
|
||||
let remote_control_enabled = remote_control_config_enabled && state_db.is_some();
|
||||
if remote_control_config_enabled && state_db.is_none() {
|
||||
error!("remote control disabled because sqlite state db is unavailable");
|
||||
}
|
||||
if transport_accept_handles.is_empty() && !remote_control_enabled {
|
||||
return Err(std::io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"no transport configured; use --listen or enable remote control",
|
||||
if remote_control_config_enabled && state_db.is_none() {
|
||||
"no transport configured; remote control disabled because sqlite state db is unavailable"
|
||||
} else {
|
||||
"no transport configured; use --listen or enable remote control"
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -38,13 +38,15 @@ pub(super) async fn load_persisted_remote_control_enrollment(
|
||||
remote_control_target: &RemoteControlTarget,
|
||||
account_id: &str,
|
||||
app_server_client_name: Option<&str>,
|
||||
) -> Option<RemoteControlEnrollment> {
|
||||
) -> io::Result<Option<RemoteControlEnrollment>> {
|
||||
let Some(state_db) = state_db else {
|
||||
info!(
|
||||
"remote control enrollment cache unavailable because sqlite state db is disabled: websocket_url={}, account_id={}, app_server_client_name={:?}",
|
||||
remote_control_target.websocket_url, account_id, app_server_client_name
|
||||
);
|
||||
return None;
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::NotFound,
|
||||
format!(
|
||||
"remote control enrollment cache unavailable because sqlite state db is disabled: websocket_url={}, account_id={}, app_server_client_name={:?}",
|
||||
remote_control_target.websocket_url, account_id, app_server_client_name
|
||||
),
|
||||
));
|
||||
};
|
||||
let enrollment = match state_db
|
||||
.get_remote_control_enrollment(
|
||||
@@ -60,7 +62,7 @@ pub(super) async fn load_persisted_remote_control_enrollment(
|
||||
"failed to load persisted remote control enrollment: websocket_url={}, account_id={}, app_server_client_name={:?}, err={err}",
|
||||
remote_control_target.websocket_url, account_id, app_server_client_name
|
||||
);
|
||||
return None;
|
||||
return Err(io::Error::other(err));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -74,19 +76,19 @@ pub(super) async fn load_persisted_remote_control_enrollment(
|
||||
enrollment.server_id,
|
||||
enrollment.environment_id
|
||||
);
|
||||
Some(RemoteControlEnrollment {
|
||||
Ok(Some(RemoteControlEnrollment {
|
||||
account_id: enrollment.account_id,
|
||||
environment_id: enrollment.environment_id,
|
||||
server_id: enrollment.server_id,
|
||||
server_name: enrollment.server_name,
|
||||
})
|
||||
}))
|
||||
}
|
||||
None => {
|
||||
info!(
|
||||
"no persisted remote control enrollment found: websocket_url={}, account_id={}, app_server_client_name={:?}",
|
||||
remote_control_target.websocket_url, account_id, app_server_client_name
|
||||
);
|
||||
None
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -99,14 +101,16 @@ pub(super) async fn update_persisted_remote_control_enrollment(
|
||||
enrollment: Option<&RemoteControlEnrollment>,
|
||||
) -> io::Result<()> {
|
||||
let Some(state_db) = state_db else {
|
||||
info!(
|
||||
"skipping remote control enrollment persistence because sqlite state db is disabled: websocket_url={}, account_id={}, app_server_client_name={:?}, has_enrollment={}",
|
||||
remote_control_target.websocket_url,
|
||||
account_id,
|
||||
app_server_client_name,
|
||||
enrollment.is_some()
|
||||
);
|
||||
return Ok(());
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::NotFound,
|
||||
format!(
|
||||
"remote control enrollment persistence unavailable because sqlite state db is disabled: websocket_url={}, account_id={}, app_server_client_name={:?}, has_enrollment={}",
|
||||
remote_control_target.websocket_url,
|
||||
account_id,
|
||||
app_server_client_name,
|
||||
enrollment.is_some()
|
||||
),
|
||||
));
|
||||
};
|
||||
if let &Some(enrollment) = &enrollment
|
||||
&& enrollment.account_id != account_id
|
||||
@@ -322,7 +326,8 @@ mod tests {
|
||||
"account-a",
|
||||
Some("desktop-client"),
|
||||
)
|
||||
.await,
|
||||
.await
|
||||
.expect("first enrollment should load"),
|
||||
Some(first_enrollment.clone())
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -332,7 +337,8 @@ mod tests {
|
||||
"account-b",
|
||||
Some("desktop-client"),
|
||||
)
|
||||
.await,
|
||||
.await
|
||||
.expect("missing account should load"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -342,7 +348,8 @@ mod tests {
|
||||
"account-a",
|
||||
Some("desktop-client"),
|
||||
)
|
||||
.await,
|
||||
.await
|
||||
.expect("second enrollment should load"),
|
||||
Some(second_enrollment)
|
||||
);
|
||||
}
|
||||
@@ -405,7 +412,8 @@ mod tests {
|
||||
"account-a",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await,
|
||||
.await
|
||||
.expect("cleared enrollment should load"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -415,7 +423,8 @@ mod tests {
|
||||
"account-a",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await,
|
||||
.await
|
||||
.expect("remaining enrollment should load"),
|
||||
Some(second_enrollment)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::warn;
|
||||
|
||||
pub(super) struct QueuedServerEnvelope {
|
||||
pub(super) event: ServerEvent,
|
||||
@@ -32,10 +33,16 @@ pub(super) struct QueuedServerEnvelope {
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct RemoteControlHandle {
|
||||
enabled_tx: Arc<watch::Sender<bool>>,
|
||||
state_db_available: bool,
|
||||
}
|
||||
|
||||
impl RemoteControlHandle {
|
||||
pub(crate) fn set_enabled(&self, enabled: bool) {
|
||||
let requested_enabled = enabled;
|
||||
let enabled = enabled && self.state_db_available;
|
||||
if requested_enabled && !self.state_db_available {
|
||||
warn!("remote control cannot be enabled because sqlite state db is unavailable");
|
||||
}
|
||||
self.enabled_tx.send_if_modified(|state| {
|
||||
let changed = *state != enabled;
|
||||
*state = enabled;
|
||||
@@ -53,6 +60,12 @@ pub(crate) async fn start_remote_control(
|
||||
app_server_client_name_rx: Option<oneshot::Receiver<String>>,
|
||||
initial_enabled: bool,
|
||||
) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> {
|
||||
let state_db_available = state_db.is_some();
|
||||
let requested_initial_enabled = initial_enabled;
|
||||
let initial_enabled = initial_enabled && state_db_available;
|
||||
if requested_initial_enabled && !state_db_available {
|
||||
warn!("remote control disabled because sqlite state db is unavailable");
|
||||
}
|
||||
let remote_control_target = if initial_enabled {
|
||||
Some(normalize_remote_control_url(&remote_control_url)?)
|
||||
} else {
|
||||
@@ -78,6 +91,7 @@ pub(crate) async fn start_remote_control(
|
||||
join_handle,
|
||||
RemoteControlHandle {
|
||||
enabled_tx: Arc::new(enabled_tx),
|
||||
state_db_available,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
@@ -504,7 +504,7 @@ async fn remote_control_start_allows_missing_auth_when_enabled() {
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let (remote_task, _remote_handle) = start_remote_control(
|
||||
remote_control_url,
|
||||
/*state_db*/ None,
|
||||
Some(remote_control_state_runtime(&codex_home).await),
|
||||
auth_manager,
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
@@ -525,6 +525,43 @@ async fn remote_control_start_allows_missing_auth_when_enabled() {
|
||||
.expect("remote control task should join");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_control_start_disables_remote_control_without_state_db() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("listener should bind");
|
||||
let remote_control_url = remote_control_url_for_listener(&listener);
|
||||
let (transport_event_tx, _transport_event_rx) =
|
||||
mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let (remote_task, remote_handle) = start_remote_control(
|
||||
remote_control_url,
|
||||
/*state_db*/ None,
|
||||
remote_control_auth_manager(),
|
||||
transport_event_tx,
|
||||
shutdown_token.clone(),
|
||||
/*app_server_client_name_rx*/ None,
|
||||
/*initial_enabled*/ true,
|
||||
)
|
||||
.await
|
||||
.expect("remote control should start disabled without sqlite state db");
|
||||
|
||||
timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.expect_err("remote control should not connect without sqlite state db");
|
||||
|
||||
remote_handle.set_enabled(/*enabled*/ true);
|
||||
timeout(Duration::from_millis(100), listener.accept())
|
||||
.await
|
||||
.expect_err("remote control should remain disabled without sqlite state db");
|
||||
|
||||
shutdown_token.cancel();
|
||||
timeout(Duration::from_secs(1), remote_task)
|
||||
.await
|
||||
.expect("remote control task should stop")
|
||||
.expect("remote control task should join");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_control_handle_set_enabled_stops_and_restarts_connections() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
@@ -1001,7 +1038,8 @@ async fn remote_control_http_mode_reuses_persisted_enrollment_before_reenrolling
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await,
|
||||
.await
|
||||
.expect("persisted enrollment should load"),
|
||||
Some(persisted_enrollment)
|
||||
);
|
||||
|
||||
@@ -1231,7 +1269,8 @@ async fn remote_control_http_mode_clears_stale_persisted_enrollment_after_404()
|
||||
"account_id",
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await,
|
||||
.await
|
||||
.expect("refreshed enrollment should load"),
|
||||
Some(refreshed_enrollment)
|
||||
);
|
||||
|
||||
|
||||
@@ -753,6 +753,14 @@ pub(super) async fn connect_remote_control_websocket(
|
||||
)> {
|
||||
ensure_rustls_crypto_provider();
|
||||
|
||||
let Some(state_db) = state_db else {
|
||||
*enrollment = None;
|
||||
return Err(io::Error::new(
|
||||
ErrorKind::NotFound,
|
||||
"remote control requires sqlite state db",
|
||||
));
|
||||
};
|
||||
|
||||
let auth = load_remote_control_auth(auth_manager).await?;
|
||||
let enrollment_account_id = enrollment.as_ref().map(|enrollment| &enrollment.account_id);
|
||||
if enrollment_account_id.is_some_and(|account_id| account_id != &auth.account_id) {
|
||||
@@ -769,12 +777,12 @@ pub(super) async fn connect_remote_control_websocket(
|
||||
|
||||
if enrollment.is_none() {
|
||||
*enrollment = load_persisted_remote_control_enrollment(
|
||||
state_db,
|
||||
Some(state_db),
|
||||
remote_control_target,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
)
|
||||
.await;
|
||||
.await?;
|
||||
}
|
||||
|
||||
if enrollment.is_none() {
|
||||
@@ -796,7 +804,7 @@ pub(super) async fn connect_remote_control_websocket(
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
if let Err(err) = update_persisted_remote_control_enrollment(
|
||||
state_db,
|
||||
Some(state_db),
|
||||
remote_control_target,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
@@ -804,7 +812,9 @@ pub(super) async fn connect_remote_control_websocket(
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("failed to persist remote control enrollment in sqlite state db: {err}");
|
||||
return Err(io::Error::other(format!(
|
||||
"failed to persist remote control enrollment in sqlite state db: {err}"
|
||||
)));
|
||||
}
|
||||
info!(
|
||||
"created new remote control enrollment: websocket_url={}, account_id={}, server_id={}, environment_id={}",
|
||||
@@ -839,7 +849,7 @@ pub(super) async fn connect_remote_control_websocket(
|
||||
enrollment_ref.environment_id
|
||||
);
|
||||
if let Err(clear_err) = update_persisted_remote_control_enrollment(
|
||||
state_db,
|
||||
Some(state_db),
|
||||
remote_control_target,
|
||||
&auth.account_id,
|
||||
app_server_client_name,
|
||||
@@ -1214,6 +1224,36 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connect_remote_control_websocket_requires_sqlite_state_db() {
|
||||
let remote_control_target = normalize_remote_control_url("http://127.0.0.1:9/backend-api/")
|
||||
.expect("target should parse");
|
||||
let auth_manager = remote_control_auth_manager();
|
||||
let mut auth_recovery = auth_manager.unauthorized_recovery();
|
||||
let mut enrollment = Some(RemoteControlEnrollment {
|
||||
account_id: "account_id".to_string(),
|
||||
environment_id: "env_test".to_string(),
|
||||
server_id: "srv_e_test".to_string(),
|
||||
server_name: "test-server".to_string(),
|
||||
});
|
||||
|
||||
let err = connect_remote_control_websocket(
|
||||
&remote_control_target,
|
||||
/*state_db*/ None,
|
||||
&auth_manager,
|
||||
&mut auth_recovery,
|
||||
&mut enrollment,
|
||||
/*subscribe_cursor*/ None,
|
||||
/*app_server_client_name*/ None,
|
||||
)
|
||||
.await
|
||||
.expect_err("missing sqlite state db should fail remote control");
|
||||
|
||||
assert_eq!(err.kind(), ErrorKind::NotFound);
|
||||
assert_eq!(err.to_string(), "remote control requires sqlite state db");
|
||||
assert_eq!(enrollment, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_remote_control_websocket_loop_shutdown_cancels_reconnect_backoff() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
|
||||
@@ -287,6 +287,8 @@ pub fn create_text_param_for_request(
|
||||
|
||||
pub struct ResponseStream {
|
||||
pub rx_event: mpsc::Receiver<Result<ResponseEvent, ApiError>>,
|
||||
/// Server-assigned `x-request-id` response header, when present.
|
||||
pub upstream_request_id: Option<String>,
|
||||
}
|
||||
|
||||
impl Stream for ResponseStream {
|
||||
|
||||
@@ -279,7 +279,10 @@ impl ResponsesWebsocketConnection {
|
||||
.instrument(current_span),
|
||||
);
|
||||
|
||||
Ok(ResponseStream { rx_event })
|
||||
Ok(ResponseStream {
|
||||
rx_event,
|
||||
upstream_request_id: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ use tracing::trace;
|
||||
|
||||
const X_REASONING_INCLUDED_HEADER: &str = "x-reasoning-included";
|
||||
const OPENAI_MODEL_HEADER: &str = "openai-model";
|
||||
const REQUEST_ID_HEADER: &str = "x-request-id";
|
||||
const TRUSTED_ACCESS_FOR_CYBER_VERIFICATION: &str = "trusted_access_for_cyber";
|
||||
|
||||
/// Streams SSE events from an on-disk fixture for tests.
|
||||
@@ -53,7 +54,10 @@ pub fn stream_from_fixture(
|
||||
idle_timeout,
|
||||
/*telemetry*/ None,
|
||||
));
|
||||
Ok(ResponseStream { rx_event })
|
||||
Ok(ResponseStream {
|
||||
rx_event,
|
||||
upstream_request_id: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn spawn_response_stream(
|
||||
@@ -77,6 +81,11 @@ pub fn spawn_response_stream(
|
||||
.headers
|
||||
.get(X_REASONING_INCLUDED_HEADER)
|
||||
.is_some();
|
||||
let upstream_request_id = stream_response
|
||||
.headers
|
||||
.get(REQUEST_ID_HEADER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_string);
|
||||
if let Some(turn_state) = turn_state.as_ref()
|
||||
&& let Some(header_value) = stream_response
|
||||
.headers
|
||||
@@ -104,7 +113,10 @@ pub fn spawn_response_stream(
|
||||
process_sse(stream_response.bytes, tx_event, idle_timeout, telemetry).await;
|
||||
});
|
||||
|
||||
ResponseStream { rx_event }
|
||||
ResponseStream {
|
||||
rx_event,
|
||||
upstream_request_id,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -1058,8 +1070,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spawn_response_stream_emits_server_model_header() {
|
||||
async fn spawn_response_stream_emits_header_events() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(REQUEST_ID_HEADER, HeaderValue::from_static("req-1"));
|
||||
headers.insert(
|
||||
OPENAI_MODEL_HEADER,
|
||||
HeaderValue::from_static(CYBER_RESTRICTED_MODEL_FOR_TESTS),
|
||||
@@ -1077,13 +1090,13 @@ mod tests {
|
||||
/*telemetry*/ None,
|
||||
/*turn_state*/ None,
|
||||
);
|
||||
assert_eq!(stream.upstream_request_id.as_deref(), Some("req-1"));
|
||||
let event = stream
|
||||
.rx_event
|
||||
.recv()
|
||||
.await
|
||||
.expect("expected server model event")
|
||||
.expect("expected ok event");
|
||||
|
||||
match event {
|
||||
ResponseEvent::ServerModel(model) => {
|
||||
assert_eq!(model, CYBER_RESTRICTED_MODEL_FOR_TESTS);
|
||||
|
||||
+133
-152
@@ -1,4 +1,5 @@
|
||||
use crate::OPENAI_CURATED_MARKETPLACE_NAME;
|
||||
use crate::manifest::PluginManifestHooks;
|
||||
use crate::manifest::PluginManifestPaths;
|
||||
use crate::manifest::load_plugin_manifest;
|
||||
use crate::marketplace::MarketplacePluginSource;
|
||||
@@ -7,6 +8,7 @@ use crate::marketplace::load_marketplace;
|
||||
use crate::store::PluginStore;
|
||||
use crate::store::plugin_version_for_source;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::HooksFile;
|
||||
use codex_config::types::McpServerConfig;
|
||||
use codex_config::types::PluginConfig;
|
||||
use codex_core_skills::SkillMetadata;
|
||||
@@ -19,6 +21,7 @@ use codex_exec_server::LOCAL_FS;
|
||||
use codex_plugin::AppConnectorId;
|
||||
use codex_plugin::LoadedPlugin;
|
||||
use codex_plugin::PluginCapabilitySummary;
|
||||
use codex_plugin::PluginHookSource;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::PluginIdError;
|
||||
use codex_plugin::PluginLoadOutcome;
|
||||
@@ -26,6 +29,7 @@ use codex_plugin::PluginTelemetryMetadata;
|
||||
use codex_protocol::protocol::Product;
|
||||
use codex_protocol::protocol::SkillScope;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_plugins::find_plugin_manifest_path;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Map as JsonMap;
|
||||
use serde_json::Value as JsonValue;
|
||||
@@ -39,6 +43,7 @@ use tempfile::TempDir;
|
||||
use tracing::warn;
|
||||
|
||||
const DEFAULT_SKILLS_DIR_NAME: &str = "skills";
|
||||
const DEFAULT_HOOKS_CONFIG_FILE: &str = "hooks/hooks.json";
|
||||
const DEFAULT_MCP_CONFIG_FILE: &str = ".mcp.json";
|
||||
const DEFAULT_APP_CONFIG_FILE: &str = ".app.json";
|
||||
const CONFIG_TOML_FILE: &str = "config.toml";
|
||||
@@ -477,6 +482,8 @@ async fn load_plugin(
|
||||
has_enabled_skills: false,
|
||||
mcp_servers: HashMap::new(),
|
||||
apps: Vec::new(),
|
||||
hook_sources: Vec::new(),
|
||||
hook_load_warnings: Vec::new(),
|
||||
error: None,
|
||||
};
|
||||
|
||||
@@ -484,14 +491,14 @@ async fn load_plugin(
|
||||
return loaded_plugin;
|
||||
}
|
||||
|
||||
let plugin_root = match plugin_id {
|
||||
Ok(_) => match active_plugin_root {
|
||||
Some(plugin_root) => plugin_root,
|
||||
None => {
|
||||
let (loaded_plugin_id, plugin_root) = match plugin_id {
|
||||
Ok(plugin_id) => {
|
||||
let Some(plugin_root) = active_plugin_root else {
|
||||
loaded_plugin.error = Some("plugin is not installed".to_string());
|
||||
return loaded_plugin;
|
||||
}
|
||||
},
|
||||
};
|
||||
(plugin_id, plugin_root)
|
||||
}
|
||||
Err(err) => {
|
||||
loaded_plugin.error = Some(err.to_string());
|
||||
return loaded_plugin;
|
||||
@@ -545,6 +552,14 @@ async fn load_plugin(
|
||||
}
|
||||
loaded_plugin.mcp_servers = mcp_servers;
|
||||
loaded_plugin.apps = load_plugin_apps(plugin_root.as_path()).await;
|
||||
let (hook_sources, hook_load_warnings) = load_plugin_hooks(
|
||||
&plugin_root,
|
||||
&loaded_plugin_id,
|
||||
&store.plugin_data_root(&loaded_plugin_id),
|
||||
manifest_paths,
|
||||
);
|
||||
loaded_plugin.hook_sources = hook_sources;
|
||||
loaded_plugin.hook_load_warnings = hook_load_warnings;
|
||||
loaded_plugin
|
||||
}
|
||||
|
||||
@@ -674,6 +689,116 @@ fn default_app_config_paths(plugin_root: &Path) -> Vec<AbsolutePathBuf> {
|
||||
paths
|
||||
}
|
||||
|
||||
// Discover plugin-bundled hooks from manifest `hooks` entries when present
|
||||
// (path, paths, inline object, or inline objects), otherwise from the default
|
||||
// `hooks/hooks.json` file.
|
||||
pub fn load_plugin_hooks(
|
||||
plugin_root: &AbsolutePathBuf,
|
||||
plugin_id: &PluginId,
|
||||
plugin_data_root: &AbsolutePathBuf,
|
||||
manifest_paths: &PluginManifestPaths,
|
||||
) -> (Vec<PluginHookSource>, Vec<String>) {
|
||||
let mut sources = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
match &manifest_paths.hooks {
|
||||
Some(PluginManifestHooks::Paths(paths)) => {
|
||||
for path in paths {
|
||||
append_plugin_hook_file(
|
||||
plugin_root,
|
||||
plugin_id,
|
||||
plugin_data_root,
|
||||
path,
|
||||
&mut sources,
|
||||
&mut warnings,
|
||||
);
|
||||
}
|
||||
}
|
||||
Some(PluginManifestHooks::Inline(hooks_files)) => {
|
||||
let manifest_path = find_plugin_manifest_path(plugin_root.as_path())
|
||||
.and_then(|path| AbsolutePathBuf::try_from(path).ok())
|
||||
.unwrap_or_else(|| plugin_root.join(".codex-plugin/plugin.json"));
|
||||
for (index, hooks_file) in hooks_files.iter().enumerate() {
|
||||
if hooks_file.hooks.is_empty() {
|
||||
continue;
|
||||
}
|
||||
sources.push(PluginHookSource {
|
||||
plugin_id: plugin_id.clone(),
|
||||
plugin_root: plugin_root.clone(),
|
||||
plugin_data_root: plugin_data_root.clone(),
|
||||
source_path: manifest_path.clone(),
|
||||
source_relative_path: format!("plugin.json#hooks[{index}]"),
|
||||
hooks: hooks_file.hooks.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let default_path = plugin_root.join(DEFAULT_HOOKS_CONFIG_FILE);
|
||||
if default_path.as_path().is_file() {
|
||||
append_plugin_hook_file(
|
||||
plugin_root,
|
||||
plugin_id,
|
||||
plugin_data_root,
|
||||
&default_path,
|
||||
&mut sources,
|
||||
&mut warnings,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
(sources, warnings)
|
||||
}
|
||||
|
||||
// Append one resolved plugin hook file, keeping source metadata for runtime
|
||||
// reporting and collecting load warnings for startup surfacing.
|
||||
fn append_plugin_hook_file(
|
||||
plugin_root: &AbsolutePathBuf,
|
||||
plugin_id: &PluginId,
|
||||
plugin_data_root: &AbsolutePathBuf,
|
||||
path: &AbsolutePathBuf,
|
||||
sources: &mut Vec<PluginHookSource>,
|
||||
warnings: &mut Vec<String>,
|
||||
) {
|
||||
let contents = match fs::read_to_string(path.as_path()) {
|
||||
Ok(contents) => contents,
|
||||
Err(err) => {
|
||||
warnings.push(format!(
|
||||
"failed to read plugin hooks config {}: {err}",
|
||||
path.display()
|
||||
));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let parsed = match serde_json::from_str::<HooksFile>(&contents) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(err) => {
|
||||
warnings.push(format!(
|
||||
"failed to parse plugin hooks config {}: {err}",
|
||||
path.display()
|
||||
));
|
||||
return;
|
||||
}
|
||||
};
|
||||
if parsed.hooks.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let source_relative_path = path
|
||||
.as_path()
|
||||
.strip_prefix(plugin_root.as_path())
|
||||
.unwrap_or(path.as_path())
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
|
||||
sources.push(PluginHookSource {
|
||||
plugin_id: plugin_id.clone(),
|
||||
plugin_root: plugin_root.clone(),
|
||||
plugin_data_root: plugin_data_root.clone(),
|
||||
source_path: path.clone(),
|
||||
source_relative_path,
|
||||
hooks: parsed.hooks,
|
||||
});
|
||||
}
|
||||
|
||||
async fn load_apps_from_paths(
|
||||
plugin_root: &Path,
|
||||
app_config_paths: Vec<AbsolutePathBuf>,
|
||||
@@ -1014,149 +1139,5 @@ fn run_git(args: &[&str], cwd: Option<&Path>) -> Result<(), String> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn plugin_mcp_file_supports_mcp_servers_object_format() {
|
||||
let parsed = serde_json::from_str::<PluginMcpFile>(
|
||||
r#"{
|
||||
"mcpServers": {
|
||||
"sample": {
|
||||
"command": "sample-mcp"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.expect("parse wrapped plugin mcp config")
|
||||
.into_mcp_servers();
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
HashMap::from([(
|
||||
"sample".to_string(),
|
||||
serde_json::json!({
|
||||
"command": "sample-mcp"
|
||||
}),
|
||||
)])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_mcp_file_supports_mcp_servers_object_format_with_metadata() {
|
||||
let parsed = serde_json::from_str::<PluginMcpFile>(
|
||||
r#"{
|
||||
"$schema": "https://example.com/plugin-mcp.schema.json",
|
||||
"mcpServers": {
|
||||
"sample": {
|
||||
"command": "sample-mcp"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.expect("parse plugin mcp config with metadata")
|
||||
.into_mcp_servers();
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
HashMap::from([(
|
||||
"sample".to_string(),
|
||||
serde_json::json!({
|
||||
"command": "sample-mcp"
|
||||
}),
|
||||
)])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_mcp_file_supports_top_level_server_map_format() {
|
||||
let parsed = serde_json::from_str::<PluginMcpFile>(
|
||||
r#"{
|
||||
"linear": {
|
||||
"type": "http",
|
||||
"url": "https://mcp.linear.app/mcp"
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.expect("parse flat plugin mcp config")
|
||||
.into_mcp_servers();
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
HashMap::from([(
|
||||
"linear".to_string(),
|
||||
serde_json::json!({
|
||||
"type": "http",
|
||||
"url": "https://mcp.linear.app/mcp"
|
||||
}),
|
||||
)])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curated_plugin_cache_version_shortens_full_git_sha() {
|
||||
assert_eq!(
|
||||
curated_plugin_cache_version("0123456789abcdef0123456789abcdef01234567"),
|
||||
"01234567"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curated_plugin_cache_version_preserves_non_git_sha_versions() {
|
||||
assert_eq!(
|
||||
curated_plugin_cache_version("export-backup"),
|
||||
"export-backup"
|
||||
);
|
||||
assert_eq!(curated_plugin_cache_version("0123456"), "0123456");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialize_git_subdir_uses_sparse_checkout() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let repo = tempfile::tempdir().expect("create git repo");
|
||||
let plugin_dir = repo.path().join("plugins/toolkit");
|
||||
fs::create_dir_all(&plugin_dir).expect("create plugin directory");
|
||||
fs::create_dir_all(repo.path().join("plugins/other")).expect("create other plugin");
|
||||
fs::write(plugin_dir.join("marker.txt"), "toolkit").expect("write plugin marker");
|
||||
fs::write(repo.path().join("plugins/other/marker.txt"), "other")
|
||||
.expect("write other marker");
|
||||
fs::write(repo.path().join("root.txt"), "root").expect("write root marker");
|
||||
|
||||
run_git(&["init"], Some(repo.path())).expect("init git repo");
|
||||
run_git(
|
||||
&["config", "user.email", "test@example.com"],
|
||||
Some(repo.path()),
|
||||
)
|
||||
.expect("configure git email");
|
||||
run_git(&["config", "user.name", "Test User"], Some(repo.path()))
|
||||
.expect("configure git name");
|
||||
run_git(&["add", "."], Some(repo.path())).expect("stage git repo");
|
||||
run_git(&["commit", "-m", "init"], Some(repo.path())).expect("commit git repo");
|
||||
|
||||
let materialized = materialize_marketplace_plugin_source(
|
||||
codex_home.path(),
|
||||
&MarketplacePluginSource::Git {
|
||||
url: repo.path().display().to_string(),
|
||||
path: Some("plugins/toolkit".to_string()),
|
||||
ref_name: None,
|
||||
sha: None,
|
||||
},
|
||||
)
|
||||
.expect("materialize git source");
|
||||
|
||||
assert_eq!(
|
||||
plugin_dir.file_name(),
|
||||
materialized.path.as_path().file_name()
|
||||
);
|
||||
assert!(materialized.path.as_path().join("marker.txt").is_file());
|
||||
let checkout_root = materialized
|
||||
.path
|
||||
.as_path()
|
||||
.parent()
|
||||
.and_then(Path::parent)
|
||||
.expect("materialized path should be nested under checkout root");
|
||||
assert!(!checkout_root.join("root.txt").exists());
|
||||
assert!(!checkout_root.join("plugins/other/marker.txt").exists());
|
||||
}
|
||||
}
|
||||
#[path = "loader_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,369 @@
|
||||
use super::*;
|
||||
use crate::manifest::load_plugin_manifest;
|
||||
use codex_plugin::PluginId;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn plugin_mcp_file_supports_mcp_servers_object_format() {
|
||||
let parsed = serde_json::from_str::<PluginMcpFile>(
|
||||
r#"{
|
||||
"mcpServers": {
|
||||
"sample": {
|
||||
"command": "sample-mcp"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.expect("parse wrapped plugin mcp config")
|
||||
.into_mcp_servers();
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
HashMap::from([(
|
||||
"sample".to_string(),
|
||||
serde_json::json!({
|
||||
"command": "sample-mcp"
|
||||
}),
|
||||
)])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_mcp_file_supports_mcp_servers_object_format_with_metadata() {
|
||||
let parsed = serde_json::from_str::<PluginMcpFile>(
|
||||
r#"{
|
||||
"$schema": "https://example.com/plugin-mcp.schema.json",
|
||||
"mcpServers": {
|
||||
"sample": {
|
||||
"command": "sample-mcp"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.expect("parse plugin mcp config with metadata")
|
||||
.into_mcp_servers();
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
HashMap::from([(
|
||||
"sample".to_string(),
|
||||
serde_json::json!({
|
||||
"command": "sample-mcp"
|
||||
}),
|
||||
)])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_mcp_file_supports_top_level_server_map_format() {
|
||||
let parsed = serde_json::from_str::<PluginMcpFile>(
|
||||
r#"{
|
||||
"linear": {
|
||||
"type": "http",
|
||||
"url": "https://mcp.linear.app/mcp"
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.expect("parse flat plugin mcp config")
|
||||
.into_mcp_servers();
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
HashMap::from([(
|
||||
"linear".to_string(),
|
||||
serde_json::json!({
|
||||
"type": "http",
|
||||
"url": "https://mcp.linear.app/mcp"
|
||||
}),
|
||||
)])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curated_plugin_cache_version_shortens_full_git_sha() {
|
||||
assert_eq!(
|
||||
curated_plugin_cache_version("0123456789abcdef0123456789abcdef01234567"),
|
||||
"01234567"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curated_plugin_cache_version_preserves_non_git_sha_versions() {
|
||||
assert_eq!(
|
||||
curated_plugin_cache_version("export-backup"),
|
||||
"export-backup"
|
||||
);
|
||||
assert_eq!(curated_plugin_cache_version("0123456"), "0123456");
|
||||
}
|
||||
|
||||
fn plugin_id() -> PluginId {
|
||||
PluginId::parse("demo-plugin@test-marketplace").expect("plugin id")
|
||||
}
|
||||
|
||||
fn plugin_root() -> (tempfile::TempDir, AbsolutePathBuf) {
|
||||
let tmp = tempfile::tempdir().expect("tempdir");
|
||||
let plugin_root =
|
||||
AbsolutePathBuf::try_from(tmp.path().join("demo-plugin")).expect("plugin root");
|
||||
fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create manifest dir");
|
||||
fs::create_dir_all(plugin_root.join("hooks")).expect("create hooks dir");
|
||||
(tmp, plugin_root)
|
||||
}
|
||||
|
||||
fn write_manifest(plugin_root: &AbsolutePathBuf, manifest: &str) {
|
||||
fs::write(plugin_root.join(".codex-plugin/plugin.json"), manifest).expect("write manifest");
|
||||
}
|
||||
|
||||
fn write_hook_file(plugin_root: &AbsolutePathBuf, relative_path: &str, event: &str, command: &str) {
|
||||
fs::write(
|
||||
plugin_root.join(relative_path),
|
||||
format!(
|
||||
r#"{{
|
||||
"hooks": {{
|
||||
"{event}": [
|
||||
{{
|
||||
"hooks": [{{ "type": "command", "command": "{command}" }}]
|
||||
}}
|
||||
]
|
||||
}}
|
||||
}}"#
|
||||
),
|
||||
)
|
||||
.expect("write hooks");
|
||||
}
|
||||
|
||||
fn load_sources(plugin_root: &AbsolutePathBuf) -> (Vec<PluginHookSource>, Vec<String>) {
|
||||
let manifest = load_plugin_manifest(plugin_root.as_path()).expect("manifest");
|
||||
let plugin_data_root = AbsolutePathBuf::try_from(
|
||||
plugin_root
|
||||
.as_path()
|
||||
.parent()
|
||||
.expect("plugin root parent")
|
||||
.join("plugin-data"),
|
||||
)
|
||||
.expect("plugin data root");
|
||||
load_plugin_hooks(
|
||||
plugin_root,
|
||||
&plugin_id(),
|
||||
&plugin_data_root,
|
||||
&manifest.paths,
|
||||
)
|
||||
}
|
||||
|
||||
fn assert_sources(sources: &[PluginHookSource], expected_relative_paths: &[&str]) {
|
||||
assert_eq!(
|
||||
sources
|
||||
.iter()
|
||||
.map(|source| source.plugin_id.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![plugin_id(); expected_relative_paths.len()]
|
||||
);
|
||||
assert_eq!(
|
||||
sources
|
||||
.iter()
|
||||
.map(|source| source.source_relative_path.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
expected_relative_paths
|
||||
);
|
||||
assert_eq!(
|
||||
sources
|
||||
.iter()
|
||||
.map(|source| source.hooks.handler_count())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![1; expected_relative_paths.len()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_plugin_hooks_discovers_default_hooks_file() {
|
||||
let (_tmp, plugin_root) = plugin_root();
|
||||
write_manifest(&plugin_root, r#"{ "name": "demo-plugin" }"#);
|
||||
fs::write(
|
||||
plugin_root.join("hooks/hooks.json"),
|
||||
r#"{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [{ "type": "command", "command": "echo default" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.expect("write hooks");
|
||||
|
||||
let (sources, warnings) = load_sources(&plugin_root);
|
||||
|
||||
assert_eq!(warnings, Vec::<String>::new());
|
||||
assert_sources(&sources, &["hooks/hooks.json"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_plugin_hooks_supports_manifest_hook_path() {
|
||||
let (_tmp, plugin_root) = plugin_root();
|
||||
write_manifest(
|
||||
&plugin_root,
|
||||
r#"{
|
||||
"name": "demo-plugin",
|
||||
"hooks": "./hooks/one.json"
|
||||
}"#,
|
||||
);
|
||||
write_hook_file(&plugin_root, "hooks/one.json", "PreToolUse", "echo one");
|
||||
|
||||
let (sources, warnings) = load_sources(&plugin_root);
|
||||
|
||||
assert_eq!(warnings, Vec::<String>::new());
|
||||
assert_sources(&sources, &["hooks/one.json"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_plugin_hooks_manifest_paths_replace_default_hooks_file() {
|
||||
let (_tmp, plugin_root) = plugin_root();
|
||||
write_manifest(
|
||||
&plugin_root,
|
||||
r#"{
|
||||
"name": "demo-plugin",
|
||||
"hooks": ["./hooks/one.json", "./hooks/two.json"]
|
||||
}"#,
|
||||
);
|
||||
write_hook_file(
|
||||
&plugin_root,
|
||||
"hooks/hooks.json",
|
||||
"PreToolUse",
|
||||
"echo ignored",
|
||||
);
|
||||
write_hook_file(&plugin_root, "hooks/one.json", "PreToolUse", "echo one");
|
||||
write_hook_file(&plugin_root, "hooks/two.json", "PostToolUse", "echo two");
|
||||
|
||||
let (sources, warnings) = load_sources(&plugin_root);
|
||||
|
||||
assert_eq!(warnings, Vec::<String>::new());
|
||||
assert_sources(&sources, &["hooks/one.json", "hooks/two.json"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_plugin_hooks_supports_inline_manifest_hooks() {
|
||||
let (_tmp, plugin_root) = plugin_root();
|
||||
write_manifest(
|
||||
&plugin_root,
|
||||
r#"{
|
||||
"name": "demo-plugin",
|
||||
"hooks": {
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"matcher": "startup",
|
||||
"hooks": [{ "type": "command", "command": "echo inline" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
);
|
||||
|
||||
let (sources, warnings) = load_sources(&plugin_root);
|
||||
|
||||
assert_eq!(warnings, Vec::<String>::new());
|
||||
assert_sources(&sources, &["plugin.json#hooks[0]"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_plugin_hooks_reports_invalid_hook_file() {
|
||||
let (_tmp, plugin_root) = plugin_root();
|
||||
write_manifest(&plugin_root, r#"{ "name": "demo-plugin" }"#);
|
||||
fs::write(plugin_root.join("hooks/hooks.json"), "{ not-json").expect("write invalid hooks");
|
||||
|
||||
let (sources, warnings) = load_sources(&plugin_root);
|
||||
|
||||
assert_eq!(sources, Vec::<PluginHookSource>::new());
|
||||
assert_eq!(
|
||||
warnings,
|
||||
vec![format!(
|
||||
"failed to parse plugin hooks config {}: key must be a string at line 1 column 3",
|
||||
plugin_root.join("hooks/hooks.json").display()
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_plugin_hooks_supports_inline_manifest_hook_list() {
|
||||
let (_tmp, plugin_root) = plugin_root();
|
||||
write_manifest(
|
||||
&plugin_root,
|
||||
r#"{
|
||||
"name": "demo-plugin",
|
||||
"hooks": [
|
||||
{
|
||||
"hooks": {
|
||||
"SessionStart": [
|
||||
{
|
||||
"hooks": [{ "type": "command", "command": "echo inline one" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"hooks": {
|
||||
"Stop": [
|
||||
{
|
||||
"hooks": [{ "type": "command", "command": "echo inline two" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}"#,
|
||||
);
|
||||
|
||||
let (sources, warnings) = load_sources(&plugin_root);
|
||||
|
||||
assert_eq!(warnings, Vec::<String>::new());
|
||||
assert_sources(&sources, &["plugin.json#hooks[0]", "plugin.json#hooks[1]"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialize_git_subdir_uses_sparse_checkout() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let repo = tempfile::tempdir().expect("create git repo");
|
||||
let plugin_dir = repo.path().join("plugins/toolkit");
|
||||
fs::create_dir_all(&plugin_dir).expect("create plugin directory");
|
||||
fs::create_dir_all(repo.path().join("plugins/other")).expect("create other plugin");
|
||||
fs::write(plugin_dir.join("marker.txt"), "toolkit").expect("write plugin marker");
|
||||
fs::write(repo.path().join("plugins/other/marker.txt"), "other").expect("write other marker");
|
||||
fs::write(repo.path().join("root.txt"), "root").expect("write root marker");
|
||||
|
||||
run_git(&["init"], Some(repo.path())).expect("init git repo");
|
||||
run_git(
|
||||
&["config", "user.email", "test@example.com"],
|
||||
Some(repo.path()),
|
||||
)
|
||||
.expect("configure git email");
|
||||
run_git(&["config", "user.name", "Test User"], Some(repo.path())).expect("configure git name");
|
||||
run_git(&["add", "."], Some(repo.path())).expect("stage git repo");
|
||||
run_git(&["commit", "-m", "init"], Some(repo.path())).expect("commit git repo");
|
||||
|
||||
let materialized = materialize_marketplace_plugin_source(
|
||||
codex_home.path(),
|
||||
&MarketplacePluginSource::Git {
|
||||
url: repo.path().display().to_string(),
|
||||
path: Some("plugins/toolkit".to_string()),
|
||||
ref_name: None,
|
||||
sha: None,
|
||||
},
|
||||
)
|
||||
.expect("materialize git source");
|
||||
|
||||
assert_eq!(
|
||||
plugin_dir.file_name(),
|
||||
materialized.path.as_path().file_name()
|
||||
);
|
||||
assert!(materialized.path.as_path().join("marker.txt").is_file());
|
||||
let checkout_root = materialized
|
||||
.path
|
||||
.as_path()
|
||||
.parent()
|
||||
.and_then(Path::parent)
|
||||
.expect("materialized path should be nested under checkout root");
|
||||
assert!(!checkout_root.join("root.txt").exists());
|
||||
assert!(!checkout_root.join("plugins/other/marker.txt").exists());
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use codex_config::HooksFile;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_plugins::find_plugin_manifest_path;
|
||||
use serde::Deserialize;
|
||||
@@ -26,6 +27,8 @@ struct RawPluginManifest {
|
||||
#[serde(default)]
|
||||
apps: Option<String>,
|
||||
#[serde(default)]
|
||||
hooks: Option<RawPluginManifestHooks>,
|
||||
#[serde(default)]
|
||||
interface: Option<RawPluginManifestInterface>,
|
||||
}
|
||||
|
||||
@@ -43,6 +46,13 @@ pub struct PluginManifestPaths {
|
||||
pub skills: Option<AbsolutePathBuf>,
|
||||
pub mcp_servers: Option<AbsolutePathBuf>,
|
||||
pub apps: Option<AbsolutePathBuf>,
|
||||
pub hooks: Option<PluginManifestHooks>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum PluginManifestHooks {
|
||||
Paths(Vec<AbsolutePathBuf>),
|
||||
Inline(Vec<HooksFile>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
@@ -114,6 +124,16 @@ enum RawPluginManifestDefaultPromptEntry {
|
||||
Invalid(JsonValue),
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum RawPluginManifestHooks {
|
||||
Path(String),
|
||||
Paths(Vec<String>),
|
||||
Inline(HooksFile),
|
||||
InlineList(Vec<HooksFile>),
|
||||
Invalid(JsonValue),
|
||||
}
|
||||
|
||||
pub fn load_plugin_manifest(plugin_root: &Path) -> Option<PluginManifest> {
|
||||
let manifest_path = find_plugin_manifest_path(plugin_root)?;
|
||||
let contents = fs::read_to_string(&manifest_path).ok()?;
|
||||
@@ -126,6 +146,7 @@ pub fn load_plugin_manifest(plugin_root: &Path) -> Option<PluginManifest> {
|
||||
skills,
|
||||
mcp_servers,
|
||||
apps,
|
||||
hooks,
|
||||
interface,
|
||||
} = manifest;
|
||||
let name = plugin_root
|
||||
@@ -219,6 +240,7 @@ pub fn load_plugin_manifest(plugin_root: &Path) -> Option<PluginManifest> {
|
||||
mcp_servers.as_deref(),
|
||||
),
|
||||
apps: resolve_manifest_path(plugin_root, "apps", apps.as_deref()),
|
||||
hooks: resolve_manifest_hooks(plugin_root, hooks),
|
||||
},
|
||||
interface,
|
||||
})
|
||||
@@ -233,6 +255,36 @@ pub fn load_plugin_manifest(plugin_root: &Path) -> Option<PluginManifest> {
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_manifest_hooks(
|
||||
plugin_root: &Path,
|
||||
hooks: Option<RawPluginManifestHooks>,
|
||||
) -> Option<PluginManifestHooks> {
|
||||
match hooks? {
|
||||
RawPluginManifestHooks::Path(path) => {
|
||||
resolve_manifest_path(plugin_root, "hooks", Some(&path))
|
||||
.map(|path| PluginManifestHooks::Paths(vec![path]))
|
||||
}
|
||||
RawPluginManifestHooks::Paths(paths) => {
|
||||
let hooks = paths
|
||||
.iter()
|
||||
.filter_map(|path| resolve_manifest_path(plugin_root, "hooks", Some(path)))
|
||||
.collect::<Vec<_>>();
|
||||
(!hooks.is_empty()).then_some(PluginManifestHooks::Paths(hooks))
|
||||
}
|
||||
RawPluginManifestHooks::Inline(hooks) => Some(PluginManifestHooks::Inline(vec![hooks])),
|
||||
RawPluginManifestHooks::InlineList(hooks) => {
|
||||
(!hooks.is_empty()).then_some(PluginManifestHooks::Inline(hooks))
|
||||
}
|
||||
RawPluginManifestHooks::Invalid(value) => {
|
||||
tracing::warn!(
|
||||
"ignoring hooks: expected a string, string array, object, or object array; found {}",
|
||||
json_value_type(&value)
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_interface_asset_path(
|
||||
plugin_root: &Path,
|
||||
field: &'static str,
|
||||
|
||||
@@ -123,14 +123,12 @@ where
|
||||
let marketplace_name = validate_marketplace_source_root(path)?;
|
||||
if marketplace_name == OPENAI_CURATED_MARKETPLACE_NAME {
|
||||
return Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"marketplace '{OPENAI_CURATED_MARKETPLACE_NAME}' is reserved and cannot be added from {}",
|
||||
source.display()
|
||||
"marketplace '{OPENAI_CURATED_MARKETPLACE_NAME}' is reserved and cannot be added from this source"
|
||||
)));
|
||||
}
|
||||
if find_marketplace_root_by_name(codex_home, &install_root, &marketplace_name)?.is_some() {
|
||||
return Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"marketplace '{marketplace_name}' is already added from a different source; remove it before adding {}",
|
||||
source.display()
|
||||
"marketplace '{marketplace_name}' is already added from a different source; remove it before adding this source"
|
||||
)));
|
||||
}
|
||||
record_added_marketplace_entry(codex_home, &marketplace_name, &install_metadata)?;
|
||||
@@ -169,8 +167,7 @@ where
|
||||
let marketplace_name = validate_marketplace_source_root(&staged_root)?;
|
||||
if marketplace_name == OPENAI_CURATED_MARKETPLACE_NAME {
|
||||
return Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"marketplace '{OPENAI_CURATED_MARKETPLACE_NAME}' is reserved and cannot be added from {}",
|
||||
source.display()
|
||||
"marketplace '{OPENAI_CURATED_MARKETPLACE_NAME}' is reserved and cannot be added from this source"
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -178,8 +175,7 @@ where
|
||||
ensure_marketplace_destination_is_inside_install_root(&install_root, &destination)?;
|
||||
if destination.exists() {
|
||||
return Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"marketplace '{marketplace_name}' is already added from a different source; remove it before adding {}",
|
||||
source.display()
|
||||
"marketplace '{marketplace_name}' is already added from a different source; remove it before adding this source"
|
||||
)));
|
||||
}
|
||||
|
||||
|
||||
@@ -58,9 +58,10 @@ pub(crate) fn parse_marketplace_source(
|
||||
});
|
||||
}
|
||||
|
||||
Err(MarketplaceAddError::InvalidRequest(format!(
|
||||
"invalid marketplace source format: {source}"
|
||||
)))
|
||||
Err(MarketplaceAddError::InvalidRequest(
|
||||
"invalid marketplace source format; expected owner/repo, a git URL, or a local marketplace path"
|
||||
.to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn stage_marketplace_source<F>(
|
||||
@@ -160,8 +161,7 @@ fn resolve_local_source_path(source: &str) -> Result<PathBuf, MarketplaceAddErro
|
||||
|
||||
path.canonicalize().map_err(|err| {
|
||||
MarketplaceAddError::InvalidRequest(format!(
|
||||
"failed to resolve local marketplace source {}: {err}",
|
||||
path.display()
|
||||
"failed to resolve local marketplace source path: {err}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ use std::path::PathBuf;
|
||||
|
||||
pub const DEFAULT_PLUGIN_VERSION: &str = "local";
|
||||
pub const PLUGINS_CACHE_DIR: &str = "plugins/cache";
|
||||
pub const PLUGINS_DATA_DIR: &str = "plugins/data";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PluginInstallResult {
|
||||
@@ -24,6 +25,7 @@ pub struct PluginInstallResult {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PluginStore {
|
||||
root: AbsolutePathBuf,
|
||||
data_root: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
impl PluginStore {
|
||||
@@ -35,8 +37,11 @@ impl PluginStore {
|
||||
pub fn try_new(codex_home: PathBuf) -> Result<Self, PluginStoreError> {
|
||||
let root = AbsolutePathBuf::from_absolute_path_checked(codex_home.join(PLUGINS_CACHE_DIR))
|
||||
.map_err(|err| PluginStoreError::io("failed to resolve plugin cache root", err))?;
|
||||
let data_root =
|
||||
AbsolutePathBuf::from_absolute_path_checked(codex_home.join(PLUGINS_DATA_DIR))
|
||||
.map_err(|err| PluginStoreError::io("failed to resolve plugin data root", err))?;
|
||||
|
||||
Ok(Self { root })
|
||||
Ok(Self { root, data_root })
|
||||
}
|
||||
|
||||
pub fn root(&self) -> &AbsolutePathBuf {
|
||||
@@ -53,6 +58,13 @@ impl PluginStore {
|
||||
self.plugin_base_root(plugin_id).join(plugin_version)
|
||||
}
|
||||
|
||||
pub fn plugin_data_root(&self, plugin_id: &PluginId) -> AbsolutePathBuf {
|
||||
self.data_root.join(format!(
|
||||
"{}-{}",
|
||||
plugin_id.plugin_name, plugin_id.marketplace_name
|
||||
))
|
||||
}
|
||||
|
||||
pub fn active_plugin_version(&self, plugin_id: &PluginId) -> Option<String> {
|
||||
let mut discovered_versions = fs::read_dir(self.plugin_base_root(plugin_id).as_path())
|
||||
.ok()?
|
||||
|
||||
@@ -109,6 +109,18 @@ fn plugin_root_derives_path_from_key_and_version() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_data_root_derives_path_from_key() {
|
||||
let tmp = tempdir().unwrap();
|
||||
let store = PluginStore::new(tmp.path().to_path_buf());
|
||||
let plugin_id = PluginId::new("sample".to_string(), "debug".to_string()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
store.plugin_data_root(&plugin_id).as_path(),
|
||||
tmp.path().join("plugins/data/sample-debug")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_with_version_uses_requested_cache_version() {
|
||||
let tmp = tempdir().unwrap();
|
||||
|
||||
@@ -463,6 +463,9 @@
|
||||
"personality": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"plugin_hooks": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"plugins": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -3379,6 +3382,9 @@
|
||||
"personality": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"plugin_hooks": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"plugins": {
|
||||
"type": "boolean"
|
||||
},
|
||||
|
||||
+75
-13
@@ -1234,8 +1234,13 @@ impl ModelClientSession {
|
||||
Err(ApiError::Transport(
|
||||
unauthorized_transport @ TransportError::Http { status, .. },
|
||||
)) if status == StatusCode::UNAUTHORIZED => {
|
||||
inference_trace_attempt
|
||||
.record_failed(&unauthorized_transport, /*output_items*/ &[]);
|
||||
let response_debug_context =
|
||||
extract_response_debug_context(&unauthorized_transport);
|
||||
inference_trace_attempt.record_failed(
|
||||
&unauthorized_transport,
|
||||
response_debug_context.request_id.as_deref(),
|
||||
/*output_items*/ &[],
|
||||
);
|
||||
pending_retry = PendingUnauthorizedRetry::from_recovery(
|
||||
handle_unauthorized(
|
||||
unauthorized_transport,
|
||||
@@ -1247,8 +1252,14 @@ impl ModelClientSession {
|
||||
continue;
|
||||
}
|
||||
Err(err) => {
|
||||
let response_debug_context =
|
||||
extract_response_debug_context_from_api_error(&err);
|
||||
let err = map_api_error(err);
|
||||
inference_trace_attempt.record_failed(&err, /*output_items*/ &[]);
|
||||
inference_trace_attempt.record_failed(
|
||||
&err,
|
||||
response_debug_context.request_id.as_deref(),
|
||||
/*output_items*/ &[],
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
@@ -1374,8 +1385,14 @@ impl ModelClientSession {
|
||||
.stream_request(ws_request, self.websocket_session.connection_reused())
|
||||
.await
|
||||
.map_err(|err| {
|
||||
let response_debug_context =
|
||||
extract_response_debug_context_from_api_error(&err);
|
||||
let err = map_api_error(err);
|
||||
inference_trace_attempt.record_failed(&err, /*output_items*/ &[]);
|
||||
inference_trace_attempt.record_failed(
|
||||
&err,
|
||||
response_debug_context.request_id.as_deref(),
|
||||
/*output_items*/ &[],
|
||||
);
|
||||
err
|
||||
})?;
|
||||
let (stream, last_request_rx) = map_response_stream(
|
||||
@@ -1636,7 +1653,29 @@ fn parent_thread_id_header_value(session_source: &SessionSource) -> Option<Strin
|
||||
const RESPONSE_STREAM_CHANNEL_CAPACITY: usize = 1600;
|
||||
const STREAM_DROPPED_REASON: &str = "response stream dropped before provider terminal event";
|
||||
|
||||
fn map_response_stream<S>(
|
||||
fn map_response_stream(
|
||||
api_stream: codex_api::ResponseStream,
|
||||
session_telemetry: SessionTelemetry,
|
||||
inference_trace_attempt: InferenceTraceAttempt,
|
||||
) -> (ResponseStream, oneshot::Receiver<LastResponse>) {
|
||||
let codex_api::ResponseStream {
|
||||
rx_event,
|
||||
upstream_request_id,
|
||||
} = api_stream;
|
||||
let api_stream = codex_api::ResponseStream {
|
||||
rx_event,
|
||||
upstream_request_id: None,
|
||||
};
|
||||
map_response_events(
|
||||
upstream_request_id,
|
||||
api_stream,
|
||||
session_telemetry,
|
||||
inference_trace_attempt,
|
||||
)
|
||||
}
|
||||
|
||||
fn map_response_events<S>(
|
||||
upstream_request_id: Option<String>,
|
||||
api_stream: S,
|
||||
session_telemetry: SessionTelemetry,
|
||||
inference_trace_attempt: InferenceTraceAttempt,
|
||||
@@ -1658,10 +1697,15 @@ where
|
||||
let mut tx_last_response = Some(tx_last_response);
|
||||
let mut items_added: Vec<ResponseItem> = Vec::new();
|
||||
let mut api_stream = api_stream;
|
||||
let upstream_request_id = upstream_request_id.as_deref();
|
||||
loop {
|
||||
let event = tokio::select! {
|
||||
_ = consumer_dropped.cancelled() => {
|
||||
inference_trace_attempt.record_cancelled(STREAM_DROPPED_REASON, &items_added);
|
||||
inference_trace_attempt.record_cancelled(
|
||||
STREAM_DROPPED_REASON,
|
||||
upstream_request_id,
|
||||
&items_added,
|
||||
);
|
||||
return;
|
||||
}
|
||||
event = api_stream.next() => event,
|
||||
@@ -1677,8 +1721,11 @@ where
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
inference_trace_attempt
|
||||
.record_cancelled(STREAM_DROPPED_REASON, &items_added);
|
||||
inference_trace_attempt.record_cancelled(
|
||||
STREAM_DROPPED_REASON,
|
||||
upstream_request_id,
|
||||
&items_added,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1698,6 +1745,7 @@ where
|
||||
}
|
||||
inference_trace_attempt.record_completed(
|
||||
&response_id,
|
||||
upstream_request_id,
|
||||
&token_usage,
|
||||
&items_added,
|
||||
);
|
||||
@@ -1721,14 +1769,25 @@ where
|
||||
}
|
||||
Ok(event) => {
|
||||
if tx_event.send(Ok(event)).await.is_err() {
|
||||
inference_trace_attempt
|
||||
.record_cancelled(STREAM_DROPPED_REASON, &items_added);
|
||||
inference_trace_attempt.record_cancelled(
|
||||
STREAM_DROPPED_REASON,
|
||||
upstream_request_id,
|
||||
&items_added,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
let response_debug_context =
|
||||
extract_response_debug_context_from_api_error(&err);
|
||||
let upstream_request_id =
|
||||
upstream_request_id.or(response_debug_context.request_id.as_deref());
|
||||
let mapped = map_api_error(err);
|
||||
inference_trace_attempt.record_failed(&mapped, &items_added);
|
||||
inference_trace_attempt.record_failed(
|
||||
&mapped,
|
||||
upstream_request_id,
|
||||
&items_added,
|
||||
);
|
||||
if !logged_error {
|
||||
session_telemetry.see_event_completed_failed(&mapped);
|
||||
logged_error = true;
|
||||
@@ -1739,8 +1798,11 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
inference_trace_attempt
|
||||
.record_failed("stream closed before response.completed", &items_added);
|
||||
inference_trace_attempt.record_failed(
|
||||
"stream closed before response.completed",
|
||||
upstream_request_id,
|
||||
&items_added,
|
||||
);
|
||||
});
|
||||
|
||||
(
|
||||
|
||||
@@ -282,7 +282,12 @@ async fn dropped_response_stream_traces_cancelled_partial_output() -> anyhow::Re
|
||||
let item = output_message("msg-1", "partial answer");
|
||||
let api_stream = futures::stream::iter([Ok(ResponseEvent::OutputItemDone(item))])
|
||||
.chain(futures::stream::pending());
|
||||
let (mut stream, _) = super::map_response_stream(api_stream, test_session_telemetry(), attempt);
|
||||
let (mut stream, _) = super::map_response_events(
|
||||
/*upstream_request_id*/ None,
|
||||
api_stream,
|
||||
test_session_telemetry(),
|
||||
attempt,
|
||||
);
|
||||
|
||||
let observed = stream
|
||||
.next()
|
||||
@@ -332,7 +337,12 @@ async fn dropped_backpressured_response_stream_traces_cancelled_partial_output()
|
||||
notify: Arc::clone(&backpressured_item_yielded),
|
||||
};
|
||||
|
||||
let (stream, _) = super::map_response_stream(api_stream, test_session_telemetry(), attempt);
|
||||
let (stream, _) = super::map_response_events(
|
||||
/*upstream_request_id*/ None,
|
||||
api_stream,
|
||||
test_session_telemetry(),
|
||||
attempt,
|
||||
);
|
||||
|
||||
// Fill the mapper channel with non-terminal events, then yield one output
|
||||
// item. The mapper has observed that item and is blocked trying to send it
|
||||
|
||||
@@ -15,6 +15,7 @@ use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
use codex_protocol::mcp::CallToolResult;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
@@ -48,6 +49,7 @@ pub struct ThreadConfigSnapshot {
|
||||
pub approval_policy: AskForApproval,
|
||||
pub approvals_reviewer: ApprovalsReviewer,
|
||||
pub permission_profile: PermissionProfile,
|
||||
pub active_permission_profile: Option<ActivePermissionProfile>,
|
||||
pub cwd: AbsolutePathBuf,
|
||||
pub ephemeral: bool,
|
||||
pub reasoning_effort: Option<ReasoningEffort>,
|
||||
|
||||
@@ -906,6 +906,14 @@ async fn default_permissions_profile_populates_runtime_sandbox_policy() -> std::
|
||||
config.permissions.network_sandbox_policy(),
|
||||
NetworkSandboxPolicy::Restricted
|
||||
);
|
||||
assert_eq!(
|
||||
config
|
||||
.permissions
|
||||
.active_permission_profile()
|
||||
.as_ref()
|
||||
.map(|active| active.id.as_str()),
|
||||
Some("workspace")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -927,6 +935,7 @@ async fn permission_profile_override_populates_runtime_permissions() -> std::io:
|
||||
.await?;
|
||||
|
||||
assert_eq!(config.permissions.permission_profile(), permission_profile);
|
||||
assert_eq!(config.permissions.active_permission_profile(), None);
|
||||
assert_eq!(
|
||||
&config.legacy_sandbox_policy(),
|
||||
&SandboxPolicy::DangerFullAccess
|
||||
@@ -1266,6 +1275,14 @@ async fn default_permissions_can_select_builtin_profile_without_permissions_tabl
|
||||
.await?;
|
||||
|
||||
let policy = config.permissions.file_system_sandbox_policy();
|
||||
assert_eq!(
|
||||
config
|
||||
.permissions
|
||||
.active_permission_profile()
|
||||
.as_ref()
|
||||
.map(|active| active.id.as_str()),
|
||||
Some(":workspace")
|
||||
);
|
||||
assert!(
|
||||
policy.can_write_path_with_cwd(cwd.path(), cwd.path()),
|
||||
"expected :workspace to allow writing the project root, policy: {policy:?}"
|
||||
@@ -1302,6 +1319,18 @@ async fn empty_config_defaults_to_builtin_profile_for_trusted_project() -> std::
|
||||
.await?;
|
||||
|
||||
let policy = config.permissions.file_system_sandbox_policy();
|
||||
assert_eq!(
|
||||
config
|
||||
.permissions
|
||||
.active_permission_profile()
|
||||
.as_ref()
|
||||
.map(|active| active.id.as_str()),
|
||||
Some(if cfg!(target_os = "windows") {
|
||||
":read-only"
|
||||
} else {
|
||||
":workspace"
|
||||
})
|
||||
);
|
||||
if cfg!(target_os = "windows") {
|
||||
assert!(
|
||||
!policy.can_write_path_with_cwd(cwd.path(), cwd.path()),
|
||||
@@ -1483,6 +1512,14 @@ async fn default_permissions_can_select_builtin_no_sandbox_profile() -> std::io:
|
||||
config.permissions.permission_profile(),
|
||||
PermissionProfile::Disabled
|
||||
);
|
||||
assert_eq!(
|
||||
config
|
||||
.permissions
|
||||
.active_permission_profile()
|
||||
.as_ref()
|
||||
.map(|active| active.id.as_str()),
|
||||
Some(":danger-no-sandbox")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -5893,6 +5930,7 @@ async fn test_precedence_fixture_with_o3_profile() -> std::io::Result<()> {
|
||||
permissions: Permissions {
|
||||
approval_policy: Constrained::allow_any(AskForApproval::Never),
|
||||
permission_profile: Constrained::allow_any(PermissionProfile::read_only()),
|
||||
active_permission_profile: None,
|
||||
network: None,
|
||||
allow_login_shell: true,
|
||||
shell_environment_policy: ShellEnvironmentPolicy::default(),
|
||||
@@ -6087,6 +6125,7 @@ async fn test_precedence_fixture_with_gpt3_profile() -> std::io::Result<()> {
|
||||
permissions: Permissions {
|
||||
approval_policy: Constrained::allow_any(AskForApproval::UnlessTrusted),
|
||||
permission_profile: Constrained::allow_any(PermissionProfile::read_only()),
|
||||
active_permission_profile: None,
|
||||
network: None,
|
||||
allow_login_shell: true,
|
||||
shell_environment_policy: ShellEnvironmentPolicy::default(),
|
||||
@@ -6235,6 +6274,7 @@ async fn test_precedence_fixture_with_zdr_profile() -> std::io::Result<()> {
|
||||
permissions: Permissions {
|
||||
approval_policy: Constrained::allow_any(AskForApproval::OnFailure),
|
||||
permission_profile: Constrained::allow_any(PermissionProfile::read_only()),
|
||||
active_permission_profile: None,
|
||||
network: None,
|
||||
allow_login_shell: true,
|
||||
shell_environment_policy: ShellEnvironmentPolicy::default(),
|
||||
@@ -6368,6 +6408,7 @@ async fn test_precedence_fixture_with_gpt5_profile() -> std::io::Result<()> {
|
||||
permissions: Permissions {
|
||||
approval_policy: Constrained::allow_any(AskForApproval::OnFailure),
|
||||
permission_profile: Constrained::allow_any(PermissionProfile::read_only()),
|
||||
active_permission_profile: None,
|
||||
network: None,
|
||||
allow_login_shell: true,
|
||||
shell_environment_policy: ShellEnvironmentPolicy::default(),
|
||||
|
||||
@@ -82,6 +82,7 @@ use codex_protocol::config_types::Verbosity;
|
||||
use codex_protocol::config_types::WebSearchConfig;
|
||||
use codex_protocol::config_types::WebSearchMode;
|
||||
use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::models::SandboxEnforcement;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
@@ -224,6 +225,9 @@ pub struct Permissions {
|
||||
/// Canonical effective runtime permissions after config requirements and
|
||||
/// runtime readable-root additions have been applied.
|
||||
pub permission_profile: Constrained<PermissionProfile>,
|
||||
/// Named profile selected by config, when the active permissions came from
|
||||
/// `default_permissions` rather than an ad-hoc override.
|
||||
pub active_permission_profile: Option<ActivePermissionProfile>,
|
||||
/// Effective network configuration applied to all spawned processes.
|
||||
pub network: Option<NetworkProxySpec>,
|
||||
/// Whether the model may request a login shell for shell-based tools.
|
||||
@@ -251,6 +255,11 @@ impl Permissions {
|
||||
self.permission_profile.get().clone()
|
||||
}
|
||||
|
||||
/// Named profile selected by config, if the current profile has one.
|
||||
pub fn active_permission_profile(&self) -> Option<ActivePermissionProfile> {
|
||||
self.active_permission_profile.clone()
|
||||
}
|
||||
|
||||
/// Effective filesystem sandbox policy derived from the canonical profile.
|
||||
pub fn file_system_sandbox_policy(&self) -> FileSystemSandboxPolicy {
|
||||
self.permission_profile.get().file_system_sandbox_policy()
|
||||
@@ -309,6 +318,7 @@ impl Permissions {
|
||||
);
|
||||
|
||||
self.permission_profile.set(permission_profile)?;
|
||||
self.active_permission_profile = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -316,10 +326,21 @@ impl Permissions {
|
||||
pub fn set_permission_profile(
|
||||
&mut self,
|
||||
permission_profile: PermissionProfile,
|
||||
) -> ConstraintResult<()> {
|
||||
self.set_permission_profile_with_active_profile(permission_profile, None)
|
||||
}
|
||||
|
||||
/// Replace permissions from the canonical profile and record the named
|
||||
/// source profile, if one is known.
|
||||
pub fn set_permission_profile_with_active_profile(
|
||||
&mut self,
|
||||
permission_profile: PermissionProfile,
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
) -> ConstraintResult<()> {
|
||||
self.permission_profile.can_set(&permission_profile)?;
|
||||
|
||||
self.permission_profile.set(permission_profile)?;
|
||||
self.active_permission_profile = active_permission_profile;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1947,6 +1968,7 @@ impl Config {
|
||||
configured_network_proxy_config,
|
||||
permission_profile,
|
||||
file_system_sandbox_policy,
|
||||
active_permission_profile,
|
||||
) = if let Some(mut permission_profile) = permission_profile {
|
||||
let (mut file_system_sandbox_policy, network_sandbox_policy) =
|
||||
permission_profile.to_runtime_permissions();
|
||||
@@ -1992,6 +2014,7 @@ impl Config {
|
||||
configured_network_proxy_config,
|
||||
permission_profile,
|
||||
file_system_sandbox_policy,
|
||||
None,
|
||||
)
|
||||
} else if profiles_are_active {
|
||||
let default_permissions = cfg.default_permissions.as_deref().unwrap_or_else(|| {
|
||||
@@ -2046,6 +2069,7 @@ impl Config {
|
||||
configured_network_proxy_config,
|
||||
permission_profile,
|
||||
file_system_sandbox_policy,
|
||||
Some(ActivePermissionProfile::new(default_permissions)),
|
||||
)
|
||||
} else {
|
||||
let configured_network_proxy_config = NetworkProxyConfig::default();
|
||||
@@ -2107,6 +2131,7 @@ impl Config {
|
||||
configured_network_proxy_config,
|
||||
permission_profile,
|
||||
file_system_sandbox_policy,
|
||||
None,
|
||||
)
|
||||
};
|
||||
let approval_policy_was_explicit = approval_policy_override.is_some()
|
||||
@@ -2564,6 +2589,7 @@ impl Config {
|
||||
permissions: Permissions {
|
||||
approval_policy: constrained_approval_policy.value,
|
||||
permission_profile: constrained_permission_profile.value,
|
||||
active_permission_profile,
|
||||
network,
|
||||
allow_login_shell,
|
||||
shell_environment_policy,
|
||||
|
||||
@@ -473,6 +473,7 @@ fn hook_run_metric_tags(run: &HookRunSummary) -> [(&'static str, &'static str);
|
||||
HookSource::Project => "project",
|
||||
HookSource::Mdm => "mdm",
|
||||
HookSource::SessionFlags => "session_flags",
|
||||
HookSource::Plugin => "plugin",
|
||||
HookSource::LegacyManagedConfigFile => "legacy_managed_config_file",
|
||||
HookSource::LegacyManagedConfigMdm => "legacy_managed_config_mdm",
|
||||
HookSource::Unknown => "unknown",
|
||||
|
||||
@@ -219,6 +219,8 @@ async fn load_plugins_loads_default_skills_and_mcp_servers() {
|
||||
},
|
||||
)]),
|
||||
apps: vec![AppConnectorId("connector_example".to_string())],
|
||||
hook_sources: Vec::new(),
|
||||
hook_load_warnings: Vec::new(),
|
||||
error: None,
|
||||
}]
|
||||
);
|
||||
@@ -719,6 +721,8 @@ async fn load_plugins_preserves_disabled_plugins_without_effective_contributions
|
||||
has_enabled_skills: false,
|
||||
mcp_servers: HashMap::new(),
|
||||
apps: Vec::new(),
|
||||
hook_sources: Vec::new(),
|
||||
hook_load_warnings: Vec::new(),
|
||||
error: None,
|
||||
}]
|
||||
);
|
||||
@@ -836,6 +840,8 @@ fn capability_index_filters_inactive_and_zero_capability_plugins() {
|
||||
has_enabled_skills: false,
|
||||
mcp_servers: HashMap::new(),
|
||||
apps: Vec::new(),
|
||||
hook_sources: Vec::new(),
|
||||
hook_load_warnings: Vec::new(),
|
||||
error: None,
|
||||
};
|
||||
let summary = |config_name: &str, display_name: &str| PluginCapabilitySummary {
|
||||
|
||||
@@ -90,6 +90,7 @@ use codex_protocol::dynamic_tools::DynamicToolSpec;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::items::UserMessageItem;
|
||||
use codex_protocol::mcp::CallToolResult;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::AdditionalPermissionProfile;
|
||||
use codex_protocol::models::BaseInstructions;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
@@ -601,6 +602,7 @@ impl Codex {
|
||||
approval_policy: config.permissions.approval_policy.clone(),
|
||||
approvals_reviewer: config.approvals_reviewer,
|
||||
permission_profile: config.permissions.permission_profile.clone(),
|
||||
active_permission_profile: config.permissions.active_permission_profile(),
|
||||
windows_sandbox_level: WindowsSandboxLevel::from_config(&config),
|
||||
cwd: config.cwd.clone(),
|
||||
codex_home: config.codex_home.clone(),
|
||||
|
||||
@@ -60,6 +60,8 @@ pub(crate) struct SessionConfiguration {
|
||||
pub(super) approvals_reviewer: ApprovalsReviewer,
|
||||
/// Canonical permission profile for the session.
|
||||
pub(super) permission_profile: Constrained<PermissionProfile>,
|
||||
/// Named permissions profile selected from config, if any.
|
||||
pub(super) active_permission_profile: Option<ActivePermissionProfile>,
|
||||
pub(super) windows_sandbox_level: WindowsSandboxLevel,
|
||||
|
||||
/// Absolute working directory that should be treated as the *root* of the
|
||||
@@ -97,6 +99,10 @@ impl SessionConfiguration {
|
||||
self.permission_profile.get().clone()
|
||||
}
|
||||
|
||||
pub(super) fn active_permission_profile(&self) -> Option<ActivePermissionProfile> {
|
||||
self.active_permission_profile.clone()
|
||||
}
|
||||
|
||||
pub(super) fn sandbox_policy(&self) -> SandboxPolicy {
|
||||
self.permission_profile()
|
||||
.to_legacy_sandbox_policy(&self.cwd)
|
||||
@@ -127,6 +133,7 @@ impl SessionConfiguration {
|
||||
approval_policy: self.approval_policy.value(),
|
||||
approvals_reviewer: self.approvals_reviewer,
|
||||
permission_profile: self.permission_profile(),
|
||||
active_permission_profile: self.active_permission_profile(),
|
||||
cwd: self.cwd.clone(),
|
||||
ephemeral: self.original_config_do_not_use.ephemeral,
|
||||
reasoning_effort: self.collaboration_mode.reasoning_effort(),
|
||||
@@ -210,6 +217,7 @@ impl SessionConfiguration {
|
||||
permission_profile,
|
||||
Some(¤t_file_system_sandbox_policy),
|
||||
)?;
|
||||
next_configuration.active_permission_profile = None;
|
||||
} else if let Some(sandbox_policy) = updates.sandbox_policy.clone() {
|
||||
let file_system_sandbox_policy =
|
||||
FileSystemSandboxPolicy::from_legacy_sandbox_policy_preserving_deny_entries(
|
||||
@@ -225,6 +233,7 @@ impl SessionConfiguration {
|
||||
network_sandbox_policy,
|
||||
),
|
||||
)?;
|
||||
next_configuration.active_permission_profile = None;
|
||||
} else if cwd_changed
|
||||
&& file_system_policy_matches_legacy
|
||||
&& file_system_policy_has_rebindable_project_root_write
|
||||
@@ -750,10 +759,22 @@ impl Session {
|
||||
default_shell.derive_exec_args("", /*use_login_shell*/ false);
|
||||
let hook_shell_program = hook_shell_argv.remove(0);
|
||||
let _ = hook_shell_argv.pop();
|
||||
let plugin_hooks_enabled = config.features.enabled(Feature::PluginHooks);
|
||||
let (plugin_hook_sources, plugin_hook_load_warnings) = if plugin_hooks_enabled {
|
||||
let plugin_outcome = plugins_manager.plugins_for_config(&config).await;
|
||||
(
|
||||
plugin_outcome.effective_plugin_hook_sources(),
|
||||
plugin_outcome.effective_plugin_hook_warnings(),
|
||||
)
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
let hooks = Hooks::new(HooksConfig {
|
||||
legacy_notify_argv: config.notify.clone(),
|
||||
feature_enabled: config.features.enabled(Feature::CodexHooks),
|
||||
config_layer_stack: Some(config.config_layer_stack.clone()),
|
||||
plugin_hook_sources,
|
||||
plugin_hook_load_warnings,
|
||||
shell_program: Some(hook_shell_program),
|
||||
shell_args: hook_shell_argv,
|
||||
});
|
||||
@@ -875,6 +896,7 @@ impl Session {
|
||||
approval_policy: session_configuration.approval_policy.value(),
|
||||
approvals_reviewer: session_configuration.approvals_reviewer,
|
||||
permission_profile: session_configuration.permission_profile(),
|
||||
active_permission_profile: session_configuration.active_permission_profile(),
|
||||
cwd: session_configuration.cwd.clone(),
|
||||
reasoning_effort: session_configuration.collaboration_mode.reasoning_effort(),
|
||||
history_log_id,
|
||||
|
||||
@@ -2293,6 +2293,7 @@ async fn set_rate_limits_retains_previous_credits() {
|
||||
approval_policy: config.permissions.approval_policy.clone(),
|
||||
approvals_reviewer: config.approvals_reviewer,
|
||||
permission_profile: config.permissions.permission_profile.clone(),
|
||||
active_permission_profile: config.permissions.active_permission_profile(),
|
||||
windows_sandbox_level: WindowsSandboxLevel::from_config(&config),
|
||||
cwd: config.cwd.clone(),
|
||||
codex_home: config.codex_home.clone(),
|
||||
@@ -2395,6 +2396,7 @@ async fn set_rate_limits_updates_plan_type_when_present() {
|
||||
approval_policy: config.permissions.approval_policy.clone(),
|
||||
approvals_reviewer: config.approvals_reviewer,
|
||||
permission_profile: config.permissions.permission_profile.clone(),
|
||||
active_permission_profile: config.permissions.active_permission_profile(),
|
||||
windows_sandbox_level: WindowsSandboxLevel::from_config(&config),
|
||||
cwd: config.cwd.clone(),
|
||||
codex_home: config.codex_home.clone(),
|
||||
@@ -2842,6 +2844,7 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati
|
||||
approval_policy: config.permissions.approval_policy.clone(),
|
||||
approvals_reviewer: config.approvals_reviewer,
|
||||
permission_profile: config.permissions.permission_profile.clone(),
|
||||
active_permission_profile: config.permissions.active_permission_profile(),
|
||||
windows_sandbox_level: WindowsSandboxLevel::from_config(&config),
|
||||
cwd: config.cwd.clone(),
|
||||
codex_home: config.codex_home.clone(),
|
||||
@@ -3278,6 +3281,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() {
|
||||
approval_policy: config.permissions.approval_policy.clone(),
|
||||
approvals_reviewer: config.approvals_reviewer,
|
||||
permission_profile: config.permissions.permission_profile.clone(),
|
||||
active_permission_profile: config.permissions.active_permission_profile(),
|
||||
windows_sandbox_level: WindowsSandboxLevel::from_config(&config),
|
||||
cwd: config.cwd.clone(),
|
||||
codex_home: config.codex_home.clone(),
|
||||
@@ -3382,6 +3386,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
approval_policy: config.permissions.approval_policy.clone(),
|
||||
approvals_reviewer: config.approvals_reviewer,
|
||||
permission_profile: config.permissions.permission_profile.clone(),
|
||||
active_permission_profile: config.permissions.active_permission_profile(),
|
||||
windows_sandbox_level: WindowsSandboxLevel::from_config(&config),
|
||||
cwd: config.cwd.clone(),
|
||||
codex_home: config.codex_home.clone(),
|
||||
@@ -3594,6 +3599,7 @@ async fn make_session_with_config_and_rx(
|
||||
approval_policy: config.permissions.approval_policy.clone(),
|
||||
approvals_reviewer: config.approvals_reviewer,
|
||||
permission_profile: config.permissions.permission_profile.clone(),
|
||||
active_permission_profile: config.permissions.active_permission_profile(),
|
||||
windows_sandbox_level: WindowsSandboxLevel::from_config(&config),
|
||||
cwd: config.cwd.clone(),
|
||||
codex_home: config.codex_home.clone(),
|
||||
@@ -4776,6 +4782,7 @@ where
|
||||
approval_policy: config.permissions.approval_policy.clone(),
|
||||
approvals_reviewer: config.approvals_reviewer,
|
||||
permission_profile: config.permissions.permission_profile.clone(),
|
||||
active_permission_profile: config.permissions.active_permission_profile(),
|
||||
windows_sandbox_level: WindowsSandboxLevel::from_config(&config),
|
||||
cwd: config.cwd.clone(),
|
||||
codex_home: config.codex_home.clone(),
|
||||
|
||||
@@ -727,7 +727,7 @@ fn request_message_input_texts(body: &[u8], role: &str) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn stop_hook_can_block_multiple_times_in_same_turn() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -841,7 +841,7 @@ async fn stop_hook_can_block_multiple_times_in_same_turn() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn session_start_hook_sees_materialized_transcript_path() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -886,7 +886,7 @@ async fn session_start_hook_sees_materialized_transcript_path() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn resumed_thread_keeps_stop_continuation_prompt_in_history() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -962,7 +962,7 @@ async fn resumed_thread_keeps_stop_continuation_prompt_in_history() -> Result<()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn multiple_blocking_stop_hooks_persist_multiple_hook_prompt_fragments() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -1028,7 +1028,7 @@ async fn multiple_blocking_stop_hooks_persist_multiple_hook_prompt_fragments() -
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn blocked_user_prompt_submit_persists_additional_context_for_next_turn() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -1111,7 +1111,7 @@ async fn blocked_user_prompt_submit_persists_additional_context_for_next_turn()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn blocked_queued_prompt_does_not_strand_earlier_accepted_prompt() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -1276,7 +1276,7 @@ async fn blocked_queued_prompt_does_not_strand_earlier_accepted_prompt() -> Resu
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn permission_request_hook_allows_shell_command_without_user_approval() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -1355,7 +1355,7 @@ async fn permission_request_hook_allows_shell_command_without_user_approval() ->
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn permission_request_hook_allows_apply_patch_with_write_alias() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -1437,7 +1437,7 @@ async fn permission_request_hook_allows_apply_patch_with_write_alias() -> Result
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn permission_request_hook_sees_raw_exec_command_input() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -1518,7 +1518,7 @@ async fn permission_request_hook_sees_raw_exec_command_input() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn permission_request_hook_allows_network_approval_without_prompt() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -1649,7 +1649,7 @@ allow_local_binding = true
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn permission_request_hook_sees_retry_context_after_sandbox_denial() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -1719,7 +1719,7 @@ async fn permission_request_hook_sees_retry_context_after_sandbox_denial() -> Re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn pre_tool_use_blocks_shell_command_before_execution() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -1821,7 +1821,151 @@ async fn pre_tool_use_blocks_shell_command_before_execution() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn plugin_pre_tool_use_blocks_shell_command_before_execution() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let call_id = "plugin-pretooluse-shell-command";
|
||||
let marker = std::env::temp_dir().join("plugin-pretooluse-shell-command-marker");
|
||||
let command = format!("printf blocked > {}", marker.display());
|
||||
let args = serde_json::json!({ "command": command });
|
||||
let responses = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_response_created("resp-1"),
|
||||
core_test_support::responses::ev_function_call(
|
||||
call_id,
|
||||
"shell_command",
|
||||
&serde_json::to_string(&args)?,
|
||||
),
|
||||
ev_completed("resp-1"),
|
||||
]),
|
||||
sse(vec![
|
||||
ev_response_created("resp-2"),
|
||||
ev_assistant_message("msg-1", "plugin hook blocked it"),
|
||||
ev_completed("resp-2"),
|
||||
]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
|
||||
let home = Arc::new(TempDir::new()?);
|
||||
let plugin_root = home.path().join("plugins/cache/test/sample/local");
|
||||
let hooks_dir = plugin_root.join("hooks");
|
||||
fs::create_dir_all(plugin_root.join(".codex-plugin"))
|
||||
.context("create plugin manifest directory")?;
|
||||
fs::create_dir_all(&hooks_dir).context("create plugin hooks directory")?;
|
||||
fs::write(
|
||||
plugin_root.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"sample"}"#,
|
||||
)
|
||||
.context("write plugin manifest")?;
|
||||
fs::write(
|
||||
home.path().join("config.toml"),
|
||||
r#"[plugins."sample@test"]
|
||||
enabled = true
|
||||
"#,
|
||||
)
|
||||
.context("write plugin config")?;
|
||||
|
||||
let script_path = hooks_dir.join("pre_tool_use_hook.py");
|
||||
let log_path = hooks_dir.join("pre_tool_use_hook_log.jsonl");
|
||||
fs::write(
|
||||
&script_path,
|
||||
format!(
|
||||
r#"import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
payload = json.load(sys.stdin)
|
||||
with Path(r"{log_path}").open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(payload) + "\n")
|
||||
|
||||
print(json.dumps({{
|
||||
"hookSpecificOutput": {{
|
||||
"hookEventName": "PreToolUse",
|
||||
"permissionDecision": "deny",
|
||||
"permissionDecisionReason": "blocked by plugin hook"
|
||||
}}
|
||||
}}))
|
||||
"#,
|
||||
log_path = log_path.display(),
|
||||
),
|
||||
)
|
||||
.context("write plugin pre tool use hook script")?;
|
||||
fs::write(
|
||||
hooks_dir.join("hooks.json"),
|
||||
r#"{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "^Bash$",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "python3 ${PLUGIN_ROOT}/hooks/pre_tool_use_hook.py"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.context("write plugin hooks config")?;
|
||||
|
||||
let mut builder = test_codex()
|
||||
.with_home(Arc::clone(&home))
|
||||
.with_config(|config| {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::Plugins)
|
||||
.expect("test config should allow feature update");
|
||||
config
|
||||
.features
|
||||
.enable(Feature::CodexHooks)
|
||||
.expect("test config should allow feature update");
|
||||
config
|
||||
.features
|
||||
.enable(Feature::PluginHooks)
|
||||
.expect("test config should allow feature update");
|
||||
});
|
||||
let test = builder.build(&server).await?;
|
||||
|
||||
if marker.exists() {
|
||||
fs::remove_file(&marker).context("remove leftover plugin pre tool use marker")?;
|
||||
}
|
||||
|
||||
test.submit_turn_with_policy(
|
||||
"run the shell command blocked by a plugin hook",
|
||||
codex_protocol::protocol::SandboxPolicy::DangerFullAccess,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let requests = responses.requests();
|
||||
assert_eq!(requests.len(), 2);
|
||||
let output_item = requests[1].function_call_output(call_id);
|
||||
let output = output_item
|
||||
.get("output")
|
||||
.and_then(Value::as_str)
|
||||
.expect("shell command output string");
|
||||
assert!(
|
||||
output.contains("Command blocked by PreToolUse hook: blocked by plugin hook"),
|
||||
"blocked tool output should surface the plugin hook reason",
|
||||
);
|
||||
assert!(
|
||||
!marker.exists(),
|
||||
"plugin hook should block shell command execution"
|
||||
);
|
||||
|
||||
let hook_inputs = read_hook_inputs_from_log(&log_path)?;
|
||||
assert_eq!(hook_inputs.len(), 1);
|
||||
assert_eq!(hook_inputs[0]["hook_event_name"], "PreToolUse");
|
||||
assert_eq!(hook_inputs[0]["tool_name"], "Bash");
|
||||
assert_eq!(hook_inputs[0]["tool_use_id"], call_id);
|
||||
assert_eq!(hook_inputs[0]["tool_input"]["command"], command);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pre_tool_use_blocks_shell_when_defined_in_config_toml() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -1904,7 +2048,7 @@ async fn pre_tool_use_blocks_shell_when_defined_in_config_toml() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn pre_tool_use_merges_hooks_json_and_config_toml() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -2005,7 +2149,7 @@ async fn pre_tool_use_merges_hooks_json_and_config_toml() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn pre_tool_use_blocks_local_shell_before_execution() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -2099,7 +2243,7 @@ async fn pre_tool_use_blocks_local_shell_before_execution() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn pre_tool_use_blocks_exec_command_before_execution() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -2186,7 +2330,7 @@ async fn pre_tool_use_blocks_exec_command_before_execution() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn pre_tool_use_blocks_apply_patch_before_execution() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -2263,7 +2407,7 @@ async fn pre_tool_use_blocks_apply_patch_before_execution() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn pre_tool_use_blocks_apply_patch_with_write_alias() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -2338,7 +2482,7 @@ async fn pre_tool_use_blocks_apply_patch_with_write_alias() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn pre_tool_use_does_not_fire_for_plan_tool() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -2410,7 +2554,7 @@ async fn pre_tool_use_does_not_fire_for_plan_tool() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn post_tool_use_records_additional_context_for_shell_command() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -2507,7 +2651,7 @@ async fn post_tool_use_records_additional_context_for_shell_command() -> Result<
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn post_tool_use_block_decision_replaces_shell_command_output_with_reason() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -2575,7 +2719,7 @@ async fn post_tool_use_block_decision_replaces_shell_command_output_with_reason(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn post_tool_use_continue_false_replaces_shell_command_output_with_stop_reason() -> Result<()>
|
||||
{
|
||||
skip_if_no_network!(Ok(()));
|
||||
@@ -2644,7 +2788,7 @@ async fn post_tool_use_continue_false_replaces_shell_command_output_with_stop_re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn post_tool_use_records_additional_context_for_local_shell() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -2718,7 +2862,7 @@ async fn post_tool_use_records_additional_context_for_local_shell() -> Result<()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn post_tool_use_exit_two_replaces_one_shot_exec_command_output_with_feedback() -> Result<()>
|
||||
{
|
||||
skip_if_no_network!(Ok(()));
|
||||
@@ -2793,7 +2937,7 @@ async fn post_tool_use_exit_two_replaces_one_shot_exec_command_output_with_feedb
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn post_tool_use_blocks_when_exec_session_completes_via_write_stdin() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
skip_if_windows!(Ok(()));
|
||||
@@ -2899,7 +3043,7 @@ async fn post_tool_use_blocks_when_exec_session_completes_via_write_stdin() -> R
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn post_tool_use_records_additional_context_for_apply_patch() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -2990,7 +3134,7 @@ async fn post_tool_use_records_additional_context_for_apply_patch() -> Result<()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn post_tool_use_records_apply_patch_context_with_edit_alias() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
@@ -3063,7 +3207,7 @@ async fn post_tool_use_records_apply_patch_context_with_edit_alias() -> Result<(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[tokio::test]
|
||||
async fn post_tool_use_does_not_fire_for_plan_tool() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
|
||||
@@ -1050,6 +1050,7 @@ fn session_configured_from_thread_response(
|
||||
permission_profile: permission_profile.unwrap_or_else(|| {
|
||||
PermissionProfile::from_legacy_sandbox_policy_for_cwd(&sandbox_policy, cwd.as_path())
|
||||
}),
|
||||
active_permission_profile: None,
|
||||
cwd,
|
||||
reasoning_effort,
|
||||
history_log_id: 0,
|
||||
|
||||
@@ -432,6 +432,7 @@ fn session_configured_from_thread_response_uses_review_policy_from_response() {
|
||||
)
|
||||
.into(),
|
||||
),
|
||||
active_permission_profile: None,
|
||||
reasoning_effort: None,
|
||||
};
|
||||
|
||||
|
||||
@@ -115,6 +115,7 @@ fn session_configured_produces_thread_started_event() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/tmp/project").abs(),
|
||||
reasoning_effort: None,
|
||||
history_log_id: 0,
|
||||
|
||||
@@ -159,6 +159,8 @@ pub enum Feature {
|
||||
ToolSuggest,
|
||||
/// Enable plugins.
|
||||
Plugins,
|
||||
/// Enable plugin-bundled lifecycle hooks.
|
||||
PluginHooks,
|
||||
/// Allow the in-app browser pane in desktop apps.
|
||||
///
|
||||
/// Requirements-only gate: this should be set from requirements, not user config.
|
||||
@@ -876,6 +878,12 @@ pub const FEATURES: &[FeatureSpec] = &[
|
||||
stage: Stage::Stable,
|
||||
default_enabled: true,
|
||||
},
|
||||
FeatureSpec {
|
||||
id: Feature::PluginHooks,
|
||||
key: "plugin_hooks",
|
||||
stage: Stage::UnderDevelopment,
|
||||
default_enabled: false,
|
||||
},
|
||||
FeatureSpec {
|
||||
id: Feature::InAppBrowser,
|
||||
key: "in_app_browser",
|
||||
|
||||
@@ -16,6 +16,7 @@ workspace = true
|
||||
anyhow = { workspace = true }
|
||||
chrono = { workspace = true, features = ["serde"] }
|
||||
codex-config = { workspace = true }
|
||||
codex-plugin = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
futures = { workspace = true, features = ["alloc"] }
|
||||
|
||||
@@ -108,12 +108,12 @@ fn build_command(shell: &CommandShell, handler: &ConfiguredHandler) -> Command {
|
||||
};
|
||||
if shell.program.is_empty() {
|
||||
command.arg(&handler.command);
|
||||
command
|
||||
} else {
|
||||
command.args(&shell.args);
|
||||
command.arg(&handler.command);
|
||||
command
|
||||
}
|
||||
command.envs(&handler.env);
|
||||
command
|
||||
}
|
||||
|
||||
fn default_shell_command() -> Command {
|
||||
|
||||
@@ -12,8 +12,10 @@ use codex_config::HooksFile;
|
||||
use codex_config::ManagedHooksRequirementsToml;
|
||||
use codex_config::MatcherGroup;
|
||||
use codex_config::RequirementSource;
|
||||
use codex_plugin::PluginHookSource;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::ConfiguredHandler;
|
||||
use crate::events::common::matcher_pattern_for_event;
|
||||
@@ -25,23 +27,34 @@ pub(crate) struct DiscoveryResult {
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
#[derive(Clone)]
|
||||
struct HookHandlerSource<'a> {
|
||||
path: &'a AbsolutePathBuf,
|
||||
is_managed: bool,
|
||||
source: HookSource,
|
||||
env: HashMap<String, String>,
|
||||
}
|
||||
|
||||
pub(crate) fn discover_handlers(config_layer_stack: Option<&ConfigLayerStack>) -> DiscoveryResult {
|
||||
pub(crate) fn discover_handlers(
|
||||
config_layer_stack: Option<&ConfigLayerStack>,
|
||||
plugin_hook_sources: Vec<PluginHookSource>,
|
||||
plugin_hook_load_warnings: Vec<String>,
|
||||
) -> DiscoveryResult {
|
||||
let Some(config_layer_stack) = config_layer_stack else {
|
||||
return DiscoveryResult {
|
||||
handlers: Vec::new(),
|
||||
warnings: Vec::new(),
|
||||
};
|
||||
let mut handlers = Vec::new();
|
||||
let mut warnings = plugin_hook_load_warnings;
|
||||
let mut display_order = 0_i64;
|
||||
append_plugin_hook_sources(
|
||||
&mut handlers,
|
||||
&mut warnings,
|
||||
&mut display_order,
|
||||
plugin_hook_sources,
|
||||
);
|
||||
return DiscoveryResult { handlers, warnings };
|
||||
};
|
||||
|
||||
let mut handlers = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
let mut warnings = plugin_hook_load_warnings;
|
||||
let mut display_order = 0_i64;
|
||||
|
||||
append_managed_requirement_handlers(
|
||||
@@ -80,6 +93,7 @@ pub(crate) fn discover_handlers(config_layer_stack: Option<&ConfigLayerStack>) -
|
||||
path: &source_path,
|
||||
is_managed: false,
|
||||
source: hook_source,
|
||||
env: HashMap::new(),
|
||||
},
|
||||
hook_events,
|
||||
);
|
||||
@@ -94,12 +108,20 @@ pub(crate) fn discover_handlers(config_layer_stack: Option<&ConfigLayerStack>) -
|
||||
path: &source_path,
|
||||
is_managed: false,
|
||||
source: hook_source,
|
||||
env: HashMap::new(),
|
||||
},
|
||||
hook_events,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
append_plugin_hook_sources(
|
||||
&mut handlers,
|
||||
&mut warnings,
|
||||
&mut display_order,
|
||||
plugin_hook_sources,
|
||||
);
|
||||
|
||||
DiscoveryResult { handlers, warnings }
|
||||
}
|
||||
|
||||
@@ -125,11 +147,51 @@ fn append_managed_requirement_handlers(
|
||||
path: &source_path,
|
||||
is_managed: true,
|
||||
source: hook_source_for_requirement_source(managed_hooks.source.as_ref()),
|
||||
env: HashMap::new(),
|
||||
},
|
||||
managed_hooks.get().hooks.clone(),
|
||||
);
|
||||
}
|
||||
|
||||
fn append_plugin_hook_sources(
|
||||
handlers: &mut Vec<ConfiguredHandler>,
|
||||
warnings: &mut Vec<String>,
|
||||
display_order: &mut i64,
|
||||
plugin_hook_sources: Vec<PluginHookSource>,
|
||||
) {
|
||||
// TODO(abhinav): check enabled/trusted state here before plugin hooks become runnable.
|
||||
for source in plugin_hook_sources {
|
||||
let PluginHookSource {
|
||||
plugin_root,
|
||||
plugin_data_root,
|
||||
source_path,
|
||||
hooks,
|
||||
..
|
||||
} = source;
|
||||
let mut env = HashMap::new();
|
||||
let plugin_root_value = plugin_root.display().to_string();
|
||||
let plugin_data_root_value = plugin_data_root.display().to_string();
|
||||
env.insert("PLUGIN_ROOT".to_string(), plugin_root_value.clone());
|
||||
// For OOTB compat with existing plugins that use this env var.
|
||||
env.insert("CLAUDE_PLUGIN_ROOT".to_string(), plugin_root_value);
|
||||
env.insert("PLUGIN_DATA".to_string(), plugin_data_root_value.clone());
|
||||
// For OOTB compat with existing plugins that use this env var.
|
||||
env.insert("CLAUDE_PLUGIN_DATA".to_string(), plugin_data_root_value);
|
||||
append_hook_events(
|
||||
handlers,
|
||||
warnings,
|
||||
display_order,
|
||||
HookHandlerSource {
|
||||
path: &source_path,
|
||||
is_managed: false,
|
||||
source: HookSource::Plugin,
|
||||
env,
|
||||
},
|
||||
hooks,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn managed_hooks_source_path(
|
||||
managed_hooks: &ManagedHooksRequirementsToml,
|
||||
requirement_source: Option<&RequirementSource>,
|
||||
@@ -278,7 +340,7 @@ fn append_hook_events(
|
||||
handlers,
|
||||
warnings,
|
||||
display_order,
|
||||
source,
|
||||
source.clone(),
|
||||
event_name,
|
||||
groups,
|
||||
);
|
||||
@@ -298,7 +360,7 @@ fn append_matcher_groups(
|
||||
handlers,
|
||||
warnings,
|
||||
display_order,
|
||||
source,
|
||||
source.clone(),
|
||||
event_name,
|
||||
matcher_pattern_for_event(event_name, group.matcher.as_deref()),
|
||||
group.hooks,
|
||||
@@ -347,6 +409,9 @@ fn append_group_handlers(
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let command = source.env.iter().fold(command, |command, (key, value)| {
|
||||
command.replace(&format!("${{{key}}}"), value)
|
||||
});
|
||||
let timeout_sec = timeout_sec.unwrap_or(600).max(1);
|
||||
handlers.push(ConfiguredHandler {
|
||||
event_name,
|
||||
@@ -358,6 +423,7 @@ fn append_group_handlers(
|
||||
source_path: source.path.clone(),
|
||||
source: source.source,
|
||||
display_order: *display_order,
|
||||
env: source.env.clone(),
|
||||
});
|
||||
*display_order += 1;
|
||||
}
|
||||
@@ -431,6 +497,7 @@ mod tests {
|
||||
path,
|
||||
is_managed: false,
|
||||
source: hook_source(),
|
||||
env: std::collections::HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -475,6 +542,7 @@ mod tests {
|
||||
source_path: source_path.clone(),
|
||||
source: hook_source(),
|
||||
display_order: 0,
|
||||
env: std::collections::HashMap::new(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -508,6 +576,7 @@ mod tests {
|
||||
source_path: source_path.clone(),
|
||||
source: hook_source(),
|
||||
display_order: 0,
|
||||
env: std::collections::HashMap::new(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -164,6 +164,7 @@ mod tests {
|
||||
source_path: test_path_buf("/tmp/hooks.json").abs(),
|
||||
source: HookSource::User,
|
||||
display_order,
|
||||
env: std::collections::HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,10 @@ pub(crate) mod dispatcher;
|
||||
pub(crate) mod output_parser;
|
||||
pub(crate) mod schema_loader;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_plugin::PluginHookSource;
|
||||
use codex_protocol::protocol::HookRunSummary;
|
||||
use codex_protocol::protocol::HookSource;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
@@ -39,6 +42,7 @@ pub(crate) struct ConfiguredHandler {
|
||||
pub source_path: AbsolutePathBuf,
|
||||
pub source: HookSource,
|
||||
pub display_order: i64,
|
||||
pub env: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl ConfiguredHandler {
|
||||
@@ -74,6 +78,8 @@ impl ClaudeHooksEngine {
|
||||
pub(crate) fn new(
|
||||
enabled: bool,
|
||||
config_layer_stack: Option<&ConfigLayerStack>,
|
||||
plugin_hook_sources: Vec<PluginHookSource>,
|
||||
plugin_hook_load_warnings: Vec<String>,
|
||||
shell: CommandShell,
|
||||
) -> Self {
|
||||
if !enabled {
|
||||
@@ -85,7 +91,11 @@ impl ClaudeHooksEngine {
|
||||
}
|
||||
|
||||
let _ = schema_loader::generated_hook_schemas();
|
||||
let discovered = discovery::discover_handlers(config_layer_stack);
|
||||
let discovered = discovery::discover_handlers(
|
||||
config_layer_stack,
|
||||
plugin_hook_sources,
|
||||
plugin_hook_load_warnings,
|
||||
);
|
||||
Self {
|
||||
handlers: discovered.handlers,
|
||||
warnings: discovered.warnings,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
@@ -15,7 +16,12 @@ use codex_config::ManagedHooksRequirementsToml;
|
||||
use codex_config::MatcherGroup;
|
||||
use codex_config::RequirementSource;
|
||||
use codex_config::TomlValue;
|
||||
use codex_plugin::PluginHookSource;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::HookOutputEntryKind;
|
||||
use codex_protocol::protocol::HookRunStatus;
|
||||
use codex_protocol::protocol::HookSource;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
|
||||
@@ -105,6 +111,8 @@ with Path(r"{log_path}").open("a", encoding="utf-8") as handle:
|
||||
let engine = ClaudeHooksEngine::new(
|
||||
/*enabled*/ true,
|
||||
Some(&config_layer_stack),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
CommandShell {
|
||||
program: String::new(),
|
||||
args: Vec::new(),
|
||||
@@ -188,6 +196,8 @@ fn requirements_managed_hooks_warn_when_managed_dir_is_missing() {
|
||||
let engine = ClaudeHooksEngine::new(
|
||||
/*enabled*/ true,
|
||||
Some(&config_layer_stack),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
CommandShell {
|
||||
program: String::new(),
|
||||
args: Vec::new(),
|
||||
@@ -295,6 +305,8 @@ fn discovers_hooks_from_json_and_toml_in_the_same_layer() {
|
||||
let engine = ClaudeHooksEngine::new(
|
||||
/*enabled*/ true,
|
||||
Some(&config_layer_stack),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
CommandShell {
|
||||
program: String::new(),
|
||||
args: Vec::new(),
|
||||
@@ -325,3 +337,194 @@ fn discovers_hooks_from_json_and_toml_in_the_same_layer() {
|
||||
assert_eq!(preview[0].source_path, hooks_json_path);
|
||||
assert_eq!(preview[1].source_path, config_path);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plugin_hook_sources_run_with_plugin_env_and_plugin_source() {
|
||||
let temp = tempdir().expect("create temp dir");
|
||||
let plugin_root =
|
||||
AbsolutePathBuf::try_from(temp.path().join("demo-plugin")).expect("plugin root");
|
||||
let plugin_data_root =
|
||||
AbsolutePathBuf::try_from(temp.path().join("plugin-data")).expect("plugin data root");
|
||||
fs::create_dir_all(plugin_root.join("hooks")).expect("create hooks dir");
|
||||
let source_path = plugin_root.join("hooks/hooks.json");
|
||||
let script_path = plugin_root.join("hooks/write_env.py");
|
||||
fs::write(
|
||||
script_path.as_path(),
|
||||
r#"import json
|
||||
import os
|
||||
print(json.dumps({
|
||||
"systemMessage": json.dumps({
|
||||
"plugin": os.environ.get("PLUGIN_ROOT"),
|
||||
"claude": os.environ.get("CLAUDE_PLUGIN_ROOT"),
|
||||
})
|
||||
}))
|
||||
"#,
|
||||
)
|
||||
.expect("write hook script");
|
||||
let plugin_id = PluginId::parse("demo-plugin@test-marketplace").expect("plugin id");
|
||||
let plugin_hook_sources = vec![PluginHookSource {
|
||||
plugin_id,
|
||||
plugin_root: plugin_root.clone(),
|
||||
plugin_data_root: plugin_data_root.clone(),
|
||||
source_path: source_path.clone(),
|
||||
source_relative_path: "hooks/hooks.json".to_string(),
|
||||
hooks: HookEventsToml {
|
||||
pre_tool_use: vec![MatcherGroup {
|
||||
matcher: Some("Bash".to_string()),
|
||||
hooks: vec![HookHandlerConfig::Command {
|
||||
command: format!("python3 {}", script_path.display()),
|
||||
timeout_sec: Some(5),
|
||||
r#async: false,
|
||||
status_message: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
}];
|
||||
let engine = ClaudeHooksEngine::new(
|
||||
/*enabled*/ true,
|
||||
/*config_layer_stack*/ None,
|
||||
plugin_hook_sources,
|
||||
Vec::new(),
|
||||
CommandShell {
|
||||
program: String::new(),
|
||||
args: Vec::new(),
|
||||
},
|
||||
);
|
||||
|
||||
let preview = engine.preview_pre_tool_use(&PreToolUseRequest {
|
||||
session_id: ThreadId::new(),
|
||||
turn_id: "turn-1".to_string(),
|
||||
cwd: cwd(),
|
||||
transcript_path: None,
|
||||
model: "gpt-test".to_string(),
|
||||
permission_mode: "default".to_string(),
|
||||
tool_name: "Bash".to_string(),
|
||||
matcher_aliases: Vec::new(),
|
||||
tool_use_id: "tool-1".to_string(),
|
||||
tool_input: serde_json::json!({ "command": "echo hello" }),
|
||||
});
|
||||
assert_eq!(preview.len(), 1);
|
||||
assert_eq!(preview[0].source, HookSource::Plugin);
|
||||
assert_eq!(preview[0].source_path, source_path);
|
||||
|
||||
let outcome = engine
|
||||
.run_pre_tool_use(PreToolUseRequest {
|
||||
session_id: ThreadId::new(),
|
||||
turn_id: "turn-1".to_string(),
|
||||
cwd: cwd(),
|
||||
transcript_path: None,
|
||||
model: "gpt-test".to_string(),
|
||||
permission_mode: "default".to_string(),
|
||||
tool_name: "Bash".to_string(),
|
||||
matcher_aliases: Vec::new(),
|
||||
tool_use_id: "tool-1".to_string(),
|
||||
tool_input: serde_json::json!({ "command": "echo hello" }),
|
||||
})
|
||||
.await;
|
||||
|
||||
assert_eq!(outcome.hook_events.len(), 1);
|
||||
assert_eq!(outcome.hook_events[0].run.source, HookSource::Plugin);
|
||||
assert_eq!(outcome.hook_events[0].run.status, HookRunStatus::Completed);
|
||||
assert_eq!(outcome.hook_events[0].run.entries.len(), 1);
|
||||
assert_eq!(
|
||||
outcome.hook_events[0].run.entries[0].kind,
|
||||
HookOutputEntryKind::Warning
|
||||
);
|
||||
let logged: serde_json::Value =
|
||||
serde_json::from_str(&outcome.hook_events[0].run.entries[0].text)
|
||||
.expect("parse env payload");
|
||||
assert_eq!(
|
||||
logged,
|
||||
serde_json::json!({
|
||||
"plugin": plugin_root.display().to_string(),
|
||||
"claude": plugin_root.display().to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_hook_sources_expand_plugin_placeholders() {
|
||||
let temp = tempdir().expect("create temp dir");
|
||||
let plugin_root =
|
||||
AbsolutePathBuf::try_from(temp.path().join("demo-plugin")).expect("plugin root");
|
||||
let plugin_data_root =
|
||||
AbsolutePathBuf::try_from(temp.path().join("plugin-data")).expect("plugin data root");
|
||||
let source_path = plugin_root.join("hooks/hooks.json");
|
||||
let plugin_id = PluginId::parse("demo-plugin@test-marketplace").expect("plugin id");
|
||||
let plugin_hook_sources = vec![PluginHookSource {
|
||||
plugin_id,
|
||||
plugin_root: plugin_root.clone(),
|
||||
plugin_data_root: plugin_data_root.clone(),
|
||||
source_path,
|
||||
source_relative_path: "hooks/hooks.json".to_string(),
|
||||
hooks: HookEventsToml {
|
||||
pre_tool_use: vec![MatcherGroup {
|
||||
matcher: Some("Bash".to_string()),
|
||||
hooks: vec![HookHandlerConfig::Command {
|
||||
command: "run ${PLUGIN_ROOT} ${CLAUDE_PLUGIN_ROOT} ${PLUGIN_DATA} ${CLAUDE_PLUGIN_DATA}"
|
||||
.to_string(),
|
||||
timeout_sec: Some(5),
|
||||
r#async: false,
|
||||
status_message: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
}];
|
||||
let engine = ClaudeHooksEngine::new(
|
||||
/*enabled*/ true,
|
||||
/*config_layer_stack*/ None,
|
||||
plugin_hook_sources,
|
||||
Vec::new(),
|
||||
CommandShell {
|
||||
program: String::new(),
|
||||
args: Vec::new(),
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
engine.handlers[0].command,
|
||||
format!(
|
||||
"run {} {} {} {}",
|
||||
plugin_root.display(),
|
||||
plugin_root.display(),
|
||||
plugin_data_root.display(),
|
||||
plugin_data_root.display()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
engine.handlers[0].env,
|
||||
HashMap::from([
|
||||
("PLUGIN_ROOT".to_string(), plugin_root.display().to_string()),
|
||||
(
|
||||
"CLAUDE_PLUGIN_ROOT".to_string(),
|
||||
plugin_root.display().to_string()
|
||||
),
|
||||
(
|
||||
"PLUGIN_DATA".to_string(),
|
||||
plugin_data_root.display().to_string()
|
||||
),
|
||||
(
|
||||
"CLAUDE_PLUGIN_DATA".to_string(),
|
||||
plugin_data_root.display().to_string()
|
||||
),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_hook_load_warnings_are_startup_warnings() {
|
||||
let engine = ClaudeHooksEngine::new(
|
||||
/*enabled*/ true,
|
||||
/*config_layer_stack*/ None,
|
||||
Vec::new(),
|
||||
vec!["failed plugin hook".to_string()],
|
||||
CommandShell {
|
||||
program: String::new(),
|
||||
args: Vec::new(),
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(engine.warnings(), &["failed plugin hook".to_string()]);
|
||||
}
|
||||
|
||||
@@ -551,6 +551,7 @@ mod tests {
|
||||
source_path: test_path_buf("/tmp/hooks.json").abs(),
|
||||
source: codex_protocol::protocol::HookSource::User,
|
||||
display_order: 0,
|
||||
env: std::collections::HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -542,6 +542,7 @@ mod tests {
|
||||
source_path: test_path_buf("/tmp/hooks.json").abs(),
|
||||
source: codex_protocol::protocol::HookSource::User,
|
||||
display_order: 0,
|
||||
env: std::collections::HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -364,6 +364,7 @@ mod tests {
|
||||
source_path: test_path_buf("/tmp/hooks.json").abs(),
|
||||
source: codex_protocol::protocol::HookSource::User,
|
||||
display_order: 0,
|
||||
env: std::collections::HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -531,6 +531,7 @@ mod tests {
|
||||
source_path: test_path_buf("/tmp/hooks.json").abs(),
|
||||
source: codex_protocol::protocol::HookSource::User,
|
||||
display_order: 0,
|
||||
env: std::collections::HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -422,6 +422,7 @@ mod tests {
|
||||
source_path: test_path_buf("/tmp/hooks.json").abs(),
|
||||
source: codex_protocol::protocol::HookSource::User,
|
||||
display_order: 0,
|
||||
env: std::collections::HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_plugin::PluginHookSource;
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::engine::ClaudeHooksEngine;
|
||||
@@ -25,6 +26,8 @@ pub struct HooksConfig {
|
||||
pub legacy_notify_argv: Option<Vec<String>>,
|
||||
pub feature_enabled: bool,
|
||||
pub config_layer_stack: Option<ConfigLayerStack>,
|
||||
pub plugin_hook_sources: Vec<PluginHookSource>,
|
||||
pub plugin_hook_load_warnings: Vec<String>,
|
||||
pub shell_program: Option<String>,
|
||||
pub shell_args: Vec<String>,
|
||||
}
|
||||
@@ -53,6 +56,8 @@ impl Hooks {
|
||||
let engine = ClaudeHooksEngine::new(
|
||||
config.feature_enabled,
|
||||
config.config_layer_stack.as_ref(),
|
||||
config.plugin_hook_sources,
|
||||
config.plugin_hook_load_warnings,
|
||||
CommandShell {
|
||||
program: config.shell_program.unwrap_or_default(),
|
||||
args: config.shell_args,
|
||||
|
||||
@@ -1034,7 +1034,10 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn http_connect_accept_allows_allowlisted_host_in_full_mode() {
|
||||
let policy = {
|
||||
let mut policy = NetworkProxySettings::default();
|
||||
let mut policy = NetworkProxySettings {
|
||||
allow_local_binding: true,
|
||||
..NetworkProxySettings::default()
|
||||
};
|
||||
policy.set_allowed_domains(vec!["example.com".to_string()]);
|
||||
policy
|
||||
};
|
||||
|
||||
@@ -32,7 +32,7 @@ impl Host {
|
||||
/// Returns true if the host is a loopback hostname or IP literal.
|
||||
pub fn is_loopback_host(host: &Host) -> bool {
|
||||
let host = host.as_str();
|
||||
let host = host.split_once('%').map(|(ip, _)| ip).unwrap_or(host);
|
||||
let host = unscoped_ip_literal(host).unwrap_or(host);
|
||||
if host == "localhost" {
|
||||
return true;
|
||||
}
|
||||
@@ -103,24 +103,48 @@ pub fn normalize_host(host: &str) -> String {
|
||||
if host.starts_with('[')
|
||||
&& let Some(end) = host.find(']')
|
||||
{
|
||||
return normalize_dns_host(&host[1..end]);
|
||||
return normalize_dns_host_or_ip_literal(&host[1..end]);
|
||||
}
|
||||
|
||||
// The proxy stack should typically hand us a host without a port, but be
|
||||
// defensive and strip `:port` when there is exactly one `:`.
|
||||
if host.bytes().filter(|b| *b == b':').count() == 1 {
|
||||
let host = host.split(':').next().unwrap_or_default();
|
||||
return normalize_dns_host(host);
|
||||
return normalize_dns_host_or_ip_literal(host);
|
||||
}
|
||||
|
||||
// Avoid mangling unbracketed IPv6 literals, but strip trailing dots so fully qualified domain
|
||||
// names are treated the same as their dotless variants.
|
||||
normalize_dns_host(host)
|
||||
normalize_dns_host_or_ip_literal(host)
|
||||
}
|
||||
|
||||
fn normalize_dns_host(host: &str) -> String {
|
||||
fn normalize_dns_host_or_ip_literal(host: &str) -> String {
|
||||
let host = host.to_ascii_lowercase();
|
||||
host.trim_end_matches('.').to_string()
|
||||
let host = host.trim_end_matches('.');
|
||||
if let Some(ip) = normalize_ip_literal(host) {
|
||||
return ip;
|
||||
}
|
||||
host.to_string()
|
||||
}
|
||||
|
||||
pub(crate) fn unscoped_ip_literal(host: &str) -> Option<&str> {
|
||||
let (ip, _) = host.split_once('%')?;
|
||||
ip.parse::<IpAddr>().ok()?;
|
||||
Some(ip)
|
||||
}
|
||||
|
||||
fn normalize_ip_literal(host: &str) -> Option<String> {
|
||||
if host.parse::<IpAddr>().is_ok() {
|
||||
return Some(host.to_string());
|
||||
}
|
||||
for delimiter in ["%25", "%"] {
|
||||
if let Some((ip, scope)) = host.split_once(delimiter)
|
||||
&& ip.parse::<IpAddr>().is_ok()
|
||||
{
|
||||
return Some(format!("{ip}%{scope}"));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn normalize_pattern(pattern: &str) -> String {
|
||||
@@ -392,6 +416,15 @@ mod tests {
|
||||
assert_eq!(true, set.is_match("::1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compile_globset_preserves_scoped_ipv6_literals() {
|
||||
let set = compile_denylist_globset(&["[fe80::1%25lo0]".to_string()]).unwrap();
|
||||
|
||||
assert_eq!(true, set.is_match("fe80::1%lo0"));
|
||||
assert_eq!(false, set.is_match("fe80::1%lo1"));
|
||||
assert_eq!(false, set.is_match("fe80::1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_loopback_host_handles_localhost_variants() {
|
||||
assert!(is_loopback_host(&Host::parse("localhost").unwrap()));
|
||||
@@ -462,4 +495,11 @@ mod tests {
|
||||
assert_eq!(normalize_host("[::1]"), "::1");
|
||||
assert_eq!(normalize_host("[::1]:443"), "::1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_host_preserves_ipv6_scope_ids() {
|
||||
assert_eq!(normalize_host("fe80::1%lo0"), "fe80::1%lo0");
|
||||
assert_eq!(normalize_host("[fe80::1%lo0]"), "fe80::1%lo0");
|
||||
assert_eq!(normalize_host("[fe80::1%25lo0]"), "fe80::1%lo0");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -790,9 +790,16 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_proxy_builder_uses_loopback_ports() {
|
||||
let http_listener = StdTcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0))).unwrap();
|
||||
let http_addr = http_listener.local_addr().unwrap();
|
||||
let socks_listener = StdTcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0))).unwrap();
|
||||
let socks_addr = socks_listener.local_addr().unwrap();
|
||||
drop(http_listener);
|
||||
drop(socks_listener);
|
||||
|
||||
let state = Arc::new(network_proxy_state_for_policy(NetworkProxySettings {
|
||||
proxy_url: "http://127.0.0.1:43128".to_string(),
|
||||
socks_url: "http://127.0.0.1:48081".to_string(),
|
||||
proxy_url: format!("http://{http_addr}"),
|
||||
socks_url: format!("http://{socks_addr}"),
|
||||
..NetworkProxySettings::default()
|
||||
}));
|
||||
let proxy = match NetworkProxy::builder().state(state).build().await {
|
||||
@@ -812,14 +819,8 @@ mod tests {
|
||||
assert!(proxy.socks_addr.ip().is_loopback());
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
assert_eq!(
|
||||
proxy.http_addr,
|
||||
"127.0.0.1:43128".parse::<SocketAddr>().unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
proxy.socks_addr,
|
||||
"127.0.0.1:48081".parse::<SocketAddr>().unwrap()
|
||||
);
|
||||
assert_eq!(proxy.http_addr, http_addr);
|
||||
assert_eq!(proxy.socks_addr, socks_addr);
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::policy::Host;
|
||||
use crate::policy::is_loopback_host;
|
||||
use crate::policy::is_non_public_ip;
|
||||
use crate::policy::normalize_host;
|
||||
use crate::policy::unscoped_ip_literal;
|
||||
use crate::reasons::REASON_DENIED;
|
||||
use crate::reasons::REASON_NOT_ALLOWED;
|
||||
use crate::reasons::REASON_NOT_ALLOWED_LOCAL;
|
||||
@@ -371,11 +372,11 @@ impl NetworkProxyState {
|
||||
// 1) explicit deny always wins
|
||||
// 2) local/private networking is opt-in (defense-in-depth)
|
||||
// 3) allowlist is enforced when configured
|
||||
if deny_set.is_match(host_str) {
|
||||
if globset_matches_host_or_unscoped(&deny_set, host_str) {
|
||||
return Ok(HostBlockDecision::Blocked(HostBlockReason::Denied));
|
||||
}
|
||||
|
||||
let is_allowlisted = allow_set.is_match(host_str);
|
||||
let is_allowlisted = globset_matches_host_or_unscoped(&allow_set, host_str);
|
||||
if !allow_local_binding {
|
||||
// If the intent is "prevent access to local/internal networks", we must not rely solely
|
||||
// on string checks like `localhost` / `127.0.0.1`. Attackers can use DNS rebinding or
|
||||
@@ -386,10 +387,7 @@ impl NetworkProxyState {
|
||||
// allowlisted; hostnames that resolve to local/private IPs are blocked even if
|
||||
// allowlisted.
|
||||
let local_literal = {
|
||||
let host_no_scope = host_str
|
||||
.split_once('%')
|
||||
.map(|(ip, _)| ip)
|
||||
.unwrap_or(host_str);
|
||||
let host_no_scope = unscoped_ip_literal(host_str).unwrap_or(host_str);
|
||||
if is_loopback_host(&host) {
|
||||
true
|
||||
} else if let Ok(ip) = host_no_scope.parse::<IpAddr>() {
|
||||
@@ -797,8 +795,13 @@ fn log_domain_list_changes(list_name: &str, previous: &[String], next: &[String]
|
||||
}
|
||||
}
|
||||
|
||||
fn globset_matches_host_or_unscoped(set: &GlobSet, host: &str) -> bool {
|
||||
set.is_match(host) || unscoped_ip_literal(host).is_some_and(|ip| set.is_match(ip))
|
||||
}
|
||||
|
||||
fn is_explicit_local_allowlisted(allowed_domains: &[String], host: &Host) -> bool {
|
||||
let normalized_host = host.as_str();
|
||||
let unscoped_host = unscoped_ip_literal(normalized_host);
|
||||
allowed_domains.iter().any(|pattern| {
|
||||
let pattern = pattern.trim();
|
||||
if pattern == "*" || pattern.starts_with("*.") || pattern.starts_with("**.") {
|
||||
@@ -807,7 +810,9 @@ fn is_explicit_local_allowlisted(allowed_domains: &[String], host: &Host) -> boo
|
||||
if pattern.contains('*') || pattern.contains('?') {
|
||||
return false;
|
||||
}
|
||||
normalize_host(pattern) == normalized_host
|
||||
let normalized_pattern = normalize_host(pattern);
|
||||
normalized_pattern == normalized_host
|
||||
|| unscoped_host.is_some_and(|ip| normalized_pattern == ip)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1247,7 +1252,7 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn host_blocked_allows_scoped_ipv6_literal_when_explicitly_allowlisted() {
|
||||
let state = network_proxy_state_for_policy(network_settings(&["fe80::1%lo0"], &[]));
|
||||
let state = network_proxy_state_for_policy(network_settings(&["fe80::1"], &[]));
|
||||
|
||||
assert_eq!(
|
||||
state
|
||||
@@ -1258,6 +1263,68 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn host_blocked_requires_exact_scoped_ipv6_allowlist_match() {
|
||||
let state = network_proxy_state_for_policy(NetworkProxySettings {
|
||||
allow_local_binding: true,
|
||||
..network_settings(&["fe80::1%eth0"], &[])
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
state
|
||||
.host_blocked("fe80::1%eth0", /*port*/ 80)
|
||||
.await
|
||||
.unwrap(),
|
||||
HostBlockDecision::Allowed
|
||||
);
|
||||
assert_eq!(
|
||||
state
|
||||
.host_blocked("fe80::1%eth1", /*port*/ 80)
|
||||
.await
|
||||
.unwrap(),
|
||||
HostBlockDecision::Blocked(HostBlockReason::NotAllowed)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn host_blocked_denies_scoped_ipv6_literal_before_local_binding() {
|
||||
let state = network_proxy_state_for_policy(NetworkProxySettings {
|
||||
allow_local_binding: true,
|
||||
..network_settings(&["*"], &["fd00::1"])
|
||||
});
|
||||
|
||||
for host in ["fd00::1%eth0", "[fd00::1%eth0]", "[fd00::1%25eth0]"] {
|
||||
assert_eq!(
|
||||
state.host_blocked(host, /*port*/ 80).await.unwrap(),
|
||||
HostBlockDecision::Blocked(HostBlockReason::Denied),
|
||||
"host should be denied after normalization: {host}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn host_blocked_requires_exact_scoped_ipv6_denylist_match() {
|
||||
let state = network_proxy_state_for_policy(NetworkProxySettings {
|
||||
allow_local_binding: true,
|
||||
..network_settings(&["*"], &["fd00::1%eth0"])
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
state
|
||||
.host_blocked("fd00::1%eth0", /*port*/ 80)
|
||||
.await
|
||||
.unwrap(),
|
||||
HostBlockDecision::Blocked(HostBlockReason::Denied)
|
||||
);
|
||||
assert_eq!(
|
||||
state
|
||||
.host_blocked("fd00::1%eth1", /*port*/ 80)
|
||||
.await
|
||||
.unwrap(),
|
||||
HostBlockDecision::Allowed
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn host_blocked_rejects_private_ip_literals_when_local_binding_disabled() {
|
||||
let state = network_proxy_state_for_policy(network_settings(&["example.com"], &[]));
|
||||
|
||||
@@ -13,6 +13,7 @@ path = "src/lib.rs"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
codex-config = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
codex-utils-plugins = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
@@ -6,6 +6,8 @@ pub use codex_utils_plugins::plugin_namespace_for_skill_path;
|
||||
mod load_outcome;
|
||||
mod plugin_id;
|
||||
|
||||
use codex_config::HookEventsToml;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
pub use load_outcome::EffectiveSkillRoots;
|
||||
pub use load_outcome::LoadedPlugin;
|
||||
pub use load_outcome::PluginLoadOutcome;
|
||||
@@ -27,6 +29,16 @@ pub struct PluginCapabilitySummary {
|
||||
pub app_connector_ids: Vec<AppConnectorId>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PluginHookSource {
|
||||
pub plugin_id: PluginId,
|
||||
pub plugin_root: AbsolutePathBuf,
|
||||
pub plugin_data_root: AbsolutePathBuf,
|
||||
pub source_path: AbsolutePathBuf,
|
||||
pub source_relative_path: String,
|
||||
pub hooks: HookEventsToml,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PluginTelemetryMetadata {
|
||||
pub plugin_id: PluginId,
|
||||
|
||||
@@ -5,6 +5,7 @@ use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
use crate::AppConnectorId;
|
||||
use crate::PluginCapabilitySummary;
|
||||
use crate::PluginHookSource;
|
||||
|
||||
const MAX_CAPABILITY_SUMMARY_DESCRIPTION_LEN: usize = 1024;
|
||||
|
||||
@@ -21,6 +22,8 @@ pub struct LoadedPlugin<M> {
|
||||
pub has_enabled_skills: bool,
|
||||
pub mcp_servers: HashMap<String, M>,
|
||||
pub apps: Vec<AppConnectorId>,
|
||||
pub hook_sources: Vec<PluginHookSource>,
|
||||
pub hook_load_warnings: Vec<String>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
@@ -140,6 +143,22 @@ impl<M: Clone> PluginLoadOutcome<M> {
|
||||
apps
|
||||
}
|
||||
|
||||
pub fn effective_plugin_hook_sources(&self) -> Vec<PluginHookSource> {
|
||||
self.plugins
|
||||
.iter()
|
||||
.filter(|plugin| plugin.is_active())
|
||||
.flat_map(|plugin| plugin.hook_sources.iter().cloned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn effective_plugin_hook_warnings(&self) -> Vec<String> {
|
||||
self.plugins
|
||||
.iter()
|
||||
.filter(|plugin| plugin.is_active())
|
||||
.flat_map(|plugin| plugin.hook_load_warnings.iter().cloned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn capability_summaries(&self) -> &[PluginCapabilitySummary] {
|
||||
&self.capability_summaries
|
||||
}
|
||||
|
||||
@@ -317,6 +317,34 @@ pub enum PermissionProfile {
|
||||
External { network: NetworkSandboxPolicy },
|
||||
}
|
||||
|
||||
/// Metadata for the named permissions profile that produced the active
|
||||
/// `PermissionProfile`.
|
||||
///
|
||||
/// The runtime must honor `PermissionProfile`; this sidecar exists so clients
|
||||
/// can display stable profile identity without trying to reverse-engineer a
|
||||
/// name from the compiled permissions.
|
||||
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, JsonSchema, TS)]
|
||||
pub struct ActivePermissionProfile {
|
||||
/// Profile identifier from `default_permissions`, such as `:workspace` or a
|
||||
/// user-defined `[permissions.<id>]` profile.
|
||||
pub id: String,
|
||||
|
||||
/// Optional parent profile identifier once permissions profiles support
|
||||
/// inheritance. This is always `None` until that config feature exists.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub extends: Option<String>,
|
||||
}
|
||||
|
||||
impl ActivePermissionProfile {
|
||||
pub fn new(id: impl Into<String>) -> Self {
|
||||
Self {
|
||||
id: id.into(),
|
||||
extends: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PermissionProfile {
|
||||
fn default() -> Self {
|
||||
Self::Managed {
|
||||
|
||||
@@ -33,6 +33,7 @@ use crate::mcp::ResourceTemplate as McpResourceTemplate;
|
||||
use crate::mcp::Tool as McpTool;
|
||||
use crate::memory_citation::MemoryCitation;
|
||||
use crate::message_history::HistoryEntry;
|
||||
use crate::models::ActivePermissionProfile;
|
||||
use crate::models::BaseInstructions;
|
||||
use crate::models::ContentItem;
|
||||
use crate::models::MessagePhase;
|
||||
@@ -1563,6 +1564,7 @@ pub enum HookSource {
|
||||
Project,
|
||||
Mdm,
|
||||
SessionFlags,
|
||||
Plugin,
|
||||
LegacyManagedConfigFile,
|
||||
LegacyManagedConfigMdm,
|
||||
#[default]
|
||||
@@ -3507,6 +3509,12 @@ pub struct SessionConfiguredEvent {
|
||||
/// Canonical effective permissions for commands executed in the session.
|
||||
pub permission_profile: PermissionProfile,
|
||||
|
||||
/// Named profile that produced `permission_profile`, when the active
|
||||
/// permissions came from `default_permissions`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub active_permission_profile: Option<ActivePermissionProfile>,
|
||||
|
||||
/// Working directory that should be treated as the *root* of the
|
||||
/// session.
|
||||
pub cwd: AbsolutePathBuf,
|
||||
@@ -3558,6 +3566,8 @@ impl<'de> Deserialize<'de> for SessionConfiguredEvent {
|
||||
// and immediately project it into the canonical `permission_profile`.
|
||||
sandbox_policy: Option<SandboxPolicy>,
|
||||
permission_profile: Option<PermissionProfile>,
|
||||
#[serde(default)]
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
cwd: AbsolutePathBuf,
|
||||
reasoning_effort: Option<ReasoningEffortConfig>,
|
||||
history_log_id: u64,
|
||||
@@ -3589,6 +3599,7 @@ impl<'de> Deserialize<'de> for SessionConfiguredEvent {
|
||||
approval_policy: wire.approval_policy,
|
||||
approvals_reviewer: wire.approvals_reviewer,
|
||||
permission_profile,
|
||||
active_permission_profile: wire.active_permission_profile,
|
||||
cwd: wire.cwd,
|
||||
reasoning_effort: wire.reasoning_effort,
|
||||
history_log_id: wire.history_log_id,
|
||||
@@ -5101,6 +5112,7 @@ mod tests {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: permission_profile.clone(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
|
||||
@@ -84,6 +84,7 @@ struct EnabledInferenceTraceAttempt {
|
||||
#[derive(Serialize)]
|
||||
struct TracedResponseStreamOutput<'a> {
|
||||
response_id: Option<&'a str>,
|
||||
upstream_request_id: Option<&'a str>,
|
||||
token_usage: Option<&'a TokenUsage>,
|
||||
output_items: Vec<JsonValue>,
|
||||
}
|
||||
@@ -174,6 +175,7 @@ impl InferenceTraceAttempt {
|
||||
pub fn record_completed(
|
||||
&self,
|
||||
response_id: &str,
|
||||
upstream_request_id: Option<&str>,
|
||||
token_usage: &Option<TokenUsage>,
|
||||
output_items: &[ResponseItem],
|
||||
) {
|
||||
@@ -183,6 +185,7 @@ impl InferenceTraceAttempt {
|
||||
let Some(response_payload) = write_response_payload_best_effort(
|
||||
attempt,
|
||||
Some(response_id),
|
||||
upstream_request_id,
|
||||
token_usage.as_ref(),
|
||||
output_items,
|
||||
) else {
|
||||
@@ -194,13 +197,19 @@ impl InferenceTraceAttempt {
|
||||
RawTraceEventPayload::InferenceCompleted {
|
||||
inference_call_id: attempt.inference_call_id.clone(),
|
||||
response_id: Some(response_id.to_string()),
|
||||
upstream_request_id: upstream_request_id.map(str::to_string),
|
||||
response_payload,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Records pre-response and mid-stream failures.
|
||||
pub fn record_failed(&self, error: impl Display, output_items: &[ResponseItem]) {
|
||||
pub fn record_failed(
|
||||
&self,
|
||||
error: impl Display,
|
||||
upstream_request_id: Option<&str>,
|
||||
output_items: &[ResponseItem],
|
||||
) {
|
||||
let Some(attempt) = self.take_terminal_attempt() else {
|
||||
return;
|
||||
};
|
||||
@@ -210,6 +219,7 @@ impl InferenceTraceAttempt {
|
||||
write_response_payload_best_effort(
|
||||
attempt,
|
||||
/*response_id*/ None,
|
||||
upstream_request_id,
|
||||
/*token_usage*/ None,
|
||||
output_items,
|
||||
)
|
||||
@@ -218,6 +228,7 @@ impl InferenceTraceAttempt {
|
||||
&attempt.context,
|
||||
RawTraceEventPayload::InferenceFailed {
|
||||
inference_call_id: attempt.inference_call_id.clone(),
|
||||
upstream_request_id: upstream_request_id.map(str::to_string),
|
||||
error: error.to_string(),
|
||||
partial_response_payload,
|
||||
},
|
||||
@@ -229,7 +240,12 @@ impl InferenceTraceAttempt {
|
||||
/// This happens when the turn is interrupted or when mailbox delivery
|
||||
/// preempts the current sampling request. Complete output items observed
|
||||
/// before that point are retained as partial response evidence.
|
||||
pub fn record_cancelled(&self, reason: impl Display, output_items: &[ResponseItem]) {
|
||||
pub fn record_cancelled(
|
||||
&self,
|
||||
reason: impl Display,
|
||||
upstream_request_id: Option<&str>,
|
||||
output_items: &[ResponseItem],
|
||||
) {
|
||||
let Some(attempt) = self.take_terminal_attempt() else {
|
||||
return;
|
||||
};
|
||||
@@ -239,6 +255,7 @@ impl InferenceTraceAttempt {
|
||||
write_response_payload_best_effort(
|
||||
attempt,
|
||||
/*response_id*/ None,
|
||||
upstream_request_id,
|
||||
/*token_usage*/ None,
|
||||
output_items,
|
||||
)
|
||||
@@ -247,6 +264,7 @@ impl InferenceTraceAttempt {
|
||||
&attempt.context,
|
||||
RawTraceEventPayload::InferenceCancelled {
|
||||
inference_call_id: attempt.inference_call_id.clone(),
|
||||
upstream_request_id: upstream_request_id.map(str::to_string),
|
||||
reason: reason.to_string(),
|
||||
partial_response_payload,
|
||||
},
|
||||
@@ -312,11 +330,13 @@ fn write_json_payload_best_effort(
|
||||
fn write_response_payload_best_effort(
|
||||
attempt: &EnabledInferenceTraceAttempt,
|
||||
response_id: Option<&str>,
|
||||
upstream_request_id: Option<&str>,
|
||||
token_usage: Option<&TokenUsage>,
|
||||
output_items: &[ResponseItem],
|
||||
) -> Option<crate::RawPayloadRef> {
|
||||
let response_payload = TracedResponseStreamOutput {
|
||||
response_id,
|
||||
upstream_request_id,
|
||||
token_usage,
|
||||
output_items: output_items.iter().map(trace_response_item_json).collect(),
|
||||
};
|
||||
@@ -387,7 +407,7 @@ mod tests {
|
||||
"content": [{"type": "input_text", "text": "hello"}]
|
||||
}],
|
||||
}));
|
||||
attempt.record_completed("resp-1", &None, &[]);
|
||||
attempt.record_completed("resp-1", Some("req-1"), &None, &[]);
|
||||
|
||||
let rollout = replay_bundle(temp.path())?;
|
||||
let inference = rollout
|
||||
@@ -400,7 +420,7 @@ mod tests {
|
||||
assert_eq!(inference.thread_id, "thread-root");
|
||||
assert_eq!(inference.codex_turn_id, "turn-1");
|
||||
assert_eq!(inference.execution.status, ExecutionStatus::Completed);
|
||||
assert_eq!(inference.upstream_request_id, Some("resp-1".to_string()));
|
||||
assert_eq!(inference.upstream_request_id, Some("req-1".to_string()));
|
||||
assert_eq!(rollout.raw_payloads.len(), 2);
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -152,7 +152,9 @@ pub struct InferenceCall {
|
||||
pub execution: ExecutionWindow,
|
||||
pub model: String,
|
||||
pub provider_name: String,
|
||||
/// Upstream request ID returned by HTTP/proxy/engine infrastructure.
|
||||
/// Responses API response id, used by follow-up `previous_response_id` requests.
|
||||
pub response_id: Option<String>,
|
||||
/// Request id returned by HTTP/proxy/engine infrastructure.
|
||||
pub upstream_request_id: Option<String>,
|
||||
/// Complete ordered input snapshot sent with this request.
|
||||
pub request_item_ids: Vec<ConversationItemId>,
|
||||
|
||||
@@ -101,17 +101,26 @@ pub enum RawTraceEventPayload {
|
||||
},
|
||||
InferenceCompleted {
|
||||
inference_call_id: InferenceCallId,
|
||||
/// Responses API `response.id`; used by `previous_response_id`.
|
||||
response_id: Option<String>,
|
||||
/// Provider transport request id, such as `x-request-id`.
|
||||
upstream_request_id: Option<String>,
|
||||
response_payload: RawPayloadRef,
|
||||
},
|
||||
InferenceFailed {
|
||||
inference_call_id: InferenceCallId,
|
||||
/// Provider transport request id, such as `x-request-id`, when the
|
||||
/// provider returned one before the stream failed.
|
||||
upstream_request_id: Option<String>,
|
||||
error: String,
|
||||
/// Partial response payload, when stream events arrived before failure.
|
||||
partial_response_payload: Option<RawPayloadRef>,
|
||||
},
|
||||
InferenceCancelled {
|
||||
inference_call_id: InferenceCallId,
|
||||
/// Provider transport request id, such as `x-request-id`, when observed
|
||||
/// before Codex stopped consuming the stream.
|
||||
upstream_request_id: Option<String>,
|
||||
/// Why Codex stopped consuming the provider stream before a terminal response event.
|
||||
reason: String,
|
||||
/// Completed output items observed before cancellation, if any.
|
||||
|
||||
@@ -64,6 +64,7 @@ fn code_cell_lifecycle_links_nested_tools_waits_and_outputs() -> anyhow::Result<
|
||||
writer.append(RawTraceEventPayload::InferenceCompleted {
|
||||
inference_call_id: "inference-1".to_string(),
|
||||
response_id: Some("resp-1".to_string()),
|
||||
upstream_request_id: None,
|
||||
response_payload: response,
|
||||
})?;
|
||||
writer.append_with_context(
|
||||
@@ -247,6 +248,7 @@ fn fast_code_cell_lifecycle_waits_for_source_item() -> anyhow::Result<()> {
|
||||
writer.append(RawTraceEventPayload::InferenceCompleted {
|
||||
inference_call_id: "inference-1".to_string(),
|
||||
response_id: Some("resp-1".to_string()),
|
||||
upstream_request_id: None,
|
||||
response_payload: response,
|
||||
})?;
|
||||
|
||||
@@ -301,6 +303,7 @@ fn cancelled_turn_terminates_unfinished_code_cell() -> anyhow::Result<()> {
|
||||
writer.append(RawTraceEventPayload::InferenceCompleted {
|
||||
inference_call_id: "inference-1".to_string(),
|
||||
response_id: Some("resp-1".to_string()),
|
||||
upstream_request_id: None,
|
||||
response_payload: response,
|
||||
})?;
|
||||
writer.append_with_context(
|
||||
@@ -388,6 +391,7 @@ fn runtime_code_cell_ids_can_repeat_across_threads() -> anyhow::Result<()> {
|
||||
writer.append(RawTraceEventPayload::InferenceCompleted {
|
||||
inference_call_id: inference_call_id.to_string(),
|
||||
response_id: Some(format!("resp-{thread_id}")),
|
||||
upstream_request_id: None,
|
||||
response_payload: response,
|
||||
})?;
|
||||
writer.append_with_context(
|
||||
|
||||
@@ -76,7 +76,7 @@ impl TraceReducer {
|
||||
.values()
|
||||
.find(|inference| {
|
||||
inference.thread_id == thread_id
|
||||
&& inference.upstream_request_id.as_deref() == Some(previous_response_id)
|
||||
&& inference.response_id.as_deref() == Some(previous_response_id)
|
||||
})
|
||||
.map(|inference| {
|
||||
let mut ids = inference.request_item_ids.clone();
|
||||
|
||||
@@ -13,6 +13,7 @@ use crate::model::InferenceCall;
|
||||
use crate::model::InferenceCallId;
|
||||
use crate::payload::RawPayloadRef;
|
||||
use crate::raw_event::RawEventSeq;
|
||||
use crate::raw_event::RawTraceEventPayload;
|
||||
|
||||
/// Raw inference-start fields after dispatch has stripped the common event envelope.
|
||||
///
|
||||
@@ -91,6 +92,7 @@ impl TraceReducer {
|
||||
},
|
||||
model: started.model,
|
||||
provider_name: started.provider_name,
|
||||
response_id: None,
|
||||
upstream_request_id: None,
|
||||
request_item_ids,
|
||||
response_item_ids: Vec::new(),
|
||||
@@ -137,11 +139,49 @@ impl TraceReducer {
|
||||
&mut self,
|
||||
seq: RawEventSeq,
|
||||
wall_time_unix_ms: i64,
|
||||
inference_call_id: InferenceCallId,
|
||||
status: ExecutionStatus,
|
||||
response_id: Option<String>,
|
||||
response_payload: Option<RawPayloadRef>,
|
||||
payload: RawTraceEventPayload,
|
||||
) -> Result<()> {
|
||||
let (inference_call_id, status, response_id, upstream_request_id, response_payload) =
|
||||
match payload {
|
||||
RawTraceEventPayload::InferenceCompleted {
|
||||
inference_call_id,
|
||||
response_id,
|
||||
upstream_request_id,
|
||||
response_payload,
|
||||
} => (
|
||||
inference_call_id,
|
||||
ExecutionStatus::Completed,
|
||||
response_id,
|
||||
upstream_request_id,
|
||||
Some(response_payload),
|
||||
),
|
||||
RawTraceEventPayload::InferenceFailed {
|
||||
inference_call_id,
|
||||
upstream_request_id,
|
||||
partial_response_payload,
|
||||
..
|
||||
} => (
|
||||
inference_call_id,
|
||||
ExecutionStatus::Failed,
|
||||
None,
|
||||
upstream_request_id,
|
||||
partial_response_payload,
|
||||
),
|
||||
RawTraceEventPayload::InferenceCancelled {
|
||||
inference_call_id,
|
||||
upstream_request_id,
|
||||
partial_response_payload,
|
||||
..
|
||||
} => (
|
||||
inference_call_id,
|
||||
ExecutionStatus::Cancelled,
|
||||
None,
|
||||
upstream_request_id,
|
||||
partial_response_payload,
|
||||
),
|
||||
_ => bail!("complete_inference_call received a non-terminal inference event"),
|
||||
};
|
||||
|
||||
if !self
|
||||
.rollout
|
||||
.inference_calls
|
||||
@@ -156,23 +196,31 @@ impl TraceReducer {
|
||||
self.reduce_inference_response(wall_time_unix_ms, &inference_call_id, payload)
|
||||
})
|
||||
.transpose()?;
|
||||
let Some(inference) = self.rollout.inference_calls.get_mut(&inference_call_id) else {
|
||||
bail!("inference call {inference_call_id} disappeared during response reduction");
|
||||
};
|
||||
// Turn-end cleanup can close a stream before the async mapper observes
|
||||
// cancellation. Preserve that terminal status while still retaining any
|
||||
// late partial response evidence from the mapper.
|
||||
if inference.execution.status == ExecutionStatus::Running {
|
||||
inference.execution.ended_at_unix_ms = Some(wall_time_unix_ms);
|
||||
inference.execution.ended_seq = Some(seq);
|
||||
inference.execution.status = status;
|
||||
inference.upstream_request_id = response_id;
|
||||
}
|
||||
if let Some(response_payload) = response_payload {
|
||||
inference.raw_response_payload_id = Some(response_payload.raw_payload_id);
|
||||
}
|
||||
if let Some(response_item_ids) = response_item_ids {
|
||||
inference.response_item_ids = response_item_ids;
|
||||
{
|
||||
let Some(inference) = self.rollout.inference_calls.get_mut(&inference_call_id) else {
|
||||
bail!("inference call {inference_call_id} disappeared during response reduction");
|
||||
};
|
||||
inference.response_id = response_id;
|
||||
// Turn-end cleanup can close a stream before the async mapper observes
|
||||
// cancellation. Preserve that terminal status while still retaining any
|
||||
// late partial response evidence from the mapper.
|
||||
if inference.execution.status == ExecutionStatus::Running {
|
||||
inference.execution.ended_at_unix_ms = Some(wall_time_unix_ms);
|
||||
inference.execution.ended_seq = Some(seq);
|
||||
inference.execution.status = status;
|
||||
}
|
||||
// Turn-end cleanup can mark an inference terminal before the stream
|
||||
// mapper records its late partial payload. Keep the server request
|
||||
// id from that late payload even when the status is already closed.
|
||||
if let Some(upstream_request_id) = upstream_request_id {
|
||||
inference.upstream_request_id = Some(upstream_request_id);
|
||||
}
|
||||
if let Some(response_payload) = response_payload {
|
||||
inference.raw_response_payload_id = Some(response_payload.raw_payload_id);
|
||||
}
|
||||
if let Some(response_item_ids) = response_item_ids {
|
||||
inference.response_item_ids = response_item_ids;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ fn cancelled_inference_reduces_partial_response_items() -> anyhow::Result<()> {
|
||||
)?;
|
||||
writer.append(RawTraceEventPayload::InferenceCancelled {
|
||||
inference_call_id: "inference-1".to_string(),
|
||||
upstream_request_id: Some("req-cancelled".to_string()),
|
||||
reason: "test interruption".to_string(),
|
||||
partial_response_payload: Some(partial_response),
|
||||
})?;
|
||||
@@ -49,6 +50,10 @@ fn cancelled_inference_reduces_partial_response_items() -> anyhow::Result<()> {
|
||||
let response_item_id = &inference.response_item_ids[0];
|
||||
|
||||
assert_eq!(inference.execution.status, ExecutionStatus::Cancelled);
|
||||
assert_eq!(
|
||||
inference.upstream_request_id,
|
||||
Some("req-cancelled".to_string()),
|
||||
);
|
||||
assert_eq!(inference.response_item_ids.len(), 1);
|
||||
assert_eq!(
|
||||
rollout.conversation_items[response_item_id].kind,
|
||||
@@ -123,6 +128,7 @@ fn late_cancelled_inference_preserves_turn_end_status() -> anyhow::Result<()> {
|
||||
)?;
|
||||
writer.append(RawTraceEventPayload::InferenceCancelled {
|
||||
inference_call_id: "inference-1".to_string(),
|
||||
upstream_request_id: Some("req-late-cancelled".to_string()),
|
||||
reason: "stream mapper noticed cancellation after turn end".to_string(),
|
||||
partial_response_payload: Some(partial_response.clone()),
|
||||
})?;
|
||||
@@ -135,6 +141,10 @@ fn late_cancelled_inference_preserves_turn_end_status() -> anyhow::Result<()> {
|
||||
inference.raw_response_payload_id,
|
||||
Some(partial_response.raw_payload_id),
|
||||
);
|
||||
assert_eq!(
|
||||
inference.upstream_request_id,
|
||||
Some("req-late-cancelled".to_string()),
|
||||
);
|
||||
assert_eq!(inference.response_item_ids.len(), 1);
|
||||
let response_item_id = &inference.response_item_ids[0];
|
||||
assert_eq!(
|
||||
|
||||
@@ -226,47 +226,10 @@ impl TraceReducer {
|
||||
},
|
||||
)?;
|
||||
}
|
||||
RawTraceEventPayload::InferenceCompleted {
|
||||
inference_call_id,
|
||||
response_id,
|
||||
response_payload,
|
||||
} => {
|
||||
self.complete_inference_call(
|
||||
event.seq,
|
||||
event.wall_time_unix_ms,
|
||||
inference_call_id,
|
||||
ExecutionStatus::Completed,
|
||||
response_id,
|
||||
Some(response_payload),
|
||||
)?;
|
||||
}
|
||||
RawTraceEventPayload::InferenceFailed {
|
||||
inference_call_id,
|
||||
partial_response_payload,
|
||||
..
|
||||
} => {
|
||||
self.complete_inference_call(
|
||||
event.seq,
|
||||
event.wall_time_unix_ms,
|
||||
inference_call_id,
|
||||
ExecutionStatus::Failed,
|
||||
/*response_id*/ None,
|
||||
partial_response_payload,
|
||||
)?;
|
||||
}
|
||||
RawTraceEventPayload::InferenceCancelled {
|
||||
inference_call_id,
|
||||
partial_response_payload,
|
||||
..
|
||||
} => {
|
||||
self.complete_inference_call(
|
||||
event.seq,
|
||||
event.wall_time_unix_ms,
|
||||
inference_call_id,
|
||||
ExecutionStatus::Cancelled,
|
||||
/*response_id*/ None,
|
||||
partial_response_payload,
|
||||
)?;
|
||||
payload @ (RawTraceEventPayload::InferenceCompleted { .. }
|
||||
| RawTraceEventPayload::InferenceFailed { .. }
|
||||
| RawTraceEventPayload::InferenceCancelled { .. }) => {
|
||||
self.complete_inference_call(event.seq, event.wall_time_unix_ms, payload)?;
|
||||
}
|
||||
RawTraceEventPayload::ProtocolEventObserved { .. } => {
|
||||
// Protocol wrappers are raw debug breadcrumbs. Typed hooks own
|
||||
|
||||
@@ -146,6 +146,7 @@ pub(crate) fn append_inference_completion(
|
||||
writer.append(RawTraceEventPayload::InferenceCompleted {
|
||||
inference_call_id: inference_call_id.to_string(),
|
||||
response_id: Some(response_id.to_string()),
|
||||
upstream_request_id: None,
|
||||
response_payload,
|
||||
})?;
|
||||
Ok(())
|
||||
@@ -184,6 +185,7 @@ pub(crate) fn append_completed_inference(
|
||||
RawTraceEventPayload::InferenceCompleted {
|
||||
inference_call_id: inference_id.to_string(),
|
||||
response_id: Some(format!("resp-{inference_id}")),
|
||||
upstream_request_id: None,
|
||||
response_payload: response,
|
||||
},
|
||||
)?;
|
||||
|
||||
@@ -551,6 +551,7 @@ fn append_inference_with_tool_call(writer: &TraceWriter) -> anyhow::Result<()> {
|
||||
writer.append(RawTraceEventPayload::InferenceCompleted {
|
||||
inference_call_id: "inference-1".to_string(),
|
||||
response_id: Some("resp-1".to_string()),
|
||||
upstream_request_id: None,
|
||||
response_payload: response,
|
||||
})?;
|
||||
Ok(())
|
||||
|
||||
@@ -133,8 +133,8 @@ fn disabled_thread_context_accepts_trace_calls_without_writing() -> anyhow::Resu
|
||||
let inference_attempt = inference_trace.start_attempt();
|
||||
inference_attempt.record_started(&serde_json::json!({ "kind": "inference" }));
|
||||
let token_usage: Option<codex_protocol::protocol::TokenUsage> = None;
|
||||
inference_attempt.record_completed("response-1", &token_usage, &[]);
|
||||
inference_attempt.record_failed("inference failed", &[]);
|
||||
inference_attempt.record_completed("response-1", Some("req-1"), &token_usage, &[]);
|
||||
inference_attempt.record_failed("inference failed", /*upstream_request_id*/ None, &[]);
|
||||
|
||||
let compaction_trace = thread_trace.compaction_trace_context(
|
||||
"turn-1",
|
||||
|
||||
@@ -226,6 +226,7 @@ mod tests {
|
||||
writer.append(RawTraceEventPayload::InferenceCompleted {
|
||||
inference_call_id: "inference-1".to_string(),
|
||||
response_id: Some("resp-1".to_string()),
|
||||
upstream_request_id: Some("req-1".to_string()),
|
||||
response_payload: inference_response.clone(),
|
||||
})?;
|
||||
writer.append(RawTraceEventPayload::CodexTurnEnded {
|
||||
|
||||
@@ -58,7 +58,10 @@ fn is_git_global_option_with_inline_value(arg: &str) -> bool {
|
||||
pub(crate) fn git_global_option_requires_prompt(arg: &str) -> bool {
|
||||
matches!(
|
||||
arg,
|
||||
"-c" | "--config-env"
|
||||
// `-C` can redirect Git into a repo whose config runs helpers such as
|
||||
// `core.fsmonitor` during read-only commands like `status`.
|
||||
"-C" | "-c"
|
||||
| "--config-env"
|
||||
| "--exec-path"
|
||||
| "--git-dir"
|
||||
| "--namespace"
|
||||
@@ -66,7 +69,7 @@ pub(crate) fn git_global_option_requires_prompt(arg: &str) -> bool {
|
||||
| "--work-tree"
|
||||
) || matches!(
|
||||
arg,
|
||||
s if (s.starts_with("-c") && s.len() > 2)
|
||||
s if ((s.starts_with("-C") || s.starts_with("-c")) && s.len() > 2)
|
||||
|| s.starts_with("--config-env=")
|
||||
|| s.starts_with("--exec-path=")
|
||||
|| s.starts_with("--git-dir=")
|
||||
@@ -181,4 +184,10 @@ mod tests {
|
||||
fn rm_f_is_dangerous() {
|
||||
assert!(command_might_be_dangerous(&vec_str(&["rm", "-f", "/"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_dash_c_requires_prompt() {
|
||||
assert!(git_global_option_requires_prompt("-C"));
|
||||
assert!(git_global_option_requires_prompt("-C/path/to/repo"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,20 +331,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn git_branch_global_options_respect_safety_rules() {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
assert_eq!(
|
||||
is_known_safe_command(&vec_str(&["git", "-C", ".", "branch", "--show-current"])),
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
is_known_safe_command(&vec_str(&["git", "-C", ".", "branch", "-d", "feature"])),
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
is_known_safe_command(&vec_str(&["bash", "-lc", "git -C . branch -d feature",])),
|
||||
false
|
||||
);
|
||||
assert!(is_known_safe_command(&vec_str(&[
|
||||
"git",
|
||||
"branch",
|
||||
"--show-current",
|
||||
])));
|
||||
assert!(!is_known_safe_command(&vec_str(&[
|
||||
"git", "branch", "-d", "feature",
|
||||
])));
|
||||
assert!(!is_known_safe_command(&vec_str(&[
|
||||
"bash",
|
||||
"-lc",
|
||||
"git branch -d feature",
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -381,6 +380,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn git_global_override_flags_are_not_safe() {
|
||||
assert!(!is_known_safe_command(&vec_str(&[
|
||||
"git", "-C", ".", "status",
|
||||
])));
|
||||
assert!(!is_known_safe_command(&vec_str(&["git", "-C.", "status",])));
|
||||
assert!(!is_known_safe_command(&vec_str(&[
|
||||
"git",
|
||||
"-c",
|
||||
@@ -415,6 +418,11 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
assert!(!is_known_safe_command(&vec_str(&[
|
||||
"bash",
|
||||
"-lc",
|
||||
"git -C .project-deps/test-fixtures status",
|
||||
])));
|
||||
assert!(!is_known_safe_command(&vec_str(&[
|
||||
"bash",
|
||||
"-lc",
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
//! the main event loop remains single-threaded.
|
||||
|
||||
use super::*;
|
||||
use codex_app_server_protocol::MarketplaceAddParams;
|
||||
use codex_app_server_protocol::MarketplaceAddResponse;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
impl App {
|
||||
pub(super) fn fetch_mcp_inventory(
|
||||
@@ -105,6 +108,28 @@ impl App {
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn fetch_marketplace_add(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
cwd: PathBuf,
|
||||
source: String,
|
||||
) {
|
||||
let request_handle = app_server.request_handle();
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let cwd_for_event = cwd.clone();
|
||||
let source_for_event = source.clone();
|
||||
let result = fetch_marketplace_add(request_handle, cwd, source)
|
||||
.await
|
||||
.map_err(|err| format!("Failed to add marketplace: {err}"));
|
||||
app_event_tx.send(AppEvent::MarketplaceAddLoaded {
|
||||
cwd: cwd_for_event,
|
||||
source: source_for_event,
|
||||
result,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn fetch_plugin_install(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
@@ -509,6 +534,54 @@ pub(super) async fn fetch_plugin_detail(
|
||||
.wrap_err("plugin/read failed in TUI")
|
||||
}
|
||||
|
||||
pub(super) async fn fetch_marketplace_add(
|
||||
request_handle: AppServerRequestHandle,
|
||||
cwd: PathBuf,
|
||||
source: String,
|
||||
) -> Result<MarketplaceAddResponse> {
|
||||
let cwd = AbsolutePathBuf::try_from(cwd).wrap_err("marketplace/add cwd must be absolute")?;
|
||||
let source = marketplace_add_source_for_request(cwd.as_path(), source);
|
||||
let request_id = RequestId::String(format!("marketplace-add-{}", Uuid::new_v4()));
|
||||
request_handle
|
||||
.request_typed(ClientRequest::MarketplaceAdd {
|
||||
request_id,
|
||||
params: MarketplaceAddParams {
|
||||
source,
|
||||
ref_name: None,
|
||||
sparse_paths: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.wrap_err("marketplace/add failed in TUI")
|
||||
}
|
||||
|
||||
fn marketplace_add_source_for_request(cwd: &std::path::Path, source: String) -> String {
|
||||
let (base_source, suffix) = if let Some((base, ref_name)) = source.rsplit_once('#') {
|
||||
(base, Some(format!("#{ref_name}")))
|
||||
} else if let Some((base, ref_name)) = source.rsplit_once('@') {
|
||||
(base, Some(format!("@{ref_name}")))
|
||||
} else {
|
||||
(source.as_str(), None)
|
||||
};
|
||||
|
||||
if matches!(base_source, "." | "..")
|
||||
|| base_source.starts_with("./")
|
||||
|| base_source.starts_with("../")
|
||||
|| base_source.starts_with(".\\")
|
||||
|| base_source.starts_with("..\\")
|
||||
{
|
||||
let mut resolved = AbsolutePathBuf::resolve_path_against_base(base_source, cwd)
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
if let Some(suffix) = suffix {
|
||||
resolved.push_str(&suffix);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
source
|
||||
}
|
||||
|
||||
pub(super) async fn fetch_plugin_install(
|
||||
request_handle: AppServerRequestHandle,
|
||||
marketplace_path: AbsolutePathBuf,
|
||||
@@ -650,6 +723,31 @@ mod tests {
|
||||
AbsolutePathBuf::try_from(PathBuf::from(path)).expect("absolute test path")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marketplace_add_source_for_request_resolves_relative_local_paths() {
|
||||
let cwd = if cfg!(windows) {
|
||||
PathBuf::from(r"C:\workspace\project")
|
||||
} else {
|
||||
PathBuf::from("/workspace/project")
|
||||
};
|
||||
|
||||
let resolved = marketplace_add_source_for_request(&cwd, "./marketplace".to_string());
|
||||
assert!(std::path::Path::new(&resolved).is_absolute());
|
||||
assert_eq!(resolved, cwd.join("marketplace").display().to_string());
|
||||
assert_eq!(
|
||||
marketplace_add_source_for_request(&cwd, "./marketplace#main".to_string()),
|
||||
format!("{}#main", cwd.join("marketplace").display())
|
||||
);
|
||||
assert_eq!(
|
||||
marketplace_add_source_for_request(&cwd, "owner/repo".to_string()),
|
||||
"owner/repo"
|
||||
);
|
||||
assert_eq!(
|
||||
marketplace_add_source_for_request(&cwd, "~/marketplace".to_string()),
|
||||
"~/marketplace"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_cli_only_plugin_marketplaces_removes_openai_bundled() {
|
||||
let mut response = PluginListResponse {
|
||||
|
||||
@@ -648,6 +648,7 @@ mod tests {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: next_cwd.clone().abs(),
|
||||
reasoning_effort: None,
|
||||
history_log_id: 0,
|
||||
|
||||
@@ -385,6 +385,12 @@ impl App {
|
||||
AppEvent::FetchPluginsList { cwd } => {
|
||||
self.fetch_plugins_list(app_server, cwd);
|
||||
}
|
||||
AppEvent::OpenMarketplaceAddPrompt => {
|
||||
self.chat_widget.open_marketplace_add_prompt();
|
||||
}
|
||||
AppEvent::OpenMarketplaceAddLoading { source } => {
|
||||
self.chat_widget.open_marketplace_add_loading_popup(&source);
|
||||
}
|
||||
AppEvent::OpenPluginDetailLoading {
|
||||
plugin_display_name,
|
||||
} => {
|
||||
@@ -406,6 +412,21 @@ impl App {
|
||||
AppEvent::PluginsLoaded { cwd, result } => {
|
||||
self.chat_widget.on_plugins_loaded(cwd, result);
|
||||
}
|
||||
AppEvent::FetchMarketplaceAdd { cwd, source } => {
|
||||
self.fetch_marketplace_add(app_server, cwd, source);
|
||||
}
|
||||
AppEvent::MarketplaceAddLoaded {
|
||||
cwd,
|
||||
source,
|
||||
result,
|
||||
} => {
|
||||
let add_succeeded = result.is_ok();
|
||||
self.chat_widget
|
||||
.on_marketplace_add_loaded(cwd.clone(), source, result);
|
||||
if add_succeeded && self.chat_widget.config_ref().cwd.as_path() == cwd.as_path() {
|
||||
self.fetch_plugins_list(app_server, cwd);
|
||||
}
|
||||
}
|
||||
AppEvent::FetchPluginDetail { cwd, params } => {
|
||||
self.fetch_plugin_detail(app_server, cwd, params);
|
||||
}
|
||||
|
||||
@@ -3570,6 +3570,7 @@ async fn render_clear_ui_header_after_long_transcript_for_snapshot() -> String {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/tmp/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::High),
|
||||
history_log_id: 0,
|
||||
@@ -3809,6 +3810,7 @@ fn test_thread_session(thread_id: ThreadId, cwd: PathBuf) -> ThreadSessionState
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: cwd.abs(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
@@ -4321,6 +4323,7 @@ async fn backtrack_selection_with_duplicate_history_targets_unique_turn() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: None,
|
||||
history_log_id: 0,
|
||||
@@ -4384,6 +4387,7 @@ async fn backtrack_selection_with_duplicate_history_targets_unique_turn() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: None,
|
||||
history_log_id: 0,
|
||||
@@ -4477,6 +4481,7 @@ async fn backtrack_resubmit_preserves_data_image_urls_in_user_turn() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: None,
|
||||
history_log_id: 0,
|
||||
@@ -4863,6 +4868,7 @@ async fn new_session_requests_shutdown_for_previous_conversation() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: None,
|
||||
history_log_id: 0,
|
||||
@@ -4975,6 +4981,7 @@ async fn clear_only_ui_reset_preserves_chat_session_state() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/tmp/project").abs(),
|
||||
reasoning_effort: None,
|
||||
history_log_id: 0,
|
||||
|
||||
@@ -350,6 +350,7 @@ mod tests {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: cwd.abs(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::app_server_session::ThreadSessionState;
|
||||
use crate::read_session_model;
|
||||
use codex_app_server_protocol::Thread;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
|
||||
impl App {
|
||||
@@ -18,10 +19,16 @@ impl App {
|
||||
.config_ref()
|
||||
.permissions
|
||||
.permission_profile();
|
||||
let active_permission_profile = self
|
||||
.chat_widget
|
||||
.config_ref()
|
||||
.permissions
|
||||
.active_permission_profile();
|
||||
let update_session = |session: &mut ThreadSessionState| {
|
||||
session.approval_policy = approval_policy;
|
||||
session.approvals_reviewer = approvals_reviewer;
|
||||
session.permission_profile = permission_profile.clone();
|
||||
session.active_permission_profile = active_permission_profile.clone();
|
||||
};
|
||||
|
||||
if self.primary_thread_id == Some(active_thread_id)
|
||||
@@ -43,7 +50,8 @@ impl App {
|
||||
thread_id: ThreadId,
|
||||
thread: &Thread,
|
||||
) -> ThreadSessionState {
|
||||
let permission_profile = self.active_permission_profile();
|
||||
let permission_profile = self.current_permission_profile();
|
||||
let active_permission_profile = self.current_active_permission_profile();
|
||||
let mut session = self
|
||||
.primary_session_configured
|
||||
.clone()
|
||||
@@ -58,6 +66,7 @@ impl App {
|
||||
approval_policy: self.config.permissions.approval_policy.value(),
|
||||
approvals_reviewer: self.config.approvals_reviewer,
|
||||
permission_profile: permission_profile.clone(),
|
||||
active_permission_profile: active_permission_profile.clone(),
|
||||
cwd: thread.cwd.clone(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: self.chat_widget.current_reasoning_effort(),
|
||||
@@ -71,6 +80,7 @@ impl App {
|
||||
session.model_provider_id = thread.model_provider.clone();
|
||||
session.cwd = thread.cwd.clone();
|
||||
session.permission_profile = permission_profile;
|
||||
session.active_permission_profile = active_permission_profile;
|
||||
session.instruction_source_paths = Vec::new();
|
||||
session.rollout_path = thread.path.clone();
|
||||
if let Some(model) =
|
||||
@@ -85,12 +95,19 @@ impl App {
|
||||
session
|
||||
}
|
||||
|
||||
fn active_permission_profile(&self) -> PermissionProfile {
|
||||
fn current_permission_profile(&self) -> PermissionProfile {
|
||||
self.chat_widget
|
||||
.config_ref()
|
||||
.permissions
|
||||
.permission_profile()
|
||||
}
|
||||
|
||||
fn current_active_permission_profile(&self) -> Option<ActivePermissionProfile> {
|
||||
self.chat_widget
|
||||
.config_ref()
|
||||
.permissions
|
||||
.active_permission_profile()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -125,6 +142,7 @@ mod tests {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: cwd.abs(),
|
||||
instruction_source_paths: Vec::new(),
|
||||
reasoning_effort: None,
|
||||
|
||||
@@ -13,6 +13,7 @@ use std::path::PathBuf;
|
||||
use codex_app_server_protocol::AddCreditsNudgeCreditType;
|
||||
use codex_app_server_protocol::AddCreditsNudgeEmailStatus;
|
||||
use codex_app_server_protocol::AppInfo;
|
||||
use codex_app_server_protocol::MarketplaceAddResponse;
|
||||
use codex_app_server_protocol::McpServerStatus;
|
||||
use codex_app_server_protocol::McpServerStatusDetail;
|
||||
use codex_app_server_protocol::PluginInstallResponse;
|
||||
@@ -287,6 +288,27 @@ pub(crate) enum AppEvent {
|
||||
result: Result<PluginListResponse, String>,
|
||||
},
|
||||
|
||||
/// Open the prompt for adding a marketplace source.
|
||||
OpenMarketplaceAddPrompt,
|
||||
|
||||
/// Replace the plugins popup with a marketplace-add loading state.
|
||||
OpenMarketplaceAddLoading {
|
||||
source: String,
|
||||
},
|
||||
|
||||
/// Add a marketplace from the provided source.
|
||||
FetchMarketplaceAdd {
|
||||
cwd: PathBuf,
|
||||
source: String,
|
||||
},
|
||||
|
||||
/// Result of adding a marketplace.
|
||||
MarketplaceAddLoaded {
|
||||
cwd: PathBuf,
|
||||
source: String,
|
||||
result: Result<MarketplaceAddResponse, String>,
|
||||
},
|
||||
|
||||
/// Replace the plugins popup with a plugin-detail loading state.
|
||||
OpenPluginDetailLoading {
|
||||
plugin_display_name: String,
|
||||
|
||||
@@ -93,6 +93,7 @@ use codex_app_server_protocol::TurnSteerParams;
|
||||
use codex_app_server_protocol::TurnSteerResponse;
|
||||
use codex_otel::TelemetryAuthMode;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::openai_models::ModelAvailabilityNux;
|
||||
@@ -160,6 +161,9 @@ pub(crate) struct ThreadSessionState {
|
||||
/// responses are converted to a profile at ingestion time using the
|
||||
/// response cwd so cached sessions do not reinterpret cwd-bound grants.
|
||||
pub(crate) permission_profile: PermissionProfile,
|
||||
/// Named profile that produced `permission_profile`, when the server knows
|
||||
/// the permissions came from `default_permissions`.
|
||||
pub(crate) active_permission_profile: Option<ActivePermissionProfile>,
|
||||
pub(crate) cwd: AbsolutePathBuf,
|
||||
pub(crate) instruction_source_paths: Vec<AbsolutePathBuf>,
|
||||
pub(crate) reasoning_effort: Option<codex_protocol::openai_models::ReasoningEffort>,
|
||||
@@ -1311,6 +1315,7 @@ async fn thread_session_state_from_thread_start_response(
|
||||
response.cwd.as_path(),
|
||||
)
|
||||
}),
|
||||
response.active_permission_profile.clone().map(Into::into),
|
||||
response.cwd.clone(),
|
||||
response.instruction_sources.clone(),
|
||||
response.reasoning_effort,
|
||||
@@ -1343,6 +1348,7 @@ async fn thread_session_state_from_thread_resume_response(
|
||||
response.cwd.as_path(),
|
||||
)
|
||||
}),
|
||||
response.active_permission_profile.clone().map(Into::into),
|
||||
response.cwd.clone(),
|
||||
response.instruction_sources.clone(),
|
||||
response.reasoning_effort,
|
||||
@@ -1375,6 +1381,7 @@ async fn thread_session_state_from_thread_fork_response(
|
||||
response.cwd.as_path(),
|
||||
)
|
||||
}),
|
||||
response.active_permission_profile.clone().map(Into::into),
|
||||
response.cwd.clone(),
|
||||
response.instruction_sources.clone(),
|
||||
response.reasoning_effort,
|
||||
@@ -1417,6 +1424,7 @@ async fn thread_session_state_from_thread_response(
|
||||
approval_policy: AskForApproval,
|
||||
approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer,
|
||||
permission_profile: PermissionProfile,
|
||||
active_permission_profile: Option<ActivePermissionProfile>,
|
||||
cwd: AbsolutePathBuf,
|
||||
instruction_source_paths: Vec<AbsolutePathBuf>,
|
||||
reasoning_effort: Option<codex_protocol::openai_models::ReasoningEffort>,
|
||||
@@ -1442,6 +1450,7 @@ async fn thread_session_state_from_thread_response(
|
||||
approval_policy,
|
||||
approvals_reviewer,
|
||||
permission_profile,
|
||||
active_permission_profile,
|
||||
cwd,
|
||||
instruction_source_paths,
|
||||
reasoning_effort,
|
||||
@@ -1792,6 +1801,7 @@ mod tests {
|
||||
.expect("read-only profile must be legacy-compatible")
|
||||
.into(),
|
||||
permission_profile: Some(read_only_profile.into()),
|
||||
active_permission_profile: None,
|
||||
reasoning_effort: None,
|
||||
};
|
||||
|
||||
@@ -1839,6 +1849,7 @@ mod tests {
|
||||
AskForApproval::Never,
|
||||
codex_protocol::config_types::ApprovalsReviewer::User,
|
||||
PermissionProfile::read_only(),
|
||||
None,
|
||||
test_path_buf("/tmp/project").abs(),
|
||||
Vec::new(),
|
||||
/*reasoning_effort*/ None,
|
||||
@@ -1869,6 +1880,7 @@ mod tests {
|
||||
AskForApproval::Never,
|
||||
codex_protocol::config_types::ApprovalsReviewer::User,
|
||||
PermissionProfile::read_only(),
|
||||
None,
|
||||
test_path_buf("/tmp/project").abs(),
|
||||
Vec::new(),
|
||||
/*reasoning_effort*/ None,
|
||||
|
||||
@@ -910,6 +910,7 @@ pub(crate) struct ChatWidget {
|
||||
plugin_install_apps_needing_auth: Vec<AppSummary>,
|
||||
plugin_install_auth_flow: Option<PluginInstallAuthFlowState>,
|
||||
plugins_active_tab_id: Option<String>,
|
||||
newly_installed_marketplace_tab_id: Option<String>,
|
||||
// Queue of interruptive UI events deferred during an active write cycle
|
||||
interrupts: InterruptManager,
|
||||
// Accumulates the current reasoning block text to extract a header
|
||||
@@ -1650,6 +1651,7 @@ fn thread_session_state_to_legacy_event(
|
||||
approval_policy: session.approval_policy,
|
||||
approvals_reviewer: session.approvals_reviewer,
|
||||
permission_profile: session.permission_profile,
|
||||
active_permission_profile: session.active_permission_profile,
|
||||
cwd: session.cwd,
|
||||
reasoning_effort: session.reasoning_effort,
|
||||
history_log_id: session.history_log_id,
|
||||
@@ -2382,11 +2384,16 @@ impl ChatWidget {
|
||||
let permission_sync = self
|
||||
.config
|
||||
.permissions
|
||||
.set_permission_profile(event.permission_profile.clone());
|
||||
.set_permission_profile_with_active_profile(
|
||||
event.permission_profile.clone(),
|
||||
event.active_permission_profile.clone(),
|
||||
);
|
||||
if let Err(err) = permission_sync {
|
||||
tracing::warn!(%err, "failed to sync permissions from SessionConfigured");
|
||||
self.config.permissions.permission_profile =
|
||||
Constrained::allow_only(event.permission_profile.clone());
|
||||
self.config.permissions.active_permission_profile =
|
||||
event.active_permission_profile.clone();
|
||||
}
|
||||
self.config.approvals_reviewer = event.approvals_reviewer;
|
||||
self.status_line_project_root_name_cache = None;
|
||||
@@ -5599,6 +5606,7 @@ impl ChatWidget {
|
||||
plugin_install_apps_needing_auth: Vec::new(),
|
||||
plugin_install_auth_flow: None,
|
||||
plugins_active_tab_id: None,
|
||||
newly_installed_marketplace_tab_id: None,
|
||||
interrupts: InterruptManager::new(),
|
||||
reasoning_buffer: String::new(),
|
||||
full_reasoning_buffer: String::new(),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
@@ -11,12 +12,14 @@ use crate::bottom_pane::SelectionRowDisplay;
|
||||
use crate::bottom_pane::SelectionTab;
|
||||
use crate::bottom_pane::SelectionToggle;
|
||||
use crate::bottom_pane::SelectionViewParams;
|
||||
use crate::bottom_pane::custom_prompt_view::CustomPromptView;
|
||||
use crate::history_cell;
|
||||
use crate::onboarding::mark_url_hyperlink;
|
||||
use crate::render::renderable::ColumnRenderable;
|
||||
use crate::render::renderable::Renderable;
|
||||
use crate::shimmer::shimmer_spans;
|
||||
use crate::tui::FrameRequester;
|
||||
use codex_app_server_protocol::MarketplaceAddResponse;
|
||||
use codex_app_server_protocol::PluginDetail;
|
||||
use codex_app_server_protocol::PluginInstallPolicy;
|
||||
use codex_app_server_protocol::PluginInstallResponse;
|
||||
@@ -41,7 +44,9 @@ use unicode_width::UnicodeWidthStr;
|
||||
const PLUGINS_SELECTION_VIEW_ID: &str = "plugins-selection";
|
||||
const ALL_PLUGINS_TAB_ID: &str = "all-plugins";
|
||||
const INSTALLED_PLUGINS_TAB_ID: &str = "installed-plugins";
|
||||
const MARKETPLACE_TAB_ID_PREFIX: &str = "marketplace:";
|
||||
const OPENAI_CURATED_TAB_ID: &str = "marketplace:openai-curated";
|
||||
const ADD_MARKETPLACE_TAB_ID: &str = "add-marketplace";
|
||||
const PLUGIN_ROW_PREFIX_WIDTH: usize = 6;
|
||||
const LOADING_ANIMATION_DELAY: Duration = Duration::from_secs(1);
|
||||
const LOADING_ANIMATION_INTERVAL: Duration = Duration::from_millis(100);
|
||||
@@ -183,10 +188,25 @@ impl ChatWidget {
|
||||
match result {
|
||||
Ok(response) => {
|
||||
self.plugins_fetch_state.cache_cwd = Some(cwd);
|
||||
let active_tab_id = self
|
||||
.plugins_active_tab_id
|
||||
.as_deref()
|
||||
.and_then(|tab_id| {
|
||||
marketplace_tab_id_matching_saved_id(tab_id, &response.marketplaces)
|
||||
})
|
||||
.or_else(|| self.plugins_active_tab_id.clone());
|
||||
self.newly_installed_marketplace_tab_id = self
|
||||
.newly_installed_marketplace_tab_id
|
||||
.as_deref()
|
||||
.and_then(|tab_id| {
|
||||
marketplace_tab_id_matching_saved_id(tab_id, &response.marketplaces)
|
||||
});
|
||||
self.plugins_active_tab_id = active_tab_id;
|
||||
self.plugins_cache = PluginsCacheState::Ready(response.clone());
|
||||
if !auth_flow_active {
|
||||
self.refresh_plugins_popup_if_open(&response);
|
||||
}
|
||||
self.newly_installed_marketplace_tab_id = None;
|
||||
}
|
||||
Err(err) => {
|
||||
if !auth_flow_active {
|
||||
@@ -243,6 +263,44 @@ impl ChatWidget {
|
||||
));
|
||||
}
|
||||
|
||||
pub(crate) fn open_marketplace_add_prompt(&mut self) {
|
||||
self.plugins_active_tab_id = Some(ADD_MARKETPLACE_TAB_ID.to_string());
|
||||
let tx = self.app_event_tx.clone();
|
||||
let cwd = self.config.cwd.to_path_buf();
|
||||
let view = CustomPromptView::new(
|
||||
"Add marketplace".to_string(),
|
||||
"owner/repo, git URL, or local marketplace path".to_string(),
|
||||
String::new(),
|
||||
Some("Examples: owner/repo, git URL, ./marketplace".to_string()),
|
||||
Box::new(move |source: String| {
|
||||
let source = source.trim().to_string();
|
||||
if source.is_empty() {
|
||||
return;
|
||||
}
|
||||
tx.send(AppEvent::OpenMarketplaceAddLoading {
|
||||
source: source.clone(),
|
||||
});
|
||||
tx.send(AppEvent::FetchMarketplaceAdd {
|
||||
cwd: cwd.clone(),
|
||||
source,
|
||||
});
|
||||
}),
|
||||
);
|
||||
self.bottom_pane.show_view(Box::new(view));
|
||||
}
|
||||
|
||||
pub(crate) fn open_marketplace_add_loading_popup(&mut self, _source: &str) {
|
||||
self.plugins_active_tab_id = Some(ADD_MARKETPLACE_TAB_ID.to_string());
|
||||
let params = self.marketplace_add_loading_popup_params();
|
||||
if !self
|
||||
.bottom_pane
|
||||
.replace_selection_view_if_active(PLUGINS_SELECTION_VIEW_ID, params)
|
||||
{
|
||||
self.bottom_pane
|
||||
.show_selection_view(self.marketplace_add_loading_popup_params());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn open_plugin_detail_loading_popup(&mut self, plugin_display_name: &str) {
|
||||
self.plugins_active_tab_id = self
|
||||
.bottom_pane
|
||||
@@ -361,6 +419,52 @@ impl ChatWidget {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn on_marketplace_add_loaded(
|
||||
&mut self,
|
||||
cwd: PathBuf,
|
||||
_source: String,
|
||||
result: Result<MarketplaceAddResponse, String>,
|
||||
) {
|
||||
if self.config.cwd.as_path() != cwd.as_path() {
|
||||
return;
|
||||
}
|
||||
|
||||
match result {
|
||||
Ok(response) => {
|
||||
let marketplace_tab_id = marketplace_tab_id_from_path(&response.installed_root);
|
||||
self.plugins_active_tab_id = Some(marketplace_tab_id.clone());
|
||||
self.newly_installed_marketplace_tab_id =
|
||||
(!response.already_added).then_some(marketplace_tab_id);
|
||||
let message = if response.already_added {
|
||||
format!(
|
||||
"Marketplace {} is already added.",
|
||||
response.marketplace_name
|
||||
)
|
||||
} else {
|
||||
format!("Added marketplace {}.", response.marketplace_name)
|
||||
};
|
||||
self.add_info_message(
|
||||
message,
|
||||
Some(format!(
|
||||
"Marketplace root: {}",
|
||||
response.installed_root.as_path().display()
|
||||
)),
|
||||
);
|
||||
}
|
||||
Err(_) => {
|
||||
self.plugins_active_tab_id = Some(ADD_MARKETPLACE_TAB_ID.to_string());
|
||||
let params = self.marketplace_add_error_popup_params();
|
||||
if !self
|
||||
.bottom_pane
|
||||
.replace_selection_view_if_active(PLUGINS_SELECTION_VIEW_ID, params)
|
||||
{
|
||||
self.bottom_pane
|
||||
.show_selection_view(self.marketplace_add_error_popup_params());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn on_plugin_enabled_set(
|
||||
&mut self,
|
||||
cwd: PathBuf,
|
||||
@@ -655,6 +759,27 @@ impl ChatWidget {
|
||||
}
|
||||
}
|
||||
|
||||
fn marketplace_add_loading_popup_params(&self) -> SelectionViewParams {
|
||||
SelectionViewParams {
|
||||
view_id: Some(PLUGINS_SELECTION_VIEW_ID),
|
||||
header: Box::new(DelayedLoadingHeader::new(
|
||||
self.frame_requester.clone(),
|
||||
self.config.animations,
|
||||
"Adding marketplace...".to_string(),
|
||||
/*note*/ None,
|
||||
)),
|
||||
items: vec![SelectionItem {
|
||||
name: "Adding marketplace...".to_string(),
|
||||
description: Some(
|
||||
"This updates when marketplace installation completes.".to_string(),
|
||||
),
|
||||
is_disabled: true,
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_detail_loading_popup_params(&self, plugin_display_name: &str) -> SelectionViewParams {
|
||||
SelectionViewParams {
|
||||
view_id: Some(PLUGINS_SELECTION_VIEW_ID),
|
||||
@@ -738,6 +863,56 @@ impl ChatWidget {
|
||||
}
|
||||
}
|
||||
|
||||
fn marketplace_add_error_popup_params(&self) -> SelectionViewParams {
|
||||
let mut header = ColumnRenderable::new();
|
||||
header.push(Line::from("Plugins".bold()));
|
||||
header.push(Line::from("Failed to add marketplace.".dim()));
|
||||
|
||||
let mut items = vec![
|
||||
SelectionItem {
|
||||
name: "Marketplace add failed".to_string(),
|
||||
description: Some(
|
||||
"Failed to add marketplace from the provided source.".to_string(),
|
||||
),
|
||||
is_disabled: true,
|
||||
..Default::default()
|
||||
},
|
||||
SelectionItem {
|
||||
name: "Try again".to_string(),
|
||||
description: Some("Enter a marketplace source.".to_string()),
|
||||
selected_description: Some("Enter a marketplace source.".to_string()),
|
||||
actions: vec![Box::new(|tx| {
|
||||
tx.send(AppEvent::OpenMarketplaceAddPrompt);
|
||||
})],
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
|
||||
if let PluginsCacheState::Ready(plugins_response) = self.plugins_cache_for_current_cwd() {
|
||||
let cwd = self.config.cwd.to_path_buf();
|
||||
items.push(SelectionItem {
|
||||
name: "Back to plugins".to_string(),
|
||||
description: Some("Return to the plugin list.".to_string()),
|
||||
selected_description: Some("Return to the plugin list.".to_string()),
|
||||
actions: vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::PluginsLoaded {
|
||||
cwd: cwd.clone(),
|
||||
result: Ok(plugins_response.clone()),
|
||||
});
|
||||
})],
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
|
||||
SelectionViewParams {
|
||||
view_id: Some(PLUGINS_SELECTION_VIEW_ID),
|
||||
header: Box::new(header),
|
||||
footer_hint: Some(plugin_detail_hint_line()),
|
||||
items,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_detail_error_popup_params(
|
||||
&self,
|
||||
err: &str,
|
||||
@@ -802,6 +977,7 @@ impl ChatWidget {
|
||||
.map(|(_, _, display_name)| {
|
||||
PLUGIN_ROW_PREFIX_WIDTH + UnicodeWidthStr::width(display_name.as_str())
|
||||
})
|
||||
.chain([UnicodeWidthStr::width("Add marketplace")])
|
||||
.max();
|
||||
let installed_entries = all_entries
|
||||
.iter()
|
||||
@@ -893,15 +1069,25 @@ impl ChatWidget {
|
||||
.iter()
|
||||
.filter(|(_, plugin, _)| plugin.installed)
|
||||
.count();
|
||||
tabs.push(SelectionTab {
|
||||
id: marketplace_tab_id(marketplace),
|
||||
label: label.clone(),
|
||||
header: plugins_header(
|
||||
let tab_id = marketplace_tab_id(marketplace);
|
||||
let header = if self.newly_installed_marketplace_tab_id.as_deref() == Some(&tab_id) {
|
||||
plugins_header(
|
||||
format!("{label} installed successfully."),
|
||||
"Select the plugins you want to use and press Enter to install or view details."
|
||||
.to_string(),
|
||||
)
|
||||
} else {
|
||||
plugins_header(
|
||||
format!("{label}."),
|
||||
format!(
|
||||
"Installed {marketplace_installed} of {marketplace_total} {label} plugins."
|
||||
),
|
||||
),
|
||||
)
|
||||
};
|
||||
tabs.push(SelectionTab {
|
||||
id: tab_id,
|
||||
label: label.clone(),
|
||||
header,
|
||||
items: self.plugin_selection_items(
|
||||
entries,
|
||||
/*include_marketplace_names*/ false,
|
||||
@@ -911,6 +1097,8 @@ impl ChatWidget {
|
||||
});
|
||||
}
|
||||
|
||||
tabs.push(self.marketplace_add_tab());
|
||||
|
||||
SelectionViewParams {
|
||||
view_id: Some(PLUGINS_SELECTION_VIEW_ID),
|
||||
header: Box::new(()),
|
||||
@@ -927,6 +1115,30 @@ impl ChatWidget {
|
||||
}
|
||||
}
|
||||
|
||||
fn marketplace_add_tab(&self) -> SelectionTab {
|
||||
SelectionTab {
|
||||
id: ADD_MARKETPLACE_TAB_ID.to_string(),
|
||||
label: "Add Marketplace".to_string(),
|
||||
header: plugins_header(
|
||||
"Add a marketplace from a Git repo or local root.".to_string(),
|
||||
"Enter a source to make its plugins available in this menu.".to_string(),
|
||||
),
|
||||
items: vec![SelectionItem {
|
||||
name: "Add marketplace".to_string(),
|
||||
description: Some(
|
||||
"Enter owner/repo, a Git URL, or a local marketplace path.".to_string(),
|
||||
),
|
||||
selected_description: Some(
|
||||
"Press Enter to enter a marketplace source.".to_string(),
|
||||
),
|
||||
actions: vec![Box::new(|tx| {
|
||||
tx.send(AppEvent::OpenMarketplaceAddPrompt);
|
||||
})],
|
||||
..Default::default()
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn plugin_detail_popup_params(
|
||||
&self,
|
||||
plugins_response: &PluginListResponse,
|
||||
@@ -1107,7 +1319,7 @@ impl ChatWidget {
|
||||
format!("{selected_status_label} Space to {toggle_action}.")
|
||||
}
|
||||
} else if can_view_details {
|
||||
format!("{selected_status_label} Press Enter to view plugin details.")
|
||||
format!("{selected_status_label} Press Enter to install or view plugin details.")
|
||||
} else {
|
||||
format!("{selected_status_label} Remote plugin details are not available yet.")
|
||||
};
|
||||
@@ -1227,11 +1439,40 @@ fn sort_plugin_entries(entries: &mut [(&PluginMarketplaceEntry, &PluginSummary,
|
||||
|
||||
fn marketplace_tab_id(marketplace: &PluginMarketplaceEntry) -> String {
|
||||
match marketplace.path.as_ref() {
|
||||
Some(path) => format!("marketplace:{}", path.display()),
|
||||
Some(path) => marketplace_tab_id_from_path(path.as_path()),
|
||||
None => format!("marketplace:{}", marketplace.name),
|
||||
}
|
||||
}
|
||||
|
||||
fn marketplace_tab_id_from_path(path: &Path) -> String {
|
||||
format!("{MARKETPLACE_TAB_ID_PREFIX}{}", path.display())
|
||||
}
|
||||
|
||||
fn marketplace_tab_id_matching_saved_id(
|
||||
saved_tab_id: &str,
|
||||
marketplaces: &[PluginMarketplaceEntry],
|
||||
) -> Option<String> {
|
||||
if let Some(tab_id) = marketplaces.iter().find_map(|marketplace| {
|
||||
let tab_id = marketplace_tab_id(marketplace);
|
||||
(tab_id == saved_tab_id).then_some(tab_id)
|
||||
}) {
|
||||
return Some(tab_id);
|
||||
}
|
||||
|
||||
let root = saved_tab_id.strip_prefix(MARKETPLACE_TAB_ID_PREFIX)?;
|
||||
if root.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let root = Path::new(root);
|
||||
marketplaces.iter().find_map(|marketplace| {
|
||||
marketplace
|
||||
.path
|
||||
.as_ref()
|
||||
.is_some_and(|path| path.as_path().starts_with(root))
|
||||
.then(|| marketplace_tab_id(marketplace))
|
||||
})
|
||||
}
|
||||
|
||||
fn disambiguate_duplicate_tab_labels(labels: Vec<String>) -> Vec<String> {
|
||||
let mut counts: Vec<(String, usize)> = Vec::new();
|
||||
for label in &labels {
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ expression: popup
|
||||
Browse plugins from available marketplaces.
|
||||
Installed 1 of 4 available plugins.
|
||||
|
||||
[All Plugins] Installed (1) OpenAI Curated Repo Marketplace
|
||||
[All Plugins] Installed (1) OpenAI Curated Repo Marketplace Add Marketplace
|
||||
|
||||
Type to search plugins
|
||||
› [ ] Alpha Sync Disabled Space to enable; Enter view details.
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: tui/src/chatwidget/tests/popups_and_settings.rs
|
||||
assertion_line: 329
|
||||
expression: popup
|
||||
---
|
||||
Plugins
|
||||
Debug Marketplace installed successfully.
|
||||
Select the plugins you want to use and press Enter to install or view details.
|
||||
|
||||
All Plugins Installed (0) OpenAI Curated [Debug Marketplace] Add Marketplace
|
||||
|
||||
Type to search plugins
|
||||
› [-] Debug Plugin Available Press Enter to install or view plugin details.
|
||||
|
||||
space enable/disable · ←/→ select marketplace · enter view details · esc close
|
||||
+4
-3
@@ -1,14 +1,15 @@
|
||||
---
|
||||
source: tui/src/chatwidget/tests.rs
|
||||
source: tui/src/chatwidget/tests/popups_and_settings.rs
|
||||
assertion_line: 767
|
||||
expression: popup
|
||||
---
|
||||
Plugins
|
||||
Browse plugins from available marketplaces.
|
||||
Installed 0 of 3 available plugins.
|
||||
|
||||
[All Plugins] Installed (0) OpenAI Curated
|
||||
[All Plugins] Installed (0) OpenAI Curated Add Marketplace
|
||||
|
||||
sla
|
||||
› [-] Slack Available Press Enter to view plugin details.
|
||||
› [-] Slack Available Press Enter to install or view plugin details.
|
||||
|
||||
space enable/disable · ←/→ select marketplace · enter view details · esc close
|
||||
|
||||
@@ -65,6 +65,7 @@ pub(super) use codex_app_server_protocol::ItemCompletedNotification;
|
||||
pub(super) use codex_app_server_protocol::ItemGuardianApprovalReviewCompletedNotification;
|
||||
pub(super) use codex_app_server_protocol::ItemGuardianApprovalReviewStartedNotification;
|
||||
pub(super) use codex_app_server_protocol::ItemStartedNotification;
|
||||
pub(super) use codex_app_server_protocol::MarketplaceAddResponse;
|
||||
pub(super) use codex_app_server_protocol::MarketplaceInterface;
|
||||
pub(super) use codex_app_server_protocol::McpServerStartupState;
|
||||
pub(super) use codex_app_server_protocol::McpServerStatusDetail;
|
||||
|
||||
@@ -17,6 +17,7 @@ async fn submission_preserves_text_elements_and_local_images() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -121,6 +122,7 @@ async fn submission_includes_configured_permission_profile() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: expected_permission_profile.clone(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -171,6 +173,7 @@ async fn submission_keeps_profile_when_legacy_projection_is_external() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: expected_permission_profile.clone(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -214,6 +217,7 @@ async fn submission_with_remote_and_local_images_keeps_local_placeholder_numberi
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -309,6 +313,7 @@ async fn enter_with_only_remote_images_submits_user_turn() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -374,6 +379,7 @@ async fn shift_enter_with_only_remote_images_does_not_submit_user_turn() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -414,6 +420,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_modal_is_active() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -454,6 +461,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_input_disabled() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -497,6 +505,7 @@ async fn submission_prefers_selected_duplicate_skill_path() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
|
||||
@@ -1059,6 +1059,7 @@ async fn bang_shell_enter_while_task_running_submits_run_user_shell_command() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
|
||||
@@ -244,6 +244,7 @@ pub(super) async fn make_chatwidget_manual(
|
||||
plugin_install_apps_needing_auth: Vec::new(),
|
||||
plugin_install_auth_flow: None,
|
||||
plugins_active_tab_id: None,
|
||||
newly_installed_marketplace_tab_id: None,
|
||||
connectors_prefetch_in_flight: false,
|
||||
connectors_force_refetch_pending: false,
|
||||
plugins_cache: PluginsCacheState::default(),
|
||||
|
||||
@@ -24,6 +24,7 @@ async fn resumed_initial_messages_render_history() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: codex_protocol::models::PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -137,6 +138,7 @@ async fn replayed_user_message_preserves_text_elements_and_local_images() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: codex_protocol::models::PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -198,6 +200,7 @@ async fn replayed_user_message_preserves_remote_image_urls() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: codex_protocol::models::PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -286,6 +289,7 @@ async fn session_configured_syncs_widget_config_permissions_and_cwd() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: expected_permission_profile.clone(),
|
||||
active_permission_profile: None,
|
||||
cwd: expected_cwd.clone(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -344,6 +348,7 @@ async fn session_configured_external_sandbox_keeps_external_runtime_policy() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: expected_permission_profile,
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/external").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -393,6 +398,7 @@ async fn replayed_user_message_with_only_remote_images_renders_history_cell() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: codex_protocol::models::PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -446,6 +452,7 @@ async fn replayed_user_message_with_only_local_images_does_not_render_history_ce
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: codex_protocol::models::PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_path_buf("/home/user/project").abs(),
|
||||
reasoning_effort: Some(ReasoningEffortConfig::default()),
|
||||
history_log_id: 0,
|
||||
@@ -767,6 +774,7 @@ async fn replayed_reasoning_item_hides_raw_reasoning_when_disabled() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: codex_protocol::models::PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_project_path().abs(),
|
||||
reasoning_effort: None,
|
||||
history_log_id: 0,
|
||||
@@ -814,6 +822,7 @@ async fn replayed_reasoning_item_shows_raw_reasoning_when_enabled() {
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: ApprovalsReviewer::User,
|
||||
permission_profile: codex_protocol::models::PermissionProfile::read_only(),
|
||||
active_permission_profile: None,
|
||||
cwd: test_project_path().abs(),
|
||||
reasoning_effort: None,
|
||||
history_log_id: 0,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user