mirror of
https://github.com/openai/codex.git
synced 2026-11-16 22:00:36 +00:00
Merge branch 'main' into abhinav/requirements-shell-rules
This commit is contained in:
Generated
+7
-1
@@ -1946,7 +1946,6 @@ dependencies = [
|
||||
"schemars 0.8.22",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-test",
|
||||
@@ -2761,6 +2760,7 @@ dependencies = [
|
||||
"codex-otel",
|
||||
"codex-plugin",
|
||||
"codex-protocol",
|
||||
"codex-tools",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-path-uri",
|
||||
"codex-utils-plugins",
|
||||
@@ -2891,6 +2891,7 @@ dependencies = [
|
||||
"ctor 0.6.3",
|
||||
"futures",
|
||||
"http 1.4.0",
|
||||
"libc",
|
||||
"pretty_assertions",
|
||||
"prost 0.14.3",
|
||||
"reqwest 0.12.28",
|
||||
@@ -2906,6 +2907,7 @@ dependencies = [
|
||||
"toml 0.9.11+spec-1.1.0",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"windows-sys 0.52.0",
|
||||
"wiremock",
|
||||
]
|
||||
|
||||
@@ -3040,9 +3042,11 @@ dependencies = [
|
||||
name = "codex-file-system"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"codex-protocol",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-path-uri",
|
||||
"futures",
|
||||
"serde",
|
||||
]
|
||||
|
||||
@@ -3788,7 +3792,9 @@ dependencies = [
|
||||
"codex-network-proxy",
|
||||
"codex-protocol",
|
||||
"codex-utils-absolute-path",
|
||||
"codex-utils-home-dir",
|
||||
"codex-utils-path-uri",
|
||||
"codex-windows-sandbox",
|
||||
"dunce",
|
||||
"libc",
|
||||
"pretty_assertions",
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::error::Error as StdError;
|
||||
use std::fmt;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
@@ -34,21 +36,66 @@ const AGENT_TASK_REGISTRATION_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const AGENT_IDENTITY_JWKS_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const AGENT_IDENTITY_JWT_AUDIENCE: &str = "codex-app-server";
|
||||
const AGENT_IDENTITY_JWT_ISSUER: &str = "https://chatgpt.com/codex-backend/agent-identity";
|
||||
const AGENT_REGISTRATION_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const PROD_AGENT_IDENTITY_AUTHAPI_BASE_URL: &str = "https://auth.openai.com/api/accounts";
|
||||
const STAGING_AGENT_IDENTITY_AUTHAPI_BASE_URL: &str = "https://auth.api.openai.org/api/accounts";
|
||||
const AGENT_IDENTITY_KEY_SEED_BYTES: usize = 64;
|
||||
const AGENT_IDENTITY_KEY_DERIVATION_CONTEXT: &[u8] = b"codex-agent-identity-ed25519-v1";
|
||||
|
||||
/// Stored key material for a registered agent identity.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum ChatGptEnvironment {
|
||||
#[default]
|
||||
Production,
|
||||
Staging,
|
||||
}
|
||||
|
||||
impl ChatGptEnvironment {
|
||||
pub fn from_chatgpt_base_url(chatgpt_base_url: &str) -> Result<Self> {
|
||||
match chatgpt_base_url.trim_end_matches('/') {
|
||||
"https://chatgpt.com"
|
||||
| "https://chatgpt.com/backend-api"
|
||||
| "https://chatgpt.com/codex"
|
||||
| "https://chatgpt.com/backend-api/codex"
|
||||
| "https://chat.openai.com"
|
||||
| "https://chat.openai.com/backend-api"
|
||||
| "https://chat.openai.com/codex"
|
||||
| "https://chat.openai.com/backend-api/codex" => Ok(Self::Production),
|
||||
"https://chatgpt-staging.com"
|
||||
| "https://chatgpt-staging.com/backend-api"
|
||||
| "https://chatgpt-staging.com/codex"
|
||||
| "https://chatgpt-staging.com/backend-api/codex" => Ok(Self::Staging),
|
||||
_ => anyhow::bail!(
|
||||
"Agent Identity only supports production and staging ChatGPT environments"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn chatgpt_base_url(self) -> &'static str {
|
||||
match self {
|
||||
Self::Production => "https://chatgpt.com/backend-api",
|
||||
Self::Staging => "https://chatgpt-staging.com/backend-api",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn agent_identity_authapi_base_url(self) -> &'static str {
|
||||
match self {
|
||||
Self::Production => PROD_AGENT_IDENTITY_AUTHAPI_BASE_URL,
|
||||
Self::Staging => STAGING_AGENT_IDENTITY_AUTHAPI_BASE_URL,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrowed durable signing material for a registered agent identity.
|
||||
///
|
||||
/// This intentionally does not include a task id. Task ids are scoped to a
|
||||
/// single Codex run, while the agent runtime id and private key are the
|
||||
/// reusable identity material used to register and sign that run task.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct AgentIdentityKey<'a> {
|
||||
pub agent_runtime_id: &'a str,
|
||||
pub private_key_pkcs8_base64: &'a str,
|
||||
}
|
||||
|
||||
/// Task binding to use when constructing a task-scoped AgentAssertion.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct AgentTaskAuthorizationTarget<'a> {
|
||||
pub agent_runtime_id: &'a str,
|
||||
pub task_id: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct AgentBillOfMaterials {
|
||||
pub agent_version: String,
|
||||
@@ -103,23 +150,92 @@ struct RegisterTaskResponse {
|
||||
encrypted_task_id_camel: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct RegisterAgentRequest {
|
||||
abom: AgentBillOfMaterials,
|
||||
agent_public_key: String,
|
||||
capabilities: Vec<String>,
|
||||
ttl: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RegisterAgentResponse {
|
||||
agent_runtime_id: String,
|
||||
}
|
||||
|
||||
/// HTTP status failure returned by Agent Identity registration endpoints.
|
||||
#[derive(Debug)]
|
||||
pub struct AgentIdentityRegistrationHttpError {
|
||||
operation: &'static str,
|
||||
status: reqwest::StatusCode,
|
||||
body: String,
|
||||
}
|
||||
|
||||
impl AgentIdentityRegistrationHttpError {
|
||||
fn new(operation: &'static str, status: reqwest::StatusCode, body: String) -> Self {
|
||||
Self {
|
||||
operation,
|
||||
status,
|
||||
body,
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP status returned by the registration endpoint.
|
||||
pub fn status(&self) -> reqwest::StatusCode {
|
||||
self.status
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for AgentIdentityRegistrationHttpError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.body.is_empty() {
|
||||
write!(f, "{} failed with status {}", self.operation, self.status)
|
||||
} else {
|
||||
write!(
|
||||
f,
|
||||
"{} failed with status {}: {}",
|
||||
self.operation, self.status, self.body
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StdError for AgentIdentityRegistrationHttpError {}
|
||||
|
||||
/// Returns whether an Agent Identity registration error is safe to retry.
|
||||
pub fn is_retryable_registration_error(error: &anyhow::Error) -> bool {
|
||||
error.chain().any(is_retryable_registration_cause)
|
||||
}
|
||||
|
||||
fn is_retryable_registration_cause(cause: &(dyn StdError + 'static)) -> bool {
|
||||
if let Some(error) = cause.downcast_ref::<AgentIdentityRegistrationHttpError>() {
|
||||
return is_retryable_registration_status(error.status());
|
||||
}
|
||||
|
||||
if let Some(error) = cause.downcast_ref::<reqwest::Error>() {
|
||||
if let Some(status) = error.status() {
|
||||
return is_retryable_registration_status(status);
|
||||
}
|
||||
return error.is_timeout() || error.is_connect() || error.is_request();
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn is_retryable_registration_status(status: reqwest::StatusCode) -> bool {
|
||||
status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error()
|
||||
}
|
||||
|
||||
pub fn authorization_header_for_agent_task(
|
||||
key: AgentIdentityKey<'_>,
|
||||
target: AgentTaskAuthorizationTarget<'_>,
|
||||
task_id: &str,
|
||||
) -> Result<String> {
|
||||
anyhow::ensure!(
|
||||
key.agent_runtime_id == target.agent_runtime_id,
|
||||
"agent task runtime {} does not match stored agent identity {}",
|
||||
target.agent_runtime_id,
|
||||
key.agent_runtime_id
|
||||
);
|
||||
|
||||
let timestamp = Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true);
|
||||
let envelope = AgentAssertionEnvelope {
|
||||
agent_runtime_id: target.agent_runtime_id.to_string(),
|
||||
task_id: target.task_id.to_string(),
|
||||
agent_runtime_id: key.agent_runtime_id.to_string(),
|
||||
task_id: task_id.to_string(),
|
||||
timestamp: timestamp.clone(),
|
||||
signature: sign_agent_assertion_payload(key, target.task_id, ×tamp)?,
|
||||
signature: sign_agent_assertion_payload(key, task_id, ×tamp)?,
|
||||
};
|
||||
let serialized_assertion = serialize_agent_assertion(&envelope)?;
|
||||
Ok(format!("AgentAssertion {serialized_assertion}"))
|
||||
@@ -127,10 +243,10 @@ pub fn authorization_header_for_agent_task(
|
||||
|
||||
pub async fn fetch_agent_identity_jwks(
|
||||
client: &reqwest::Client,
|
||||
chatgpt_base_url: &str,
|
||||
agent_identity_jwt_base_url: &str,
|
||||
) -> Result<JwkSet> {
|
||||
let response = client
|
||||
.get(agent_identity_jwks_url(chatgpt_base_url))
|
||||
.get(agent_identity_jwks_url(agent_identity_jwt_base_url))
|
||||
.timeout(AGENT_IDENTITY_JWKS_TIMEOUT)
|
||||
.send()
|
||||
.await
|
||||
@@ -195,7 +311,7 @@ pub fn sign_task_registration_payload(
|
||||
|
||||
pub async fn register_agent_task(
|
||||
client: &reqwest::Client,
|
||||
chatgpt_base_url: &str,
|
||||
agent_identity_authapi_base_url: &str,
|
||||
key: AgentIdentityKey<'_>,
|
||||
) -> Result<String> {
|
||||
let timestamp = Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true);
|
||||
@@ -203,7 +319,7 @@ pub async fn register_agent_task(
|
||||
signature: sign_task_registration_payload(key, ×tamp)?,
|
||||
timestamp,
|
||||
};
|
||||
let url = agent_task_registration_url(chatgpt_base_url, key.agent_runtime_id);
|
||||
let url = agent_task_registration_url(agent_identity_authapi_base_url, key.agent_runtime_id);
|
||||
|
||||
let response = client
|
||||
.post(url)
|
||||
@@ -220,7 +336,12 @@ pub async fn register_agent_task(
|
||||
} else {
|
||||
body
|
||||
};
|
||||
anyhow::bail!("failed to register agent task with status {status}: {body}");
|
||||
return Err(AgentIdentityRegistrationHttpError::new(
|
||||
"agent task registration",
|
||||
status,
|
||||
body,
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
let response = response
|
||||
@@ -231,6 +352,45 @@ pub async fn register_agent_task(
|
||||
task_id_from_register_task_response(key, response)
|
||||
}
|
||||
|
||||
pub async fn register_agent_identity(
|
||||
client: &reqwest::Client,
|
||||
agent_identity_authapi_base_url: &str,
|
||||
access_token: &str,
|
||||
is_fedramp_account: bool,
|
||||
key_material: &GeneratedAgentKeyMaterial,
|
||||
abom: AgentBillOfMaterials,
|
||||
capabilities: Vec<String>,
|
||||
) -> Result<String> {
|
||||
let url = agent_registration_url(agent_identity_authapi_base_url);
|
||||
let request = RegisterAgentRequest {
|
||||
abom,
|
||||
agent_public_key: key_material.public_key_ssh.clone(),
|
||||
capabilities,
|
||||
ttl: None,
|
||||
};
|
||||
|
||||
let mut request_builder = client
|
||||
.post(&url)
|
||||
.bearer_auth(access_token)
|
||||
.json(&request)
|
||||
.timeout(AGENT_REGISTRATION_TIMEOUT);
|
||||
if is_fedramp_account {
|
||||
request_builder = request_builder.header("X-OpenAI-Fedramp", "true");
|
||||
}
|
||||
|
||||
let response = request_builder
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("failed to send agent identity registration request to {url}"))?
|
||||
.error_for_status()
|
||||
.with_context(|| format!("agent identity registration failed for {url}"))?
|
||||
.json::<RegisterAgentResponse>()
|
||||
.await
|
||||
.with_context(|| format!("failed to parse agent identity response from {url}"))?;
|
||||
|
||||
Ok(response.agent_runtime_id)
|
||||
}
|
||||
|
||||
fn task_id_from_register_task_response(
|
||||
key: AgentIdentityKey<'_>,
|
||||
response: RegisterTaskResponse,
|
||||
@@ -260,10 +420,17 @@ pub fn decrypt_task_id_response(
|
||||
}
|
||||
|
||||
pub fn generate_agent_key_material() -> Result<GeneratedAgentKeyMaterial> {
|
||||
let mut secret_key_bytes = [0u8; 32];
|
||||
let mut seed_material = [0u8; AGENT_IDENTITY_KEY_SEED_BYTES];
|
||||
OsRng
|
||||
.try_fill_bytes(&mut secret_key_bytes)
|
||||
.context("failed to generate agent identity private key bytes")?;
|
||||
.try_fill_bytes(&mut seed_material)
|
||||
.context("failed to generate agent identity private key seed material")?;
|
||||
// Ed25519 stores a 32-byte seed, so derive it from all sampled seed material.
|
||||
let mut digest = Sha512::new();
|
||||
digest.update(AGENT_IDENTITY_KEY_DERIVATION_CONTEXT);
|
||||
digest.update(seed_material);
|
||||
let digest = digest.finalize();
|
||||
let mut secret_key_bytes = [0u8; 32];
|
||||
secret_key_bytes.copy_from_slice(&digest[..32]);
|
||||
let signing_key = SigningKey::from_bytes(&secret_key_bytes);
|
||||
let private_key_pkcs8 = signing_key
|
||||
.to_pkcs8_der()
|
||||
@@ -296,23 +463,22 @@ pub fn curve25519_secret_key_from_private_key_pkcs8_base64(
|
||||
Ok(curve25519_secret_key_from_signing_key(&signing_key))
|
||||
}
|
||||
|
||||
pub fn agent_registration_url(chatgpt_base_url: &str) -> String {
|
||||
let trimmed = chatgpt_base_url.trim_end_matches('/');
|
||||
format!("{trimmed}/v1/agent/register")
|
||||
pub fn agent_registration_url(agent_identity_authapi_base_url: &str) -> String {
|
||||
agent_identity_authapi_url(agent_identity_authapi_base_url, "/v1/agent/register")
|
||||
}
|
||||
|
||||
pub fn agent_task_registration_url(chatgpt_base_url: &str, agent_runtime_id: &str) -> String {
|
||||
let trimmed = chatgpt_base_url.trim_end_matches('/');
|
||||
format!("{trimmed}/v1/agent/{agent_runtime_id}/task/register")
|
||||
pub fn agent_task_registration_url(
|
||||
agent_identity_authapi_base_url: &str,
|
||||
agent_runtime_id: &str,
|
||||
) -> String {
|
||||
agent_identity_authapi_url(
|
||||
agent_identity_authapi_base_url,
|
||||
&format!("/v1/agent/{agent_runtime_id}/task/register"),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn agent_identity_biscuit_url(chatgpt_base_url: &str) -> String {
|
||||
let trimmed = chatgpt_base_url.trim_end_matches('/');
|
||||
format!("{trimmed}/authenticate_app_v2")
|
||||
}
|
||||
|
||||
pub fn agent_identity_jwks_url(chatgpt_base_url: &str) -> String {
|
||||
let trimmed = chatgpt_base_url.trim_end_matches('/');
|
||||
pub fn agent_identity_jwks_url(agent_identity_jwt_base_url: &str) -> String {
|
||||
let trimmed = agent_identity_jwt_base_url.trim_end_matches('/');
|
||||
if trimmed.contains("/backend-api") {
|
||||
format!("{trimmed}/wham/agent-identities/jwks")
|
||||
} else {
|
||||
@@ -320,15 +486,9 @@ pub fn agent_identity_jwks_url(chatgpt_base_url: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn agent_identity_request_id() -> Result<String> {
|
||||
let mut request_id_bytes = [0u8; 16];
|
||||
OsRng
|
||||
.try_fill_bytes(&mut request_id_bytes)
|
||||
.context("failed to generate agent identity request id")?;
|
||||
Ok(format!(
|
||||
"codex-agent-identity-{}",
|
||||
URL_SAFE_NO_PAD.encode(request_id_bytes)
|
||||
))
|
||||
fn agent_identity_authapi_url(agent_identity_authapi_base_url: &str, api_path: &str) -> String {
|
||||
let base_url = agent_identity_authapi_base_url.trim_end_matches('/');
|
||||
format!("{base_url}{api_path}")
|
||||
}
|
||||
|
||||
pub fn build_abom(session_source: SessionSource) -> AgentBillOfMaterials {
|
||||
@@ -412,6 +572,24 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn register_task_request_uses_single_run_task_shape() {
|
||||
let request = RegisterTaskRequest {
|
||||
timestamp: "2026-04-23T00:00:00Z".to_string(),
|
||||
signature: "signature".to_string(),
|
||||
};
|
||||
|
||||
let serialized = serde_json::to_value(request).expect("serialize request");
|
||||
|
||||
assert_eq!(
|
||||
serialized,
|
||||
serde_json::json!({
|
||||
"timestamp": "2026-04-23T00:00:00Z",
|
||||
"signature": "signature",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authorization_header_for_agent_task_serializes_signed_agent_assertion() {
|
||||
let signing_key = SigningKey::from_bytes(&[7u8; 32]);
|
||||
@@ -422,13 +600,9 @@ mod tests {
|
||||
agent_runtime_id: "agent-123",
|
||||
private_key_pkcs8_base64: &BASE64_STANDARD.encode(private_key.as_bytes()),
|
||||
};
|
||||
let target = AgentTaskAuthorizationTarget {
|
||||
agent_runtime_id: "agent-123",
|
||||
task_id: "task-123",
|
||||
};
|
||||
|
||||
let header =
|
||||
authorization_header_for_agent_task(key, target).expect("build agent assertion header");
|
||||
let header = authorization_header_for_agent_task(key, "task-123")
|
||||
.expect("build agent assertion header");
|
||||
let token = header
|
||||
.strip_prefix("AgentAssertion ")
|
||||
.expect("agent assertion scheme");
|
||||
@@ -464,31 +638,6 @@ mod tests {
|
||||
.expect("signature should verify");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authorization_header_for_agent_task_rejects_mismatched_runtime() {
|
||||
let signing_key = SigningKey::from_bytes(&[7u8; 32]);
|
||||
let private_key = signing_key
|
||||
.to_pkcs8_der()
|
||||
.expect("encode test key material");
|
||||
let private_key_pkcs8_base64 = BASE64_STANDARD.encode(private_key.as_bytes());
|
||||
let key = AgentIdentityKey {
|
||||
agent_runtime_id: "agent-123",
|
||||
private_key_pkcs8_base64: &private_key_pkcs8_base64,
|
||||
};
|
||||
let target = AgentTaskAuthorizationTarget {
|
||||
agent_runtime_id: "agent-456",
|
||||
task_id: "task-123",
|
||||
};
|
||||
|
||||
let error = authorization_header_for_agent_task(key, target)
|
||||
.expect_err("runtime mismatch should fail");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"agent task runtime agent-456 does not match stored agent identity agent-123"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_agent_identity_jwt_reads_claims() {
|
||||
let jwt = jwt_with_payload(serde_json::json!({
|
||||
@@ -704,7 +853,98 @@ J1bwkqKZTB5dHolX9A58e/xXnfZ5P8f3Z83+Izap3FwqQulk7b1WO1MQcHuVg2NN
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_identity_jwks_url_uses_backend_api_base_url() {
|
||||
fn chatgpt_environment_maps_known_urls_to_authapi() -> anyhow::Result<()> {
|
||||
assert_eq!(
|
||||
ChatGptEnvironment::from_chatgpt_base_url("https://chatgpt.com/backend-api/codex")?,
|
||||
ChatGptEnvironment::Production
|
||||
);
|
||||
assert_eq!(
|
||||
ChatGptEnvironment::Production.agent_identity_authapi_base_url(),
|
||||
"https://auth.openai.com/api/accounts"
|
||||
);
|
||||
assert_eq!(
|
||||
ChatGptEnvironment::from_chatgpt_base_url("https://chatgpt-staging.com/backend-api")?,
|
||||
ChatGptEnvironment::Staging
|
||||
);
|
||||
assert_eq!(
|
||||
ChatGptEnvironment::Staging.agent_identity_authapi_base_url(),
|
||||
"https://auth.api.openai.org/api/accounts"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chatgpt_environment_rejects_custom_urls() {
|
||||
assert!(ChatGptEnvironment::from_chatgpt_base_url("http://localhost:8080").is_err(),);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_registration_url_appends_to_authapi_base_url() {
|
||||
assert_eq!(
|
||||
agent_registration_url("https://auth.openai.com/api/accounts"),
|
||||
"https://auth.openai.com/api/accounts/v1/agent/register"
|
||||
);
|
||||
assert_eq!(
|
||||
agent_registration_url("http://localhost:8080"),
|
||||
"http://localhost:8080/v1/agent/register"
|
||||
);
|
||||
assert_eq!(
|
||||
agent_registration_url("http://localhost:8080/backend-api"),
|
||||
"http://localhost:8080/backend-api/v1/agent/register"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_task_registration_url_appends_to_authapi_base_url() {
|
||||
assert_eq!(
|
||||
agent_task_registration_url("https://auth.openai.com/api/accounts", "agent-runtime-id"),
|
||||
"https://auth.openai.com/api/accounts/v1/agent/agent-runtime-id/task/register"
|
||||
);
|
||||
assert_eq!(
|
||||
agent_task_registration_url(
|
||||
"https://auth.openai.com/api/accounts/",
|
||||
"agent-runtime-id"
|
||||
),
|
||||
"https://auth.openai.com/api/accounts/v1/agent/agent-runtime-id/task/register"
|
||||
);
|
||||
assert_eq!(
|
||||
agent_task_registration_url("http://localhost:8080", "agent-runtime-id"),
|
||||
"http://localhost:8080/v1/agent/agent-runtime-id/task/register"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retryable_registration_error_accepts_429_and_5xx() {
|
||||
let too_many_requests = anyhow::Error::new(AgentIdentityRegistrationHttpError::new(
|
||||
"agent registration",
|
||||
reqwest::StatusCode::TOO_MANY_REQUESTS,
|
||||
"rate limited".to_string(),
|
||||
));
|
||||
let unavailable = anyhow::Error::new(AgentIdentityRegistrationHttpError::new(
|
||||
"agent registration",
|
||||
reqwest::StatusCode::SERVICE_UNAVAILABLE,
|
||||
"try later".to_string(),
|
||||
));
|
||||
|
||||
assert!(is_retryable_registration_error(&too_many_requests));
|
||||
assert!(is_retryable_registration_error(&unavailable));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retryable_registration_error_rejects_hard_failures() {
|
||||
let forbidden = anyhow::Error::new(AgentIdentityRegistrationHttpError::new(
|
||||
"agent registration",
|
||||
reqwest::StatusCode::FORBIDDEN,
|
||||
"not allowed".to_string(),
|
||||
));
|
||||
let malformed = anyhow::anyhow!("failed to sign registration request");
|
||||
|
||||
assert!(!is_retryable_registration_error(&forbidden));
|
||||
assert!(!is_retryable_registration_error(&malformed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_identity_jwks_url_uses_agent_identity_jwt_route() {
|
||||
assert_eq!(
|
||||
agent_identity_jwks_url("https://chatgpt.com/backend-api"),
|
||||
"https://chatgpt.com/backend-api/wham/agent-identities/jwks"
|
||||
@@ -716,7 +956,7 @@ J1bwkqKZTB5dHolX9A58e/xXnfZ5P8f3Z83+Izap3FwqQulk7b1WO1MQcHuVg2NN
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_identity_jwks_url_uses_codex_api_base_url() {
|
||||
fn agent_identity_jwks_url_uses_jwt_issuer_base_url() {
|
||||
assert_eq!(
|
||||
agent_identity_jwks_url("http://localhost:8080/api/codex"),
|
||||
"http://localhost:8080/api/codex/agent-identities/jwks"
|
||||
|
||||
@@ -9,7 +9,11 @@ use crate::events::CodexCommandExecutionEventParams;
|
||||
use crate::events::CodexCommandExecutionEventRequest;
|
||||
use crate::events::CodexCompactionEventRequest;
|
||||
use crate::events::CodexHookRunEventRequest;
|
||||
use crate::events::CodexOnboardingExternalAgentImportFailureEventRequest;
|
||||
use crate::events::CodexOnboardingExternalAgentImportFailureMetadata;
|
||||
use crate::events::CodexPluginEventRequest;
|
||||
use crate::events::CodexPluginInstallFailedEventRequest;
|
||||
use crate::events::CodexPluginInstallFailedMetadata;
|
||||
use crate::events::CodexPluginUsedEventRequest;
|
||||
use crate::events::CodexReviewEventParams;
|
||||
use crate::events::CodexReviewEventRequest;
|
||||
@@ -51,10 +55,13 @@ use crate::facts::CompactionStatus;
|
||||
use crate::facts::CompactionStrategy;
|
||||
use crate::facts::CompactionTrigger;
|
||||
use crate::facts::CustomAnalyticsFact;
|
||||
use crate::facts::ExternalAgentConfigImportCompletedInput;
|
||||
use crate::facts::ExternalAgentConfigImportFailureInput;
|
||||
use crate::facts::HookRunFact;
|
||||
use crate::facts::HookRunInput;
|
||||
use crate::facts::InputError;
|
||||
use crate::facts::InvocationType;
|
||||
use crate::facts::PluginInstallFailedInput;
|
||||
use crate::facts::PluginState;
|
||||
use crate::facts::PluginStateChangedInput;
|
||||
use crate::facts::PluginUsedInput;
|
||||
@@ -178,6 +185,7 @@ fn sample_thread_with_metadata(
|
||||
model_provider: "openai".to_string(),
|
||||
created_at: 1,
|
||||
updated_at: 2,
|
||||
recency_at: Some(2),
|
||||
status: AppServerThreadStatus::Idle,
|
||||
path: None,
|
||||
cwd: test_path_buf("/tmp").abs(),
|
||||
@@ -861,6 +869,7 @@ fn sample_command_approval_request(request_id: i64, approval_id: Option<&str>) -
|
||||
item_id: "item-1".to_string(),
|
||||
started_at_ms: 1_000,
|
||||
approval_id: approval_id.map(str::to_string),
|
||||
environment_id: None,
|
||||
reason: None,
|
||||
network_approval_context: None,
|
||||
command: Some("echo hi".to_string()),
|
||||
@@ -3052,6 +3061,36 @@ fn plugin_management_event_serializes_expected_shape() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_install_failed_event_serializes_expected_shape() {
|
||||
let event = TrackEventRequest::PluginInstallFailed(CodexPluginInstallFailedEventRequest {
|
||||
event_type: "codex_plugin_install_failed",
|
||||
event_params: CodexPluginInstallFailedMetadata {
|
||||
plugin: codex_plugin_metadata(sample_plugin_metadata()),
|
||||
error_type: "store_io".to_string(),
|
||||
},
|
||||
});
|
||||
|
||||
let payload = serde_json::to_value(&event).expect("serialize plugin install failed event");
|
||||
|
||||
assert_eq!(
|
||||
payload,
|
||||
json!({
|
||||
"event_type": "codex_plugin_install_failed",
|
||||
"event_params": {
|
||||
"plugin_id": "sample@test",
|
||||
"plugin_name": "sample",
|
||||
"marketplace_name": "test",
|
||||
"has_skills": true,
|
||||
"mcp_server_count": 2,
|
||||
"connector_ids": ["calendar", "drive"],
|
||||
"product_client_id": originator().value,
|
||||
"error_type": "store_io"
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_management_event_can_use_remote_plugin_id_override() {
|
||||
let mut plugin = sample_plugin_metadata();
|
||||
@@ -3419,6 +3458,190 @@ async fn reducer_ingests_plugin_state_changed_fact() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reducer_ingests_plugin_install_failed_fact() {
|
||||
let mut reducer = AnalyticsReducer::default();
|
||||
let mut events = Vec::new();
|
||||
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::Custom(CustomAnalyticsFact::PluginInstallFailed(
|
||||
PluginInstallFailedInput {
|
||||
plugin: sample_plugin_metadata(),
|
||||
error_type: "invalid_plugin".to_string(),
|
||||
},
|
||||
)),
|
||||
&mut events,
|
||||
)
|
||||
.await;
|
||||
|
||||
let payload = serde_json::to_value(&events).expect("serialize events");
|
||||
assert_eq!(
|
||||
payload,
|
||||
json!([{
|
||||
"event_type": "codex_plugin_install_failed",
|
||||
"event_params": {
|
||||
"plugin_id": "sample@test",
|
||||
"plugin_name": "sample",
|
||||
"marketplace_name": "test",
|
||||
"has_skills": true,
|
||||
"mcp_server_count": 2,
|
||||
"connector_ids": ["calendar", "drive"],
|
||||
"product_client_id": originator().value,
|
||||
"error_type": "invalid_plugin"
|
||||
}
|
||||
}])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reducer_ingests_plugin_install_failed_fact_without_detail() {
|
||||
let mut reducer = AnalyticsReducer::default();
|
||||
let mut events = Vec::new();
|
||||
let mut plugin = PluginTelemetryMetadata::from_plugin_id(
|
||||
&PluginId::parse("unknown@openai-curated-remote").expect("valid plugin id"),
|
||||
);
|
||||
plugin.remote_plugin_id = Some("plugins~Plugin_00000000000000000000000000000000".to_string());
|
||||
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::Custom(CustomAnalyticsFact::PluginInstallFailed(
|
||||
PluginInstallFailedInput {
|
||||
plugin,
|
||||
error_type: "remote_catalog_unexpected_status".to_string(),
|
||||
},
|
||||
)),
|
||||
&mut events,
|
||||
)
|
||||
.await;
|
||||
|
||||
let payload = serde_json::to_value(&events).expect("serialize events");
|
||||
assert_eq!(
|
||||
payload,
|
||||
json!([{
|
||||
"event_type": "codex_plugin_install_failed",
|
||||
"event_params": {
|
||||
"plugin_id": "plugins~Plugin_00000000000000000000000000000000",
|
||||
"plugin_name": "unknown",
|
||||
"marketplace_name": "openai-curated-remote",
|
||||
"has_skills": null,
|
||||
"mcp_server_count": null,
|
||||
"connector_ids": null,
|
||||
"product_client_id": originator().value,
|
||||
"error_type": "remote_catalog_unexpected_status"
|
||||
}
|
||||
}])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reducer_ingests_external_agent_config_import_completed_fact() {
|
||||
let mut reducer = AnalyticsReducer::default();
|
||||
let mut events = Vec::new();
|
||||
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::Custom(CustomAnalyticsFact::ExternalAgentConfigImportCompleted(
|
||||
ExternalAgentConfigImportCompletedInput {
|
||||
import_id: "import-1".to_string(),
|
||||
source: "app_server".to_string(),
|
||||
item_type: "PLUGINS".to_string(),
|
||||
success_count: 2,
|
||||
failed_count: 1,
|
||||
},
|
||||
)),
|
||||
&mut events,
|
||||
)
|
||||
.await;
|
||||
|
||||
let payload = serde_json::to_value(&events).expect("serialize events");
|
||||
assert_eq!(
|
||||
payload,
|
||||
json!([{
|
||||
"event_type": "codex_onboarding_external_agent_import_complete",
|
||||
"event_params": {
|
||||
"import_id": "import-1",
|
||||
"source": "app_server",
|
||||
"type": "PLUGINS",
|
||||
"success_count": 2,
|
||||
"failed_count": 1,
|
||||
"product_client_id": originator().value,
|
||||
}
|
||||
}])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_agent_config_import_failure_event_serializes_expected_shape() {
|
||||
let event = TrackEventRequest::ExternalAgentConfigImportFailure(
|
||||
CodexOnboardingExternalAgentImportFailureEventRequest {
|
||||
event_type: "codex_onboarding_external_agent_import_failure",
|
||||
event_params: CodexOnboardingExternalAgentImportFailureMetadata {
|
||||
import_id: "import-1".to_string(),
|
||||
source: "app_server".to_string(),
|
||||
item_type: "SESSIONS".to_string(),
|
||||
failure_stage: "session_missing".to_string(),
|
||||
error_type: "session_missing".to_string(),
|
||||
product_client_id: Some(originator().value),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
let payload = serde_json::to_value(&event).expect("serialize import failure event");
|
||||
|
||||
assert_eq!(
|
||||
payload,
|
||||
json!({
|
||||
"event_type": "codex_onboarding_external_agent_import_failure",
|
||||
"event_params": {
|
||||
"import_id": "import-1",
|
||||
"source": "app_server",
|
||||
"type": "SESSIONS",
|
||||
"failure_stage": "session_missing",
|
||||
"error_type": "session_missing",
|
||||
"product_client_id": originator().value,
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reducer_ingests_external_agent_config_import_failure_fact() {
|
||||
let mut reducer = AnalyticsReducer::default();
|
||||
let mut events = Vec::new();
|
||||
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::Custom(CustomAnalyticsFact::ExternalAgentConfigImportFailure(
|
||||
ExternalAgentConfigImportFailureInput {
|
||||
import_id: "import-1".to_string(),
|
||||
source: "app_server".to_string(),
|
||||
item_type: "SESSIONS".to_string(),
|
||||
failure_stage: "session_missing".to_string(),
|
||||
error_type: "session_missing".to_string(),
|
||||
},
|
||||
)),
|
||||
&mut events,
|
||||
)
|
||||
.await;
|
||||
|
||||
let payload = serde_json::to_value(&events).expect("serialize events");
|
||||
assert_eq!(
|
||||
payload,
|
||||
json!([{
|
||||
"event_type": "codex_onboarding_external_agent_import_failure",
|
||||
"event_params": {
|
||||
"import_id": "import-1",
|
||||
"source": "app_server",
|
||||
"type": "SESSIONS",
|
||||
"failure_stage": "session_missing",
|
||||
"error_type": "session_missing",
|
||||
"product_client_id": originator().value,
|
||||
}
|
||||
}])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_event_serializes_expected_shape() {
|
||||
let event = TrackEventRequest::TurnEvent(Box::new(CodexTurnEventRequest {
|
||||
|
||||
@@ -11,8 +11,11 @@ use crate::facts::AppMentionedInput;
|
||||
use crate::facts::AppUsedInput;
|
||||
use crate::facts::CodexGoalEvent;
|
||||
use crate::facts::CustomAnalyticsFact;
|
||||
use crate::facts::ExternalAgentConfigImportCompletedInput;
|
||||
use crate::facts::ExternalAgentConfigImportFailureInput;
|
||||
use crate::facts::HookRunFact;
|
||||
use crate::facts::HookRunInput;
|
||||
use crate::facts::PluginInstallFailedInput;
|
||||
use crate::facts::PluginState;
|
||||
use crate::facts::PluginStateChangedInput;
|
||||
use crate::facts::SkillInvocation;
|
||||
@@ -343,6 +346,33 @@ impl AnalyticsEventsClient {
|
||||
));
|
||||
}
|
||||
|
||||
pub fn track_plugin_install_failed(&self, plugin: PluginTelemetryMetadata, error_type: String) {
|
||||
self.record_fact(AnalyticsFact::Custom(
|
||||
CustomAnalyticsFact::PluginInstallFailed(PluginInstallFailedInput {
|
||||
plugin,
|
||||
error_type,
|
||||
}),
|
||||
));
|
||||
}
|
||||
|
||||
pub fn track_external_agent_config_import_completed(
|
||||
&self,
|
||||
input: ExternalAgentConfigImportCompletedInput,
|
||||
) {
|
||||
self.record_fact(AnalyticsFact::Custom(
|
||||
CustomAnalyticsFact::ExternalAgentConfigImportCompleted(input),
|
||||
));
|
||||
}
|
||||
|
||||
pub fn track_external_agent_config_import_failure(
|
||||
&self,
|
||||
input: ExternalAgentConfigImportFailureInput,
|
||||
) {
|
||||
self.record_fact(AnalyticsFact::Custom(
|
||||
CustomAnalyticsFact::ExternalAgentConfigImportFailure(input),
|
||||
));
|
||||
}
|
||||
|
||||
pub fn track_plugin_uninstalled(&self, plugin: PluginTelemetryMetadata) {
|
||||
self.record_fact(AnalyticsFact::Custom(
|
||||
CustomAnalyticsFact::PluginStateChanged(PluginStateChangedInput {
|
||||
|
||||
@@ -285,6 +285,7 @@ fn sample_thread(thread_id: &str) -> Thread {
|
||||
model_provider: "openai".to_string(),
|
||||
created_at: 1,
|
||||
updated_at: 2,
|
||||
recency_at: Some(2),
|
||||
status: AppServerThreadStatus::Idle,
|
||||
path: None,
|
||||
cwd: test_path_buf("/tmp").abs(),
|
||||
|
||||
@@ -83,6 +83,9 @@ pub(crate) enum TrackEventRequest {
|
||||
PluginUninstalled(CodexPluginEventRequest),
|
||||
PluginEnabled(CodexPluginEventRequest),
|
||||
PluginDisabled(CodexPluginEventRequest),
|
||||
PluginInstallFailed(CodexPluginInstallFailedEventRequest),
|
||||
ExternalAgentConfigImportCompleted(CodexOnboardingExternalAgentImportCompleteEventRequest),
|
||||
ExternalAgentConfigImportFailure(CodexOnboardingExternalAgentImportFailureEventRequest),
|
||||
}
|
||||
|
||||
impl TrackEventRequest {
|
||||
@@ -954,6 +957,53 @@ pub(crate) struct CodexPluginEventRequest {
|
||||
pub(crate) event_params: CodexPluginMetadata,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct CodexPluginInstallFailedMetadata {
|
||||
#[serde(flatten)]
|
||||
pub(crate) plugin: CodexPluginMetadata,
|
||||
pub(crate) error_type: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct CodexPluginInstallFailedEventRequest {
|
||||
pub(crate) event_type: &'static str,
|
||||
pub(crate) event_params: CodexPluginInstallFailedMetadata,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct CodexOnboardingExternalAgentImportCompleteMetadata {
|
||||
pub(crate) import_id: String,
|
||||
pub(crate) source: String,
|
||||
#[serde(rename = "type")]
|
||||
pub(crate) item_type: String,
|
||||
pub(crate) success_count: usize,
|
||||
pub(crate) failed_count: usize,
|
||||
pub(crate) product_client_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct CodexOnboardingExternalAgentImportCompleteEventRequest {
|
||||
pub(crate) event_type: &'static str,
|
||||
pub(crate) event_params: CodexOnboardingExternalAgentImportCompleteMetadata,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct CodexOnboardingExternalAgentImportFailureMetadata {
|
||||
pub(crate) import_id: String,
|
||||
pub(crate) source: String,
|
||||
#[serde(rename = "type")]
|
||||
pub(crate) item_type: String,
|
||||
pub(crate) failure_stage: String,
|
||||
pub(crate) error_type: String,
|
||||
pub(crate) product_client_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct CodexOnboardingExternalAgentImportFailureEventRequest {
|
||||
pub(crate) event_type: &'static str,
|
||||
pub(crate) event_params: CodexOnboardingExternalAgentImportFailureMetadata,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct CodexPluginUsedEventRequest {
|
||||
pub(crate) event_type: &'static str,
|
||||
|
||||
@@ -504,6 +504,9 @@ pub(crate) enum CustomAnalyticsFact {
|
||||
HookRun(HookRunInput),
|
||||
PluginUsed(PluginUsedInput),
|
||||
PluginStateChanged(PluginStateChangedInput),
|
||||
PluginInstallFailed(PluginInstallFailedInput),
|
||||
ExternalAgentConfigImportCompleted(ExternalAgentConfigImportCompletedInput),
|
||||
ExternalAgentConfigImportFailure(ExternalAgentConfigImportFailureInput),
|
||||
}
|
||||
|
||||
pub(crate) struct SkillInvokedInput {
|
||||
@@ -542,6 +545,27 @@ pub(crate) struct PluginStateChangedInput {
|
||||
pub state: PluginState,
|
||||
}
|
||||
|
||||
pub(crate) struct PluginInstallFailedInput {
|
||||
pub plugin: PluginTelemetryMetadata,
|
||||
pub error_type: String,
|
||||
}
|
||||
|
||||
pub struct ExternalAgentConfigImportCompletedInput {
|
||||
pub import_id: String,
|
||||
pub source: String,
|
||||
pub item_type: String,
|
||||
pub success_count: usize,
|
||||
pub failed_count: usize,
|
||||
}
|
||||
|
||||
pub struct ExternalAgentConfigImportFailureInput {
|
||||
pub import_id: String,
|
||||
pub source: String,
|
||||
pub item_type: String,
|
||||
pub failure_stage: String,
|
||||
pub error_type: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum PluginState {
|
||||
Installed,
|
||||
|
||||
@@ -36,6 +36,8 @@ pub use facts::CompactionReason;
|
||||
pub use facts::CompactionStatus;
|
||||
pub use facts::CompactionStrategy;
|
||||
pub use facts::CompactionTrigger;
|
||||
pub use facts::ExternalAgentConfigImportCompletedInput;
|
||||
pub use facts::ExternalAgentConfigImportFailureInput;
|
||||
pub use facts::GoalEventKind;
|
||||
pub use facts::HookRunFact;
|
||||
pub use facts::InputError;
|
||||
|
||||
@@ -21,7 +21,13 @@ use crate::events::CodexImageGenerationEventParams;
|
||||
use crate::events::CodexImageGenerationEventRequest;
|
||||
use crate::events::CodexMcpToolCallEventParams;
|
||||
use crate::events::CodexMcpToolCallEventRequest;
|
||||
use crate::events::CodexOnboardingExternalAgentImportCompleteEventRequest;
|
||||
use crate::events::CodexOnboardingExternalAgentImportCompleteMetadata;
|
||||
use crate::events::CodexOnboardingExternalAgentImportFailureEventRequest;
|
||||
use crate::events::CodexOnboardingExternalAgentImportFailureMetadata;
|
||||
use crate::events::CodexPluginEventRequest;
|
||||
use crate::events::CodexPluginInstallFailedEventRequest;
|
||||
use crate::events::CodexPluginInstallFailedMetadata;
|
||||
use crate::events::CodexPluginUsedEventRequest;
|
||||
use crate::events::CodexReviewEventParams;
|
||||
use crate::events::CodexReviewEventRequest;
|
||||
@@ -66,7 +72,10 @@ use crate::facts::AppUsedInput;
|
||||
use crate::facts::CodexCompactionEvent;
|
||||
use crate::facts::CodexGoalEvent;
|
||||
use crate::facts::CustomAnalyticsFact;
|
||||
use crate::facts::ExternalAgentConfigImportCompletedInput;
|
||||
use crate::facts::ExternalAgentConfigImportFailureInput;
|
||||
use crate::facts::HookRunInput;
|
||||
use crate::facts::PluginInstallFailedInput;
|
||||
use crate::facts::PluginState;
|
||||
use crate::facts::PluginStateChangedInput;
|
||||
use crate::facts::PluginUsedInput;
|
||||
@@ -511,6 +520,15 @@ impl AnalyticsReducer {
|
||||
CustomAnalyticsFact::PluginStateChanged(input) => {
|
||||
self.ingest_plugin_state_changed(input, out);
|
||||
}
|
||||
CustomAnalyticsFact::PluginInstallFailed(input) => {
|
||||
self.ingest_plugin_install_failed(input, out);
|
||||
}
|
||||
CustomAnalyticsFact::ExternalAgentConfigImportCompleted(input) => {
|
||||
self.ingest_external_agent_config_import_completed(input, out);
|
||||
}
|
||||
CustomAnalyticsFact::ExternalAgentConfigImportFailure(input) => {
|
||||
self.ingest_external_agent_config_import_failure(input, out);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -775,6 +793,63 @@ impl AnalyticsReducer {
|
||||
});
|
||||
}
|
||||
|
||||
fn ingest_plugin_install_failed(
|
||||
&mut self,
|
||||
input: PluginInstallFailedInput,
|
||||
out: &mut Vec<TrackEventRequest>,
|
||||
) {
|
||||
let PluginInstallFailedInput { plugin, error_type } = input;
|
||||
out.push(TrackEventRequest::PluginInstallFailed(
|
||||
CodexPluginInstallFailedEventRequest {
|
||||
event_type: "codex_plugin_install_failed",
|
||||
event_params: CodexPluginInstallFailedMetadata {
|
||||
plugin: codex_plugin_metadata(plugin),
|
||||
error_type,
|
||||
},
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
fn ingest_external_agent_config_import_completed(
|
||||
&mut self,
|
||||
input: ExternalAgentConfigImportCompletedInput,
|
||||
out: &mut Vec<TrackEventRequest>,
|
||||
) {
|
||||
out.push(TrackEventRequest::ExternalAgentConfigImportCompleted(
|
||||
CodexOnboardingExternalAgentImportCompleteEventRequest {
|
||||
event_type: "codex_onboarding_external_agent_import_complete",
|
||||
event_params: CodexOnboardingExternalAgentImportCompleteMetadata {
|
||||
import_id: input.import_id,
|
||||
source: input.source,
|
||||
item_type: input.item_type,
|
||||
success_count: input.success_count,
|
||||
failed_count: input.failed_count,
|
||||
product_client_id: Some(originator().value),
|
||||
},
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
fn ingest_external_agent_config_import_failure(
|
||||
&mut self,
|
||||
input: ExternalAgentConfigImportFailureInput,
|
||||
out: &mut Vec<TrackEventRequest>,
|
||||
) {
|
||||
out.push(TrackEventRequest::ExternalAgentConfigImportFailure(
|
||||
CodexOnboardingExternalAgentImportFailureEventRequest {
|
||||
event_type: "codex_onboarding_external_agent_import_failure",
|
||||
event_params: CodexOnboardingExternalAgentImportFailureMetadata {
|
||||
import_id: input.import_id,
|
||||
source: input.source,
|
||||
item_type: input.item_type,
|
||||
failure_stage: input.failure_stage,
|
||||
error_type: input.error_type,
|
||||
product_client_id: Some(originator().value),
|
||||
},
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
async fn ingest_response(
|
||||
&mut self,
|
||||
connection_id: u64,
|
||||
|
||||
+43
-3
@@ -800,7 +800,7 @@
|
||||
]
|
||||
},
|
||||
"includeHome": {
|
||||
"description": "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).",
|
||||
"description": "If true, include detection under the user's home directory.",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
@@ -813,6 +813,13 @@
|
||||
"$ref": "#/definitions/ExternalAgentConfigMigrationItem"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"source": {
|
||||
"description": "Source product that produced the migration items. Missing means unspecified.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -1303,6 +1310,9 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"LegacyAppPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"ListMcpServerStatusParams": {
|
||||
"properties": {
|
||||
"cursor": {
|
||||
@@ -2937,6 +2947,12 @@
|
||||
},
|
||||
"ResponseItemMetadata": {
|
||||
"properties": {
|
||||
"source_call_id": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"turn_id": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -4155,7 +4171,8 @@
|
||||
"ThreadSortKey": {
|
||||
"enum": [
|
||||
"created_at",
|
||||
"updated_at"
|
||||
"updated_at",
|
||||
"recency_at"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
@@ -4331,7 +4348,7 @@
|
||||
"TurnEnvironmentParams": {
|
||||
"properties": {
|
||||
"cwd": {
|
||||
"$ref": "#/definitions/AbsolutePathBuf"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"environmentId": {
|
||||
"type": "string"
|
||||
@@ -6620,6 +6637,29 @@
|
||||
"title": "ExternalAgentConfig/importRequest",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
"$ref": "#/definitions/RequestId"
|
||||
},
|
||||
"method": {
|
||||
"enum": [
|
||||
"externalAgentConfig/import/readHistories"
|
||||
],
|
||||
"title": "ExternalAgentConfig/import/readHistoriesRequestMethod",
|
||||
"type": "string"
|
||||
},
|
||||
"params": {
|
||||
"type": "null"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"method"
|
||||
],
|
||||
"title": "ExternalAgentConfig/import/readHistoriesRequest",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
|
||||
+14
-6
@@ -27,7 +27,7 @@
|
||||
"read": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -37,7 +37,7 @@
|
||||
"write": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -84,9 +84,6 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"ApiPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"CommandAction": {
|
||||
"oneOf": [
|
||||
{
|
||||
@@ -289,7 +286,7 @@
|
||||
{
|
||||
"properties": {
|
||||
"path": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": {
|
||||
"enum": [
|
||||
@@ -472,6 +469,9 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"LegacyAppPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"NetworkApprovalContext": {
|
||||
"properties": {
|
||||
"host": {
|
||||
@@ -555,6 +555,14 @@
|
||||
],
|
||||
"description": "The command's working directory."
|
||||
},
|
||||
"environmentId": {
|
||||
"default": null,
|
||||
"description": "Environment in which the command will run.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"itemId": {
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
+6
-6
@@ -27,7 +27,7 @@
|
||||
"read": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -37,7 +37,7 @@
|
||||
"write": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -58,9 +58,6 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"ApiPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"FileSystemAccessMode": {
|
||||
"enum": [
|
||||
"read",
|
||||
@@ -74,7 +71,7 @@
|
||||
{
|
||||
"properties": {
|
||||
"path": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": {
|
||||
"enum": [
|
||||
@@ -257,6 +254,9 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"LegacyAppPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"RequestPermissionProfile": {
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
|
||||
+6
-6
@@ -23,7 +23,7 @@
|
||||
"read": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -33,7 +33,7 @@
|
||||
"write": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -54,9 +54,6 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"ApiPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"FileSystemAccessMode": {
|
||||
"enum": [
|
||||
"read",
|
||||
@@ -70,7 +67,7 @@
|
||||
{
|
||||
"properties": {
|
||||
"path": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": {
|
||||
"enum": [
|
||||
@@ -278,6 +275,9 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"LegacyAppPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"PermissionGrantScope": {
|
||||
"enum": [
|
||||
"turn",
|
||||
|
||||
@@ -107,7 +107,7 @@
|
||||
"read": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -117,7 +117,7 @@
|
||||
"write": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -164,9 +164,6 @@
|
||||
"AgentPath": {
|
||||
"type": "string"
|
||||
},
|
||||
"ApiPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"AppBranding": {
|
||||
"description": "EXPERIMENTAL - app metadata returned by app-list APIs.",
|
||||
"properties": {
|
||||
@@ -1167,6 +1164,12 @@
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"errorType": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"failureStage": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -1219,6 +1222,24 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportProgressNotification": {
|
||||
"properties": {
|
||||
"importId": {
|
||||
"type": "string"
|
||||
},
|
||||
"itemTypeResults": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportTypeResult"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"importId",
|
||||
"itemTypeResults"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportTypeResult": {
|
||||
"properties": {
|
||||
"failures": {
|
||||
@@ -1321,7 +1342,7 @@
|
||||
{
|
||||
"properties": {
|
||||
"path": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": {
|
||||
"enum": [
|
||||
@@ -2315,6 +2336,9 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"LegacyAppPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"McpServerOauthLoginCompletedNotification": {
|
||||
"properties": {
|
||||
"error": {
|
||||
@@ -3558,6 +3582,14 @@
|
||||
"description": "Usually the first user message in the thread, if available.",
|
||||
"type": "string"
|
||||
},
|
||||
"recencyAt": {
|
||||
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
|
||||
"format": "int64",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sessionId": {
|
||||
"description": "Session id shared by threads that belong to the same session tree.",
|
||||
"type": "string"
|
||||
@@ -6333,6 +6365,26 @@
|
||||
"title": "RemoteControl/status/changedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"method": {
|
||||
"enum": [
|
||||
"externalAgentConfig/import/progress"
|
||||
],
|
||||
"title": "ExternalAgentConfig/import/progressNotificationMethod",
|
||||
"type": "string"
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportProgressNotification"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"method",
|
||||
"params"
|
||||
],
|
||||
"title": "ExternalAgentConfig/import/progressNotification",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"method": {
|
||||
|
||||
+14
-6
@@ -27,7 +27,7 @@
|
||||
"read": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -37,7 +37,7 @@
|
||||
"write": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -84,9 +84,6 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"ApiPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"ApplyPatchApprovalParams": {
|
||||
"properties": {
|
||||
"callId": {
|
||||
@@ -382,6 +379,14 @@
|
||||
],
|
||||
"description": "The command's working directory."
|
||||
},
|
||||
"environmentId": {
|
||||
"default": null,
|
||||
"description": "Environment in which the command will run.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"itemId": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -643,7 +648,7 @@
|
||||
{
|
||||
"properties": {
|
||||
"path": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": {
|
||||
"enum": [
|
||||
@@ -826,6 +831,9 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"LegacyAppPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"McpElicitationArrayType": {
|
||||
"enum": [
|
||||
"array"
|
||||
|
||||
+179
-9
@@ -2124,6 +2124,29 @@
|
||||
"title": "ExternalAgentConfig/importRequest",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
"$ref": "#/definitions/v2/RequestId"
|
||||
},
|
||||
"method": {
|
||||
"enum": [
|
||||
"externalAgentConfig/import/readHistories"
|
||||
],
|
||||
"title": "ExternalAgentConfig/import/readHistoriesRequestMethod",
|
||||
"type": "string"
|
||||
},
|
||||
"params": {
|
||||
"type": "null"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"method"
|
||||
],
|
||||
"title": "ExternalAgentConfig/import/readHistoriesRequest",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
@@ -2363,6 +2386,14 @@
|
||||
],
|
||||
"description": "The command's working directory."
|
||||
},
|
||||
"environmentId": {
|
||||
"default": null,
|
||||
"description": "Environment in which the command will run.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"itemId": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -4834,6 +4865,26 @@
|
||||
"title": "RemoteControl/status/changedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"method": {
|
||||
"enum": [
|
||||
"externalAgentConfig/import/progress"
|
||||
],
|
||||
"title": "ExternalAgentConfig/import/progressNotificationMethod",
|
||||
"type": "string"
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/definitions/v2/ExternalAgentConfigImportProgressNotification"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"method",
|
||||
"params"
|
||||
],
|
||||
"title": "ExternalAgentConfig/import/progressNotification",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"method": {
|
||||
@@ -5804,6 +5855,14 @@
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"credentialSource": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/v2/AmazonBedrockCredentialSource"
|
||||
}
|
||||
],
|
||||
"default": "awsManaged"
|
||||
},
|
||||
"type": {
|
||||
"enum": [
|
||||
"amazonBedrock"
|
||||
@@ -6020,7 +6079,7 @@
|
||||
"read": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/v2/ApiPathString"
|
||||
"$ref": "#/definitions/v2/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -6030,7 +6089,7 @@
|
||||
"write": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/v2/ApiPathString"
|
||||
"$ref": "#/definitions/v2/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -6123,6 +6182,13 @@
|
||||
"AgentPath": {
|
||||
"type": "string"
|
||||
},
|
||||
"AmazonBedrockCredentialSource": {
|
||||
"enum": [
|
||||
"codexManaged",
|
||||
"awsManaged"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"AnalyticsConfig": {
|
||||
"additionalProperties": true,
|
||||
"properties": {
|
||||
@@ -6135,9 +6201,6 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"ApiPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"AppBranding": {
|
||||
"description": "EXPERIMENTAL - app metadata returned by app-list APIs.",
|
||||
"properties": {
|
||||
@@ -6641,6 +6704,16 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"default_tools_approval_mode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/v2/AppToolApproval"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"destructive_enabled": {
|
||||
"default": true,
|
||||
"type": "boolean"
|
||||
@@ -9046,7 +9119,7 @@
|
||||
]
|
||||
},
|
||||
"includeHome": {
|
||||
"description": "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).",
|
||||
"description": "If true, include detection under the user's home directory.",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
@@ -9089,6 +9162,52 @@
|
||||
"title": "ExternalAgentConfigImportCompletedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportHistoriesReadResponse": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"properties": {
|
||||
"data": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/v2/ExternalAgentConfigImportHistory"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"title": "ExternalAgentConfigImportHistoriesReadResponse",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportHistory": {
|
||||
"properties": {
|
||||
"completedAtMs": {
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
},
|
||||
"failures": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/v2/ExternalAgentConfigImportItemTypeFailure"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"importId": {
|
||||
"type": "string"
|
||||
},
|
||||
"successes": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/v2/ExternalAgentConfigImportItemTypeSuccess"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"completedAtMs",
|
||||
"failures",
|
||||
"importId",
|
||||
"successes"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportItemTypeFailure": {
|
||||
"properties": {
|
||||
"cwd": {
|
||||
@@ -9097,6 +9216,12 @@
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"errorType": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"failureStage": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -9157,6 +9282,13 @@
|
||||
"$ref": "#/definitions/v2/ExternalAgentConfigMigrationItem"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"source": {
|
||||
"description": "Source product that produced the migration items. Missing means unspecified.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -9165,6 +9297,26 @@
|
||||
"title": "ExternalAgentConfigImportParams",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportProgressNotification": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"properties": {
|
||||
"importId": {
|
||||
"type": "string"
|
||||
},
|
||||
"itemTypeResults": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/v2/ExternalAgentConfigImportTypeResult"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"importId",
|
||||
"itemTypeResults"
|
||||
],
|
||||
"title": "ExternalAgentConfigImportProgressNotification",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportResponse": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"properties": {
|
||||
@@ -9375,7 +9527,7 @@
|
||||
{
|
||||
"properties": {
|
||||
"path": {
|
||||
"$ref": "#/definitions/v2/ApiPathString"
|
||||
"$ref": "#/definitions/v2/LegacyAppPathString"
|
||||
},
|
||||
"type": {
|
||||
"enum": [
|
||||
@@ -11054,6 +11206,9 @@
|
||||
"title": "ItemStartedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
"LegacyAppPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"ListMcpServerStatusParams": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"properties": {
|
||||
@@ -15294,6 +15449,12 @@
|
||||
},
|
||||
"ResponseItemMetadata": {
|
||||
"properties": {
|
||||
"source_call_id": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"turn_id": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -16491,6 +16652,14 @@
|
||||
"description": "Usually the first user message in the thread, if available.",
|
||||
"type": "string"
|
||||
},
|
||||
"recencyAt": {
|
||||
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
|
||||
"format": "int64",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sessionId": {
|
||||
"description": "Session id shared by threads that belong to the same session tree.",
|
||||
"type": "string"
|
||||
@@ -18750,7 +18919,8 @@
|
||||
"ThreadSortKey": {
|
||||
"enum": [
|
||||
"created_at",
|
||||
"updated_at"
|
||||
"updated_at",
|
||||
"recency_at"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
@@ -19387,7 +19557,7 @@
|
||||
"TurnEnvironmentParams": {
|
||||
"properties": {
|
||||
"cwd": {
|
||||
"$ref": "#/definitions/v2/AbsolutePathBuf"
|
||||
"$ref": "#/definitions/v2/LegacyAppPathString"
|
||||
},
|
||||
"environmentId": {
|
||||
"type": "string"
|
||||
|
||||
+171
-9
@@ -49,6 +49,14 @@
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"credentialSource": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/AmazonBedrockCredentialSource"
|
||||
}
|
||||
],
|
||||
"default": "awsManaged"
|
||||
},
|
||||
"type": {
|
||||
"enum": [
|
||||
"amazonBedrock"
|
||||
@@ -265,7 +273,7 @@
|
||||
"read": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -275,7 +283,7 @@
|
||||
"write": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -368,6 +376,13 @@
|
||||
"AgentPath": {
|
||||
"type": "string"
|
||||
},
|
||||
"AmazonBedrockCredentialSource": {
|
||||
"enum": [
|
||||
"codexManaged",
|
||||
"awsManaged"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"AnalyticsConfig": {
|
||||
"additionalProperties": true,
|
||||
"properties": {
|
||||
@@ -380,9 +395,6 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"ApiPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"AppBranding": {
|
||||
"description": "EXPERIMENTAL - app metadata returned by app-list APIs.",
|
||||
"properties": {
|
||||
@@ -886,6 +898,16 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"default_tools_approval_mode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/AppToolApproval"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"destructive_enabled": {
|
||||
"default": true,
|
||||
"type": "boolean"
|
||||
@@ -3111,6 +3133,29 @@
|
||||
"title": "ExternalAgentConfig/importRequest",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
"$ref": "#/definitions/RequestId"
|
||||
},
|
||||
"method": {
|
||||
"enum": [
|
||||
"externalAgentConfig/import/readHistories"
|
||||
],
|
||||
"title": "ExternalAgentConfig/import/readHistoriesRequestMethod",
|
||||
"type": "string"
|
||||
},
|
||||
"params": {
|
||||
"type": "null"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"method"
|
||||
],
|
||||
"title": "ExternalAgentConfig/import/readHistoriesRequest",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
@@ -5359,7 +5404,7 @@
|
||||
]
|
||||
},
|
||||
"includeHome": {
|
||||
"description": "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).",
|
||||
"description": "If true, include detection under the user's home directory.",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
@@ -5402,6 +5447,52 @@
|
||||
"title": "ExternalAgentConfigImportCompletedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportHistoriesReadResponse": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"properties": {
|
||||
"data": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportHistory"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"title": "ExternalAgentConfigImportHistoriesReadResponse",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportHistory": {
|
||||
"properties": {
|
||||
"completedAtMs": {
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
},
|
||||
"failures": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportItemTypeFailure"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"importId": {
|
||||
"type": "string"
|
||||
},
|
||||
"successes": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportItemTypeSuccess"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"completedAtMs",
|
||||
"failures",
|
||||
"importId",
|
||||
"successes"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportItemTypeFailure": {
|
||||
"properties": {
|
||||
"cwd": {
|
||||
@@ -5410,6 +5501,12 @@
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"errorType": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"failureStage": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -5470,6 +5567,13 @@
|
||||
"$ref": "#/definitions/ExternalAgentConfigMigrationItem"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"source": {
|
||||
"description": "Source product that produced the migration items. Missing means unspecified.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -5478,6 +5582,26 @@
|
||||
"title": "ExternalAgentConfigImportParams",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportProgressNotification": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"properties": {
|
||||
"importId": {
|
||||
"type": "string"
|
||||
},
|
||||
"itemTypeResults": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportTypeResult"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"importId",
|
||||
"itemTypeResults"
|
||||
],
|
||||
"title": "ExternalAgentConfigImportProgressNotification",
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportResponse": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"properties": {
|
||||
@@ -5688,7 +5812,7 @@
|
||||
{
|
||||
"properties": {
|
||||
"path": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": {
|
||||
"enum": [
|
||||
@@ -7527,6 +7651,9 @@
|
||||
"title": "ItemStartedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
"LegacyAppPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"ListMcpServerStatusParams": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"properties": {
|
||||
@@ -11767,6 +11894,12 @@
|
||||
},
|
||||
"ResponseItemMetadata": {
|
||||
"properties": {
|
||||
"source_call_id": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"turn_id": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -13011,6 +13144,26 @@
|
||||
"title": "RemoteControl/status/changedNotification",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"method": {
|
||||
"enum": [
|
||||
"externalAgentConfig/import/progress"
|
||||
],
|
||||
"title": "ExternalAgentConfig/import/progressNotificationMethod",
|
||||
"type": "string"
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportProgressNotification"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"method",
|
||||
"params"
|
||||
],
|
||||
"title": "ExternalAgentConfig/import/progressNotification",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"method": {
|
||||
@@ -14299,6 +14452,14 @@
|
||||
"description": "Usually the first user message in the thread, if available.",
|
||||
"type": "string"
|
||||
},
|
||||
"recencyAt": {
|
||||
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
|
||||
"format": "int64",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sessionId": {
|
||||
"description": "Session id shared by threads that belong to the same session tree.",
|
||||
"type": "string"
|
||||
@@ -16558,7 +16719,8 @@
|
||||
"ThreadSortKey": {
|
||||
"enum": [
|
||||
"created_at",
|
||||
"updated_at"
|
||||
"updated_at",
|
||||
"recency_at"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
@@ -17195,7 +17357,7 @@
|
||||
"TurnEnvironmentParams": {
|
||||
"properties": {
|
||||
"cwd": {
|
||||
"$ref": "#/definitions/AbsolutePathBuf"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"environmentId": {
|
||||
"type": "string"
|
||||
|
||||
@@ -143,6 +143,16 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"default_tools_approval_mode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/definitions/AppToolApproval"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"destructive_enabled": {
|
||||
"default": true,
|
||||
"type": "boolean"
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
]
|
||||
},
|
||||
"includeHome": {
|
||||
"description": "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).",
|
||||
"description": "If true, include detection under the user's home directory.",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
|
||||
Generated
+6
@@ -9,6 +9,12 @@
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"errorType": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"failureStage": {
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
Generated
+128
@@ -0,0 +1,128 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"definitions": {
|
||||
"ExternalAgentConfigImportHistory": {
|
||||
"properties": {
|
||||
"completedAtMs": {
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
},
|
||||
"failures": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportItemTypeFailure"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"importId": {
|
||||
"type": "string"
|
||||
},
|
||||
"successes": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportItemTypeSuccess"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"completedAtMs",
|
||||
"failures",
|
||||
"importId",
|
||||
"successes"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportItemTypeFailure": {
|
||||
"properties": {
|
||||
"cwd": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"errorType": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"failureStage": {
|
||||
"type": "string"
|
||||
},
|
||||
"itemType": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigMigrationItemType"
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
},
|
||||
"source": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"failureStage",
|
||||
"itemType",
|
||||
"message"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportItemTypeSuccess": {
|
||||
"properties": {
|
||||
"cwd": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"itemType": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigMigrationItemType"
|
||||
},
|
||||
"source": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"target": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"itemType"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigMigrationItemType": {
|
||||
"enum": [
|
||||
"AGENTS_MD",
|
||||
"CONFIG",
|
||||
"SKILLS",
|
||||
"PLUGINS",
|
||||
"MCP_SERVER_CONFIG",
|
||||
"SUBAGENTS",
|
||||
"HOOKS",
|
||||
"COMMANDS",
|
||||
"SESSIONS"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"data": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportHistory"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"title": "ExternalAgentConfigImportHistoriesReadResponse",
|
||||
"type": "object"
|
||||
}
|
||||
+7
@@ -184,6 +184,13 @@
|
||||
"$ref": "#/definitions/ExternalAgentConfigMigrationItem"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"source": {
|
||||
"description": "Source product that produced the migration items. Missing means unspecified.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
Generated
+127
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"definitions": {
|
||||
"ExternalAgentConfigImportItemTypeFailure": {
|
||||
"properties": {
|
||||
"cwd": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"errorType": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"failureStage": {
|
||||
"type": "string"
|
||||
},
|
||||
"itemType": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigMigrationItemType"
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
},
|
||||
"source": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"failureStage",
|
||||
"itemType",
|
||||
"message"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportItemTypeSuccess": {
|
||||
"properties": {
|
||||
"cwd": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"itemType": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigMigrationItemType"
|
||||
},
|
||||
"source": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"target": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"itemType"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigImportTypeResult": {
|
||||
"properties": {
|
||||
"failures": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportItemTypeFailure"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"itemType": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigMigrationItemType"
|
||||
},
|
||||
"successes": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportItemTypeSuccess"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"failures",
|
||||
"itemType",
|
||||
"successes"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalAgentConfigMigrationItemType": {
|
||||
"enum": [
|
||||
"AGENTS_MD",
|
||||
"CONFIG",
|
||||
"SKILLS",
|
||||
"PLUGINS",
|
||||
"MCP_SERVER_CONFIG",
|
||||
"SUBAGENTS",
|
||||
"HOOKS",
|
||||
"COMMANDS",
|
||||
"SESSIONS"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"importId": {
|
||||
"type": "string"
|
||||
},
|
||||
"itemTypeResults": {
|
||||
"items": {
|
||||
"$ref": "#/definitions/ExternalAgentConfigImportTypeResult"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"importId",
|
||||
"itemTypeResults"
|
||||
],
|
||||
"title": "ExternalAgentConfigImportProgressNotification",
|
||||
"type": "object"
|
||||
}
|
||||
@@ -45,6 +45,14 @@
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"credentialSource": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/AmazonBedrockCredentialSource"
|
||||
}
|
||||
],
|
||||
"default": "awsManaged"
|
||||
},
|
||||
"type": {
|
||||
"enum": [
|
||||
"amazonBedrock"
|
||||
@@ -61,6 +69,13 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"AmazonBedrockCredentialSource": {
|
||||
"enum": [
|
||||
"codexManaged",
|
||||
"awsManaged"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"PlanType": {
|
||||
"enum": [
|
||||
"free",
|
||||
|
||||
Generated
+6
-6
@@ -27,7 +27,7 @@
|
||||
"read": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -37,7 +37,7 @@
|
||||
"write": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -58,9 +58,6 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"ApiPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"AutoReviewDecisionSource": {
|
||||
"description": "[UNSTABLE] Source that produced a terminal approval auto-review decision.",
|
||||
"enum": [
|
||||
@@ -81,7 +78,7 @@
|
||||
{
|
||||
"properties": {
|
||||
"path": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": {
|
||||
"enum": [
|
||||
@@ -536,6 +533,9 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"LegacyAppPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"NetworkApprovalProtocol": {
|
||||
"enum": [
|
||||
"http",
|
||||
|
||||
Generated
+6
-6
@@ -27,7 +27,7 @@
|
||||
"read": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -37,7 +37,7 @@
|
||||
"write": {
|
||||
"description": "This will be removed in favor of `entries`.",
|
||||
"items": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": [
|
||||
"array",
|
||||
@@ -58,9 +58,6 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"ApiPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"FileSystemAccessMode": {
|
||||
"enum": [
|
||||
"read",
|
||||
@@ -74,7 +71,7 @@
|
||||
{
|
||||
"properties": {
|
||||
"path": {
|
||||
"$ref": "#/definitions/ApiPathString"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"type": {
|
||||
"enum": [
|
||||
@@ -529,6 +526,9 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"LegacyAppPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"NetworkApprovalProtocol": {
|
||||
"enum": [
|
||||
"http",
|
||||
|
||||
+6
@@ -1035,6 +1035,12 @@
|
||||
},
|
||||
"ResponseItemMetadata": {
|
||||
"properties": {
|
||||
"source_call_id": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"turn_id": {
|
||||
"type": [
|
||||
"string",
|
||||
|
||||
@@ -1055,6 +1055,14 @@
|
||||
"description": "Usually the first user message in the thread, if available.",
|
||||
"type": "string"
|
||||
},
|
||||
"recencyAt": {
|
||||
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
|
||||
"format": "int64",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sessionId": {
|
||||
"description": "Session id shared by threads that belong to the same session tree.",
|
||||
"type": "string"
|
||||
|
||||
@@ -24,7 +24,8 @@
|
||||
"ThreadSortKey": {
|
||||
"enum": [
|
||||
"created_at",
|
||||
"updated_at"
|
||||
"updated_at",
|
||||
"recency_at"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
|
||||
@@ -870,6 +870,14 @@
|
||||
"description": "Usually the first user message in the thread, if available.",
|
||||
"type": "string"
|
||||
},
|
||||
"recencyAt": {
|
||||
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
|
||||
"format": "int64",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sessionId": {
|
||||
"description": "Session id shared by threads that belong to the same session tree.",
|
||||
"type": "string"
|
||||
|
||||
+8
@@ -870,6 +870,14 @@
|
||||
"description": "Usually the first user message in the thread, if available.",
|
||||
"type": "string"
|
||||
},
|
||||
"recencyAt": {
|
||||
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
|
||||
"format": "int64",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sessionId": {
|
||||
"description": "Session id shared by threads that belong to the same session tree.",
|
||||
"type": "string"
|
||||
|
||||
@@ -870,6 +870,14 @@
|
||||
"description": "Usually the first user message in the thread, if available.",
|
||||
"type": "string"
|
||||
},
|
||||
"recencyAt": {
|
||||
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
|
||||
"format": "int64",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sessionId": {
|
||||
"description": "Session id shared by threads that belong to the same session tree.",
|
||||
"type": "string"
|
||||
|
||||
@@ -1106,6 +1106,12 @@
|
||||
},
|
||||
"ResponseItemMetadata": {
|
||||
"properties": {
|
||||
"source_call_id": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"turn_id": {
|
||||
"type": [
|
||||
"string",
|
||||
|
||||
@@ -1055,6 +1055,14 @@
|
||||
"description": "Usually the first user message in the thread, if available.",
|
||||
"type": "string"
|
||||
},
|
||||
"recencyAt": {
|
||||
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
|
||||
"format": "int64",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sessionId": {
|
||||
"description": "Session id shared by threads that belong to the same session tree.",
|
||||
"type": "string"
|
||||
|
||||
@@ -870,6 +870,14 @@
|
||||
"description": "Usually the first user message in the thread, if available.",
|
||||
"type": "string"
|
||||
},
|
||||
"recencyAt": {
|
||||
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
|
||||
"format": "int64",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sessionId": {
|
||||
"description": "Session id shared by threads that belong to the same session tree.",
|
||||
"type": "string"
|
||||
|
||||
@@ -191,6 +191,9 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"LegacyAppPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"Personality": {
|
||||
"enum": [
|
||||
"none",
|
||||
@@ -242,7 +245,7 @@
|
||||
"TurnEnvironmentParams": {
|
||||
"properties": {
|
||||
"cwd": {
|
||||
"$ref": "#/definitions/AbsolutePathBuf"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"environmentId": {
|
||||
"type": "string"
|
||||
|
||||
@@ -1055,6 +1055,14 @@
|
||||
"description": "Usually the first user message in the thread, if available.",
|
||||
"type": "string"
|
||||
},
|
||||
"recencyAt": {
|
||||
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
|
||||
"format": "int64",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sessionId": {
|
||||
"description": "Session id shared by threads that belong to the same session tree.",
|
||||
"type": "string"
|
||||
|
||||
@@ -870,6 +870,14 @@
|
||||
"description": "Usually the first user message in the thread, if available.",
|
||||
"type": "string"
|
||||
},
|
||||
"recencyAt": {
|
||||
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
|
||||
"format": "int64",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sessionId": {
|
||||
"description": "Session id shared by threads that belong to the same session tree.",
|
||||
"type": "string"
|
||||
|
||||
@@ -870,6 +870,14 @@
|
||||
"description": "Usually the first user message in the thread, if available.",
|
||||
"type": "string"
|
||||
},
|
||||
"recencyAt": {
|
||||
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
|
||||
"format": "int64",
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"sessionId": {
|
||||
"description": "Session id shared by threads that belong to the same session tree.",
|
||||
"type": "string"
|
||||
|
||||
@@ -130,6 +130,9 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"LegacyAppPathString": {
|
||||
"type": "string"
|
||||
},
|
||||
"ModeKind": {
|
||||
"description": "Initial collaboration mode to use when the TUI starts.",
|
||||
"enum": [
|
||||
@@ -331,7 +334,7 @@
|
||||
"TurnEnvironmentParams": {
|
||||
"properties": {
|
||||
"cwd": {
|
||||
"$ref": "#/definitions/AbsolutePathBuf"
|
||||
"$ref": "#/definitions/LegacyAppPathString"
|
||||
},
|
||||
"environmentId": {
|
||||
"type": "string"
|
||||
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
// 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 AmazonBedrockCredentialSource = "codexManaged" | "awsManaged";
|
||||
File diff suppressed because one or more lines are too long
+1
-1
@@ -23,4 +23,4 @@
|
||||
* [`AbsolutePathBuf`]. Relative path text remains valid until an operation
|
||||
* such as [`Self::to_path_uri`] requires an absolute path.
|
||||
*/
|
||||
export type ApiPathString = string;
|
||||
export type LegacyAppPathString = string;
|
||||
@@ -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 ResponseItemMetadata = { turn_id?: string, };
|
||||
export type ResponseItemMetadata = { turn_id?: string, source_call_id?: string, };
|
||||
|
||||
File diff suppressed because one or more lines are too long
+2
-1
@@ -3,7 +3,7 @@
|
||||
export type { AbsolutePathBuf } from "./AbsolutePathBuf";
|
||||
export type { AgentMessageInputContent } from "./AgentMessageInputContent";
|
||||
export type { AgentPath } from "./AgentPath";
|
||||
export type { ApiPathString } from "./ApiPathString";
|
||||
export type { AmazonBedrockCredentialSource } from "./AmazonBedrockCredentialSource";
|
||||
export type { ApplyPatchApprovalParams } from "./ApplyPatchApprovalParams";
|
||||
export type { ApplyPatchApprovalResponse } from "./ApplyPatchApprovalResponse";
|
||||
export type { AuthMode } from "./AuthMode";
|
||||
@@ -42,6 +42,7 @@ export type { InitializeParams } from "./InitializeParams";
|
||||
export type { InitializeResponse } from "./InitializeResponse";
|
||||
export type { InputModality } from "./InputModality";
|
||||
export type { InternalSessionSource } from "./InternalSessionSource";
|
||||
export type { LegacyAppPathString } from "./LegacyAppPathString";
|
||||
export type { LocalShellAction } from "./LocalShellAction";
|
||||
export type { LocalShellExecAction } from "./LocalShellExecAction";
|
||||
export type { LocalShellStatus } from "./LocalShellStatus";
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { AmazonBedrockCredentialSource } from "../AmazonBedrockCredentialSource";
|
||||
import type { PlanType } from "../PlanType";
|
||||
|
||||
export type Account = { "type": "apiKey", } | { "type": "chatgpt", email: string, planType: PlanType, } | { "type": "amazonBedrock", };
|
||||
export type Account = { "type": "apiKey", } | { "type": "chatgpt", email: string, planType: PlanType, } | { "type": "amazonBedrock", credentialSource: AmazonBedrockCredentialSource, };
|
||||
|
||||
+3
-3
@@ -1,15 +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.
|
||||
import type { ApiPathString } from "../ApiPathString";
|
||||
import type { LegacyAppPathString } from "../LegacyAppPathString";
|
||||
import type { FileSystemSandboxEntry } from "./FileSystemSandboxEntry";
|
||||
|
||||
export type AdditionalFileSystemPermissions = {
|
||||
/**
|
||||
* This will be removed in favor of `entries`.
|
||||
*/
|
||||
read: Array<ApiPathString> | null,
|
||||
read: Array<LegacyAppPathString> | null,
|
||||
/**
|
||||
* This will be removed in favor of `entries`.
|
||||
*/
|
||||
write: Array<ApiPathString> | null, globScanMaxDepth?: number, entries?: Array<FileSystemSandboxEntry>, };
|
||||
write: Array<LegacyAppPathString> | null, globScanMaxDepth?: number, entries?: Array<FileSystemSandboxEntry>, };
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { AppToolApproval } from "./AppToolApproval";
|
||||
import type { ApprovalsReviewer } from "./ApprovalsReviewer";
|
||||
|
||||
export type AppsDefaultConfig = { enabled: boolean, approvals_reviewer: ApprovalsReviewer | null, destructive_enabled: boolean, open_world_enabled: boolean, };
|
||||
export type AppsDefaultConfig = { enabled: boolean, approvals_reviewer: ApprovalsReviewer | null, destructive_enabled: boolean, open_world_enabled: boolean, default_tools_approval_mode: AppToolApproval | null, };
|
||||
|
||||
Generated
+3
@@ -20,6 +20,9 @@ startedAtMs: number, /**
|
||||
* (a UUID) used to disambiguate routing.
|
||||
*/
|
||||
approvalId?: string | null, /**
|
||||
* Environment in which the command will run.
|
||||
*/
|
||||
environmentId: string | null, /**
|
||||
* Optional explanatory reason (e.g. request for network access).
|
||||
*/
|
||||
reason?: string | null, /**
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
|
||||
export type ExternalAgentConfigDetectParams = {
|
||||
/**
|
||||
* If true, include detection under the user's home (~/.claude, ~/.codex, etc.).
|
||||
* If true, include detection under the user's home directory.
|
||||
*/
|
||||
includeHome?: boolean,
|
||||
/**
|
||||
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { ExternalAgentConfigImportHistory } from "./ExternalAgentConfigImportHistory";
|
||||
|
||||
export type ExternalAgentConfigImportHistoriesReadResponse = { data: Array<ExternalAgentConfigImportHistory>, };
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { ExternalAgentConfigImportItemTypeFailure } from "./ExternalAgentConfigImportItemTypeFailure";
|
||||
import type { ExternalAgentConfigImportItemTypeSuccess } from "./ExternalAgentConfigImportItemTypeSuccess";
|
||||
|
||||
export type ExternalAgentConfigImportHistory = { importId: string, completedAtMs: bigint, successes: Array<ExternalAgentConfigImportItemTypeSuccess>, failures: Array<ExternalAgentConfigImportItemTypeFailure>, };
|
||||
Generated
+1
-1
@@ -3,4 +3,4 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { ExternalAgentConfigMigrationItemType } from "./ExternalAgentConfigMigrationItemType";
|
||||
|
||||
export type ExternalAgentConfigImportItemTypeFailure = { itemType: ExternalAgentConfigMigrationItemType, failureStage: string, message: string, cwd: string | null, source: string | null, };
|
||||
export type ExternalAgentConfigImportItemTypeFailure = { itemType: ExternalAgentConfigMigrationItemType, errorType: string | null, failureStage: string, message: string, cwd: string | null, source: string | null, };
|
||||
|
||||
+5
-1
@@ -3,4 +3,8 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { ExternalAgentConfigMigrationItem } from "./ExternalAgentConfigMigrationItem";
|
||||
|
||||
export type ExternalAgentConfigImportParams = { migrationItems: Array<ExternalAgentConfigMigrationItem>, };
|
||||
export type ExternalAgentConfigImportParams = { migrationItems: Array<ExternalAgentConfigMigrationItem>,
|
||||
/**
|
||||
* Source product that produced the migration items. Missing means unspecified.
|
||||
*/
|
||||
source?: string | null, };
|
||||
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { ExternalAgentConfigImportTypeResult } from "./ExternalAgentConfigImportTypeResult";
|
||||
|
||||
export type ExternalAgentConfigImportProgressNotification = { importId: string, itemTypeResults: Array<ExternalAgentConfigImportTypeResult>, };
|
||||
@@ -1,7 +1,7 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { ApiPathString } from "../ApiPathString";
|
||||
import type { LegacyAppPathString } from "../LegacyAppPathString";
|
||||
import type { FileSystemSpecialPath } from "./FileSystemSpecialPath";
|
||||
|
||||
export type FileSystemPath = { "type": "path", path: ApiPathString, } | { "type": "glob_pattern", pattern: string, } | { "type": "special", value: FileSystemSpecialPath, };
|
||||
export type FileSystemPath = { "type": "path", path: LegacyAppPathString, } | { "type": "glob_pattern", pattern: string, } | { "type": "special", value: FileSystemSpecialPath, };
|
||||
|
||||
@@ -41,6 +41,10 @@ createdAt: number,
|
||||
* Unix timestamp (in seconds) when the thread was last updated.
|
||||
*/
|
||||
updatedAt: number,
|
||||
/**
|
||||
* Unix timestamp (in seconds) used for thread recency ordering.
|
||||
*/
|
||||
recencyAt: number | null,
|
||||
/**
|
||||
* Current runtime status for the thread.
|
||||
*/
|
||||
|
||||
@@ -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 ThreadSortKey = "created_at" | "updated_at";
|
||||
export type ThreadSortKey = "created_at" | "updated_at" | "recency_at";
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { AbsolutePathBuf } from "../AbsolutePathBuf";
|
||||
import type { LegacyAppPathString } from "../LegacyAppPathString";
|
||||
|
||||
export type TurnEnvironmentParams = { environmentId: string, cwd: AbsolutePathBuf, };
|
||||
export type TurnEnvironmentParams = { environmentId: string, cwd: LegacyAppPathString, };
|
||||
|
||||
@@ -110,9 +110,12 @@ export type { ExperimentalFeatureStage } from "./ExperimentalFeatureStage";
|
||||
export type { ExternalAgentConfigDetectParams } from "./ExternalAgentConfigDetectParams";
|
||||
export type { ExternalAgentConfigDetectResponse } from "./ExternalAgentConfigDetectResponse";
|
||||
export type { ExternalAgentConfigImportCompletedNotification } from "./ExternalAgentConfigImportCompletedNotification";
|
||||
export type { ExternalAgentConfigImportHistoriesReadResponse } from "./ExternalAgentConfigImportHistoriesReadResponse";
|
||||
export type { ExternalAgentConfigImportHistory } from "./ExternalAgentConfigImportHistory";
|
||||
export type { ExternalAgentConfigImportItemTypeFailure } from "./ExternalAgentConfigImportItemTypeFailure";
|
||||
export type { ExternalAgentConfigImportItemTypeSuccess } from "./ExternalAgentConfigImportItemTypeSuccess";
|
||||
export type { ExternalAgentConfigImportParams } from "./ExternalAgentConfigImportParams";
|
||||
export type { ExternalAgentConfigImportProgressNotification } from "./ExternalAgentConfigImportProgressNotification";
|
||||
export type { ExternalAgentConfigImportResponse } from "./ExternalAgentConfigImportResponse";
|
||||
export type { ExternalAgentConfigImportTypeResult } from "./ExternalAgentConfigImportTypeResult";
|
||||
export type { ExternalAgentConfigMigrationItem } from "./ExternalAgentConfigMigrationItem";
|
||||
|
||||
@@ -1103,6 +1103,11 @@ client_request_definitions! {
|
||||
serialization: global("config"),
|
||||
response: v2::ExternalAgentConfigImportResponse,
|
||||
},
|
||||
ExternalAgentConfigImportHistoriesRead => "externalAgentConfig/import/readHistories" {
|
||||
params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
|
||||
serialization: global_shared_read("config"),
|
||||
response: v2::ExternalAgentConfigImportHistoriesReadResponse,
|
||||
},
|
||||
ConfigValueWrite => "config/value/write" {
|
||||
params: v2::ConfigValueWriteParams,
|
||||
serialization: global("config"),
|
||||
@@ -1614,6 +1619,7 @@ server_notification_definitions! {
|
||||
AccountRateLimitsUpdated => "account/rateLimits/updated" (v2::AccountRateLimitsUpdatedNotification),
|
||||
AppListUpdated => "app/list/updated" (v2::AppListUpdatedNotification),
|
||||
RemoteControlStatusChanged => "remoteControl/status/changed" (v2::RemoteControlStatusChangedNotification),
|
||||
ExternalAgentConfigImportProgress => "externalAgentConfig/import/progress" (v2::ExternalAgentConfigImportProgressNotification),
|
||||
ExternalAgentConfigImportCompleted => "externalAgentConfig/import/completed" (v2::ExternalAgentConfigImportCompletedNotification),
|
||||
FsChanged => "fs/changed" (v2::FsChangedNotification),
|
||||
ReasoningSummaryTextDelta => "item/reasoning/summaryTextDelta" (v2::ReasoningSummaryTextDeltaNotification),
|
||||
@@ -1668,6 +1674,7 @@ mod tests {
|
||||
use super::*;
|
||||
use anyhow::Result;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::account::AmazonBedrockCredentialSource;
|
||||
use codex_protocol::account::PlanType;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_READ_ONLY;
|
||||
use codex_protocol::parse_command::ParsedCommand;
|
||||
@@ -2494,6 +2501,7 @@ mod tests {
|
||||
model_provider: "openai".to_string(),
|
||||
created_at: 1,
|
||||
updated_at: 2,
|
||||
recency_at: Some(3),
|
||||
status: v2::ThreadStatus::Idle,
|
||||
path: None,
|
||||
cwd: cwd.clone(),
|
||||
@@ -2537,6 +2545,7 @@ mod tests {
|
||||
"modelProvider": "openai",
|
||||
"createdAt": 1,
|
||||
"updatedAt": 2,
|
||||
"recencyAt": 3,
|
||||
"status": {
|
||||
"type": "idle"
|
||||
},
|
||||
@@ -2771,6 +2780,41 @@ mod tests {
|
||||
serde_json::to_value(&chatgpt)?,
|
||||
);
|
||||
|
||||
let codex_managed_bedrock = v2::Account::AmazonBedrock {
|
||||
credential_source: AmazonBedrockCredentialSource::CodexManaged,
|
||||
};
|
||||
assert_eq!(
|
||||
json!({
|
||||
"type": "amazonBedrock",
|
||||
"credentialSource": "codexManaged",
|
||||
}),
|
||||
serde_json::to_value(&codex_managed_bedrock)?,
|
||||
);
|
||||
|
||||
let aws_managed_bedrock = v2::Account::AmazonBedrock {
|
||||
credential_source: AmazonBedrockCredentialSource::AwsManaged,
|
||||
};
|
||||
assert_eq!(
|
||||
json!({
|
||||
"type": "amazonBedrock",
|
||||
"credentialSource": "awsManaged",
|
||||
}),
|
||||
serde_json::to_value(&aws_managed_bedrock)?,
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_defaults_legacy_bedrock_credential_source() -> Result<()> {
|
||||
assert_eq!(
|
||||
v2::Account::AmazonBedrock {
|
||||
credential_source: AmazonBedrockCredentialSource::AwsManaged,
|
||||
},
|
||||
serde_json::from_value(json!({
|
||||
"type": "amazonBedrock",
|
||||
}))?,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -3496,6 +3540,7 @@ mod tests {
|
||||
item_id: "call_123".to_string(),
|
||||
started_at_ms: 0,
|
||||
approval_id: None,
|
||||
environment_id: None,
|
||||
reason: None,
|
||||
network_approval_context: None,
|
||||
command: Some("cat file".to_string()),
|
||||
|
||||
@@ -83,12 +83,154 @@ pub fn build_turns_from_rollout_items(items: &[RolloutItem]) -> Vec<Turn> {
|
||||
builder.finish()
|
||||
}
|
||||
|
||||
/// A materialized `ThreadItem` snapshot that changed while handling one input.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ThreadHistoryItemChange {
|
||||
pub turn_id: String,
|
||||
pub item: ThreadItem,
|
||||
}
|
||||
|
||||
/// Lightweight turn metadata snapshot for projectors that track turn status without
|
||||
/// re-reading the full item list.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ThreadHistoryTurnChange {
|
||||
pub turn_id: String,
|
||||
pub status: TurnStatus,
|
||||
pub error: Option<TurnError>,
|
||||
pub started_at: Option<i64>,
|
||||
pub completed_at: Option<i64>,
|
||||
pub duration_ms: Option<i64>,
|
||||
}
|
||||
|
||||
/// Incremental changes produced by opt-in `ThreadHistoryBuilder` handlers.
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct ThreadHistoryChangeSet {
|
||||
pub changed_items: Vec<ThreadHistoryItemChange>,
|
||||
pub changed_turns: Vec<ThreadHistoryTurnChange>,
|
||||
pub removed_turn_ids: Vec<String>,
|
||||
}
|
||||
|
||||
impl ThreadHistoryChangeSet {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.changed_items.is_empty()
|
||||
&& self.changed_turns.is_empty()
|
||||
&& self.removed_turn_ids.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadHistoryTurnChange {
|
||||
fn from_pending_turn(turn: &PendingTurn) -> Self {
|
||||
Self {
|
||||
turn_id: turn.id.clone(),
|
||||
status: turn.status.clone(),
|
||||
error: turn.error.clone(),
|
||||
started_at: turn.started_at,
|
||||
completed_at: turn.completed_at,
|
||||
duration_ms: turn.duration_ms,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_turn(turn: &Turn) -> Self {
|
||||
Self {
|
||||
turn_id: turn.id.clone(),
|
||||
status: turn.status.clone(),
|
||||
error: turn.error.clone(),
|
||||
started_at: turn.started_at,
|
||||
completed_at: turn.completed_at,
|
||||
duration_ms: turn.duration_ms,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Coalesces per-rollout-item changes into an end-of-batch view. It preserves
|
||||
/// first-change order while replacing repeated item/turn snapshots with their
|
||||
/// latest value, and drops accumulated changes for turns removed by rollback.
|
||||
#[derive(Default)]
|
||||
struct ThreadHistoryChangeAccumulator {
|
||||
changed_items: Vec<Option<ThreadHistoryItemChange>>,
|
||||
changed_item_indexes: HashMap<(String, String), usize>,
|
||||
changed_turns: Vec<Option<ThreadHistoryTurnChange>>,
|
||||
changed_turn_indexes: HashMap<String, usize>,
|
||||
removed_turn_ids: Vec<String>,
|
||||
removed_turn_indexes: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl ThreadHistoryChangeAccumulator {
|
||||
fn push(&mut self, changes: ThreadHistoryChangeSet) {
|
||||
for turn_id in changes.removed_turn_ids {
|
||||
self.push_removed_turn_id(turn_id);
|
||||
}
|
||||
for item_change in changes.changed_items {
|
||||
self.push_item_change(item_change);
|
||||
}
|
||||
for turn_change in changes.changed_turns {
|
||||
self.push_turn_change(turn_change);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self) -> ThreadHistoryChangeSet {
|
||||
ThreadHistoryChangeSet {
|
||||
changed_items: self.changed_items.into_iter().flatten().collect(),
|
||||
changed_turns: self.changed_turns.into_iter().flatten().collect(),
|
||||
removed_turn_ids: self.removed_turn_ids,
|
||||
}
|
||||
}
|
||||
|
||||
fn push_item_change(&mut self, change: ThreadHistoryItemChange) {
|
||||
let key = (change.turn_id.clone(), change.item.id().to_string());
|
||||
if let Some(index) = self.changed_item_indexes.get(&key).copied() {
|
||||
self.changed_items[index] = Some(change);
|
||||
return;
|
||||
}
|
||||
|
||||
self.changed_item_indexes
|
||||
.insert(key, self.changed_items.len());
|
||||
self.changed_items.push(Some(change));
|
||||
}
|
||||
|
||||
fn push_turn_change(&mut self, change: ThreadHistoryTurnChange) {
|
||||
if let Some(index) = self.changed_turn_indexes.get(&change.turn_id).copied() {
|
||||
self.changed_turns[index] = Some(change);
|
||||
return;
|
||||
}
|
||||
|
||||
self.changed_turn_indexes
|
||||
.insert(change.turn_id.clone(), self.changed_turns.len());
|
||||
self.changed_turns.push(Some(change));
|
||||
}
|
||||
|
||||
fn push_removed_turn_id(&mut self, turn_id: String) {
|
||||
if !self.removed_turn_indexes.contains_key(&turn_id) {
|
||||
self.removed_turn_indexes
|
||||
.insert(turn_id.clone(), self.removed_turn_ids.len());
|
||||
self.removed_turn_ids.push(turn_id.clone());
|
||||
}
|
||||
|
||||
if let Some(index) = self.changed_turn_indexes.remove(&turn_id) {
|
||||
self.changed_turns[index] = None;
|
||||
}
|
||||
|
||||
let removed_item_keys: Vec<(String, String)> = self
|
||||
.changed_item_indexes
|
||||
.keys()
|
||||
.filter(|(item_turn_id, _)| item_turn_id == &turn_id)
|
||||
.cloned()
|
||||
.collect();
|
||||
for key in removed_item_keys {
|
||||
if let Some(index) = self.changed_item_indexes.remove(&key) {
|
||||
self.changed_items[index] = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ThreadHistoryBuilder {
|
||||
turns: Vec<Turn>,
|
||||
current_turn: Option<PendingTurn>,
|
||||
next_item_index: i64,
|
||||
current_rollout_index: usize,
|
||||
next_rollout_index: usize,
|
||||
active_change_set: Option<ThreadHistoryChangeSet>,
|
||||
}
|
||||
|
||||
impl Default for ThreadHistoryBuilder {
|
||||
@@ -105,6 +247,7 @@ impl ThreadHistoryBuilder {
|
||||
next_item_index: 1,
|
||||
current_rollout_index: 0,
|
||||
next_rollout_index: 0,
|
||||
active_change_set: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,6 +390,42 @@ impl ThreadHistoryBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles one event and returns the materialized items or turn metadata
|
||||
/// changed by that event.
|
||||
pub fn handle_event_with_changes(&mut self, event: &EventMsg) -> ThreadHistoryChangeSet {
|
||||
self.collect_changes(|builder| builder.handle_event(event))
|
||||
}
|
||||
|
||||
/// Handles a rollout item and returns the materialized items or turn metadata
|
||||
/// changed by that one append.
|
||||
pub fn handle_rollout_item_with_changes(
|
||||
&mut self,
|
||||
item: &RolloutItem,
|
||||
) -> ThreadHistoryChangeSet {
|
||||
self.collect_changes(|builder| builder.handle_rollout_item(item))
|
||||
}
|
||||
|
||||
/// Handles rollout items in order and returns a coalesced end-of-batch
|
||||
/// change set. Multiple changes to the same item or turn are deduplicated
|
||||
/// so only the latest snapshot is emitted.
|
||||
pub fn handle_rollout_items_with_changes(
|
||||
&mut self,
|
||||
items: &[RolloutItem],
|
||||
) -> ThreadHistoryChangeSet {
|
||||
let mut accumulator = ThreadHistoryChangeAccumulator::default();
|
||||
for item in items {
|
||||
accumulator.push(self.handle_rollout_item_with_changes(item));
|
||||
}
|
||||
accumulator.finish()
|
||||
}
|
||||
|
||||
fn collect_changes(&mut self, handle: impl FnOnce(&mut Self)) -> ThreadHistoryChangeSet {
|
||||
debug_assert!(self.active_change_set.is_none());
|
||||
self.active_change_set = Some(ThreadHistoryChangeSet::default());
|
||||
handle(self);
|
||||
self.active_change_set.take().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn handle_response_item(&mut self, item: &codex_protocol::models::ResponseItem) {
|
||||
let codex_protocol::models::ResponseItem::Message {
|
||||
role, content, id, ..
|
||||
@@ -263,7 +442,7 @@ impl ThreadHistoryBuilder {
|
||||
return;
|
||||
};
|
||||
|
||||
self.ensure_turn().items.push(ThreadItem::HookPrompt {
|
||||
self.push_item_in_current_turn(ThreadItem::HookPrompt {
|
||||
id: hook_prompt.id,
|
||||
fragments: hook_prompt
|
||||
.fragments
|
||||
@@ -283,18 +462,13 @@ impl ThreadHistoryBuilder {
|
||||
{
|
||||
self.finish_current_turn();
|
||||
}
|
||||
let mut turn = self
|
||||
.current_turn
|
||||
.take()
|
||||
.unwrap_or_else(|| self.new_turn(/*id*/ None));
|
||||
let id = self.next_item_id();
|
||||
let content = self.build_user_inputs(payload);
|
||||
turn.items.push(ThreadItem::UserMessage {
|
||||
self.push_item_in_current_turn(ThreadItem::UserMessage {
|
||||
id,
|
||||
client_id: payload.client_id.clone(),
|
||||
content,
|
||||
});
|
||||
self.current_turn = Some(turn);
|
||||
}
|
||||
|
||||
fn handle_agent_message(
|
||||
@@ -308,7 +482,7 @@ impl ThreadHistoryBuilder {
|
||||
}
|
||||
|
||||
let id = self.next_item_id();
|
||||
self.ensure_turn().items.push(ThreadItem::AgentMessage {
|
||||
self.push_item_in_current_turn(ThreadItem::AgentMessage {
|
||||
id,
|
||||
text,
|
||||
phase,
|
||||
@@ -322,14 +496,34 @@ impl ThreadHistoryBuilder {
|
||||
}
|
||||
|
||||
// If the last item is a reasoning item, add the new text to the summary.
|
||||
if let Some(ThreadItem::Reasoning { summary, .. }) = self.ensure_turn().items.last_mut() {
|
||||
summary.push(payload.text.clone());
|
||||
let existing_item_change = {
|
||||
let tracking_changes = self.is_tracking_changes();
|
||||
let turn = self.ensure_turn();
|
||||
if let Some(ThreadItem::Reasoning { summary, .. }) = turn.items.last_mut() {
|
||||
summary.push(payload.text.clone());
|
||||
let changed_item = if tracking_changes {
|
||||
turn.items
|
||||
.last()
|
||||
.cloned()
|
||||
.map(|item| (turn.id.clone(), item))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(changed_item)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(changed_item) = existing_item_change {
|
||||
if let Some((turn_id, item)) = changed_item {
|
||||
self.record_changed_item(turn_id, item);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, create a new reasoning item.
|
||||
let id = self.next_item_id();
|
||||
self.ensure_turn().items.push(ThreadItem::Reasoning {
|
||||
self.push_item_in_current_turn(ThreadItem::Reasoning {
|
||||
id,
|
||||
summary: vec![payload.text.clone()],
|
||||
content: Vec::new(),
|
||||
@@ -342,14 +536,34 @@ impl ThreadHistoryBuilder {
|
||||
}
|
||||
|
||||
// If the last item is a reasoning item, add the new text to the content.
|
||||
if let Some(ThreadItem::Reasoning { content, .. }) = self.ensure_turn().items.last_mut() {
|
||||
content.push(payload.text.clone());
|
||||
let existing_item_change = {
|
||||
let tracking_changes = self.is_tracking_changes();
|
||||
let turn = self.ensure_turn();
|
||||
if let Some(ThreadItem::Reasoning { content, .. }) = turn.items.last_mut() {
|
||||
content.push(payload.text.clone());
|
||||
let changed_item = if tracking_changes {
|
||||
turn.items
|
||||
.last()
|
||||
.cloned()
|
||||
.map(|item| (turn.id.clone(), item))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(changed_item)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(changed_item) = existing_item_change {
|
||||
if let Some((turn_id, item)) = changed_item {
|
||||
self.record_changed_item(turn_id, item);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, create a new reasoning item.
|
||||
let id = self.next_item_id();
|
||||
self.ensure_turn().items.push(ThreadItem::Reasoning {
|
||||
self.push_item_in_current_turn(ThreadItem::Reasoning {
|
||||
id,
|
||||
summary: Vec::new(),
|
||||
content: vec![payload.text.clone()],
|
||||
@@ -884,9 +1098,7 @@ impl ThreadHistoryBuilder {
|
||||
|
||||
fn handle_context_compacted(&mut self, _payload: &ContextCompactedEvent) {
|
||||
let id = self.next_item_id();
|
||||
self.ensure_turn()
|
||||
.items
|
||||
.push(ThreadItem::ContextCompaction { id });
|
||||
self.push_item_in_current_turn(ThreadItem::ContextCompaction { id });
|
||||
}
|
||||
|
||||
fn handle_entered_review_mode(&mut self, payload: &codex_protocol::protocol::ReviewRequest) {
|
||||
@@ -895,9 +1107,7 @@ impl ThreadHistoryBuilder {
|
||||
.clone()
|
||||
.unwrap_or_else(|| "Review requested.".to_string());
|
||||
let id = self.next_item_id();
|
||||
self.ensure_turn()
|
||||
.items
|
||||
.push(ThreadItem::EnteredReviewMode { id, review });
|
||||
self.push_item_in_current_turn(ThreadItem::EnteredReviewMode { id, review });
|
||||
}
|
||||
|
||||
fn handle_exited_review_mode(
|
||||
@@ -910,24 +1120,28 @@ impl ThreadHistoryBuilder {
|
||||
.map(render_review_output_text)
|
||||
.unwrap_or_else(|| REVIEW_FALLBACK_MESSAGE.to_string());
|
||||
let id = self.next_item_id();
|
||||
self.ensure_turn()
|
||||
.items
|
||||
.push(ThreadItem::ExitedReviewMode { id, review });
|
||||
self.push_item_in_current_turn(ThreadItem::ExitedReviewMode { id, review });
|
||||
}
|
||||
|
||||
fn handle_error(&mut self, payload: &ErrorEvent) {
|
||||
if !payload.affects_turn_status() {
|
||||
return;
|
||||
}
|
||||
let Some(turn) = self.current_turn.as_mut() else {
|
||||
return;
|
||||
let tracking_changes = self.is_tracking_changes();
|
||||
let changed_turn = if let Some(turn) = self.current_turn.as_mut() {
|
||||
turn.status = TurnStatus::Failed;
|
||||
turn.error = Some(V2TurnError {
|
||||
message: payload.message.clone(),
|
||||
codex_error_info: payload.codex_error_info.clone().map(Into::into),
|
||||
additional_details: None,
|
||||
});
|
||||
tracking_changes.then(|| ThreadHistoryTurnChange::from_pending_turn(turn))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
turn.status = TurnStatus::Failed;
|
||||
turn.error = Some(V2TurnError {
|
||||
message: payload.message.clone(),
|
||||
codex_error_info: payload.codex_error_info.clone().map(Into::into),
|
||||
additional_details: None,
|
||||
});
|
||||
if let Some(changed_turn) = changed_turn {
|
||||
self.record_changed_turn(changed_turn);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_turn_aborted(&mut self, payload: &TurnAbortedEvent) {
|
||||
@@ -935,11 +1149,13 @@ impl ThreadHistoryBuilder {
|
||||
turn.status = TurnStatus::Interrupted;
|
||||
turn.completed_at = payload.completed_at;
|
||||
turn.duration_ms = payload.duration_ms;
|
||||
ThreadHistoryTurnChange::from_pending_turn(turn)
|
||||
};
|
||||
if let Some(turn_id) = payload.turn_id.as_deref() {
|
||||
// Prefer an exact ID match so we interrupt the turn explicitly targeted by the event.
|
||||
if let Some(turn) = self.current_turn.as_mut().filter(|turn| turn.id == turn_id) {
|
||||
apply_abort(turn);
|
||||
let changed_turn = apply_abort(turn);
|
||||
self.record_changed_turn(changed_turn);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -947,24 +1163,28 @@ impl ThreadHistoryBuilder {
|
||||
turn.status = TurnStatus::Interrupted;
|
||||
turn.completed_at = payload.completed_at;
|
||||
turn.duration_ms = payload.duration_ms;
|
||||
let changed_turn = ThreadHistoryTurnChange::from_turn(turn);
|
||||
self.record_changed_turn(changed_turn);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// If the event has no ID (or refers to an unknown turn), fall back to the active turn.
|
||||
if let Some(turn) = self.current_turn.as_mut() {
|
||||
apply_abort(turn);
|
||||
let changed_turn = apply_abort(turn);
|
||||
self.record_changed_turn(changed_turn);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_turn_started(&mut self, payload: &TurnStartedEvent) {
|
||||
self.finish_current_turn();
|
||||
self.current_turn = Some(
|
||||
self.new_turn(Some(payload.turn_id.clone()))
|
||||
.with_status(TurnStatus::InProgress)
|
||||
.with_started_at(payload.started_at)
|
||||
.opened_explicitly(),
|
||||
);
|
||||
let turn = self
|
||||
.new_turn(Some(payload.turn_id.clone()))
|
||||
.with_status(TurnStatus::InProgress)
|
||||
.with_started_at(payload.started_at)
|
||||
.opened_explicitly();
|
||||
self.record_changed_pending_turn(&turn);
|
||||
self.current_turn = Some(turn);
|
||||
}
|
||||
|
||||
fn handle_turn_complete(&mut self, payload: &TurnCompleteEvent) {
|
||||
@@ -974,6 +1194,7 @@ impl ThreadHistoryBuilder {
|
||||
}
|
||||
turn.completed_at = payload.completed_at;
|
||||
turn.duration_ms = payload.duration_ms;
|
||||
ThreadHistoryTurnChange::from_pending_turn(turn)
|
||||
};
|
||||
|
||||
// Prefer an exact ID match from the active turn and then close it.
|
||||
@@ -982,7 +1203,8 @@ impl ThreadHistoryBuilder {
|
||||
.as_mut()
|
||||
.filter(|turn| turn.id == payload.turn_id)
|
||||
{
|
||||
mark_completed(current_turn);
|
||||
let changed_turn = mark_completed(current_turn);
|
||||
self.record_changed_turn(changed_turn);
|
||||
self.finish_current_turn();
|
||||
return;
|
||||
}
|
||||
@@ -997,12 +1219,15 @@ impl ThreadHistoryBuilder {
|
||||
}
|
||||
turn.completed_at = payload.completed_at;
|
||||
turn.duration_ms = payload.duration_ms;
|
||||
let changed_turn = ThreadHistoryTurnChange::from_turn(turn);
|
||||
self.record_changed_turn(changed_turn);
|
||||
return;
|
||||
}
|
||||
|
||||
// If the completion event cannot be matched, apply it to the active turn.
|
||||
if let Some(current_turn) = self.current_turn.as_mut() {
|
||||
mark_completed(current_turn);
|
||||
let changed_turn = mark_completed(current_turn);
|
||||
self.record_changed_turn(changed_turn);
|
||||
self.finish_current_turn();
|
||||
}
|
||||
}
|
||||
@@ -1020,6 +1245,18 @@ impl ThreadHistoryBuilder {
|
||||
self.finish_current_turn();
|
||||
|
||||
let n = usize::try_from(payload.num_turns).unwrap_or(usize::MAX);
|
||||
let removed_turn_ids = if n >= self.turns.len() {
|
||||
self.turns.iter().map(|turn| turn.id.clone()).collect()
|
||||
} else if n == 0 {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.turns[self.turns.len() - n..]
|
||||
.iter()
|
||||
.map(|turn| turn.id.clone())
|
||||
.collect()
|
||||
};
|
||||
self.record_removed_turn_ids(removed_turn_ids);
|
||||
|
||||
if n >= self.turns.len() {
|
||||
self.turns.clear();
|
||||
} else {
|
||||
@@ -1064,7 +1301,8 @@ impl ThreadHistoryBuilder {
|
||||
fn ensure_turn(&mut self) -> &mut PendingTurn {
|
||||
if self.current_turn.is_none() {
|
||||
let turn = self.new_turn(/*id*/ None);
|
||||
return self.current_turn.insert(turn);
|
||||
self.record_changed_pending_turn(&turn);
|
||||
self.current_turn = Some(turn);
|
||||
}
|
||||
|
||||
if let Some(turn) = self.current_turn.as_mut() {
|
||||
@@ -1074,16 +1312,42 @@ impl ThreadHistoryBuilder {
|
||||
unreachable!("current turn must exist after initialization");
|
||||
}
|
||||
|
||||
fn push_item_in_current_turn(&mut self, item: ThreadItem) {
|
||||
let tracking_changes = self.is_tracking_changes();
|
||||
let changed_item = {
|
||||
let turn = self.ensure_turn();
|
||||
let changed_item = tracking_changes.then(|| (turn.id.clone(), item.clone()));
|
||||
turn.items.push(item);
|
||||
changed_item
|
||||
};
|
||||
if let Some((turn_id, item)) = changed_item {
|
||||
self.record_changed_item(turn_id, item);
|
||||
}
|
||||
}
|
||||
|
||||
fn upsert_item_in_turn_id(&mut self, turn_id: &str, item: ThreadItem) {
|
||||
let tracking_changes = self.is_tracking_changes();
|
||||
if let Some(turn) = self.current_turn.as_mut()
|
||||
&& turn.id == turn_id
|
||||
{
|
||||
upsert_turn_item(&mut turn.items, item);
|
||||
let changed_item = {
|
||||
let item = upsert_turn_item(&mut turn.items, item);
|
||||
tracking_changes.then(|| (turn.id.clone(), item.clone()))
|
||||
};
|
||||
if let Some((turn_id, item)) = changed_item {
|
||||
self.record_changed_item(turn_id, item);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(turn) = self.turns.iter_mut().find(|turn| turn.id == turn_id) {
|
||||
upsert_turn_item(&mut turn.items, item);
|
||||
let changed_item = {
|
||||
let item = upsert_turn_item(&mut turn.items, item);
|
||||
tracking_changes.then(|| (turn.id.clone(), item.clone()))
|
||||
};
|
||||
if let Some((turn_id, item)) = changed_item {
|
||||
self.record_changed_item(turn_id, item);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1094,8 +1358,45 @@ impl ThreadHistoryBuilder {
|
||||
}
|
||||
|
||||
fn upsert_item_in_current_turn(&mut self, item: ThreadItem) {
|
||||
let turn = self.ensure_turn();
|
||||
upsert_turn_item(&mut turn.items, item);
|
||||
let tracking_changes = self.is_tracking_changes();
|
||||
let changed_item = {
|
||||
let turn = self.ensure_turn();
|
||||
let item = upsert_turn_item(&mut turn.items, item);
|
||||
tracking_changes.then(|| (turn.id.clone(), item.clone()))
|
||||
};
|
||||
if let Some((turn_id, item)) = changed_item {
|
||||
self.record_changed_item(turn_id, item);
|
||||
}
|
||||
}
|
||||
|
||||
fn is_tracking_changes(&self) -> bool {
|
||||
self.active_change_set.is_some()
|
||||
}
|
||||
|
||||
fn record_changed_item(&mut self, turn_id: String, item: ThreadItem) {
|
||||
if let Some(change_set) = self.active_change_set.as_mut() {
|
||||
change_set
|
||||
.changed_items
|
||||
.push(ThreadHistoryItemChange { turn_id, item });
|
||||
}
|
||||
}
|
||||
|
||||
fn record_changed_pending_turn(&mut self, turn: &PendingTurn) {
|
||||
if self.is_tracking_changes() {
|
||||
self.record_changed_turn(ThreadHistoryTurnChange::from_pending_turn(turn));
|
||||
}
|
||||
}
|
||||
|
||||
fn record_changed_turn(&mut self, turn: ThreadHistoryTurnChange) {
|
||||
if let Some(change_set) = self.active_change_set.as_mut() {
|
||||
change_set.changed_turns.push(turn);
|
||||
}
|
||||
}
|
||||
|
||||
fn record_removed_turn_ids(&mut self, removed_turn_ids: Vec<String>) {
|
||||
if let Some(change_set) = self.active_change_set.as_mut() {
|
||||
change_set.removed_turn_ids.extend(removed_turn_ids);
|
||||
}
|
||||
}
|
||||
|
||||
fn next_item_id(&mut self) -> String {
|
||||
@@ -1163,15 +1464,17 @@ fn convert_dynamic_tool_content_items(
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn upsert_turn_item(items: &mut Vec<ThreadItem>, item: ThreadItem) {
|
||||
if let Some(existing_item) = items
|
||||
.iter_mut()
|
||||
.find(|existing_item| existing_item.id() == item.id())
|
||||
fn upsert_turn_item(items: &mut Vec<ThreadItem>, item: ThreadItem) -> &ThreadItem {
|
||||
if let Some(existing_item_index) = items
|
||||
.iter()
|
||||
.position(|existing_item| existing_item.id() == item.id())
|
||||
{
|
||||
*existing_item = item;
|
||||
return;
|
||||
items[existing_item_index] = item;
|
||||
return &items[existing_item_index];
|
||||
}
|
||||
let inserted_item_index = items.len();
|
||||
items.push(item);
|
||||
&items[inserted_item_index]
|
||||
}
|
||||
|
||||
struct PendingTurn {
|
||||
@@ -1275,6 +1578,7 @@ mod tests {
|
||||
use codex_protocol::protocol::TurnCompleteEvent;
|
||||
use codex_protocol::protocol::TurnStartedEvent;
|
||||
use codex_protocol::protocol::UserMessageEvent;
|
||||
use codex_protocol::protocol::WebSearchBeginEvent;
|
||||
use codex_protocol::protocol::WebSearchEndEvent;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_absolute_path::test_support::test_path_buf;
|
||||
@@ -3457,4 +3761,299 @@ mod tests {
|
||||
assert_eq!(turns.len(), 1);
|
||||
assert!(turns[0].items.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_rollout_item_reports_new_item_snapshot() {
|
||||
let mut builder = ThreadHistoryBuilder::new();
|
||||
|
||||
let changes = builder.handle_rollout_item_with_changes(&RolloutItem::EventMsg(
|
||||
EventMsg::UserMessage(UserMessageEvent {
|
||||
client_id: Some("client-message-1".into()),
|
||||
message: "hello".into(),
|
||||
images: None,
|
||||
text_elements: Vec::new(),
|
||||
local_images: Vec::new(),
|
||||
..Default::default()
|
||||
}),
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
changes,
|
||||
ThreadHistoryChangeSet {
|
||||
changed_items: vec![ThreadHistoryItemChange {
|
||||
turn_id: "rollout-0".into(),
|
||||
item: ThreadItem::UserMessage {
|
||||
id: "item-1".into(),
|
||||
client_id: Some("client-message-1".into()),
|
||||
content: vec![UserInput::Text {
|
||||
text: "hello".into(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
},
|
||||
}],
|
||||
changed_turns: vec![ThreadHistoryTurnChange {
|
||||
turn_id: "rollout-0".into(),
|
||||
status: TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
}],
|
||||
removed_turn_ids: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_rollout_item_reports_updated_existing_item_snapshot() {
|
||||
let mut builder = ThreadHistoryBuilder::new();
|
||||
builder.handle_rollout_item_with_changes(&RolloutItem::EventMsg(EventMsg::WebSearchBegin(
|
||||
WebSearchBeginEvent {
|
||||
call_id: "search-1".into(),
|
||||
},
|
||||
)));
|
||||
|
||||
let changes = builder.handle_rollout_item_with_changes(&RolloutItem::EventMsg(
|
||||
EventMsg::WebSearchEnd(WebSearchEndEvent {
|
||||
call_id: "search-1".into(),
|
||||
query: "codex".into(),
|
||||
action: CoreWebSearchAction::Search {
|
||||
query: Some("codex".into()),
|
||||
queries: None,
|
||||
},
|
||||
}),
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
changes,
|
||||
ThreadHistoryChangeSet {
|
||||
changed_items: vec![ThreadHistoryItemChange {
|
||||
turn_id: "rollout-0".into(),
|
||||
item: ThreadItem::WebSearch {
|
||||
id: "search-1".into(),
|
||||
query: "codex".into(),
|
||||
action: Some(WebSearchAction::Search {
|
||||
query: Some("codex".into()),
|
||||
queries: None,
|
||||
}),
|
||||
},
|
||||
}],
|
||||
changed_turns: Vec::new(),
|
||||
removed_turn_ids: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_rollout_item_reports_streaming_item_mutation() {
|
||||
let mut builder = ThreadHistoryBuilder::new();
|
||||
builder.handle_rollout_item_with_changes(&RolloutItem::EventMsg(EventMsg::AgentReasoning(
|
||||
AgentReasoningEvent {
|
||||
text: "summary".into(),
|
||||
},
|
||||
)));
|
||||
|
||||
let changes = builder.handle_rollout_item_with_changes(&RolloutItem::EventMsg(
|
||||
EventMsg::AgentReasoningRawContent(AgentReasoningRawContentEvent {
|
||||
text: "raw content".into(),
|
||||
}),
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
changes,
|
||||
ThreadHistoryChangeSet {
|
||||
changed_items: vec![ThreadHistoryItemChange {
|
||||
turn_id: "rollout-0".into(),
|
||||
item: ThreadItem::Reasoning {
|
||||
id: "item-1".into(),
|
||||
summary: vec!["summary".into()],
|
||||
content: vec!["raw content".into()],
|
||||
},
|
||||
}],
|
||||
changed_turns: Vec::new(),
|
||||
removed_turn_ids: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_rollout_item_reports_turn_completion_metadata() {
|
||||
let mut builder = ThreadHistoryBuilder::new();
|
||||
|
||||
let start_changes = builder.handle_rollout_item_with_changes(&RolloutItem::EventMsg(
|
||||
EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_id: "turn-a".into(),
|
||||
trace_id: None,
|
||||
started_at: Some(10),
|
||||
model_context_window: None,
|
||||
collaboration_mode_kind: Default::default(),
|
||||
}),
|
||||
));
|
||||
assert_eq!(
|
||||
start_changes,
|
||||
ThreadHistoryChangeSet {
|
||||
changed_items: Vec::new(),
|
||||
changed_turns: vec![ThreadHistoryTurnChange {
|
||||
turn_id: "turn-a".into(),
|
||||
status: TurnStatus::InProgress,
|
||||
error: None,
|
||||
started_at: Some(10),
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
}],
|
||||
removed_turn_ids: Vec::new(),
|
||||
}
|
||||
);
|
||||
|
||||
builder.handle_rollout_item_with_changes(&RolloutItem::EventMsg(EventMsg::UserMessage(
|
||||
UserMessageEvent {
|
||||
client_id: None,
|
||||
message: "hello".into(),
|
||||
images: None,
|
||||
text_elements: Vec::new(),
|
||||
local_images: Vec::new(),
|
||||
..Default::default()
|
||||
},
|
||||
)));
|
||||
let complete_changes = builder.handle_rollout_item_with_changes(&RolloutItem::EventMsg(
|
||||
EventMsg::TurnComplete(TurnCompleteEvent {
|
||||
turn_id: "turn-a".into(),
|
||||
last_agent_message: None,
|
||||
completed_at: Some(20),
|
||||
duration_ms: Some(123),
|
||||
time_to_first_token_ms: None,
|
||||
}),
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
complete_changes,
|
||||
ThreadHistoryChangeSet {
|
||||
changed_items: Vec::new(),
|
||||
changed_turns: vec![ThreadHistoryTurnChange {
|
||||
turn_id: "turn-a".into(),
|
||||
status: TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: Some(10),
|
||||
completed_at: Some(20),
|
||||
duration_ms: Some(123),
|
||||
}],
|
||||
removed_turn_ids: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_rollout_items_dedupe_updated_item_snapshots() {
|
||||
let mut builder = ThreadHistoryBuilder::new();
|
||||
let changes = builder.handle_rollout_items_with_changes(&[
|
||||
RolloutItem::EventMsg(EventMsg::WebSearchBegin(WebSearchBeginEvent {
|
||||
call_id: "search-1".into(),
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::WebSearchEnd(WebSearchEndEvent {
|
||||
call_id: "search-1".into(),
|
||||
query: "codex".into(),
|
||||
action: CoreWebSearchAction::Search {
|
||||
query: Some("codex".into()),
|
||||
queries: None,
|
||||
},
|
||||
})),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
changes,
|
||||
ThreadHistoryChangeSet {
|
||||
changed_items: vec![ThreadHistoryItemChange {
|
||||
turn_id: "rollout-0".into(),
|
||||
item: ThreadItem::WebSearch {
|
||||
id: "search-1".into(),
|
||||
query: "codex".into(),
|
||||
action: Some(WebSearchAction::Search {
|
||||
query: Some("codex".into()),
|
||||
queries: None,
|
||||
}),
|
||||
},
|
||||
}],
|
||||
changed_turns: vec![ThreadHistoryTurnChange {
|
||||
turn_id: "rollout-0".into(),
|
||||
status: TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
}],
|
||||
removed_turn_ids: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_rollout_items_dedupe_turn_metadata_snapshots() {
|
||||
let mut builder = ThreadHistoryBuilder::new();
|
||||
let changes = builder.handle_rollout_items_with_changes(&[
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_id: "turn-a".into(),
|
||||
trace_id: None,
|
||||
started_at: Some(10),
|
||||
model_context_window: None,
|
||||
collaboration_mode_kind: Default::default(),
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent {
|
||||
turn_id: "turn-a".into(),
|
||||
last_agent_message: None,
|
||||
completed_at: Some(20),
|
||||
duration_ms: Some(123),
|
||||
time_to_first_token_ms: None,
|
||||
})),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
changes,
|
||||
ThreadHistoryChangeSet {
|
||||
changed_items: Vec::new(),
|
||||
changed_turns: vec![ThreadHistoryTurnChange {
|
||||
turn_id: "turn-a".into(),
|
||||
status: TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: Some(10),
|
||||
completed_at: Some(20),
|
||||
duration_ms: Some(123),
|
||||
}],
|
||||
removed_turn_ids: Vec::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_rollout_items_drop_prior_changes_for_removed_turns() {
|
||||
let mut builder = ThreadHistoryBuilder::new();
|
||||
let changes = builder.handle_rollout_items_with_changes(&[
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_id: "turn-a".into(),
|
||||
trace_id: None,
|
||||
started_at: None,
|
||||
model_context_window: None,
|
||||
collaboration_mode_kind: Default::default(),
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
client_id: None,
|
||||
message: "hello".into(),
|
||||
images: None,
|
||||
text_elements: Vec::new(),
|
||||
local_images: Vec::new(),
|
||||
..Default::default()
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::ThreadRolledBack(ThreadRolledBackEvent {
|
||||
num_turns: 1,
|
||||
})),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
changes,
|
||||
ThreadHistoryChangeSet {
|
||||
changed_items: Vec::new(),
|
||||
changed_turns: Vec::new(),
|
||||
removed_turn_ids: vec!["turn-a".into()],
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::protocol::common::AuthMode;
|
||||
use codex_experimental_api_macros::ExperimentalApi;
|
||||
use codex_protocol::account::AmazonBedrockCredentialSource;
|
||||
use codex_protocol::account::PlanType;
|
||||
use codex_protocol::account::ProviderAccount;
|
||||
use codex_protocol::protocol::CreditsSnapshot as CoreCreditsSnapshot;
|
||||
@@ -28,7 +29,14 @@ pub enum Account {
|
||||
|
||||
#[serde(rename = "amazonBedrock", rename_all = "camelCase")]
|
||||
#[ts(rename = "amazonBedrock", rename_all = "camelCase")]
|
||||
AmazonBedrock {},
|
||||
AmazonBedrock {
|
||||
#[serde(default = "default_bedrock_credential_source")]
|
||||
credential_source: AmazonBedrockCredentialSource,
|
||||
},
|
||||
}
|
||||
|
||||
fn default_bedrock_credential_source() -> AmazonBedrockCredentialSource {
|
||||
AmazonBedrockCredentialSource::AwsManaged
|
||||
}
|
||||
|
||||
impl From<ProviderAccount> for Account {
|
||||
@@ -36,7 +44,9 @@ impl From<ProviderAccount> for Account {
|
||||
match account {
|
||||
ProviderAccount::ApiKey => Self::ApiKey {},
|
||||
ProviderAccount::Chatgpt { email, plan_type } => Self::Chatgpt { email, plan_type },
|
||||
ProviderAccount::AmazonBedrock => Self::AmazonBedrock {},
|
||||
ProviderAccount::AmazonBedrock { credential_source } => {
|
||||
Self::AmazonBedrock { credential_source }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,6 +177,7 @@ pub struct AppsDefaultConfig {
|
||||
pub destructive_enabled: bool,
|
||||
#[serde(default = "default_enabled")]
|
||||
pub open_world_enabled: bool,
|
||||
pub default_tools_approval_mode: Option<AppToolApproval>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
|
||||
@@ -650,7 +651,7 @@ pub struct ExternalAgentConfigDetectResponse {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct ExternalAgentConfigDetectParams {
|
||||
/// If true, include detection under the user's home (~/.claude, ~/.codex, etc.).
|
||||
/// If true, include detection under the user's home directory.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub include_home: bool,
|
||||
/// Zero or more working directories to include for repo-scoped detection.
|
||||
@@ -663,6 +664,9 @@ pub struct ExternalAgentConfigDetectParams {
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct ExternalAgentConfigImportParams {
|
||||
pub migration_items: Vec<ExternalAgentConfigMigrationItem>,
|
||||
/// Source product that produced the migration items. Missing means unspecified.
|
||||
#[ts(optional = nullable)]
|
||||
pub source: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
@@ -677,6 +681,7 @@ pub struct ExternalAgentConfigImportResponse {
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct ExternalAgentConfigImportItemTypeFailure {
|
||||
pub item_type: ExternalAgentConfigMigrationItemType,
|
||||
pub error_type: Option<String>,
|
||||
pub failure_stage: String,
|
||||
pub message: String,
|
||||
pub cwd: Option<PathBuf>,
|
||||
@@ -702,6 +707,31 @@ pub struct ExternalAgentConfigImportTypeResult {
|
||||
pub failures: Vec<ExternalAgentConfigImportItemTypeFailure>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct ExternalAgentConfigImportHistory {
|
||||
pub import_id: String,
|
||||
pub completed_at_ms: i64,
|
||||
pub successes: Vec<ExternalAgentConfigImportItemTypeSuccess>,
|
||||
pub failures: Vec<ExternalAgentConfigImportItemTypeFailure>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct ExternalAgentConfigImportHistoriesReadResponse {
|
||||
pub data: Vec<ExternalAgentConfigImportHistory>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct ExternalAgentConfigImportProgressNotification {
|
||||
pub import_id: String,
|
||||
pub item_type_results: Vec<ExternalAgentConfigImportTypeResult>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
|
||||
@@ -1321,6 +1321,9 @@ pub struct CommandExecutionRequestApprovalParams {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional = nullable)]
|
||||
pub approval_id: Option<String>,
|
||||
/// Environment in which the command will run.
|
||||
#[serde(default)]
|
||||
pub environment_id: Option<String>,
|
||||
/// Optional explanatory reason (e.g. request for network access).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional = nullable)]
|
||||
|
||||
@@ -16,7 +16,7 @@ use codex_protocol::protocol::NetworkAccess as CoreNetworkAccess;
|
||||
use codex_protocol::request_permissions::PermissionGrantScope as CorePermissionGrantScope;
|
||||
use codex_protocol::request_permissions::RequestPermissionProfile as CoreRequestPermissionProfile;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::ApiPathString;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
@@ -57,9 +57,9 @@ impl From<CoreNetworkApprovalContext> for NetworkApprovalContext {
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct AdditionalFileSystemPermissions {
|
||||
/// This will be removed in favor of `entries`.
|
||||
pub read: Option<Vec<ApiPathString>>,
|
||||
pub read: Option<Vec<LegacyAppPathString>>,
|
||||
/// This will be removed in favor of `entries`.
|
||||
pub write: Option<Vec<ApiPathString>>,
|
||||
pub write: Option<Vec<LegacyAppPathString>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub glob_scan_max_depth: Option<NonZeroUsize>,
|
||||
@@ -78,7 +78,7 @@ impl From<CoreFileSystemPermissions<AbsolutePathBuf>> for AdditionalFileSystemPe
|
||||
if let Some(paths) = read.as_ref() {
|
||||
entries.extend(paths.iter().map(|path| FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Path {
|
||||
path: ApiPathString::from_abs_path(path),
|
||||
path: LegacyAppPathString::from_abs_path(path),
|
||||
},
|
||||
access: FileSystemAccessMode::Read,
|
||||
}));
|
||||
@@ -86,14 +86,24 @@ impl From<CoreFileSystemPermissions<AbsolutePathBuf>> for AdditionalFileSystemPe
|
||||
if let Some(paths) = write.as_ref() {
|
||||
entries.extend(paths.iter().map(|path| FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Path {
|
||||
path: ApiPathString::from_abs_path(path),
|
||||
path: LegacyAppPathString::from_abs_path(path),
|
||||
},
|
||||
access: FileSystemAccessMode::Write,
|
||||
}));
|
||||
}
|
||||
Self {
|
||||
read: read.map(|paths| paths.iter().map(ApiPathString::from_abs_path).collect()),
|
||||
write: write.map(|paths| paths.iter().map(ApiPathString::from_abs_path).collect()),
|
||||
read: read.map(|paths| {
|
||||
paths
|
||||
.iter()
|
||||
.map(LegacyAppPathString::from_abs_path)
|
||||
.collect()
|
||||
}),
|
||||
write: write.map(|paths| {
|
||||
paths
|
||||
.iter()
|
||||
.map(LegacyAppPathString::from_abs_path)
|
||||
.collect()
|
||||
}),
|
||||
glob_scan_max_depth: None,
|
||||
entries: Some(entries),
|
||||
}
|
||||
@@ -276,7 +286,7 @@ impl From<FileSystemSpecialPath> for CoreFileSystemSpecialPath {
|
||||
#[ts(export_to = "v2/")]
|
||||
// TODO(anp): Rename this type to distinguish it from the generic protocol FileSystemPath.
|
||||
pub enum FileSystemPath {
|
||||
Path { path: ApiPathString },
|
||||
Path { path: LegacyAppPathString },
|
||||
GlobPattern { pattern: String },
|
||||
Special { value: FileSystemSpecialPath },
|
||||
}
|
||||
@@ -286,7 +296,7 @@ impl From<CoreFileSystemPath<AbsolutePathBuf>> for FileSystemPath {
|
||||
fn from(value: CoreFileSystemPath<AbsolutePathBuf>) -> Self {
|
||||
match value {
|
||||
CoreFileSystemPath::Path { path } => Self::Path {
|
||||
path: ApiPathString::from_abs_path(&path),
|
||||
path: LegacyAppPathString::from_abs_path(&path),
|
||||
},
|
||||
CoreFileSystemPath::GlobPattern { pattern } => Self::GlobPattern { pattern },
|
||||
CoreFileSystemPath::Special { value } => Self::Special {
|
||||
|
||||
@@ -35,7 +35,7 @@ use codex_protocol::user_input::UserInput as CoreUserInput;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_absolute_path::test_support::test_path_buf;
|
||||
use codex_utils_path_uri::ApiPathString;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value as JsonValue;
|
||||
use serde_json::json;
|
||||
@@ -174,6 +174,7 @@ fn thread_resume_response_round_trips_initial_turns_page() {
|
||||
model_provider: "openai".to_string(),
|
||||
created_at: 1,
|
||||
updated_at: 1,
|
||||
recency_at: Some(1),
|
||||
status: ThreadStatus::Idle,
|
||||
path: None,
|
||||
cwd: absolute_path("tmp"),
|
||||
@@ -375,6 +376,7 @@ fn external_agent_config_import_params_accept_legacy_plugin_details() {
|
||||
..Default::default()
|
||||
}),
|
||||
}],
|
||||
source: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -579,8 +581,8 @@ fn additional_file_system_permissions_populates_entries_for_legacy_roots() {
|
||||
);
|
||||
|
||||
let permissions = AdditionalFileSystemPermissions::from(core_permissions.clone());
|
||||
let read_only_api_path = ApiPathString::from_abs_path(&read_only_path);
|
||||
let read_write_api_path = ApiPathString::from_abs_path(&read_write_path);
|
||||
let read_only_api_path = LegacyAppPathString::from_abs_path(&read_only_path);
|
||||
let read_write_api_path = LegacyAppPathString::from_abs_path(&read_write_path);
|
||||
|
||||
assert_eq!(
|
||||
permissions,
|
||||
@@ -3600,6 +3602,7 @@ fn thread_lifecycle_responses_default_missing_optional_fields() {
|
||||
|
||||
assert_eq!(start.instruction_sources, Vec::<AbsolutePathBuf>::new());
|
||||
assert_eq!(start.thread.parent_thread_id, None);
|
||||
assert_eq!(start.thread.recency_at, None);
|
||||
assert_eq!(resume.instruction_sources, Vec::<AbsolutePathBuf>::new());
|
||||
assert_eq!(fork.instruction_sources, Vec::<AbsolutePathBuf>::new());
|
||||
assert_eq!(start.active_permission_profile, None);
|
||||
@@ -3608,6 +3611,14 @@ fn thread_lifecycle_responses_default_missing_optional_fields() {
|
||||
assert_eq!(fork.active_permission_profile, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_recency_sort_key_serializes_as_snake_case() {
|
||||
assert_eq!(
|
||||
serde_json::to_value(ThreadSortKey::RecencyAt).expect("sort key should serialize"),
|
||||
json!("recency_at")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_start_params_preserve_explicit_null_service_tier() {
|
||||
let params: TurnStartParams = serde_json::from_value(json!({
|
||||
@@ -3723,7 +3734,14 @@ fn thread_settings_update_params_preserve_field_level_experimental_gates() {
|
||||
|
||||
#[test]
|
||||
fn turn_start_params_round_trip_environments() {
|
||||
let cwd = test_absolute_path();
|
||||
// Use a path foreign to the test host so this exercises syntax preservation instead of the
|
||||
// host-native conversion performed by test_absolute_path().
|
||||
#[cfg(windows)]
|
||||
let raw_cwd = "/workspace";
|
||||
#[cfg(not(windows))]
|
||||
let raw_cwd = r"C:\workspace";
|
||||
let cwd: LegacyAppPathString =
|
||||
serde_json::from_value(json!(raw_cwd)).expect("API path should deserialize");
|
||||
let params: TurnStartParams = serde_json::from_value(json!({
|
||||
"threadId": "thread_123",
|
||||
"input": [],
|
||||
@@ -3805,27 +3823,6 @@ fn turn_start_params_treat_null_or_omitted_environments_as_default() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_start_params_reject_relative_environment_cwd() {
|
||||
let err = serde_json::from_value::<TurnStartParams>(json!({
|
||||
"threadId": "thread_123",
|
||||
"input": [],
|
||||
"environments": [
|
||||
{
|
||||
"environmentId": "local",
|
||||
"cwd": "relative"
|
||||
}
|
||||
],
|
||||
}))
|
||||
.expect_err("relative environment cwd should fail");
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("AbsolutePathBuf deserialized without a base path"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn realtime_append_text_defaults_role_to_user() {
|
||||
let params = serde_json::from_value::<ThreadRealtimeAppendTextParams>(json!({
|
||||
|
||||
@@ -1086,6 +1086,7 @@ pub enum ThreadSourceKind {
|
||||
pub enum ThreadSortKey {
|
||||
CreatedAt,
|
||||
UpdatedAt,
|
||||
RecencyAt,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, JsonSchema, TS)]
|
||||
|
||||
@@ -152,6 +152,9 @@ pub struct Thread {
|
||||
/// Unix timestamp (in seconds) when the thread was last updated.
|
||||
#[ts(type = "number")]
|
||||
pub updated_at: i64,
|
||||
/// Unix timestamp (in seconds) used for thread recency ordering.
|
||||
#[ts(type = "number | null")]
|
||||
pub recency_at: Option<i64>,
|
||||
/// Current runtime status for the thread.
|
||||
pub status: ThreadStatus,
|
||||
/// [UNSTABLE] Path to the thread on disk.
|
||||
|
||||
@@ -14,6 +14,7 @@ use codex_protocol::user_input::ByteRange as CoreByteRange;
|
||||
use codex_protocol::user_input::TextElement as CoreTextElement;
|
||||
use codex_protocol::user_input::UserInput as CoreUserInput;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
@@ -38,7 +39,7 @@ pub enum TurnStatus {
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct TurnEnvironmentParams {
|
||||
pub environment_id: String,
|
||||
pub cwd: AbsolutePathBuf,
|
||||
pub cwd: LegacyAppPathString,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
|
||||
|
||||
@@ -25,5 +25,4 @@ url = { workspace = true }
|
||||
uuid = { workspace = true, features = ["v4"] }
|
||||
|
||||
[lib]
|
||||
test = false
|
||||
doctest = false
|
||||
|
||||
@@ -18,6 +18,89 @@ cargo run -p codex-app-server-test-client -- \
|
||||
cargo run -p codex-app-server-test-client -- model-list
|
||||
```
|
||||
|
||||
## Testing Plugin Analytics
|
||||
|
||||
The `plugin-analytics-smoke` command exercises `plugin/installed`, plugin
|
||||
enable/disable config writes, and a structured plugin mention through one
|
||||
app-server connection. Analytics are captured to a local JSONL file and are
|
||||
not sent to the analytics backend. The model turn uses a loopback Responses
|
||||
API server.
|
||||
|
||||
The selected plugin must already be installed and enabled remotely, and the
|
||||
active Codex profile must be authenticated. On a fresh local cache, the command
|
||||
retries ephemeral turns while the installed remote bundle finishes syncing.
|
||||
|
||||
```bash
|
||||
# Build a debug Codex binary; analytics capture is unavailable in release builds.
|
||||
cargo build -p codex-cli --bin codex
|
||||
|
||||
cargo run -p codex-app-server-test-client -- \
|
||||
--codex-bin ./target/debug/codex \
|
||||
plugin-analytics-smoke \
|
||||
--plugin-id linear@openai-curated-remote
|
||||
```
|
||||
|
||||
Use `--capture-file /tmp/plugin-analytics.jsonl` to select the output path.
|
||||
The command validates one `codex_plugin_disabled`, `codex_plugin_enabled`, and
|
||||
`codex_plugin_used` event with the expected local plugin identity and capability
|
||||
metadata. The enabled and disabled events come from successful writes to the
|
||||
temporary config; the command does not mutate the remote enabled state. It
|
||||
prints the events and leaves the JSONL file in place for inspection. It does not
|
||||
install or uninstall plugins and does not modify the profile's persistent
|
||||
config.
|
||||
|
||||
### Testing remote install and uninstall analytics
|
||||
|
||||
`plugin-analytics-mutation-smoke` is a manually invoked live smoke test. It
|
||||
contacts the configured remote plugin API and temporarily changes the active
|
||||
account's installed-plugin state. It is not run by `cargo test`, `just test`,
|
||||
or CI.
|
||||
|
||||
Choose a remote plugin that is available to the active account and is not
|
||||
currently installed. The command refuses to run when the plugin is already
|
||||
installed, installs it, validates `codex_plugin_installed`, uninstalls it, and
|
||||
verifies that the original uninstalled state was restored. The current install
|
||||
event uses the backend ID as `plugin_id`. Uninstall is part of cleanup but is
|
||||
not yet an analytics assertion.
|
||||
|
||||
`--remote-plugin-id` takes the backend ID, such as `plugins~Plugin_...`, not the
|
||||
local `<plugin>@<marketplace>` ID.
|
||||
|
||||
```bash
|
||||
cargo run -p codex-app-server-test-client -- \
|
||||
--codex-bin ./target/debug/codex \
|
||||
plugin-analytics-mutation-smoke \
|
||||
--remote-plugin-id <REMOTE_PLUGIN_ID> \
|
||||
--confirm-account-mutation \
|
||||
--capture-file /tmp/plugin-mutation-analytics.jsonl
|
||||
```
|
||||
|
||||
Analytics use the normal queue, reduction, batching, and serialization path,
|
||||
but the debug capture destination suppresses analytics network delivery. The
|
||||
command prints one of these final states:
|
||||
|
||||
- `PASS`: the install event validated and the plugin is uninstalled.
|
||||
- `FAIL-CLEAN`: validation failed, but the original uninstalled state was
|
||||
restored.
|
||||
- `FAIL-LOCAL-CACHE`: the backend is uninstalled, but local cleanup reported
|
||||
an error.
|
||||
- `FAIL-DIRTY`: cleanup failed and the plugin still appears installed.
|
||||
- `FAIL-UNKNOWN`: the command could not verify the final installed state.
|
||||
|
||||
For a dirty or uncertain result, retry cleanup with:
|
||||
|
||||
```bash
|
||||
cargo run -p codex-app-server-test-client -- \
|
||||
--codex-bin ./target/debug/codex \
|
||||
plugin-remote-uninstall \
|
||||
--remote-plugin-id <REMOTE_PLUGIN_ID> \
|
||||
--confirm-account-mutation
|
||||
```
|
||||
|
||||
Cleanup does not require analytics capture or a debug Codex binary. When the
|
||||
smoke uses global `--config` overrides, its printed recovery command preserves
|
||||
them so cleanup targets the same backend and account.
|
||||
|
||||
## Watching Raw Inbound Traffic
|
||||
|
||||
Initialize a connection, then print every inbound JSON-RPC message until you stop it with
|
||||
|
||||
@@ -87,6 +87,11 @@ use tungstenite::stream::MaybeTlsStream;
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
mod loopback_responses_server;
|
||||
mod plugin_analytics_capture;
|
||||
mod plugin_analytics_mutation_smoke;
|
||||
mod plugin_analytics_smoke;
|
||||
|
||||
const NOTIFICATIONS_TO_OPT_OUT: &[&str] = &[
|
||||
// v2 item deltas.
|
||||
"command/exec/outputDelta",
|
||||
@@ -272,6 +277,39 @@ enum CliCommand {
|
||||
#[arg(long, default_value_t = 15)]
|
||||
hold_seconds: u64,
|
||||
},
|
||||
/// Exercise remote plugin analytics through production app-server RPC paths.
|
||||
#[command(name = "plugin-analytics-smoke")]
|
||||
PluginAnalyticsSmoke {
|
||||
/// Installed local plugin id, such as `linear@openai-curated-remote`.
|
||||
#[arg(long)]
|
||||
plugin_id: String,
|
||||
/// JSONL output path. Defaults to a PID-specific file under the system temp directory.
|
||||
#[arg(long)]
|
||||
capture_file: Option<PathBuf>,
|
||||
},
|
||||
/// Install and uninstall one remote plugin while validating analytics capture.
|
||||
#[command(name = "plugin-analytics-mutation-smoke")]
|
||||
PluginAnalyticsMutationSmoke {
|
||||
/// Backend remote plugin id. The plugin must be initially uninstalled.
|
||||
#[arg(long)]
|
||||
remote_plugin_id: String,
|
||||
/// Acknowledge that this command mutates the active account's plugin state.
|
||||
#[arg(long)]
|
||||
confirm_account_mutation: bool,
|
||||
/// JSONL output path. Defaults to a PID-specific file under the system temp directory.
|
||||
#[arg(long)]
|
||||
capture_file: Option<PathBuf>,
|
||||
},
|
||||
/// Best-effort recovery command that uninstalls one remote plugin.
|
||||
#[command(name = "plugin-remote-uninstall")]
|
||||
PluginRemoteUninstall {
|
||||
/// Backend remote plugin id to uninstall.
|
||||
#[arg(long)]
|
||||
remote_plugin_id: String,
|
||||
/// Acknowledge that this command mutates the active account's plugin state.
|
||||
#[arg(long)]
|
||||
confirm_account_mutation: bool,
|
||||
},
|
||||
}
|
||||
|
||||
pub async fn run() -> Result<()> {
|
||||
@@ -423,6 +461,58 @@ pub async fn run() -> Result<()> {
|
||||
hold_seconds,
|
||||
)
|
||||
}
|
||||
CliCommand::PluginAnalyticsSmoke {
|
||||
plugin_id,
|
||||
capture_file,
|
||||
} => {
|
||||
ensure_dynamic_tools_unused(&dynamic_tools, "plugin-analytics-smoke")?;
|
||||
if url.is_some() {
|
||||
bail!("plugin-analytics-smoke requires --codex-bin and does not support --url");
|
||||
}
|
||||
let codex_bin = codex_bin.context("plugin-analytics-smoke requires --codex-bin")?;
|
||||
plugin_analytics_smoke::run(&codex_bin, &config_overrides, &plugin_id, capture_file)
|
||||
}
|
||||
CliCommand::PluginAnalyticsMutationSmoke {
|
||||
remote_plugin_id,
|
||||
confirm_account_mutation,
|
||||
capture_file,
|
||||
} => {
|
||||
ensure_dynamic_tools_unused(&dynamic_tools, "plugin-analytics-mutation-smoke")?;
|
||||
if url.is_some() {
|
||||
bail!(
|
||||
"plugin-analytics-mutation-smoke requires --codex-bin and does not support --url"
|
||||
);
|
||||
}
|
||||
let codex_bin =
|
||||
codex_bin.context("plugin-analytics-mutation-smoke requires --codex-bin")?;
|
||||
plugin_analytics_mutation_smoke::run(
|
||||
&codex_bin,
|
||||
&config_overrides,
|
||||
&remote_plugin_id,
|
||||
plugin_analytics_mutation_smoke::AccountMutationConfirmation::from_flag(
|
||||
confirm_account_mutation,
|
||||
),
|
||||
capture_file,
|
||||
)
|
||||
}
|
||||
CliCommand::PluginRemoteUninstall {
|
||||
remote_plugin_id,
|
||||
confirm_account_mutation,
|
||||
} => {
|
||||
ensure_dynamic_tools_unused(&dynamic_tools, "plugin-remote-uninstall")?;
|
||||
if url.is_some() {
|
||||
bail!("plugin-remote-uninstall requires --codex-bin and does not support --url");
|
||||
}
|
||||
let codex_bin = codex_bin.context("plugin-remote-uninstall requires --codex-bin")?;
|
||||
plugin_analytics_mutation_smoke::run_cleanup(
|
||||
&codex_bin,
|
||||
&config_overrides,
|
||||
&remote_plugin_id,
|
||||
plugin_analytics_mutation_smoke::AccountMutationConfirmation::from_flag(
|
||||
confirm_account_mutation,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1440,6 +1530,14 @@ impl CodexClient {
|
||||
}
|
||||
|
||||
fn spawn_stdio(codex_bin: &Path, config_overrides: &[String]) -> Result<Self> {
|
||||
Self::spawn_stdio_with_env(codex_bin, config_overrides, &[])
|
||||
}
|
||||
|
||||
fn spawn_stdio_with_env(
|
||||
codex_bin: &Path,
|
||||
config_overrides: &[String],
|
||||
environment: &[(OsString, OsString)],
|
||||
) -> Result<Self> {
|
||||
let codex_bin_display = codex_bin.display();
|
||||
let mut cmd = Command::new(codex_bin);
|
||||
if let Some(codex_bin_parent) = codex_bin.parent() {
|
||||
@@ -1453,6 +1551,9 @@ impl CodexClient {
|
||||
for override_kv in config_overrides {
|
||||
cmd.arg("--config").arg(override_kv);
|
||||
}
|
||||
for (name, value) in environment {
|
||||
cmd.env(name, value);
|
||||
}
|
||||
let mut codex_app_server = cmd
|
||||
.arg("app-server")
|
||||
.stdin(Stdio::piped())
|
||||
@@ -1957,6 +2058,7 @@ impl CodexClient {
|
||||
item_id,
|
||||
started_at_ms: _,
|
||||
approval_id,
|
||||
environment_id,
|
||||
reason,
|
||||
network_approval_context,
|
||||
command,
|
||||
@@ -1974,6 +2076,9 @@ impl CodexClient {
|
||||
);
|
||||
self.command_approval_count += 1;
|
||||
self.command_approval_item_ids.push(item_id.clone());
|
||||
if let Some(environment_id) = environment_id.as_deref() {
|
||||
println!("< environment: {environment_id}");
|
||||
}
|
||||
if let Some(reason) = reason.as_deref() {
|
||||
println!("< reason: {reason}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::net::TcpListener;
|
||||
use std::net::TcpStream;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::thread;
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(super) struct LoopbackResponsesServer {
|
||||
base_url: String,
|
||||
shutdown: Arc<AtomicBool>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl LoopbackResponsesServer {
|
||||
pub(super) fn start() -> Result<Self> {
|
||||
let listener =
|
||||
TcpListener::bind("127.0.0.1:0").context("bind loopback Responses API server")?;
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.context("set loopback Responses API server nonblocking")?;
|
||||
let address = listener.local_addr()?;
|
||||
let shutdown = Arc::new(AtomicBool::new(false));
|
||||
let thread_shutdown = Arc::clone(&shutdown);
|
||||
let thread = thread::spawn(move || {
|
||||
while !thread_shutdown.load(Ordering::Relaxed) {
|
||||
match listener.accept() {
|
||||
Ok((stream, _)) => {
|
||||
if let Err(err) = handle_model_connection(stream) {
|
||||
eprintln!("loopback Responses API server error: {err}");
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("loopback Responses API accept error: {err}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(Self {
|
||||
base_url: format!("http://{address}"),
|
||||
shutdown,
|
||||
thread: Some(thread),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn base_url(&self) -> &str {
|
||||
&self.base_url
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LoopbackResponsesServer {
|
||||
fn drop(&mut self) {
|
||||
self.shutdown.store(true, Ordering::Relaxed);
|
||||
if let Some(thread) = self.thread.take() {
|
||||
let _ = thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_model_connection(mut stream: TcpStream) -> io::Result<()> {
|
||||
stream.set_nonblocking(false)?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
let request = read_http_request(&mut stream)?;
|
||||
let request_line = request
|
||||
.split(|byte| *byte == b'\n')
|
||||
.next()
|
||||
.and_then(|line| std::str::from_utf8(line).ok())
|
||||
.unwrap_or_default();
|
||||
if request_line.starts_with("POST ") && request_line.contains("/responses ") {
|
||||
let body = concat!(
|
||||
"event: response.created\n",
|
||||
"data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp-plugin-analytics\"}}\n\n",
|
||||
"event: response.completed\n",
|
||||
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp-plugin-analytics\",\"usage\":{\"input_tokens\":0,\"input_tokens_details\":null,\"output_tokens\":0,\"output_tokens_details\":null,\"total_tokens\":0}}}\n\n"
|
||||
);
|
||||
write_http_response(&mut stream, "200 OK", "text/event-stream", body)
|
||||
} else {
|
||||
write_http_response(
|
||||
&mut stream,
|
||||
"404 Not Found",
|
||||
"application/json",
|
||||
r#"{"error":"not found"}"#,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn read_http_request(stream: &mut TcpStream) -> io::Result<Vec<u8>> {
|
||||
let mut request = Vec::new();
|
||||
let mut buffer = [0_u8; 4096];
|
||||
let header_end = loop {
|
||||
let read = stream.read(&mut buffer)?;
|
||||
if read == 0 {
|
||||
return Ok(request);
|
||||
}
|
||||
request.extend_from_slice(&buffer[..read]);
|
||||
if let Some(position) = request.windows(4).position(|window| window == b"\r\n\r\n") {
|
||||
break position + 4;
|
||||
}
|
||||
};
|
||||
let content_length = parse_content_length(&request[..header_end]);
|
||||
while request.len() < header_end + content_length {
|
||||
let read = stream.read(&mut buffer)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
request.extend_from_slice(&buffer[..read]);
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
fn parse_content_length(headers: &[u8]) -> usize {
|
||||
String::from_utf8_lossy(headers)
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let (name, value) = line.split_once(':')?;
|
||||
name.eq_ignore_ascii_case("content-length")
|
||||
.then(|| value.trim().parse().ok())
|
||||
.flatten()
|
||||
})
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn write_http_response(
|
||||
stream: &mut TcpStream,
|
||||
status: &str,
|
||||
content_type: &str,
|
||||
body: &str,
|
||||
) -> io::Result<()> {
|
||||
write!(
|
||||
stream,
|
||||
"HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)?;
|
||||
stream.flush()
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
pub(super) fn read_events_for_remote_plugin(
|
||||
path: &Path,
|
||||
remote_plugin_id: &str,
|
||||
) -> Result<Vec<Value>> {
|
||||
let contents = match fs::read_to_string(path) {
|
||||
Ok(contents) => contents,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(err) => {
|
||||
return Err(err).with_context(|| format!("read capture file {}", path.display()));
|
||||
}
|
||||
};
|
||||
let mut matching = Vec::new();
|
||||
for (index, line) in contents.lines().enumerate() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let payload: Value = serde_json::from_str(line).with_context(|| {
|
||||
format!(
|
||||
"parse analytics capture line {} from {}",
|
||||
index + 1,
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
let events = payload["events"]
|
||||
.as_array()
|
||||
.context("analytics capture payload is missing events")?;
|
||||
matching.extend(
|
||||
events
|
||||
.iter()
|
||||
.filter(|event| event["event_params"]["plugin_id"] == remote_plugin_id)
|
||||
.cloned(),
|
||||
);
|
||||
}
|
||||
Ok(matching)
|
||||
}
|
||||
|
||||
pub(super) struct PluginEventIdentity<'a> {
|
||||
pub(super) plugin_id: &'a str,
|
||||
pub(super) plugin_name: &'a str,
|
||||
pub(super) marketplace_name: &'a str,
|
||||
}
|
||||
|
||||
pub(super) fn validate_mutation_events(
|
||||
events: Vec<Value>,
|
||||
expected: PluginEventIdentity<'_>,
|
||||
) -> Result<Vec<Value>> {
|
||||
let event_type = "codex_plugin_installed";
|
||||
let matching = events
|
||||
.iter()
|
||||
.filter(|event| event["event_type"] == event_type)
|
||||
.collect::<Vec<_>>();
|
||||
let [event] = matching.as_slice() else {
|
||||
bail!(
|
||||
"expected exactly one `{event_type}` event for `{}`, found {}",
|
||||
expected.plugin_id,
|
||||
matching.len()
|
||||
);
|
||||
};
|
||||
validate_event(event, &expected)?;
|
||||
Ok(vec![(*event).clone()])
|
||||
}
|
||||
|
||||
fn validate_event(event: &Value, expected: &PluginEventIdentity<'_>) -> Result<()> {
|
||||
let params = &event["event_params"];
|
||||
require_string(params, "plugin_id", expected.plugin_id)?;
|
||||
require_string(params, "plugin_name", expected.plugin_name)?;
|
||||
require_string(params, "marketplace_name", expected.marketplace_name)?;
|
||||
for field in [
|
||||
"has_skills",
|
||||
"mcp_server_count",
|
||||
"connector_ids",
|
||||
"product_client_id",
|
||||
] {
|
||||
if params.get(field).is_none_or(Value::is_null) {
|
||||
bail!(
|
||||
"{} event has null or missing `{field}`",
|
||||
event["event_type"]
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_string(params: &Value, field: &str, expected: &str) -> Result<()> {
|
||||
let actual = params.get(field).and_then(Value::as_str);
|
||||
if actual != Some(expected) {
|
||||
bail!("expected `{field}` to be `{expected}`, got {actual:?}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "plugin_analytics_capture_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,93 @@
|
||||
use super::PluginEventIdentity;
|
||||
use super::read_events_for_remote_plugin;
|
||||
use super::validate_mutation_events;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::process;
|
||||
use std::time::SystemTime;
|
||||
|
||||
const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_test";
|
||||
|
||||
#[test]
|
||||
fn reads_and_validates_remote_plugin_mutation_events() {
|
||||
let path = unique_capture_path("valid");
|
||||
let installed = mutation_event("codex_plugin_installed");
|
||||
let unrelated = json!({
|
||||
"event_type": "codex_plugin_installed",
|
||||
"event_params": {
|
||||
"plugin_id": "plugins~Plugin_other"
|
||||
}
|
||||
});
|
||||
let contents = [
|
||||
json!({"events": [unrelated]}),
|
||||
json!({"events": [installed]}),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|payload| serde_json::to_string(&payload).expect("serialize capture payload"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
fs::write(&path, contents).expect("write capture file");
|
||||
|
||||
let events = read_events_for_remote_plugin(&path, REMOTE_PLUGIN_ID)
|
||||
.expect("read matching plugin events");
|
||||
let validated =
|
||||
validate_mutation_events(events, expected_identity()).expect("validate mutation events");
|
||||
|
||||
assert_eq!(validated, vec![installed]);
|
||||
fs::remove_file(path).expect("remove capture file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicate_mutation_events() {
|
||||
let installed = mutation_event("codex_plugin_installed");
|
||||
let error = validate_mutation_events(vec![installed.clone(), installed], expected_identity())
|
||||
.expect_err("duplicate install events should fail validation");
|
||||
|
||||
assert!(error.to_string().contains("found 2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_capability_metadata() {
|
||||
let mut installed = mutation_event("codex_plugin_installed");
|
||||
installed["event_params"]["has_skills"] = Value::Null;
|
||||
let error = validate_mutation_events(vec![installed], expected_identity())
|
||||
.expect_err("missing capability metadata should fail validation");
|
||||
|
||||
assert!(error.to_string().contains("has_skills"));
|
||||
}
|
||||
|
||||
fn mutation_event(event_type: &str) -> Value {
|
||||
json!({
|
||||
"event_type": event_type,
|
||||
"event_params": {
|
||||
"plugin_id": REMOTE_PLUGIN_ID,
|
||||
"plugin_name": "sample",
|
||||
"marketplace_name": "openai-curated-remote",
|
||||
"has_skills": true,
|
||||
"mcp_server_count": 0,
|
||||
"connector_ids": [],
|
||||
"product_client_id": "test-client"
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn expected_identity() -> PluginEventIdentity<'static> {
|
||||
PluginEventIdentity {
|
||||
plugin_id: REMOTE_PLUGIN_ID,
|
||||
plugin_name: "sample",
|
||||
marketplace_name: "openai-curated-remote",
|
||||
}
|
||||
}
|
||||
|
||||
fn unique_capture_path(name: &str) -> PathBuf {
|
||||
let nonce = SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.expect("system clock should be after Unix epoch")
|
||||
.as_nanos();
|
||||
std::env::temp_dir().join(format!(
|
||||
"codex-plugin-analytics-capture-{name}-{}-{nonce}.jsonl",
|
||||
process::id()
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
use super::CodexClient;
|
||||
use super::plugin_analytics_capture::PluginEventIdentity;
|
||||
use super::plugin_analytics_capture::read_events_for_remote_plugin;
|
||||
use super::plugin_analytics_capture::validate_mutation_events;
|
||||
use super::plugin_analytics_smoke::ANALYTICS_CAPTURE_ENV_VAR;
|
||||
use super::plugin_analytics_smoke::prepare_capture_file;
|
||||
use super::plugin_analytics_smoke::wait_until_capture_is_ready;
|
||||
use super::shell_quote;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use anyhow::bail;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::PluginAvailability;
|
||||
use codex_app_server_protocol::PluginInstallParams;
|
||||
use codex_app_server_protocol::PluginInstallPolicy;
|
||||
use codex_app_server_protocol::PluginInstallResponse;
|
||||
use codex_app_server_protocol::PluginReadParams;
|
||||
use codex_app_server_protocol::PluginReadResponse;
|
||||
use codex_app_server_protocol::PluginUninstallParams;
|
||||
use codex_app_server_protocol::PluginUninstallResponse;
|
||||
use serde_json::Value;
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
const REMOTE_MARKETPLACE_HINT: &str = "openai-curated-remote";
|
||||
const STATE_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const CAPTURE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const POLL_INTERVAL: Duration = Duration::from_millis(100);
|
||||
|
||||
pub(super) fn run(
|
||||
codex_bin: &Path,
|
||||
config_overrides: &[String],
|
||||
remote_plugin_id: &str,
|
||||
confirmation: AccountMutationConfirmation,
|
||||
capture_file: Option<PathBuf>,
|
||||
) -> Result<()> {
|
||||
require_confirmation(confirmation)?;
|
||||
let capture_path = capture_file.unwrap_or_else(|| {
|
||||
std::env::temp_dir().join(format!(
|
||||
"codex-plugin-analytics-mutation-{}.jsonl",
|
||||
process::id()
|
||||
))
|
||||
});
|
||||
prepare_capture_file(&capture_path)?;
|
||||
let mut client = spawn_client(codex_bin, config_overrides, &capture_path)?;
|
||||
wait_until_capture_is_ready(&capture_path)?;
|
||||
client.initialize()?;
|
||||
|
||||
let initial = read_remote_plugin(&mut client, remote_plugin_id)?;
|
||||
validate_initial_plugin(&initial, remote_plugin_id)?;
|
||||
println!(
|
||||
"remote plugin mutation smoke: local_id={} remote_id={} marketplace={}",
|
||||
initial.plugin_id, initial.remote_plugin_id, initial.marketplace_name
|
||||
);
|
||||
|
||||
let MutationSequenceResult {
|
||||
result: sequence_result,
|
||||
uninstall_rpc_failed,
|
||||
} = run_mutation_sequence(&mut client, &capture_path, &initial);
|
||||
let restoration = restore_uninstalled_state(&mut client, remote_plugin_id);
|
||||
println!("capture file: {}", capture_path.display());
|
||||
|
||||
match (sequence_result, restoration) {
|
||||
(Ok(events), RestorationStatus::Clean) => {
|
||||
println!(
|
||||
"\n[plugin analytics mutation smoke validated]\n{}",
|
||||
serde_json::to_string_pretty(&events)?
|
||||
);
|
||||
println!("PASS: analytics validated; original uninstalled state restored");
|
||||
Ok(())
|
||||
}
|
||||
(Err(err), RestorationStatus::Clean) if uninstall_rpc_failed => {
|
||||
eprintln!(
|
||||
"FAIL-LOCAL-CACHE: backend state is uninstalled, but the uninstall RPC failed after the backend mutation: {err:#}"
|
||||
);
|
||||
Err(err)
|
||||
}
|
||||
(Err(err), RestorationStatus::Clean) => {
|
||||
eprintln!("FAIL-CLEAN: {err:#}");
|
||||
eprintln!("The original uninstalled account state was restored.");
|
||||
Err(err)
|
||||
}
|
||||
(sequence_result, RestorationStatus::LocalCleanupFailure(cleanup_err)) => {
|
||||
let sequence_err = sequence_result.err();
|
||||
eprintln!(
|
||||
"FAIL-LOCAL-CACHE: backend state is uninstalled, but local cleanup reported an error: {cleanup_err:#}"
|
||||
);
|
||||
Err(sequence_err.unwrap_or(cleanup_err))
|
||||
}
|
||||
(sequence_result, RestorationStatus::Dirty(cleanup_err)) => {
|
||||
if let Err(err) = sequence_result {
|
||||
eprintln!("mutation smoke failed before cleanup: {err:#}");
|
||||
}
|
||||
print_dirty_recovery(codex_bin, config_overrides, remote_plugin_id, &cleanup_err);
|
||||
Err(cleanup_err)
|
||||
}
|
||||
(sequence_result, RestorationStatus::Unknown(cleanup_err)) => {
|
||||
if let Err(err) = sequence_result {
|
||||
eprintln!("mutation smoke failed before final state verification: {err:#}");
|
||||
}
|
||||
eprintln!(
|
||||
"FAIL-UNKNOWN: could not verify whether `{remote_plugin_id}` is installed: {cleanup_err:#}"
|
||||
);
|
||||
print_recovery_command(codex_bin, config_overrides, remote_plugin_id);
|
||||
Err(cleanup_err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run_cleanup(
|
||||
codex_bin: &Path,
|
||||
config_overrides: &[String],
|
||||
remote_plugin_id: &str,
|
||||
confirmation: AccountMutationConfirmation,
|
||||
) -> Result<()> {
|
||||
require_confirmation(confirmation)?;
|
||||
let mut overrides = config_overrides.to_vec();
|
||||
overrides.extend([
|
||||
"analytics.enabled=false".to_string(),
|
||||
"features.plugins=true".to_string(),
|
||||
"features.remote_plugin=true".to_string(),
|
||||
]);
|
||||
let mut client = CodexClient::spawn_stdio(codex_bin, &overrides)?;
|
||||
client.initialize()?;
|
||||
|
||||
match restore_uninstalled_state(&mut client, remote_plugin_id) {
|
||||
RestorationStatus::Clean => {
|
||||
println!("PASS: `{remote_plugin_id}` is uninstalled");
|
||||
Ok(())
|
||||
}
|
||||
RestorationStatus::LocalCleanupFailure(err) => {
|
||||
eprintln!(
|
||||
"FAIL-LOCAL-CACHE: backend state is uninstalled, but local cleanup reported an error: {err:#}"
|
||||
);
|
||||
Err(err)
|
||||
}
|
||||
RestorationStatus::Dirty(err) => {
|
||||
print_dirty_recovery(codex_bin, config_overrides, remote_plugin_id, &err);
|
||||
Err(err)
|
||||
}
|
||||
RestorationStatus::Unknown(err) => {
|
||||
eprintln!(
|
||||
"FAIL-UNKNOWN: could not verify whether `{remote_plugin_id}` is installed: {err:#}"
|
||||
);
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum AccountMutationConfirmation {
|
||||
Confirmed,
|
||||
Missing,
|
||||
}
|
||||
|
||||
impl AccountMutationConfirmation {
|
||||
pub(super) fn from_flag(confirm_account_mutation: bool) -> Self {
|
||||
if confirm_account_mutation {
|
||||
Self::Confirmed
|
||||
} else {
|
||||
Self::Missing
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn require_confirmation(confirmation: AccountMutationConfirmation) -> Result<()> {
|
||||
if matches!(confirmation, AccountMutationConfirmation::Missing) {
|
||||
bail!(
|
||||
"this command installs and uninstalls a plugin on the active account; rerun with --confirm-account-mutation"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum ExpectedInstalledState {
|
||||
Installed,
|
||||
Uninstalled,
|
||||
}
|
||||
|
||||
impl ExpectedInstalledState {
|
||||
fn is_installed(self) -> bool {
|
||||
matches!(self, Self::Installed)
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_client(
|
||||
codex_bin: &Path,
|
||||
config_overrides: &[String],
|
||||
capture_path: &Path,
|
||||
) -> Result<CodexClient> {
|
||||
let mut overrides = config_overrides.to_vec();
|
||||
overrides.extend([
|
||||
"analytics.enabled=true".to_string(),
|
||||
"features.plugins=true".to_string(),
|
||||
"features.remote_plugin=true".to_string(),
|
||||
]);
|
||||
let environment = vec![(
|
||||
OsString::from(ANALYTICS_CAPTURE_ENV_VAR),
|
||||
capture_path.as_os_str().to_os_string(),
|
||||
)];
|
||||
CodexClient::spawn_stdio_with_env(codex_bin, &overrides, &environment)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct RemotePluginExpectation {
|
||||
plugin_id: String,
|
||||
remote_plugin_id: String,
|
||||
plugin_name: String,
|
||||
marketplace_name: String,
|
||||
installed: bool,
|
||||
install_policy: PluginInstallPolicy,
|
||||
availability: PluginAvailability,
|
||||
}
|
||||
|
||||
fn read_remote_plugin(
|
||||
client: &mut CodexClient,
|
||||
remote_plugin_id: &str,
|
||||
) -> Result<RemotePluginExpectation> {
|
||||
let request_id = client.request_id();
|
||||
let response: PluginReadResponse = client.send_request(
|
||||
ClientRequest::PluginRead {
|
||||
request_id: request_id.clone(),
|
||||
params: PluginReadParams {
|
||||
marketplace_path: None,
|
||||
remote_marketplace_name: Some(REMOTE_MARKETPLACE_HINT.to_string()),
|
||||
plugin_name: remote_plugin_id.to_string(),
|
||||
},
|
||||
},
|
||||
request_id,
|
||||
"plugin/read",
|
||||
)?;
|
||||
let summary = response.plugin.summary;
|
||||
let actual_remote_plugin_id = summary
|
||||
.remote_plugin_id
|
||||
.with_context(|| format!("plugin/read returned no remote id for `{remote_plugin_id}`"))?;
|
||||
if actual_remote_plugin_id != remote_plugin_id {
|
||||
bail!(
|
||||
"plugin/read returned remote id `{actual_remote_plugin_id}` for requested id `{remote_plugin_id}`"
|
||||
);
|
||||
}
|
||||
Ok(RemotePluginExpectation {
|
||||
plugin_id: summary.id,
|
||||
remote_plugin_id: actual_remote_plugin_id,
|
||||
plugin_name: summary.name,
|
||||
marketplace_name: response.plugin.marketplace_name,
|
||||
installed: summary.installed,
|
||||
install_policy: summary.install_policy,
|
||||
availability: summary.availability,
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_initial_plugin(plugin: &RemotePluginExpectation, remote_plugin_id: &str) -> Result<()> {
|
||||
if plugin.installed {
|
||||
bail!(
|
||||
"refusing to run: remote plugin `{remote_plugin_id}` is already installed; choose an initially uninstalled plugin"
|
||||
);
|
||||
}
|
||||
if plugin.availability != PluginAvailability::Available {
|
||||
bail!(
|
||||
"remote plugin `{remote_plugin_id}` is not available: {:?}",
|
||||
plugin.availability
|
||||
);
|
||||
}
|
||||
if plugin.install_policy == PluginInstallPolicy::NotAvailable {
|
||||
bail!("remote plugin `{remote_plugin_id}` is not available for install");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct MutationSequenceResult {
|
||||
result: Result<Vec<Value>>,
|
||||
uninstall_rpc_failed: bool,
|
||||
}
|
||||
|
||||
fn run_mutation_sequence(
|
||||
client: &mut CodexClient,
|
||||
capture_path: &Path,
|
||||
expected: &RemotePluginExpectation,
|
||||
) -> MutationSequenceResult {
|
||||
let mut uninstall_rpc_failed = false;
|
||||
let result = (|| {
|
||||
install_remote_plugin(client, expected)?;
|
||||
wait_for_installed_state(
|
||||
client,
|
||||
&expected.remote_plugin_id,
|
||||
ExpectedInstalledState::Installed,
|
||||
)?;
|
||||
wait_for_remote_plugin_event(
|
||||
capture_path,
|
||||
&expected.remote_plugin_id,
|
||||
"codex_plugin_installed",
|
||||
)?;
|
||||
|
||||
let uninstall_error = uninstall_remote_plugin(client, &expected.remote_plugin_id).err();
|
||||
uninstall_rpc_failed = uninstall_error.is_some();
|
||||
wait_for_installed_state(
|
||||
client,
|
||||
&expected.remote_plugin_id,
|
||||
ExpectedInstalledState::Uninstalled,
|
||||
)
|
||||
.map_err(|state_err| {
|
||||
if let Some(err) = uninstall_error.as_ref() {
|
||||
anyhow!("plugin/uninstall failed: {err:#}; final state check failed: {state_err:#}")
|
||||
} else {
|
||||
state_err
|
||||
}
|
||||
})?;
|
||||
|
||||
let captured_events =
|
||||
read_events_for_remote_plugin(capture_path, &expected.remote_plugin_id)?;
|
||||
let events = validate_mutation_events(
|
||||
captured_events,
|
||||
PluginEventIdentity {
|
||||
plugin_id: &expected.remote_plugin_id,
|
||||
plugin_name: &expected.plugin_name,
|
||||
marketplace_name: &expected.marketplace_name,
|
||||
},
|
||||
)?;
|
||||
if let Some(err) = uninstall_error {
|
||||
return Err(err.context(
|
||||
"plugin/uninstall reported an error after the backend became uninstalled",
|
||||
));
|
||||
}
|
||||
Ok(events)
|
||||
})();
|
||||
|
||||
MutationSequenceResult {
|
||||
result,
|
||||
uninstall_rpc_failed,
|
||||
}
|
||||
}
|
||||
|
||||
fn install_remote_plugin(client: &mut CodexClient, plugin: &RemotePluginExpectation) -> Result<()> {
|
||||
let request_id = client.request_id();
|
||||
let _: PluginInstallResponse = client.send_request(
|
||||
ClientRequest::PluginInstall {
|
||||
request_id: request_id.clone(),
|
||||
params: PluginInstallParams {
|
||||
marketplace_path: None,
|
||||
remote_marketplace_name: Some(plugin.marketplace_name.clone()),
|
||||
plugin_name: plugin.remote_plugin_id.clone(),
|
||||
},
|
||||
},
|
||||
request_id,
|
||||
"plugin/install",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn uninstall_remote_plugin(client: &mut CodexClient, remote_plugin_id: &str) -> Result<()> {
|
||||
let request_id = client.request_id();
|
||||
let _: PluginUninstallResponse = client.send_request(
|
||||
ClientRequest::PluginUninstall {
|
||||
request_id: request_id.clone(),
|
||||
params: PluginUninstallParams {
|
||||
plugin_id: remote_plugin_id.to_string(),
|
||||
},
|
||||
},
|
||||
request_id,
|
||||
"plugin/uninstall",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wait_for_installed_state(
|
||||
client: &mut CodexClient,
|
||||
remote_plugin_id: &str,
|
||||
expected_state: ExpectedInstalledState,
|
||||
) -> Result<RemotePluginExpectation> {
|
||||
let deadline = Instant::now() + STATE_TIMEOUT;
|
||||
loop {
|
||||
match read_remote_plugin(client, remote_plugin_id) {
|
||||
Ok(plugin) if plugin.installed == expected_state.is_installed() => return Ok(plugin),
|
||||
Ok(_) => {}
|
||||
Err(err) if Instant::now() >= deadline => return Err(err),
|
||||
Err(_) => {}
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
bail!(
|
||||
"timed out waiting for remote plugin `{remote_plugin_id}` to become {expected_state:?}"
|
||||
);
|
||||
}
|
||||
thread::sleep(POLL_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
enum RestorationStatus {
|
||||
Clean,
|
||||
LocalCleanupFailure(anyhow::Error),
|
||||
Dirty(anyhow::Error),
|
||||
Unknown(anyhow::Error),
|
||||
}
|
||||
|
||||
fn restore_uninstalled_state(
|
||||
client: &mut CodexClient,
|
||||
remote_plugin_id: &str,
|
||||
) -> RestorationStatus {
|
||||
let current = match read_remote_plugin(client, remote_plugin_id) {
|
||||
Ok(current) => current,
|
||||
Err(err) => return RestorationStatus::Unknown(err),
|
||||
};
|
||||
if !current.installed {
|
||||
return RestorationStatus::Clean;
|
||||
}
|
||||
|
||||
let uninstall_result = uninstall_remote_plugin(client, remote_plugin_id);
|
||||
match wait_for_installed_state(
|
||||
client,
|
||||
remote_plugin_id,
|
||||
ExpectedInstalledState::Uninstalled,
|
||||
) {
|
||||
Ok(_) => match uninstall_result {
|
||||
Ok(()) => RestorationStatus::Clean,
|
||||
Err(err) => RestorationStatus::LocalCleanupFailure(err),
|
||||
},
|
||||
Err(state_err) => {
|
||||
let error = match uninstall_result {
|
||||
Ok(()) => state_err,
|
||||
Err(uninstall_err) => anyhow!(
|
||||
"cleanup uninstall failed: {uninstall_err:#}; state verification failed: {state_err:#}"
|
||||
),
|
||||
};
|
||||
RestorationStatus::Dirty(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_for_remote_plugin_event(
|
||||
path: &Path,
|
||||
remote_plugin_id: &str,
|
||||
event_type: &str,
|
||||
) -> Result<()> {
|
||||
let deadline = Instant::now() + CAPTURE_TIMEOUT;
|
||||
loop {
|
||||
let events = read_events_for_remote_plugin(path, remote_plugin_id)?;
|
||||
if events.iter().any(|event| event["event_type"] == event_type) {
|
||||
return Ok(());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
bail!("timed out waiting for `{event_type}` for remote plugin `{remote_plugin_id}`");
|
||||
}
|
||||
thread::sleep(POLL_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
fn print_dirty_recovery(
|
||||
codex_bin: &Path,
|
||||
config_overrides: &[String],
|
||||
remote_plugin_id: &str,
|
||||
err: &anyhow::Error,
|
||||
) {
|
||||
eprintln!(
|
||||
"FAIL-DIRTY: remote plugin `{remote_plugin_id}` still appears installed after cleanup: {err:#}"
|
||||
);
|
||||
print_recovery_command(codex_bin, config_overrides, remote_plugin_id);
|
||||
}
|
||||
|
||||
fn print_recovery_command(codex_bin: &Path, config_overrides: &[String], remote_plugin_id: &str) {
|
||||
let test_client = std::env::current_exe()
|
||||
.map(|path| path.display().to_string())
|
||||
.unwrap_or_else(|_| "codex-app-server-test-client".to_string());
|
||||
let mut command = format!(
|
||||
"{} --codex-bin {}",
|
||||
shell_quote(&test_client),
|
||||
shell_quote(&codex_bin.display().to_string())
|
||||
);
|
||||
for override_kv in config_overrides {
|
||||
command.push_str(&format!(" --config {}", shell_quote(override_kv)));
|
||||
}
|
||||
command.push_str(&format!(
|
||||
" plugin-remote-uninstall --remote-plugin-id {} --confirm-account-mutation",
|
||||
shell_quote(remote_plugin_id)
|
||||
));
|
||||
eprintln!("Recovery command:");
|
||||
eprintln!(" {command}");
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
use super::CodexClient;
|
||||
use super::loopback_responses_server::LoopbackResponsesServer;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::ConfigValueWriteParams;
|
||||
use codex_app_server_protocol::ConfigWriteResponse;
|
||||
use codex_app_server_protocol::MergeStrategy;
|
||||
use codex_app_server_protocol::PluginAvailability;
|
||||
use codex_app_server_protocol::PluginInstalledParams;
|
||||
use codex_app_server_protocol::PluginInstalledResponse;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_app_server_protocol::TurnStartParams;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_app_server_protocol::UserInput;
|
||||
use codex_app_server_protocol::WriteStatus;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::ffi::OsString;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
pub(super) const ANALYTICS_CAPTURE_ENV_VAR: &str = "CODEX_ANALYTICS_EVENTS_CAPTURE_FILE";
|
||||
const TEST_USER_CONFIG_ENV_VAR: &str = "CODEX_APP_SERVER_TEST_USER_CONFIG_FILE";
|
||||
const CAPTURE_READY_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const CAPTURE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const CAPTURE_POLL_INTERVAL: Duration = Duration::from_millis(50);
|
||||
const PLUGIN_READY_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const PLUGIN_READY_RETRY_INTERVAL: Duration = Duration::from_millis(250);
|
||||
const MOCK_MODEL_SLUG: &str = "plugin-analytics-smoke";
|
||||
const MOCK_PROVIDER_ID: &str = "plugin_analytics_smoke";
|
||||
|
||||
pub(super) fn run(
|
||||
codex_bin: &Path,
|
||||
config_overrides: &[String],
|
||||
plugin_id: &str,
|
||||
capture_file: Option<PathBuf>,
|
||||
) -> Result<()> {
|
||||
let capture_path = capture_file.unwrap_or_else(|| {
|
||||
std::env::temp_dir().join(format!("codex-plugin-analytics-{}.jsonl", process::id()))
|
||||
});
|
||||
prepare_capture_file(&capture_path)?;
|
||||
|
||||
let temporary_config = TemporaryConfigFile::create()?;
|
||||
let responses_server = LoopbackResponsesServer::start()?;
|
||||
let mut overrides = config_overrides.to_vec();
|
||||
overrides.extend(smoke_config_overrides(responses_server.base_url())?);
|
||||
|
||||
let child_environment = vec![
|
||||
(
|
||||
OsString::from(ANALYTICS_CAPTURE_ENV_VAR),
|
||||
capture_path.as_os_str().to_os_string(),
|
||||
),
|
||||
(
|
||||
OsString::from(TEST_USER_CONFIG_ENV_VAR),
|
||||
temporary_config.path().as_os_str().to_os_string(),
|
||||
),
|
||||
];
|
||||
let mut client = CodexClient::spawn_stdio_with_env(codex_bin, &overrides, &child_environment)?;
|
||||
wait_until_capture_is_ready(&capture_path)?;
|
||||
client.initialize()?;
|
||||
|
||||
let installed = plugin_installed(&mut client)?;
|
||||
let expected = expected_plugin(&installed, plugin_id)?;
|
||||
write_plugin_enabled(
|
||||
&mut client,
|
||||
temporary_config.path(),
|
||||
plugin_id,
|
||||
/*enabled*/ false,
|
||||
)?;
|
||||
write_plugin_enabled(
|
||||
&mut client,
|
||||
temporary_config.path(),
|
||||
plugin_id,
|
||||
/*enabled*/ true,
|
||||
)?;
|
||||
|
||||
wait_for_plugin_usage(&mut client, &capture_path, &expected)?;
|
||||
|
||||
let events = wait_for_plugin_events(&capture_path, plugin_id)?;
|
||||
let validated = validate_plugin_events(events, &expected)?;
|
||||
println!(
|
||||
"\n[plugin analytics smoke validated]\n{}",
|
||||
serde_json::to_string_pretty(&validated)?
|
||||
);
|
||||
println!("capture file: {}", capture_path.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_plugin_turn(client: &mut CodexClient, expected: &ExpectedPlugin) -> Result<String> {
|
||||
let thread = client.thread_start(ThreadStartParams {
|
||||
model: Some(MOCK_MODEL_SLUG.to_string()),
|
||||
model_provider: Some(MOCK_PROVIDER_ID.to_string()),
|
||||
base_instructions: Some(String::new()),
|
||||
developer_instructions: Some(String::new()),
|
||||
ephemeral: Some(true),
|
||||
..Default::default()
|
||||
})?;
|
||||
let turn = client.turn_start(TurnStartParams {
|
||||
thread_id: thread.thread.id.clone(),
|
||||
client_user_message_id: None,
|
||||
input: vec![UserInput::Mention {
|
||||
name: expected.plugin_name.clone(),
|
||||
path: format!("plugin://{}", expected.plugin_id),
|
||||
}],
|
||||
..Default::default()
|
||||
})?;
|
||||
client.stream_turn(&thread.thread.id, &turn.turn.id)?;
|
||||
if client.last_turn_status != Some(TurnStatus::Completed) {
|
||||
bail!(
|
||||
"plugin analytics smoke turn did not complete: status={:?}, error={:?}",
|
||||
client.last_turn_status,
|
||||
client.last_turn_error_message
|
||||
);
|
||||
}
|
||||
Ok(turn.turn.id)
|
||||
}
|
||||
|
||||
fn wait_for_plugin_usage(
|
||||
client: &mut CodexClient,
|
||||
capture_path: &Path,
|
||||
expected: &ExpectedPlugin,
|
||||
) -> Result<()> {
|
||||
let deadline = Instant::now() + PLUGIN_READY_TIMEOUT;
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
attempts += 1;
|
||||
let turn_id = run_plugin_turn(client, expected)?;
|
||||
// Turn completion is queued after plugin usage, so its captured event is the
|
||||
// barrier that tells us whether this attempt resolved the plugin.
|
||||
let events = wait_for_turn_analytics(capture_path, &turn_id)?;
|
||||
if events.iter().any(|event| {
|
||||
event["event_type"] == "codex_plugin_used"
|
||||
&& event["event_params"]["turn_id"].as_str() == Some(turn_id.as_str())
|
||||
&& event["event_params"]["plugin_id"].as_str() == Some(expected.plugin_id.as_str())
|
||||
}) {
|
||||
if attempts > 1 {
|
||||
println!("remote plugin bundle became ready after {attempts} turn attempts");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
bail!(
|
||||
"timed out waiting for remote plugin bundle `{}` to become usable after {attempts} turn attempts",
|
||||
expected.plugin_id
|
||||
);
|
||||
}
|
||||
thread::sleep(PLUGIN_READY_RETRY_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ExpectedPlugin {
|
||||
plugin_id: String,
|
||||
plugin_name: String,
|
||||
marketplace_name: String,
|
||||
}
|
||||
|
||||
fn plugin_installed(client: &mut CodexClient) -> Result<PluginInstalledResponse> {
|
||||
let request_id = client.request_id();
|
||||
client.send_request(
|
||||
ClientRequest::PluginInstalled {
|
||||
request_id: request_id.clone(),
|
||||
params: PluginInstalledParams {
|
||||
cwds: None,
|
||||
install_suggestion_plugin_names: None,
|
||||
},
|
||||
},
|
||||
request_id,
|
||||
"plugin/installed",
|
||||
)
|
||||
}
|
||||
|
||||
fn expected_plugin(response: &PluginInstalledResponse, plugin_id: &str) -> Result<ExpectedPlugin> {
|
||||
let matches = response
|
||||
.marketplaces
|
||||
.iter()
|
||||
.flat_map(|marketplace| {
|
||||
marketplace
|
||||
.plugins
|
||||
.iter()
|
||||
.filter(move |plugin| plugin.id == plugin_id)
|
||||
.map(move |plugin| (marketplace, plugin))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let [(marketplace, plugin)] = matches.as_slice() else {
|
||||
bail!(
|
||||
"expected exactly one installed plugin with local id `{plugin_id}`, found {}",
|
||||
matches.len()
|
||||
);
|
||||
};
|
||||
if !plugin.installed {
|
||||
bail!("plugin `{plugin_id}` is not installed");
|
||||
}
|
||||
if !plugin.enabled {
|
||||
bail!("plugin `{plugin_id}` is installed remotely but disabled");
|
||||
}
|
||||
if plugin.availability != PluginAvailability::Available {
|
||||
bail!(
|
||||
"plugin `{plugin_id}` is not available: {:?}",
|
||||
plugin.availability
|
||||
);
|
||||
}
|
||||
plugin
|
||||
.remote_plugin_id
|
||||
.as_ref()
|
||||
.with_context(|| format!("plugin `{plugin_id}` does not have a remote plugin id"))?;
|
||||
|
||||
Ok(ExpectedPlugin {
|
||||
plugin_id: plugin.id.clone(),
|
||||
plugin_name: plugin.name.clone(),
|
||||
marketplace_name: marketplace.name.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn write_plugin_enabled(
|
||||
client: &mut CodexClient,
|
||||
config_path: &Path,
|
||||
plugin_id: &str,
|
||||
enabled: bool,
|
||||
) -> Result<()> {
|
||||
let request_id = client.request_id();
|
||||
let response: ConfigWriteResponse = client.send_request(
|
||||
ClientRequest::ConfigValueWrite {
|
||||
request_id: request_id.clone(),
|
||||
params: ConfigValueWriteParams {
|
||||
key_path: format!("plugins.{plugin_id}.enabled"),
|
||||
value: json!(enabled),
|
||||
merge_strategy: MergeStrategy::Replace,
|
||||
file_path: Some(config_path.display().to_string()),
|
||||
expected_version: None,
|
||||
},
|
||||
},
|
||||
request_id,
|
||||
"config/value/write",
|
||||
)?;
|
||||
println!(
|
||||
"< config/value/write plugin={plugin_id} enabled={enabled} status={:?}",
|
||||
response.status
|
||||
);
|
||||
if response.status != WriteStatus::Ok {
|
||||
bail!(
|
||||
"config/value/write for plugin `{plugin_id}` enabled={enabled} was overridden: {:?}",
|
||||
response.overridden_metadata
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn smoke_config_overrides(responses_base_url: &str) -> Result<Vec<String>> {
|
||||
let provider_base_url = serde_json::to_string(&format!("{responses_base_url}/v1"))
|
||||
.context("serialize mock provider base URL")?;
|
||||
Ok(vec![
|
||||
"analytics.enabled=true".to_string(),
|
||||
"features.plugins=true".to_string(),
|
||||
"features.remote_plugin=true".to_string(),
|
||||
format!("model={}", quoted(MOCK_MODEL_SLUG)?),
|
||||
format!("model_provider={}", quoted(MOCK_PROVIDER_ID)?),
|
||||
format!(
|
||||
"model_providers.{MOCK_PROVIDER_ID}.name={}",
|
||||
quoted("Plugin analytics smoke mock provider")?
|
||||
),
|
||||
format!("model_providers.{MOCK_PROVIDER_ID}.base_url={provider_base_url}"),
|
||||
format!(
|
||||
"model_providers.{MOCK_PROVIDER_ID}.wire_api={}",
|
||||
quoted("responses")?
|
||||
),
|
||||
format!("model_providers.{MOCK_PROVIDER_ID}.requires_openai_auth=false"),
|
||||
format!("model_providers.{MOCK_PROVIDER_ID}.request_max_retries=0"),
|
||||
format!("model_providers.{MOCK_PROVIDER_ID}.stream_max_retries=0"),
|
||||
])
|
||||
}
|
||||
|
||||
fn quoted(value: &str) -> Result<String> {
|
||||
serde_json::to_string(value).context("serialize config string")
|
||||
}
|
||||
|
||||
pub(super) fn prepare_capture_file(path: &Path) -> Result<()> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.context("capture file must have a parent directory")?;
|
||||
if !parent.is_dir() {
|
||||
bail!(
|
||||
"capture file parent directory does not exist: {}",
|
||||
parent.display()
|
||||
);
|
||||
}
|
||||
match fs::remove_file(path) {
|
||||
Ok(()) => {}
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(err) => {
|
||||
return Err(err)
|
||||
.with_context(|| format!("remove previous capture file {}", path.display()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn wait_until_capture_is_ready(path: &Path) -> Result<()> {
|
||||
let deadline = Instant::now() + CAPTURE_READY_TIMEOUT;
|
||||
loop {
|
||||
match fs::metadata(path) {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(err) => {
|
||||
return Err(err)
|
||||
.with_context(|| format!("inspect capture file {}", path.display()));
|
||||
}
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
bail!(
|
||||
"analytics capture did not become ready at {}; use a debug Codex binary",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
thread::sleep(CAPTURE_POLL_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_for_plugin_events(path: &Path, plugin_id: &str) -> Result<Vec<Value>> {
|
||||
let deadline = Instant::now() + CAPTURE_TIMEOUT;
|
||||
loop {
|
||||
let events = read_plugin_events(path, plugin_id)?;
|
||||
if required_event_types()
|
||||
.iter()
|
||||
.all(|event_type| event_count(&events, event_type) >= 1)
|
||||
{
|
||||
return Ok(events);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
bail!(
|
||||
"timed out waiting for plugin analytics events in {}: found {:?}",
|
||||
path.display(),
|
||||
events
|
||||
.iter()
|
||||
.filter_map(|event| event["event_type"].as_str())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
thread::sleep(CAPTURE_POLL_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_for_turn_analytics(path: &Path, turn_id: &str) -> Result<Vec<Value>> {
|
||||
let deadline = Instant::now() + CAPTURE_TIMEOUT;
|
||||
loop {
|
||||
let events = read_capture_events(path)?;
|
||||
if events.iter().any(|event| {
|
||||
event["event_type"] == "codex_turn_event"
|
||||
&& event["event_params"]["turn_id"].as_str() == Some(turn_id)
|
||||
}) {
|
||||
return Ok(events);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
bail!(
|
||||
"timed out waiting for turn analytics for `{turn_id}` in {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
thread::sleep(CAPTURE_POLL_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_plugin_events(path: &Path, plugin_id: &str) -> Result<Vec<Value>> {
|
||||
Ok(read_capture_events(path)?
|
||||
.into_iter()
|
||||
.filter(|event| event["event_params"]["plugin_id"] == plugin_id)
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn read_capture_events(path: &Path) -> Result<Vec<Value>> {
|
||||
let contents = match fs::read_to_string(path) {
|
||||
Ok(contents) => contents,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(err) => {
|
||||
return Err(err).with_context(|| format!("read capture file {}", path.display()));
|
||||
}
|
||||
};
|
||||
let mut captured = Vec::new();
|
||||
for (index, line) in contents.lines().enumerate() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let payload: Value = serde_json::from_str(line).with_context(|| {
|
||||
format!(
|
||||
"parse analytics capture line {} from {}",
|
||||
index + 1,
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
let events = payload["events"]
|
||||
.as_array()
|
||||
.context("analytics capture payload is missing events")?;
|
||||
captured.extend(events.iter().cloned());
|
||||
}
|
||||
Ok(captured)
|
||||
}
|
||||
|
||||
fn validate_plugin_events(events: Vec<Value>, expected: &ExpectedPlugin) -> Result<Vec<Value>> {
|
||||
let mut validated = Vec::new();
|
||||
for event_type in required_event_types() {
|
||||
let matching = events
|
||||
.iter()
|
||||
.filter(|event| event["event_type"] == event_type)
|
||||
.collect::<Vec<_>>();
|
||||
let [event] = matching.as_slice() else {
|
||||
bail!(
|
||||
"expected exactly one `{event_type}` event for `{}`, found {}",
|
||||
expected.plugin_id,
|
||||
matching.len()
|
||||
);
|
||||
};
|
||||
validate_identity(event, expected)?;
|
||||
if event_type == "codex_plugin_used" {
|
||||
validate_used_metadata(event)?;
|
||||
}
|
||||
validated.push((*event).clone());
|
||||
}
|
||||
Ok(validated)
|
||||
}
|
||||
|
||||
fn required_event_types() -> [&'static str; 3] {
|
||||
[
|
||||
"codex_plugin_disabled",
|
||||
"codex_plugin_enabled",
|
||||
"codex_plugin_used",
|
||||
]
|
||||
}
|
||||
|
||||
fn event_count(events: &[Value], event_type: &str) -> usize {
|
||||
events
|
||||
.iter()
|
||||
.filter(|event| event["event_type"] == event_type)
|
||||
.count()
|
||||
}
|
||||
|
||||
fn validate_identity(event: &Value, expected: &ExpectedPlugin) -> Result<()> {
|
||||
let params = &event["event_params"];
|
||||
require_string(params, "plugin_id", &expected.plugin_id)?;
|
||||
require_string(params, "plugin_name", &expected.plugin_name)?;
|
||||
require_string(params, "marketplace_name", &expected.marketplace_name)
|
||||
}
|
||||
|
||||
fn validate_used_metadata(event: &Value) -> Result<()> {
|
||||
let params = &event["event_params"];
|
||||
for field in [
|
||||
"has_skills",
|
||||
"mcp_server_count",
|
||||
"connector_ids",
|
||||
"mcp_server_names",
|
||||
"thread_id",
|
||||
"turn_id",
|
||||
"model_slug",
|
||||
] {
|
||||
if params.get(field).is_none_or(Value::is_null) {
|
||||
bail!("codex_plugin_used event has null or missing `{field}`");
|
||||
}
|
||||
}
|
||||
require_string(params, "model_slug", MOCK_MODEL_SLUG)
|
||||
}
|
||||
|
||||
fn require_string(params: &Value, field: &str, expected: &str) -> Result<()> {
|
||||
let actual = params.get(field).and_then(Value::as_str);
|
||||
if actual != Some(expected) {
|
||||
bail!("expected `{field}` to be `{expected}`, got {actual:?}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct TemporaryConfigFile {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TemporaryConfigFile {
|
||||
fn create() -> Result<Self> {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"codex-plugin-analytics-config-{}.toml",
|
||||
process::id()
|
||||
));
|
||||
fs::write(&path, "")
|
||||
.with_context(|| format!("create temporary config file {}", path.display()))?;
|
||||
Ok(Self { path })
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TemporaryConfigFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
@@ -232,7 +232,7 @@ Example with notification opt-out:
|
||||
- `feedback/upload` — submit a feedback report (classification + optional reason/logs, conversation_id, and optional `extraLogFiles` attachments array); returns the tracking thread id.
|
||||
- `config/read` — fetch the effective config on disk after resolving config layering, including opaque `desktop` values stored in `config.toml`.
|
||||
- `externalAgentConfig/detect` — detect migratable external-agent artifacts with `includeHome` and optional `cwds`; each detected item includes `cwd` (`null` for home), and plugin/session migration items may additionally include structured `details` grouping plugin ids or session metadata.
|
||||
- `externalAgentConfig/import` — apply selected external-agent migration items by passing explicit `migrationItems` with `cwd` (`null` for home) and any plugin/session `details` returned by detect. Returns an `importId` used to correlate the completion notification. When a request includes migration items, the server emits `externalAgentConfig/import/completed` once after the full import finishes with type-level `itemResults` containing each migrated type's success count, error count, successes, and raw errors (immediately after the response when everything completed synchronously, or after background imports finish).
|
||||
- `externalAgentConfig/import` — apply selected external-agent migration items by passing explicit `migrationItems` with `cwd` (`null` for home) and any plugin/session `details` returned by detect. Callers may pass `source` to identify the product that initiated the import; omitted or `null` means unspecified. The response acknowledges the synchronous import phase with an `importId`. Expected migration failures are reported as per-item failures rather than JSON-RPC errors, so the server still returns that `importId` and emits `externalAgentConfig/import/completed` with the same ID once all synchronous and background work finishes. The completion notification contains type-level `itemTypeResults` with successes and failures, including raw failure messages for the client to report separately.
|
||||
- `config/value/write` — write a single config key/value to the user's config.toml on disk; dotted paths such as `desktop.someKey` use the same generic write surface.
|
||||
- `config/batchWrite` — apply multiple config edits atomically to the user's config.toml on disk, with optional `reloadUserConfig: true` to hot-reload loaded threads, including multiple `desktop.*` edits.
|
||||
- `configRequirements/read` — fetch loaded requirements constraints from `requirements.toml` and/or MDM (or `null` if none are configured), including allow-lists (`allowedApprovalPolicies`, `allowedSandboxModes`, `allowedWebSearchModes`), the layered permission-profile allow map (`allowedPermissionProfiles`), the managed permission-profile default (`defaultPermissions`), lifecycle hook lockdown (`allowManagedHooksOnly`), remote-control policy (`allowRemoteControl`; `false` force-disables remote control while `true` or `null` preserves existing behavior), computer use policy (`computerUse`), pinned feature values (`featureRequirements`), managed lifecycle hooks (`hooks`), `enforceResidency`, and `network` constraints such as canonical domain/socket permissions plus `managedAllowedDomainsOnly` and `dangerFullAccessDenylistOnly`.
|
||||
@@ -364,7 +364,8 @@ Like `thread/resume`, experimental clients can pass `excludeTurns: true` to `thr
|
||||
|
||||
- `cursor` — opaque string from a prior response; omit for the first page.
|
||||
- `limit` — server defaults to a reasonable page size if unset.
|
||||
- `sortKey` — `created_at` (default) or `updated_at`.
|
||||
- `sortKey` — `created_at` (default), `updated_at`, or `recency_at`.
|
||||
- `recencyAt` is initialized when the thread is created and advances when a turn starts. Unlike `updatedAt`, background output and other persisted mutations do not advance it.
|
||||
- `sortDirection` — `desc` (default) or `asc`.
|
||||
- `modelProviders` — restrict results to specific providers; unset, null, or an empty array will include all providers.
|
||||
- `sourceKinds` — restrict results to specific sources; omit or pass `[]` for interactive sessions only (`cli`, `vscode`).
|
||||
@@ -386,8 +387,8 @@ Example:
|
||||
} }
|
||||
{ "id": 20, "result": {
|
||||
"data": [
|
||||
{ "id": "thr_a", "preview": "Create a TUI", "modelProvider": "openai", "createdAt": 1730831111, "updatedAt": 1730831111, "status": { "type": "notLoaded" }, "agentNickname": "Atlas", "agentRole": "explorer" },
|
||||
{ "id": "thr_b", "preview": "Fix tests", "modelProvider": "openai", "createdAt": 1730750000, "updatedAt": 1730750000, "status": { "type": "notLoaded" } }
|
||||
{ "id": "thr_a", "preview": "Create a TUI", "modelProvider": "openai", "createdAt": 1730831111, "updatedAt": 1730831111, "recencyAt": 1730831111, "status": { "type": "notLoaded" }, "agentNickname": "Atlas", "agentRole": "explorer" },
|
||||
{ "id": "thr_b", "preview": "Fix tests", "modelProvider": "openai", "createdAt": 1730750000, "updatedAt": 1730750000, "recencyAt": 1730750000, "status": { "type": "notLoaded" } }
|
||||
],
|
||||
"nextCursor": "opaque-token-or-null",
|
||||
"backwardsCursor": "opaque-token-or-null"
|
||||
@@ -1429,7 +1430,7 @@ Certain actions (shell commands or modifying files) may require explicit user ap
|
||||
Order of messages:
|
||||
|
||||
1. `item/started` — shows the pending `commandExecution` item with `command`, `cwd`, and other fields so you can render the proposed action.
|
||||
2. `item/commandExecution/requestApproval` (request) — carries the same `itemId`, `threadId`, `turnId`, optionally `approvalId` (for subcommand callbacks), and `reason`. For normal command approvals, it also includes `command`, `cwd`, and `commandActions` for friendly display. When `initialize.params.capabilities.experimentalApi = true`, it may also include experimental `additionalPermissions` describing requested per-command sandbox access; any filesystem paths in that payload are absolute on the wire, and network access is represented as `additionalPermissions.network.enabled`. For network-only approvals, those command fields may be omitted and `networkApprovalContext` is provided instead. Optional persistence hints may also be included via `proposedExecpolicyAmendment` and `proposedNetworkPolicyAmendments`. Clients can prefer `availableDecisions` when present to render the exact set of choices the server wants to expose, while still falling back to the older heuristics if it is omitted.
|
||||
2. `item/commandExecution/requestApproval` (request) — carries the same `itemId`, `threadId`, `turnId`, the nullable `environmentId` where the command will run, optionally `approvalId` (for subcommand callbacks), and `reason`. New shell and unified-exec approvals set `environmentId`; older events that do not provide one are exposed as `null`. For normal command approvals, the request also includes `command`, `cwd`, and `commandActions` for friendly display. When `initialize.params.capabilities.experimentalApi = true`, it may also include experimental `additionalPermissions` describing requested per-command sandbox access; any filesystem paths in that payload are absolute on the wire, and network access is represented as `additionalPermissions.network.enabled`. For network-only approvals, those command fields may be omitted and `networkApprovalContext` is provided instead. Optional persistence hints may also be included via `proposedExecpolicyAmendment` and `proposedNetworkPolicyAmendments`. Clients can prefer `availableDecisions` when present to render the exact set of choices the server wants to expose, while still falling back to the older heuristics if it is omitted.
|
||||
3. Client response — for example `{ "decision": "accept" }`, `{ "decision": "acceptForSession" }`, `{ "decision": { "acceptWithExecpolicyAmendment": { "execpolicy_amendment": [...] } } }`, `{ "decision": { "applyNetworkPolicyAmendment": { "network_policy_amendment": { "host": "example.com", "action": "allow" } } } }`, `{ "decision": "decline" }`, or `{ "decision": "cancel" }`.
|
||||
4. `serverRequest/resolved` — `{ threadId, requestId }` confirms the pending request has been resolved or cleared, including lifecycle cleanup on turn start/complete/interrupt.
|
||||
5. `item/completed` — final `commandExecution` item with `status: "completed" | "failed" | "declined"` and execution output. Render this as the authoritative result.
|
||||
@@ -1825,15 +1826,24 @@ approvals_reviewer = "auto_review"
|
||||
|
||||
[apps._default]
|
||||
approvals_reviewer = "user"
|
||||
default_tools_approval_mode = "prompt"
|
||||
|
||||
[apps.demo-app]
|
||||
approvals_reviewer = "auto_review"
|
||||
default_tools_approval_mode = "approve"
|
||||
```
|
||||
|
||||
Setting the app value to `"user"` routes its approval prompts to the user
|
||||
instead of Guardian; setting it to `"auto_review"` opts that app into Guardian
|
||||
review when allowed by configuration requirements.
|
||||
|
||||
Use `apps._default.default_tools_approval_mode` to set the approval mode for
|
||||
tools without a per-app or per-tool override. Supported values are `"auto"`,
|
||||
`"prompt"`, and `"approve"`. Tool-level `approval_mode` takes precedence over
|
||||
the per-app `default_tools_approval_mode`, which takes precedence over the
|
||||
`apps._default` value. Managed tool requirements take precedence over all of
|
||||
these settings. When none are configured, the mode defaults to `"auto"`.
|
||||
|
||||
Invoke an app by inserting `$<app-slug>` in the text input. The slug is derived from the app name and lowercased with non-alphanumeric characters replaced by `-` (for example, "Demo App" becomes `$demo-app`). Add a `mention` input item (recommended) so the server uses the exact `app://<connector-id>` path rather than guessing by name. Plugins use the same `mention` item shape, but with `plugin://<plugin-name>@<marketplace-name>` paths from `plugin/installed` or `plugin/list`.
|
||||
|
||||
Example:
|
||||
@@ -1902,12 +1912,15 @@ Response examples:
|
||||
{ "id": 1, "result": { "account": null, "requiresOpenaiAuth": true } } // OpenAI auth required (typical for OpenAI-hosted models)
|
||||
{ "id": 1, "result": { "account": { "type": "apiKey" }, "requiresOpenaiAuth": true } }
|
||||
{ "id": 1, "result": { "account": { "type": "chatgpt", "email": "user@example.com", "planType": "pro" }, "requiresOpenaiAuth": true } }
|
||||
{ "id": 1, "result": { "account": { "type": "amazonBedrock", "credentialSource": "codexManaged" }, "requiresOpenaiAuth": false } }
|
||||
{ "id": 1, "result": { "account": { "type": "amazonBedrock", "credentialSource": "awsManaged" }, "requiresOpenaiAuth": false } }
|
||||
```
|
||||
|
||||
Field notes:
|
||||
|
||||
- `refreshToken` (bool): set `true` to force a token refresh.
|
||||
- `requiresOpenaiAuth` reflects the active provider; when `false`, Codex can run without OpenAI credentials.
|
||||
- Amazon Bedrock reports `credentialSource: "codexManaged"` when it uses a Bedrock API key managed by Codex. Otherwise it reports `credentialSource: "awsManaged"` for the external AWS credential path. This identifies the selected credential source; it does not validate that the AWS credential chain can resolve credentials.
|
||||
|
||||
### 2) Log in with an API key
|
||||
|
||||
|
||||
@@ -550,6 +550,7 @@ pub(crate) async fn apply_bespoke_event_handling(
|
||||
call_id,
|
||||
approval_id,
|
||||
turn_id,
|
||||
environment_id,
|
||||
started_at_ms,
|
||||
command,
|
||||
cwd,
|
||||
@@ -626,6 +627,7 @@ pub(crate) async fn apply_bespoke_event_handling(
|
||||
item_id: call_id.clone(),
|
||||
started_at_ms,
|
||||
approval_id: approval_id.clone(),
|
||||
environment_id,
|
||||
reason,
|
||||
network_approval_context,
|
||||
command,
|
||||
@@ -2259,6 +2261,7 @@ mod tests {
|
||||
reasoning_effort: None,
|
||||
created_at,
|
||||
updated_at: created_at,
|
||||
recency_at: created_at,
|
||||
archived_at: None,
|
||||
cwd: test_path_buf("/tmp").abs().into(),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
|
||||
@@ -237,6 +237,10 @@ impl CommandExecManager {
|
||||
arg0,
|
||||
..
|
||||
} = exec_request;
|
||||
// TODO(anp): Keep PathUri through the local command launch boundary.
|
||||
let cwd = cwd
|
||||
.to_abs_path()
|
||||
.map_err(|err| invalid_request(format!("invalid command cwd: {err}")))?;
|
||||
|
||||
let stream_stdin = tty || stream_stdin;
|
||||
let stream_stdout_stderr = tty || stream_stdout_stderr;
|
||||
|
||||
@@ -129,11 +129,6 @@ impl ExternalAgentConfigImportItemResult {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_successes(&mut self, count: usize) {
|
||||
let count = u32::try_from(count).unwrap_or(u32::MAX);
|
||||
self.success_count = self.success_count.saturating_add(count);
|
||||
}
|
||||
|
||||
pub(crate) fn record_error(&mut self, raw_error: ExternalAgentConfigImportRawError) {
|
||||
self.error_count = self.error_count.saturating_add(1);
|
||||
self.raw_errors.push(raw_error);
|
||||
@@ -161,6 +156,7 @@ pub(crate) struct ExternalAgentConfigImportSuccess {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct ExternalAgentConfigImportRawError {
|
||||
pub item_type: ExternalAgentConfigMigrationItemType,
|
||||
pub error_type: Option<String>,
|
||||
pub failure_stage: String,
|
||||
pub message: String,
|
||||
pub cwd: Option<PathBuf>,
|
||||
@@ -241,7 +237,7 @@ impl ExternalAgentConfigService {
|
||||
pub(crate) async fn import(
|
||||
&self,
|
||||
migration_items: Vec<ExternalAgentConfigMigrationItem>,
|
||||
) -> io::Result<ExternalAgentConfigImportOutcome> {
|
||||
) -> ExternalAgentConfigImportOutcome {
|
||||
let mut outcome = ExternalAgentConfigImportOutcome::default();
|
||||
for migration_item in migration_items {
|
||||
let item_type = migration_item.item_type;
|
||||
@@ -254,33 +250,41 @@ impl ExternalAgentConfigService {
|
||||
);
|
||||
let import_result = match migration_item.item_type {
|
||||
ExternalAgentConfigMigrationItemType::Config => (|| {
|
||||
let migrated_count = self.import_config(migration_item.cwd.as_deref())?;
|
||||
if let Some((source, target)) =
|
||||
self.import_config(migration_item.cwd.as_deref())?
|
||||
{
|
||||
item_result.record_success(Some(source), Some(target));
|
||||
}
|
||||
emit_migration_metric(
|
||||
EXTERNAL_AGENT_CONFIG_IMPORT_METRIC,
|
||||
ExternalAgentConfigMigrationItemType::Config,
|
||||
/*skills_count*/ None,
|
||||
);
|
||||
item_result.record_successes(migrated_count);
|
||||
Ok(())
|
||||
})(),
|
||||
ExternalAgentConfigMigrationItemType::Skills => (|| {
|
||||
let skills_count = self.import_skills(migration_item.cwd.as_deref())?;
|
||||
let imported_skills = self.import_skills(migration_item.cwd.as_deref())?;
|
||||
emit_migration_metric(
|
||||
EXTERNAL_AGENT_CONFIG_IMPORT_METRIC,
|
||||
ExternalAgentConfigMigrationItemType::Skills,
|
||||
Some(skills_count),
|
||||
Some(imported_skills.len()),
|
||||
);
|
||||
item_result.record_successes(skills_count);
|
||||
for skill_name in imported_skills {
|
||||
item_result.record_success(Some(skill_name.clone()), Some(skill_name));
|
||||
}
|
||||
Ok(())
|
||||
})(),
|
||||
ExternalAgentConfigMigrationItemType::AgentsMd => (|| {
|
||||
let migrated_count = self.import_agents_md(migration_item.cwd.as_deref())?;
|
||||
if let Some((source, target)) =
|
||||
self.import_agents_md(migration_item.cwd.as_deref())?
|
||||
{
|
||||
item_result.record_success(Some(source), Some(target));
|
||||
}
|
||||
emit_migration_metric(
|
||||
EXTERNAL_AGENT_CONFIG_IMPORT_METRIC,
|
||||
ExternalAgentConfigMigrationItemType::AgentsMd,
|
||||
/*skills_count*/ None,
|
||||
);
|
||||
item_result.record_successes(migrated_count);
|
||||
Ok(())
|
||||
})(),
|
||||
ExternalAgentConfigMigrationItemType::Plugins => {
|
||||
@@ -357,59 +361,80 @@ impl ExternalAgentConfigService {
|
||||
.await
|
||||
}
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig => (|| {
|
||||
let migrated_count =
|
||||
let migrated_server_names =
|
||||
self.import_mcp_server_config(migration_item.cwd.as_deref())?;
|
||||
emit_migration_metric(
|
||||
EXTERNAL_AGENT_CONFIG_IMPORT_METRIC,
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig,
|
||||
/*skills_count*/ None,
|
||||
);
|
||||
item_result.record_successes(migrated_count);
|
||||
for server_name in migrated_server_names {
|
||||
item_result.record_success(Some(server_name.clone()), Some(server_name));
|
||||
}
|
||||
Ok(())
|
||||
})(),
|
||||
ExternalAgentConfigMigrationItemType::Subagents => (|| {
|
||||
let subagents_count = self.import_subagents(migration_item.cwd.as_deref())?;
|
||||
let imported_subagents =
|
||||
self.import_subagents(migration_item.cwd.as_deref())?;
|
||||
emit_migration_metric(
|
||||
EXTERNAL_AGENT_CONFIG_IMPORT_METRIC,
|
||||
ExternalAgentConfigMigrationItemType::Subagents,
|
||||
Some(subagents_count),
|
||||
Some(imported_subagents.len()),
|
||||
);
|
||||
item_result.record_successes(subagents_count);
|
||||
for subagent_name in imported_subagents {
|
||||
item_result
|
||||
.record_success(Some(subagent_name.clone()), Some(subagent_name));
|
||||
}
|
||||
Ok(())
|
||||
})(),
|
||||
ExternalAgentConfigMigrationItemType::Hooks => (|| {
|
||||
let migrated_count = self.import_hooks(migration_item.cwd.as_deref())?;
|
||||
let migrated_hook_names = self.import_hooks(migration_item.cwd.as_deref())?;
|
||||
emit_migration_metric(
|
||||
EXTERNAL_AGENT_CONFIG_IMPORT_METRIC,
|
||||
ExternalAgentConfigMigrationItemType::Hooks,
|
||||
/*skills_count*/ None,
|
||||
);
|
||||
item_result.record_successes(migrated_count);
|
||||
for hook_name in migrated_hook_names {
|
||||
item_result.record_success(Some(hook_name.clone()), Some(hook_name));
|
||||
}
|
||||
Ok(())
|
||||
})(),
|
||||
ExternalAgentConfigMigrationItemType::Commands => (|| {
|
||||
let commands_count = self.import_commands(migration_item.cwd.as_deref())?;
|
||||
let imported_commands = self.import_commands(migration_item.cwd.as_deref())?;
|
||||
emit_migration_metric(
|
||||
EXTERNAL_AGENT_CONFIG_IMPORT_METRIC,
|
||||
ExternalAgentConfigMigrationItemType::Commands,
|
||||
Some(commands_count),
|
||||
Some(imported_commands.len()),
|
||||
);
|
||||
item_result.record_successes(commands_count);
|
||||
for command_name in imported_commands {
|
||||
item_result.record_success(Some(command_name.clone()), Some(command_name));
|
||||
}
|
||||
Ok(())
|
||||
})(),
|
||||
ExternalAgentConfigMigrationItemType::Sessions => Ok(()),
|
||||
};
|
||||
if let Err(err) = import_result {
|
||||
if item_type == ExternalAgentConfigMigrationItemType::Plugins {
|
||||
outcome.item_results.push(item_result);
|
||||
continue;
|
||||
}
|
||||
return Err(err);
|
||||
if let Err(err) = import_result
|
||||
&& item_type != ExternalAgentConfigMigrationItemType::Plugins
|
||||
{
|
||||
let message = err.to_string();
|
||||
let error_type = if message.contains("invalid existing config.toml") {
|
||||
"invalid_existing_config"
|
||||
} else {
|
||||
"external_agent_config_import_error"
|
||||
};
|
||||
item_result.record_error(ExternalAgentConfigImportRawError {
|
||||
item_type,
|
||||
error_type: Some(error_type.to_string()),
|
||||
failure_stage: "import_request_failed".to_string(),
|
||||
message,
|
||||
cwd: item_result.cwd.clone(),
|
||||
source: None,
|
||||
});
|
||||
}
|
||||
outcome.item_results.push(item_result);
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
outcome
|
||||
}
|
||||
|
||||
async fn detect_migrations(
|
||||
@@ -957,7 +982,7 @@ impl ExternalAgentConfigService {
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
fn import_config(&self, cwd: Option<&Path>) -> io::Result<usize> {
|
||||
fn import_config(&self, cwd: Option<&Path>) -> io::Result<Option<(String, String)>> {
|
||||
let repo_root = find_repo_root(cwd)?;
|
||||
let (source_settings, target_config) = if let Some(repo_root) = repo_root.as_ref() {
|
||||
(
|
||||
@@ -965,7 +990,7 @@ impl ExternalAgentConfigService {
|
||||
repo_root.join(".codex").join("config.toml"),
|
||||
)
|
||||
} else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) {
|
||||
return Ok(0);
|
||||
return Ok(None);
|
||||
} else {
|
||||
(
|
||||
self.external_agent_home.join("settings.json"),
|
||||
@@ -973,11 +998,11 @@ impl ExternalAgentConfigService {
|
||||
)
|
||||
};
|
||||
let Some(settings) = effective_external_settings(&source_settings)? else {
|
||||
return Ok(0);
|
||||
return Ok(None);
|
||||
};
|
||||
let migrated = build_config_from_external(&settings)?;
|
||||
if is_empty_toml_table(&migrated) {
|
||||
return Ok(0);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let Some(target_parent) = target_config.parent() else {
|
||||
@@ -986,7 +1011,10 @@ impl ExternalAgentConfigService {
|
||||
fs::create_dir_all(target_parent)?;
|
||||
if !target_config.exists() {
|
||||
write_toml_file(&target_config, &migrated)?;
|
||||
return Ok(1);
|
||||
return Ok(Some((
|
||||
source_settings.display().to_string(),
|
||||
target_config.display().to_string(),
|
||||
)));
|
||||
}
|
||||
|
||||
let existing_raw = fs::read_to_string(&target_config)?;
|
||||
@@ -999,14 +1027,17 @@ impl ExternalAgentConfigService {
|
||||
|
||||
let changed = merge_missing_toml_values(&mut existing, &migrated)?;
|
||||
if !changed {
|
||||
return Ok(0);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
write_toml_file(&target_config, &existing)?;
|
||||
Ok(1)
|
||||
Ok(Some((
|
||||
source_settings.display().to_string(),
|
||||
target_config.display().to_string(),
|
||||
)))
|
||||
}
|
||||
|
||||
fn import_mcp_server_config(&self, cwd: Option<&Path>) -> io::Result<usize> {
|
||||
fn import_mcp_server_config(&self, cwd: Option<&Path>) -> io::Result<Vec<String>> {
|
||||
let repo_root = find_repo_root(cwd)?;
|
||||
let (source_settings, target_config) = if let Some(repo_root) = repo_root.as_ref() {
|
||||
(
|
||||
@@ -1014,7 +1045,7 @@ impl ExternalAgentConfigService {
|
||||
repo_root.join(".codex").join("config.toml"),
|
||||
)
|
||||
} else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) {
|
||||
return Ok(0);
|
||||
return Ok(Vec::new());
|
||||
} else {
|
||||
(
|
||||
self.external_agent_home.join("settings.json"),
|
||||
@@ -1031,7 +1062,7 @@ impl ExternalAgentConfigService {
|
||||
settings.as_ref(),
|
||||
)?;
|
||||
if is_empty_toml_table(&migrated) {
|
||||
return Ok(0);
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let Some(target_parent) = target_config.parent() else {
|
||||
@@ -1039,9 +1070,9 @@ impl ExternalAgentConfigService {
|
||||
};
|
||||
fs::create_dir_all(target_parent)?;
|
||||
if !target_config.exists() {
|
||||
let migrated_count = migrated_mcp_server_names(&migrated).len();
|
||||
let migrated_server_names = migrated_mcp_server_names(&migrated);
|
||||
write_toml_file(&target_config, &migrated)?;
|
||||
return Ok(migrated_count);
|
||||
return Ok(migrated_server_names);
|
||||
}
|
||||
|
||||
let existing_raw = fs::read_to_string(&target_config)?;
|
||||
@@ -1051,21 +1082,21 @@ impl ExternalAgentConfigService {
|
||||
toml::from_str::<TomlValue>(&existing_raw)
|
||||
.map_err(|err| invalid_data_error(format!("invalid existing config.toml: {err}")))?
|
||||
};
|
||||
let merged_server_count = merge_missing_mcp_servers(&mut existing, &migrated)?.len();
|
||||
if merged_server_count > 0 {
|
||||
let merged_server_names = merge_missing_mcp_servers(&mut existing, &migrated)?;
|
||||
if !merged_server_names.is_empty() {
|
||||
write_toml_file(&target_config, &existing)?;
|
||||
}
|
||||
Ok(merged_server_count)
|
||||
Ok(merged_server_names)
|
||||
}
|
||||
|
||||
fn import_subagents(&self, cwd: Option<&Path>) -> io::Result<usize> {
|
||||
fn import_subagents(&self, cwd: Option<&Path>) -> io::Result<Vec<String>> {
|
||||
let (source_agents, target_agents) = if let Some(repo_root) = find_repo_root(cwd)? {
|
||||
(
|
||||
repo_root.join(EXTERNAL_AGENT_DIR).join("agents"),
|
||||
repo_root.join(".codex").join("agents"),
|
||||
)
|
||||
} else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) {
|
||||
return Ok(0);
|
||||
return Ok(Vec::new());
|
||||
} else {
|
||||
(
|
||||
self.external_agent_home.join("agents"),
|
||||
@@ -1076,7 +1107,7 @@ impl ExternalAgentConfigService {
|
||||
import_subagents(&source_agents, &target_agents)
|
||||
}
|
||||
|
||||
fn import_hooks(&self, cwd: Option<&Path>) -> io::Result<usize> {
|
||||
fn import_hooks(&self, cwd: Option<&Path>) -> io::Result<Vec<String>> {
|
||||
let (source_external_agent_dir, target_hooks) =
|
||||
if let Some(repo_root) = find_repo_root(cwd)? {
|
||||
(
|
||||
@@ -1084,7 +1115,7 @@ impl ExternalAgentConfigService {
|
||||
repo_root.join(".codex").join("hooks.json"),
|
||||
)
|
||||
} else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) {
|
||||
return Ok(0);
|
||||
return Ok(Vec::new());
|
||||
} else {
|
||||
(
|
||||
self.external_agent_home.clone(),
|
||||
@@ -1092,20 +1123,22 @@ impl ExternalAgentConfigService {
|
||||
)
|
||||
};
|
||||
|
||||
Ok(usize::from(import_hooks(
|
||||
&source_external_agent_dir,
|
||||
&target_hooks,
|
||||
)?))
|
||||
let hook_names = hook_migration_event_names(&source_external_agent_dir, &target_hooks)?;
|
||||
if import_hooks(&source_external_agent_dir, &target_hooks)? {
|
||||
Ok(hook_names)
|
||||
} else {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
fn import_commands(&self, cwd: Option<&Path>) -> io::Result<usize> {
|
||||
fn import_commands(&self, cwd: Option<&Path>) -> io::Result<Vec<String>> {
|
||||
let (source_commands, target_skills) = if let Some(repo_root) = find_repo_root(cwd)? {
|
||||
(
|
||||
repo_root.join(EXTERNAL_AGENT_DIR).join("commands"),
|
||||
repo_root.join(".agents").join("skills"),
|
||||
)
|
||||
} else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) {
|
||||
return Ok(0);
|
||||
return Ok(Vec::new());
|
||||
} else {
|
||||
(
|
||||
self.external_agent_home.join("commands"),
|
||||
@@ -1116,14 +1149,14 @@ impl ExternalAgentConfigService {
|
||||
import_commands(&source_commands, &target_skills)
|
||||
}
|
||||
|
||||
fn import_skills(&self, cwd: Option<&Path>) -> io::Result<usize> {
|
||||
fn import_skills(&self, cwd: Option<&Path>) -> io::Result<Vec<String>> {
|
||||
let (source_skills, target_skills) = if let Some(repo_root) = find_repo_root(cwd)? {
|
||||
(
|
||||
repo_root.join(EXTERNAL_AGENT_DIR).join("skills"),
|
||||
repo_root.join(".agents").join("skills"),
|
||||
)
|
||||
} else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) {
|
||||
return Ok(0);
|
||||
return Ok(Vec::new());
|
||||
} else {
|
||||
(
|
||||
self.external_agent_home.join("skills"),
|
||||
@@ -1131,11 +1164,11 @@ impl ExternalAgentConfigService {
|
||||
)
|
||||
};
|
||||
if !source_skills.is_dir() {
|
||||
return Ok(0);
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
fs::create_dir_all(&target_skills)?;
|
||||
let mut copied_count = 0usize;
|
||||
let mut copied_names = Vec::new();
|
||||
|
||||
for entry in fs::read_dir(&source_skills)? {
|
||||
let entry = entry?;
|
||||
@@ -1150,20 +1183,20 @@ impl ExternalAgentConfigService {
|
||||
}
|
||||
|
||||
copy_dir_recursive(&entry.path(), &target)?;
|
||||
copied_count += 1;
|
||||
copied_names.push(entry.file_name().to_string_lossy().to_string());
|
||||
}
|
||||
|
||||
Ok(copied_count)
|
||||
Ok(copied_names)
|
||||
}
|
||||
|
||||
fn import_agents_md(&self, cwd: Option<&Path>) -> io::Result<usize> {
|
||||
fn import_agents_md(&self, cwd: Option<&Path>) -> io::Result<Option<(String, String)>> {
|
||||
let (source_agents_md, target_agents_md) = if let Some(repo_root) = find_repo_root(cwd)? {
|
||||
let Some(source_agents_md) = find_repo_agents_md_source(&repo_root)? else {
|
||||
return Ok(0);
|
||||
return Ok(None);
|
||||
};
|
||||
(source_agents_md, repo_root.join("AGENTS.md"))
|
||||
} else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) {
|
||||
return Ok(0);
|
||||
return Ok(None);
|
||||
} else {
|
||||
(
|
||||
self.external_agent_home.join(EXTERNAL_AGENT_CONFIG_MD),
|
||||
@@ -1173,7 +1206,7 @@ impl ExternalAgentConfigService {
|
||||
if !is_non_empty_text_file(&source_agents_md)?
|
||||
|| !is_missing_or_empty_text_file(&target_agents_md)?
|
||||
{
|
||||
return Ok(0);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let Some(target_parent) = target_agents_md.parent() else {
|
||||
@@ -1182,7 +1215,10 @@ impl ExternalAgentConfigService {
|
||||
fs::create_dir_all(target_parent)?;
|
||||
|
||||
rewrite_and_copy_text_file(&source_agents_md, &target_agents_md)?;
|
||||
Ok(1)
|
||||
Ok(Some((
|
||||
source_agents_md.display().to_string(),
|
||||
target_agents_md.display().to_string(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1826,6 +1862,7 @@ pub(crate) fn record_import_error(
|
||||
) {
|
||||
result.record_error(ExternalAgentConfigImportRawError {
|
||||
item_type: result.item_type,
|
||||
error_type: None,
|
||||
failure_stage: failure_stage.to_string(),
|
||||
message: message.into(),
|
||||
cwd: result.cwd.clone(),
|
||||
@@ -1856,6 +1893,7 @@ fn plugin_import_raw_error(
|
||||
) -> ExternalAgentConfigImportRawError {
|
||||
ExternalAgentConfigImportRawError {
|
||||
item_type: ExternalAgentConfigMigrationItemType::Plugins,
|
||||
error_type: None,
|
||||
failure_stage: failure_stage.to_string(),
|
||||
message,
|
||||
cwd: cwd.map(Path::to_path_buf),
|
||||
|
||||
@@ -47,11 +47,26 @@ fn assert_single_plugin_raw_error(
|
||||
ExternalAgentConfigMigrationItemType::Plugins
|
||||
);
|
||||
assert_eq!(raw_error.failure_stage, failure_stage);
|
||||
assert_eq!(raw_error.error_type, None);
|
||||
assert_eq!(raw_error.cwd, None);
|
||||
assert_eq!(raw_error.source.as_deref(), Some(source));
|
||||
assert!(!raw_error.message.is_empty());
|
||||
}
|
||||
|
||||
fn import_success(
|
||||
item_type: ExternalAgentConfigMigrationItemType,
|
||||
cwd: Option<PathBuf>,
|
||||
source: impl Into<String>,
|
||||
target: impl Into<String>,
|
||||
) -> ExternalAgentConfigImportSuccess {
|
||||
ExternalAgentConfigImportSuccess {
|
||||
item_type,
|
||||
cwd,
|
||||
source: Some(source.into()),
|
||||
target: Some(target.into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn detect_home_lists_config_skills_and_agents_md() {
|
||||
let (_root, external_agent_home, codex_home) = fixture_paths();
|
||||
@@ -546,8 +561,7 @@ async fn import_repo_migrates_mcp_hooks_commands_and_subagents() {
|
||||
details: None,
|
||||
},
|
||||
])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
let config: TomlValue = toml::from_str(
|
||||
&fs::read_to_string(repo_root.join(".codex").join("config.toml")).expect("read config"),
|
||||
@@ -709,8 +723,7 @@ url = "https://example.com/mixed-transport"
|
||||
cwd: Some(repo_root.clone()),
|
||||
details: None,
|
||||
}])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
fs::read_to_string(repo_root.join(".codex").join("config.toml")).expect("read config"),
|
||||
@@ -823,8 +836,7 @@ async fn import_home_migrates_supported_config_fields_skills_and_agents_md() {
|
||||
details: None,
|
||||
},
|
||||
])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
fs::read_to_string(codex_home.join("AGENTS.md")).expect("read agents"),
|
||||
@@ -879,8 +891,7 @@ async fn import_home_config_uses_local_settings_over_project_settings() {
|
||||
cwd: None,
|
||||
details: None,
|
||||
}])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
let config: TomlValue =
|
||||
toml::from_str(&fs::read_to_string(codex_home.join("config.toml")).expect("read config"))
|
||||
@@ -924,8 +935,7 @@ async fn import_home_config_ignores_invalid_local_settings() {
|
||||
cwd: None,
|
||||
details: None,
|
||||
}])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
fs::read_to_string(codex_home.join("config.toml")).expect("read config"),
|
||||
@@ -950,8 +960,7 @@ async fn import_home_skips_empty_config_migration() {
|
||||
cwd: None,
|
||||
details: None,
|
||||
}])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome.item_results,
|
||||
@@ -1028,8 +1037,7 @@ async fn import_local_plugins_returns_completed_status() {
|
||||
..Default::default()
|
||||
}),
|
||||
}])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome.pending_plugin_imports,
|
||||
@@ -1089,8 +1097,7 @@ async fn import_git_plugins_returns_pending_async_status() {
|
||||
..Default::default()
|
||||
}),
|
||||
}])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome.pending_plugin_imports,
|
||||
@@ -1220,8 +1227,7 @@ async fn import_repo_agents_md_rewrites_terms_and_skips_non_empty_targets() {
|
||||
details: None,
|
||||
},
|
||||
])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome.item_results,
|
||||
@@ -1232,7 +1238,15 @@ async fn import_repo_agents_md_rewrites_terms_and_skips_non_empty_targets() {
|
||||
cwd: Some(repo_root.clone()),
|
||||
success_count: 1,
|
||||
error_count: 0,
|
||||
successes: Vec::new(),
|
||||
successes: vec![import_success(
|
||||
ExternalAgentConfigMigrationItemType::AgentsMd,
|
||||
Some(repo_root.clone()),
|
||||
repo_root
|
||||
.join(EXTERNAL_AGENT_CONFIG_MD)
|
||||
.display()
|
||||
.to_string(),
|
||||
repo_root.join("AGENTS.md").display().to_string(),
|
||||
)],
|
||||
raw_errors: Vec::new(),
|
||||
},
|
||||
ExternalAgentConfigImportItemResult {
|
||||
@@ -1279,8 +1293,7 @@ async fn import_repo_agents_md_overwrites_empty_targets() {
|
||||
cwd: Some(repo_root.clone()),
|
||||
details: None,
|
||||
}])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome.item_results,
|
||||
@@ -1290,7 +1303,15 @@ async fn import_repo_agents_md_overwrites_empty_targets() {
|
||||
cwd: Some(repo_root.clone()),
|
||||
success_count: 1,
|
||||
error_count: 0,
|
||||
successes: Vec::new(),
|
||||
successes: vec![import_success(
|
||||
ExternalAgentConfigMigrationItemType::AgentsMd,
|
||||
Some(repo_root.clone()),
|
||||
repo_root
|
||||
.join(EXTERNAL_AGENT_CONFIG_MD)
|
||||
.display()
|
||||
.to_string(),
|
||||
repo_root.join("AGENTS.md").display().to_string(),
|
||||
)],
|
||||
raw_errors: Vec::new(),
|
||||
}]
|
||||
);
|
||||
@@ -1372,8 +1393,7 @@ async fn import_repo_hooks_preserves_disabled_codex_hooks_feature() {
|
||||
cwd: Some(repo_root.clone()),
|
||||
details: None,
|
||||
}])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome.item_results,
|
||||
@@ -1383,7 +1403,12 @@ async fn import_repo_hooks_preserves_disabled_codex_hooks_feature() {
|
||||
cwd: Some(repo_root.clone()),
|
||||
success_count: 1,
|
||||
error_count: 0,
|
||||
successes: Vec::new(),
|
||||
successes: vec![import_success(
|
||||
ExternalAgentConfigMigrationItemType::Hooks,
|
||||
Some(repo_root.clone()),
|
||||
"Stop",
|
||||
"Stop",
|
||||
)],
|
||||
raw_errors: Vec::new(),
|
||||
}]
|
||||
);
|
||||
@@ -1445,8 +1470,7 @@ async fn import_repo_mcp_uses_home_settings_toggles_when_repo_settings_missing()
|
||||
cwd: Some(repo_root.clone()),
|
||||
details: None,
|
||||
}])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome.item_results,
|
||||
@@ -1456,7 +1480,12 @@ async fn import_repo_mcp_uses_home_settings_toggles_when_repo_settings_missing()
|
||||
cwd: Some(repo_root.clone()),
|
||||
success_count: 1,
|
||||
error_count: 0,
|
||||
successes: Vec::new(),
|
||||
successes: vec![import_success(
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig,
|
||||
Some(repo_root.clone()),
|
||||
"allowed",
|
||||
"allowed",
|
||||
)],
|
||||
raw_errors: Vec::new(),
|
||||
}]
|
||||
);
|
||||
@@ -1518,8 +1547,7 @@ async fn import_repo_mcp_uses_local_settings_toggles_over_project_settings() {
|
||||
cwd: Some(repo_root.clone()),
|
||||
details: None,
|
||||
}])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
let config: TomlValue = toml::from_str(
|
||||
&fs::read_to_string(repo_root.join(".codex").join("config.toml")).expect("read config"),
|
||||
@@ -1566,8 +1594,7 @@ async fn import_repo_mcp_ignores_invalid_home_settings_when_repo_settings_missin
|
||||
cwd: Some(repo_root.clone()),
|
||||
details: None,
|
||||
}])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
let config: TomlValue = toml::from_str(
|
||||
&fs::read_to_string(repo_root.join(".codex").join("config.toml")).expect("read config"),
|
||||
@@ -1608,8 +1635,7 @@ async fn import_repo_uses_non_empty_external_agent_agents_source() {
|
||||
cwd: Some(repo_root.clone()),
|
||||
details: None,
|
||||
}])
|
||||
.await
|
||||
.expect("import");
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
fs::read_to_string(repo_root.join("AGENTS.md")).expect("read target"),
|
||||
@@ -1642,8 +1668,7 @@ async fn import_continues_after_failed_migration_item() {
|
||||
details: None,
|
||||
},
|
||||
])
|
||||
.await
|
||||
.expect("import continues");
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
fs::read_to_string(repo_root.join("AGENTS.md")).expect("read target"),
|
||||
@@ -2745,7 +2770,7 @@ async fn import_plugins_supports_project_relative_external_agent_plugin_marketpl
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_skills_returns_only_new_skill_directory_count() {
|
||||
fn import_skills_returns_only_new_skill_directory_names() {
|
||||
let (_root, external_agent_home, codex_home) = fixture_paths();
|
||||
let agents_skills = codex_home
|
||||
.parent()
|
||||
@@ -2757,9 +2782,9 @@ fn import_skills_returns_only_new_skill_directory_count() {
|
||||
.expect("create source b");
|
||||
fs::create_dir_all(agents_skills.join("skill-a")).expect("create existing target");
|
||||
|
||||
let copied_count = service_for_paths(external_agent_home, codex_home)
|
||||
let copied_names = service_for_paths(external_agent_home, codex_home)
|
||||
.import_skills(/*cwd*/ None)
|
||||
.expect("import skills");
|
||||
|
||||
assert_eq!(copied_count, 1);
|
||||
assert_eq!(copied_names, vec!["skill-b".to_string()]);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ use codex_config::ThreadConfigLoader;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::resolve_installation_id;
|
||||
use codex_login::AuthManager;
|
||||
#[cfg(debug_assertions)]
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
@@ -99,6 +101,7 @@ pub mod in_process;
|
||||
mod mcp_refresh;
|
||||
mod message_processor;
|
||||
mod models;
|
||||
mod models_refresh_worker;
|
||||
mod outgoing_message;
|
||||
mod request_processors;
|
||||
mod request_serialization;
|
||||
@@ -120,6 +123,8 @@ pub use crate::transport::take_remote_control_disabled_env;
|
||||
|
||||
const LOG_FORMAT_ENV_VAR: &str = "LOG_FORMAT";
|
||||
const OTEL_SERVICE_NAME: &str = "codex-app-server";
|
||||
#[cfg(debug_assertions)]
|
||||
const TEST_USER_CONFIG_FILE_ENV_VAR: &str = "CODEX_APP_SERVER_TEST_USER_CONFIG_FILE";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum LogFormat {
|
||||
@@ -437,6 +442,10 @@ pub async fn run_main_with_transport_options(
|
||||
auth: AppServerWebsocketAuthSettings,
|
||||
runtime_options: AppServerRuntimeOptions,
|
||||
) -> IoResult<()> {
|
||||
let loader_overrides = loader_overrides_with_test_user_config_file(
|
||||
loader_overrides,
|
||||
test_user_config_file_from_env(),
|
||||
)?;
|
||||
let (transport_event_tx, mut transport_event_rx) =
|
||||
mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
|
||||
let (outgoing_tx, mut outgoing_rx) = mpsc::channel::<OutgoingEnvelope>(CHANNEL_CAPACITY);
|
||||
@@ -1295,6 +1304,43 @@ fn emit_state_db_backup_warning(message: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
fn test_user_config_file_from_env() -> Option<std::path::PathBuf> {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
std::env::var_os(TEST_USER_CONFIG_FILE_ENV_VAR)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(std::path::PathBuf::from)
|
||||
}
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
None
|
||||
}
|
||||
|
||||
fn loader_overrides_with_test_user_config_file(
|
||||
mut loader_overrides: LoaderOverrides,
|
||||
test_user_config_file: Option<std::path::PathBuf>,
|
||||
) -> IoResult<LoaderOverrides> {
|
||||
#[cfg(debug_assertions)]
|
||||
if let Some(path) = test_user_config_file {
|
||||
let path = AbsolutePathBuf::from_absolute_path(path).map_err(|err| {
|
||||
std::io::Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!("invalid test user config path: {err}"),
|
||||
)
|
||||
})?;
|
||||
warn!(
|
||||
path = %path.as_path().display(),
|
||||
"using debug-only app-server test user config file"
|
||||
);
|
||||
loader_overrides.user_config_path = Some(path);
|
||||
}
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
let _ = test_user_config_file;
|
||||
|
||||
Ok(loader_overrides)
|
||||
}
|
||||
|
||||
fn analytics_rpc_transport(transport: &AppServerTransport) -> AppServerRpcTransport {
|
||||
match transport {
|
||||
AppServerTransport::Stdio => AppServerRpcTransport::Stdio,
|
||||
@@ -1307,6 +1353,12 @@ fn analytics_rpc_transport(transport: &AppServerTransport) -> AppServerRpcTransp
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::LogFormat;
|
||||
#[cfg(debug_assertions)]
|
||||
use super::loader_overrides_with_test_user_config_file;
|
||||
#[cfg(debug_assertions)]
|
||||
use codex_config::LoaderOverrides;
|
||||
#[cfg(debug_assertions)]
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
@@ -1326,4 +1378,20 @@ mod tests {
|
||||
assert_eq!(LogFormat::from_env_value(Some("text")), LogFormat::Default);
|
||||
assert_eq!(LogFormat::from_env_value(Some("jsonl")), LogFormat::Default);
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
#[test]
|
||||
fn debug_test_user_config_file_overrides_loader_path() {
|
||||
let path = std::env::temp_dir().join("codex-app-server-test-config.toml");
|
||||
let loader_overrides = loader_overrides_with_test_user_config_file(
|
||||
LoaderOverrides::default(),
|
||||
Some(path.clone()),
|
||||
)
|
||||
.expect("test config path should be valid");
|
||||
|
||||
assert_eq!(
|
||||
loader_overrides.user_config_path,
|
||||
Some(AbsolutePathBuf::from_absolute_path(path).expect("absolute test path"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ use crate::request_processors::CommandExecRequestProcessor;
|
||||
use crate::request_processors::ConfigRequestProcessor;
|
||||
use crate::request_processors::EnvironmentRequestProcessor;
|
||||
use crate::request_processors::ExternalAgentConfigRequestProcessor;
|
||||
use crate::request_processors::ExternalAgentConfigRequestProcessorArgs;
|
||||
use crate::request_processors::FeedbackRequestProcessor;
|
||||
use crate::request_processors::FsRequestProcessor;
|
||||
use crate::request_processors::GitRequestProcessor;
|
||||
@@ -91,6 +92,8 @@ use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::Instrument;
|
||||
|
||||
use crate::models_refresh_worker::ModelsRefreshWorker;
|
||||
|
||||
const EXTERNAL_AUTH_REFRESH_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const CONNECTION_RPC_DRAIN_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30);
|
||||
|
||||
@@ -181,6 +184,7 @@ impl ExternalAuth for ExternalAuthRefreshBridge {
|
||||
|
||||
pub(crate) struct MessageProcessor {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
models_refresh_worker: ModelsRefreshWorker,
|
||||
skills_watcher: Arc<SkillsWatcher>,
|
||||
account_processor: AccountRequestProcessor,
|
||||
apps_processor: AppsRequestProcessor,
|
||||
@@ -370,10 +374,12 @@ impl MessageProcessor {
|
||||
)),
|
||||
)
|
||||
});
|
||||
let models_manager = thread_manager.get_models_manager();
|
||||
let models_refresh_worker = crate::models_refresh_worker::spawn(&models_manager);
|
||||
thread_manager
|
||||
.plugins_manager()
|
||||
.set_analytics_events_client(analytics_events_client.clone());
|
||||
let skills_watcher = SkillsWatcher::new(thread_manager.skills_manager(), outgoing.clone());
|
||||
let skills_watcher = SkillsWatcher::new(thread_manager.skills_service(), outgoing.clone());
|
||||
|
||||
let pending_thread_unloads = Arc::new(Mutex::new(HashSet::new()));
|
||||
let thread_watch_manager =
|
||||
@@ -475,7 +481,7 @@ impl MessageProcessor {
|
||||
thread_watch_manager.clone(),
|
||||
Arc::clone(&thread_list_state_permit),
|
||||
thread_goal_processor.clone(),
|
||||
state_db,
|
||||
state_db.clone(),
|
||||
log_db,
|
||||
Arc::clone(&skills_watcher),
|
||||
);
|
||||
@@ -509,17 +515,20 @@ impl MessageProcessor {
|
||||
outgoing.clone(),
|
||||
config_manager.clone(),
|
||||
thread_manager.clone(),
|
||||
analytics_events_client,
|
||||
);
|
||||
let external_agent_config_processor = ExternalAgentConfigRequestProcessor::new(
|
||||
outgoing.clone(),
|
||||
Arc::clone(&thread_manager),
|
||||
Arc::clone(&thread_store),
|
||||
config_manager.clone(),
|
||||
config_processor.clone(),
|
||||
arg0_paths,
|
||||
config.codex_home.to_path_buf(),
|
||||
analytics_events_client.clone(),
|
||||
);
|
||||
let external_agent_config_processor =
|
||||
ExternalAgentConfigRequestProcessor::new(ExternalAgentConfigRequestProcessorArgs {
|
||||
outgoing: outgoing.clone(),
|
||||
thread_manager: Arc::clone(&thread_manager),
|
||||
thread_store: Arc::clone(&thread_store),
|
||||
config_manager: config_manager.clone(),
|
||||
config_processor: config_processor.clone(),
|
||||
state_db,
|
||||
analytics_events_client,
|
||||
arg0_paths,
|
||||
codex_home: config.codex_home.to_path_buf(),
|
||||
});
|
||||
let environment_processor =
|
||||
EnvironmentRequestProcessor::new(thread_manager.environment_manager());
|
||||
let fs_processor = FsRequestProcessor::new(
|
||||
@@ -534,6 +543,7 @@ impl MessageProcessor {
|
||||
|
||||
Self {
|
||||
outgoing,
|
||||
models_refresh_worker,
|
||||
skills_watcher,
|
||||
account_processor,
|
||||
apps_processor,
|
||||
@@ -563,6 +573,7 @@ impl MessageProcessor {
|
||||
pub(crate) fn clear_runtime_references(&self) {
|
||||
self.account_processor.clear_external_auth();
|
||||
self.apps_processor.shutdown();
|
||||
self.models_refresh_worker.shutdown();
|
||||
self.skills_watcher.shutdown();
|
||||
}
|
||||
|
||||
@@ -739,6 +750,7 @@ impl MessageProcessor {
|
||||
}
|
||||
|
||||
pub(crate) async fn drain_background_tasks(&self) {
|
||||
self.models_refresh_worker.shutdown();
|
||||
self.thread_processor.drain_background_tasks().await;
|
||||
}
|
||||
|
||||
@@ -947,6 +959,11 @@ impl MessageProcessor {
|
||||
.import(request_id.clone(), params)
|
||||
.await
|
||||
.map(|()| None),
|
||||
ClientRequest::ExternalAgentConfigImportHistoriesRead { .. } => self
|
||||
.external_agent_config_processor
|
||||
.read_import_histories()
|
||||
.await
|
||||
.map(|response| Some(response.into())),
|
||||
ClientRequest::ConfigValueWrite { params, .. } => {
|
||||
self.config_processor.value_write(params).await.map(Some)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
const MODELS_REFRESH_INTERVAL: Duration = Duration::from_secs(3 * 60);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ModelsRefreshWorker {
|
||||
shutdown: CancellationToken,
|
||||
_task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl ModelsRefreshWorker {
|
||||
pub(crate) fn shutdown(&self) {
|
||||
self.shutdown.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ModelsRefreshWorker {
|
||||
fn drop(&mut self) {
|
||||
self.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn spawn(models_manager: &SharedModelsManager) -> ModelsRefreshWorker {
|
||||
spawn_with_interval(models_manager, MODELS_REFRESH_INTERVAL)
|
||||
}
|
||||
|
||||
fn spawn_with_interval(
|
||||
models_manager: &SharedModelsManager,
|
||||
refresh_interval: Duration,
|
||||
) -> ModelsRefreshWorker {
|
||||
let models_manager = Arc::downgrade(models_manager);
|
||||
let shutdown = CancellationToken::new();
|
||||
let worker_shutdown = shutdown.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
loop {
|
||||
if worker_shutdown.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
let Some(models_manager) = models_manager.upgrade() else {
|
||||
break;
|
||||
};
|
||||
models_manager.list_models(RefreshStrategy::Online).await;
|
||||
drop(models_manager);
|
||||
|
||||
tokio::select! {
|
||||
_ = worker_shutdown.cancelled() => break,
|
||||
_ = tokio::time::sleep(refresh_interval) => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
ModelsRefreshWorker {
|
||||
shutdown,
|
||||
_task: task,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "models_refresh_worker_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,90 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_models_manager::manager::ModelsEndpointClient;
|
||||
use codex_models_manager::manager::ModelsEndpointFuture;
|
||||
use codex_models_manager::manager::OpenAiModelsManager;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CoreResult;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TestModelsEndpoint {
|
||||
fetch_count: AtomicUsize,
|
||||
fetched: Notify,
|
||||
release_second_fetch: Notify,
|
||||
}
|
||||
|
||||
impl TestModelsEndpoint {
|
||||
fn new() -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
fetch_count: AtomicUsize::new(0),
|
||||
fetched: Notify::new(),
|
||||
release_second_fetch: Notify::new(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn wait_for_fetch_count(&self, expected: usize) {
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while self.fetch_count.load(Ordering::SeqCst) < expected {
|
||||
self.fetched.notified().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("expected {expected} model fetches"));
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelsEndpointClient for TestModelsEndpoint {
|
||||
fn has_command_auth(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn uses_codex_backend(&self) -> ModelsEndpointFuture<'_, bool> {
|
||||
Box::pin(async { false })
|
||||
}
|
||||
|
||||
fn list_models<'a>(
|
||||
&'a self,
|
||||
_client_version: &'a str,
|
||||
) -> ModelsEndpointFuture<'a, CoreResult<(Vec<ModelInfo>, Option<String>)>> {
|
||||
Box::pin(async move {
|
||||
let fetch_index = self.fetch_count.fetch_add(1, Ordering::SeqCst);
|
||||
self.fetched.notify_one();
|
||||
if fetch_index == 0 {
|
||||
return Err(CodexErr::Io(std::io::Error::other("test failure")));
|
||||
}
|
||||
if fetch_index == 1 {
|
||||
self.release_second_fetch.notified().await;
|
||||
}
|
||||
Ok((Vec::new(), None))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refreshes_immediately_periodically_and_stops_when_dropped() {
|
||||
let codex_home = tempdir().expect("temp dir");
|
||||
let endpoint = TestModelsEndpoint::new();
|
||||
let models_manager: SharedModelsManager = Arc::new(OpenAiModelsManager::new(
|
||||
codex_home.path().to_path_buf(),
|
||||
endpoint.clone(),
|
||||
/*auth_manager*/ None,
|
||||
));
|
||||
let worker = spawn_with_interval(&models_manager, Duration::from_millis(10));
|
||||
|
||||
endpoint.wait_for_fetch_count(/*expected*/ 2).await;
|
||||
drop(worker);
|
||||
endpoint.release_second_fetch.notify_one();
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
|
||||
assert_eq!(endpoint.fetch_count.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
@@ -977,6 +977,7 @@ mod tests {
|
||||
item_id: "item-1".to_string(),
|
||||
started_at_ms: 0,
|
||||
approval_id: None,
|
||||
environment_id: None,
|
||||
reason: None,
|
||||
network_approval_context: None,
|
||||
command: Some("echo hi".to_string()),
|
||||
|
||||
@@ -506,6 +506,7 @@ pub(crate) use command_exec_processor::CommandExecRequestProcessor;
|
||||
pub(crate) use config_processor::ConfigRequestProcessor;
|
||||
pub(crate) use environment_processor::EnvironmentRequestProcessor;
|
||||
pub(crate) use external_agent_config_processor::ExternalAgentConfigRequestProcessor;
|
||||
pub(crate) use external_agent_config_processor::ExternalAgentConfigRequestProcessorArgs;
|
||||
pub(crate) use feedback_processor::FeedbackRequestProcessor;
|
||||
pub(crate) use fs_processor::FsRequestProcessor;
|
||||
pub(crate) use git_processor::GitRequestProcessor;
|
||||
@@ -540,6 +541,37 @@ fn resolve_request_cwd(cwd: Option<PathBuf>) -> Result<Option<AbsolutePathBuf>,
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn resolve_turn_environment_selections(
|
||||
thread_manager: &ThreadManager,
|
||||
environments: Option<Vec<TurnEnvironmentParams>>,
|
||||
) -> Result<Option<Vec<TurnEnvironmentSelection>>, JSONRPCErrorError> {
|
||||
let Some(environments) = environments else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut selections = Vec::with_capacity(environments.len());
|
||||
for environment in environments {
|
||||
let environment_id = environment.environment_id;
|
||||
let cwd = environment
|
||||
.cwd
|
||||
.infer_absolute_path_convention()
|
||||
.and_then(|convention| environment.cwd.to_path_uri(convention).ok())
|
||||
.ok_or_else(|| {
|
||||
invalid_request(format!(
|
||||
"invalid cwd for environment `{environment_id}`: path `{}` does not use absolute POSIX or Windows path syntax",
|
||||
environment.cwd
|
||||
))
|
||||
})?;
|
||||
selections.push(TurnEnvironmentSelection {
|
||||
environment_id,
|
||||
cwd,
|
||||
});
|
||||
}
|
||||
thread_manager
|
||||
.validate_environment_selections(&selections)
|
||||
.map_err(environment_selection_error)?;
|
||||
Ok(Some(selections))
|
||||
}
|
||||
|
||||
fn resolve_runtime_workspace_roots(workspace_roots: Vec<AbsolutePathBuf>) -> Vec<AbsolutePathBuf> {
|
||||
let mut resolved_roots = Vec::new();
|
||||
for root in workspace_roots {
|
||||
|
||||
@@ -173,7 +173,7 @@ impl AccountRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
async fn maybe_refresh_remote_installed_plugins_cache_for_current_config(
|
||||
async fn maybe_refresh_plugin_caches_for_current_config(
|
||||
config_manager: &ConfigManager,
|
||||
thread_manager: &Arc<ThreadManager>,
|
||||
auth: Option<CodexAuth>,
|
||||
@@ -181,6 +181,9 @@ impl AccountRequestProcessor {
|
||||
thread_manager
|
||||
.plugins_manager()
|
||||
.set_auth_mode(auth.as_ref().map(CodexAuth::api_auth_mode));
|
||||
thread_manager
|
||||
.plugins_manager()
|
||||
.clear_recommended_plugins_cache();
|
||||
|
||||
match config_manager
|
||||
.load_latest_config(/*fallback_cwd*/ None)
|
||||
@@ -191,7 +194,7 @@ impl AccountRequestProcessor {
|
||||
let refresh_config_manager = config_manager.clone();
|
||||
thread_manager
|
||||
.plugins_manager()
|
||||
.maybe_start_remote_installed_plugins_cache_refresh(
|
||||
.maybe_start_remote_plugin_caches_refresh(
|
||||
&config.plugins_config_input(),
|
||||
auth,
|
||||
Some(Arc::new(move || {
|
||||
@@ -216,7 +219,7 @@ impl AccountRequestProcessor {
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
thread_manager.plugins_manager().clear_cache();
|
||||
thread_manager.skills_manager().clear_cache();
|
||||
thread_manager.skills_service().clear_cache();
|
||||
if thread_manager.list_thread_ids().await.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -618,7 +621,7 @@ impl AccountRequestProcessor {
|
||||
}
|
||||
|
||||
async fn send_login_success_notifications(&self, login_id: Option<Uuid>) {
|
||||
Self::maybe_refresh_remote_installed_plugins_cache_for_current_config(
|
||||
Self::maybe_refresh_plugin_caches_for_current_config(
|
||||
&self.config_manager,
|
||||
&self.thread_manager,
|
||||
self.auth_manager.auth_cached(),
|
||||
@@ -671,7 +674,7 @@ impl AccountRequestProcessor {
|
||||
.await;
|
||||
|
||||
let auth = auth_manager.auth_cached();
|
||||
Self::maybe_refresh_remote_installed_plugins_cache_for_current_config(
|
||||
Self::maybe_refresh_plugin_caches_for_current_config(
|
||||
&config_manager,
|
||||
&thread_manager,
|
||||
auth.clone(),
|
||||
@@ -703,7 +706,7 @@ impl AccountRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
Self::maybe_refresh_remote_installed_plugins_cache_for_current_config(
|
||||
Self::maybe_refresh_plugin_caches_for_current_config(
|
||||
&self.config_manager,
|
||||
&self.thread_manager,
|
||||
self.auth_manager.auth_cached(),
|
||||
|
||||
@@ -511,7 +511,7 @@ impl CatalogRequestProcessor {
|
||||
let workspace_codex_plugins_enabled = self
|
||||
.workspace_codex_plugins_enabled(&config, auth.as_ref())
|
||||
.await;
|
||||
let skills_manager = self.thread_manager.skills_manager();
|
||||
let skills_service = self.thread_manager.skills_service();
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
let fs = self
|
||||
.thread_manager
|
||||
@@ -523,7 +523,7 @@ impl CatalogRequestProcessor {
|
||||
let config = &config;
|
||||
let fs = fs.clone();
|
||||
let plugins_manager = &plugins_manager;
|
||||
let skills_manager = &skills_manager;
|
||||
let skills_service = &skills_service;
|
||||
async move {
|
||||
let (cwd_abs, config_layer_stack) = match self.resolve_cwd_config(&cwd).await {
|
||||
Ok(resolved) => resolved,
|
||||
@@ -559,9 +559,10 @@ impl CatalogRequestProcessor {
|
||||
config_layer_stack,
|
||||
config.bundled_skills_enabled(),
|
||||
);
|
||||
let outcome = skills_manager
|
||||
.skills_for_cwd(&skills_input, force_reload, fs)
|
||||
let snapshot = skills_service
|
||||
.snapshot_for_cwd(&skills_input, force_reload, fs)
|
||||
.await;
|
||||
let outcome = snapshot.outcome();
|
||||
let errors = errors_to_info(&outcome.errors);
|
||||
let skills = skills_to_info(&outcome.skills, &outcome.disabled_paths);
|
||||
(
|
||||
@@ -590,7 +591,7 @@ impl CatalogRequestProcessor {
|
||||
self.skills_watcher
|
||||
.register_runtime_extra_roots(&extra_roots);
|
||||
self.thread_manager
|
||||
.skills_manager()
|
||||
.skills_service()
|
||||
.set_extra_roots(extra_roots);
|
||||
self.outgoing
|
||||
.send_server_notification(ServerNotification::SkillsChanged(
|
||||
@@ -703,7 +704,7 @@ impl CatalogRequestProcessor {
|
||||
.await
|
||||
.map(|()| {
|
||||
self.thread_manager.plugins_manager().clear_cache();
|
||||
self.thread_manager.skills_manager().clear_cache();
|
||||
self.thread_manager.skills_service().clear_cache();
|
||||
SkillsConfigWriteResponse {
|
||||
effective_enabled: enabled,
|
||||
}
|
||||
|
||||
@@ -169,7 +169,7 @@ impl ConfigRequestProcessor {
|
||||
|
||||
pub(crate) async fn handle_config_mutation(&self) {
|
||||
self.thread_manager.plugins_manager().clear_cache();
|
||||
self.thread_manager.skills_manager().clear_cache();
|
||||
self.thread_manager.skills_service().clear_cache();
|
||||
}
|
||||
|
||||
async fn handle_config_mutation_result<T>(
|
||||
|
||||
@@ -15,13 +15,19 @@ use crate::config_manager::ConfigManager;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::outgoing_message::ConnectionRequestId;
|
||||
use crate::outgoing_message::OutgoingMessageSender;
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_analytics::ExternalAgentConfigImportCompletedInput;
|
||||
use codex_analytics::ExternalAgentConfigImportFailureInput;
|
||||
use codex_app_server_protocol::CommandMigration;
|
||||
use codex_app_server_protocol::ExternalAgentConfigDetectParams;
|
||||
use codex_app_server_protocol::ExternalAgentConfigDetectResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportCompletedNotification;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportHistoriesReadResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportHistory;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportItemTypeFailure as ProtocolImportFailure;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportItemTypeSuccess as ProtocolImportSuccess;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportParams;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportProgressNotification;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportResponse;
|
||||
use codex_app_server_protocol::ExternalAgentConfigImportTypeResult as ProtocolImportTypeResult;
|
||||
use codex_app_server_protocol::ExternalAgentConfigMigrationItem;
|
||||
@@ -35,6 +41,9 @@ use codex_app_server_protocol::ServerNotification;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_external_agent_sessions::ExternalAgentSessionMigration as CoreSessionMigration;
|
||||
use codex_rollout::StateDbHandle;
|
||||
use codex_state::ExternalAgentConfigImportFailureRecord;
|
||||
use codex_state::ExternalAgentConfigImportSuccessRecord;
|
||||
use codex_thread_store::ThreadStore;
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
@@ -50,18 +59,35 @@ pub(crate) struct ExternalAgentConfigRequestProcessor {
|
||||
session_importer: ExternalAgentSessionImporter,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
config_processor: ConfigRequestProcessor,
|
||||
state_db: Option<StateDbHandle>,
|
||||
analytics_events_client: AnalyticsEventsClient,
|
||||
}
|
||||
|
||||
pub(crate) struct ExternalAgentConfigRequestProcessorArgs {
|
||||
pub(crate) outgoing: Arc<OutgoingMessageSender>,
|
||||
pub(crate) thread_manager: Arc<ThreadManager>,
|
||||
pub(crate) thread_store: Arc<dyn ThreadStore>,
|
||||
pub(crate) config_manager: ConfigManager,
|
||||
pub(crate) config_processor: ConfigRequestProcessor,
|
||||
pub(crate) state_db: Option<StateDbHandle>,
|
||||
pub(crate) analytics_events_client: AnalyticsEventsClient,
|
||||
pub(crate) arg0_paths: Arg0DispatchPaths,
|
||||
pub(crate) codex_home: PathBuf,
|
||||
}
|
||||
|
||||
impl ExternalAgentConfigRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
thread_store: Arc<dyn ThreadStore>,
|
||||
config_manager: ConfigManager,
|
||||
config_processor: ConfigRequestProcessor,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
codex_home: PathBuf,
|
||||
) -> Self {
|
||||
pub(crate) fn new(args: ExternalAgentConfigRequestProcessorArgs) -> Self {
|
||||
let ExternalAgentConfigRequestProcessorArgs {
|
||||
outgoing,
|
||||
thread_manager,
|
||||
thread_store,
|
||||
config_manager,
|
||||
config_processor,
|
||||
state_db,
|
||||
analytics_events_client,
|
||||
arg0_paths,
|
||||
codex_home,
|
||||
} = args;
|
||||
let session_importer = ExternalAgentSessionImporter::new(
|
||||
codex_home.clone(),
|
||||
Arc::clone(&thread_manager),
|
||||
@@ -75,6 +101,8 @@ impl ExternalAgentConfigRequestProcessor {
|
||||
session_importer,
|
||||
thread_manager,
|
||||
config_processor,
|
||||
state_db,
|
||||
analytics_events_client,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,6 +206,7 @@ impl ExternalAgentConfigRequestProcessor {
|
||||
params: ExternalAgentConfigImportParams,
|
||||
) -> Result<(), JSONRPCErrorError> {
|
||||
let import_id = Uuid::new_v4().to_string();
|
||||
let analytics_source = params.source.clone().unwrap_or_default();
|
||||
let needs_runtime_refresh = migration_items_need_runtime_refresh(¶ms.migration_items);
|
||||
let has_migration_items = !params.migration_items.is_empty();
|
||||
let has_plugin_imports = params.migration_items.iter().any(|item| {
|
||||
@@ -188,7 +217,7 @@ impl ExternalAgentConfigRequestProcessor {
|
||||
});
|
||||
let (pending_session_imports, session_validation_result) =
|
||||
self.validate_pending_session_imports(¶ms);
|
||||
let import_outcome = self.import_external_agent_config(params).await?;
|
||||
let import_outcome = self.import_external_agent_config(params).await;
|
||||
if needs_runtime_refresh {
|
||||
self.config_processor.handle_config_mutation().await;
|
||||
}
|
||||
@@ -207,23 +236,34 @@ impl ExternalAgentConfigRequestProcessor {
|
||||
|
||||
let mut completed_item_results = Vec::new();
|
||||
if let Some(session_validation_result) = session_validation_result {
|
||||
send_import_progress(&self.outgoing, &import_id, &session_validation_result).await;
|
||||
completed_item_results.push(session_validation_result);
|
||||
}
|
||||
for item_result in import_outcome.item_results {
|
||||
send_import_progress(&self.outgoing, &import_id, &item_result).await;
|
||||
completed_item_results.push(item_result);
|
||||
}
|
||||
|
||||
let has_background_imports = !import_outcome.pending_plugin_imports.is_empty()
|
||||
|| !pending_session_imports.is_empty();
|
||||
if !has_background_imports {
|
||||
send_completed_import_notification(&self.outgoing, import_id, &completed_item_results)
|
||||
.await;
|
||||
send_completed_import_notification(
|
||||
&self.outgoing,
|
||||
self.state_db.as_ref(),
|
||||
&self.analytics_events_client,
|
||||
import_id,
|
||||
analytics_source,
|
||||
&completed_item_results,
|
||||
)
|
||||
.await;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let session_importer = self.session_importer.clone();
|
||||
let plugin_processor = self.clone();
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let state_db = self.state_db.clone();
|
||||
let analytics_events_client = self.analytics_events_client.clone();
|
||||
let thread_manager = Arc::clone(&self.thread_manager);
|
||||
let session_import_result = (!pending_session_imports.is_empty()).then(|| {
|
||||
CoreImportItemResult::new(
|
||||
@@ -234,13 +274,19 @@ impl ExternalAgentConfigRequestProcessor {
|
||||
});
|
||||
let pending_plugin_imports = import_outcome.pending_plugin_imports;
|
||||
tokio::spawn(async move {
|
||||
let session_progress_outgoing = Arc::clone(&outgoing);
|
||||
let session_import_id = import_id.clone();
|
||||
let session_imports = async move {
|
||||
let session_import_result = session_import_result?;
|
||||
let item_result = session_importer
|
||||
.import_sessions(pending_session_imports, session_import_result)
|
||||
.await;
|
||||
send_import_progress(&session_progress_outgoing, &session_import_id, &item_result)
|
||||
.await;
|
||||
Some(item_result)
|
||||
};
|
||||
let plugin_progress_outgoing = Arc::clone(&outgoing);
|
||||
let plugin_import_id = import_id.clone();
|
||||
let plugin_imports = async move {
|
||||
let mut item_results = Vec::new();
|
||||
for pending_plugin_import in pending_plugin_imports {
|
||||
@@ -265,6 +311,12 @@ impl ExternalAgentConfigRequestProcessor {
|
||||
);
|
||||
}
|
||||
}
|
||||
send_import_progress(
|
||||
&plugin_progress_outgoing,
|
||||
&plugin_import_id,
|
||||
&item_result,
|
||||
)
|
||||
.await;
|
||||
item_results.push(item_result);
|
||||
}
|
||||
item_results
|
||||
@@ -278,14 +330,41 @@ impl ExternalAgentConfigRequestProcessor {
|
||||
completed_item_results.extend(background_item_results);
|
||||
if has_plugin_imports {
|
||||
thread_manager.plugins_manager().clear_cache();
|
||||
thread_manager.skills_manager().clear_cache();
|
||||
thread_manager.skills_service().clear_cache();
|
||||
}
|
||||
send_completed_import_notification(&outgoing, import_id, &completed_item_results).await;
|
||||
send_completed_import_notification(
|
||||
&outgoing,
|
||||
state_db.as_ref(),
|
||||
&analytics_events_client,
|
||||
import_id,
|
||||
analytics_source,
|
||||
&completed_item_results,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn read_import_histories(
|
||||
&self,
|
||||
) -> Result<ExternalAgentConfigImportHistoriesReadResponse, JSONRPCErrorError> {
|
||||
let state_db = self
|
||||
.state_db
|
||||
.as_ref()
|
||||
.ok_or_else(|| internal_error("state database is unavailable"))?;
|
||||
let histories = state_db
|
||||
.external_agent_config_import_history_records()
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to read import histories: {err}")))?;
|
||||
let data = histories
|
||||
.into_iter()
|
||||
.map(protocol_import_history)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(ExternalAgentConfigImportHistoriesReadResponse { data })
|
||||
}
|
||||
|
||||
fn validate_pending_session_imports(
|
||||
&self,
|
||||
params: &ExternalAgentConfigImportParams,
|
||||
@@ -355,7 +434,7 @@ impl ExternalAgentConfigRequestProcessor {
|
||||
async fn import_external_agent_config(
|
||||
&self,
|
||||
params: ExternalAgentConfigImportParams,
|
||||
) -> Result<CoreImportOutcome, JSONRPCErrorError> {
|
||||
) -> CoreImportOutcome {
|
||||
self.migration_service
|
||||
.import(
|
||||
params
|
||||
@@ -450,7 +529,6 @@ impl ExternalAgentConfigRequestProcessor {
|
||||
.collect(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| internal_error(err.to_string()))
|
||||
}
|
||||
|
||||
async fn complete_pending_plugin_import(
|
||||
@@ -467,12 +545,41 @@ impl ExternalAgentConfigRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_import_progress(
|
||||
outgoing: &OutgoingMessageSender,
|
||||
import_id: &str,
|
||||
item_result: &CoreImportItemResult,
|
||||
) {
|
||||
outgoing
|
||||
.send_server_notification(ServerNotification::ExternalAgentConfigImportProgress(
|
||||
ExternalAgentConfigImportProgressNotification {
|
||||
import_id: import_id.to_string(),
|
||||
item_type_results: vec![protocol_import_type_result(item_result)],
|
||||
},
|
||||
))
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn send_completed_import_notification(
|
||||
outgoing: &OutgoingMessageSender,
|
||||
state_db: Option<&StateDbHandle>,
|
||||
analytics_events_client: &AnalyticsEventsClient,
|
||||
import_id: String,
|
||||
analytics_source: String,
|
||||
item_results: &[CoreImportItemResult],
|
||||
) {
|
||||
let notification = completed_notification(import_id, item_results);
|
||||
log_completed_import_failures(¬ification);
|
||||
track_completed_import_notification(analytics_events_client, &analytics_source, ¬ification);
|
||||
if let Some(state_db) = state_db
|
||||
&& let Err(err) = record_completed_import_notification(state_db, ¬ification).await
|
||||
{
|
||||
tracing::warn!(
|
||||
import_id = %notification.import_id,
|
||||
error = %err,
|
||||
"failed to record external agent config import completion"
|
||||
);
|
||||
}
|
||||
outgoing
|
||||
.send_server_notification(ServerNotification::ExternalAgentConfigImportCompleted(
|
||||
notification,
|
||||
@@ -480,6 +587,172 @@ async fn send_completed_import_notification(
|
||||
.await;
|
||||
}
|
||||
|
||||
fn log_completed_import_failures(notification: &ExternalAgentConfigImportCompletedNotification) {
|
||||
for type_result in ¬ification.item_type_results {
|
||||
for failure in &type_result.failures {
|
||||
let error_type = import_failure_error_type(failure);
|
||||
tracing::warn!(
|
||||
import_id = %notification.import_id,
|
||||
item_type = ?failure.item_type,
|
||||
error_type = %error_type,
|
||||
failure_stage = %failure.failure_stage,
|
||||
cwd = ?failure.cwd,
|
||||
source = ?failure.source,
|
||||
error = %failure.message,
|
||||
"external agent config migration item failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn track_completed_import_notification(
|
||||
analytics_events_client: &AnalyticsEventsClient,
|
||||
analytics_source: &str,
|
||||
notification: &ExternalAgentConfigImportCompletedNotification,
|
||||
) {
|
||||
for type_result in ¬ification.item_type_results {
|
||||
let item_type = analytics_migration_item_type(type_result.item_type).to_string();
|
||||
analytics_events_client.track_external_agent_config_import_completed(
|
||||
ExternalAgentConfigImportCompletedInput {
|
||||
import_id: notification.import_id.clone(),
|
||||
source: analytics_source.to_string(),
|
||||
item_type: item_type.clone(),
|
||||
success_count: type_result.successes.len(),
|
||||
failed_count: type_result.failures.len(),
|
||||
},
|
||||
);
|
||||
for failure in &type_result.failures {
|
||||
analytics_events_client.track_external_agent_config_import_failure(
|
||||
ExternalAgentConfigImportFailureInput {
|
||||
import_id: notification.import_id.clone(),
|
||||
source: analytics_source.to_string(),
|
||||
item_type: item_type.clone(),
|
||||
failure_stage: failure.failure_stage.clone(),
|
||||
error_type: import_failure_error_type(failure),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn import_failure_error_type(failure: &ProtocolImportFailure) -> String {
|
||||
failure
|
||||
.error_type
|
||||
.clone()
|
||||
.unwrap_or_else(|| failure.failure_stage.clone())
|
||||
}
|
||||
|
||||
fn analytics_migration_item_type(item_type: ExternalAgentConfigMigrationItemType) -> &'static str {
|
||||
match item_type {
|
||||
ExternalAgentConfigMigrationItemType::AgentsMd => "AGENTS_MD",
|
||||
ExternalAgentConfigMigrationItemType::Config => "CONFIG",
|
||||
ExternalAgentConfigMigrationItemType::Skills => "SKILLS",
|
||||
ExternalAgentConfigMigrationItemType::Plugins => "PLUGINS",
|
||||
ExternalAgentConfigMigrationItemType::McpServerConfig => "MCP_SERVER_CONFIG",
|
||||
ExternalAgentConfigMigrationItemType::Subagents => "SUBAGENTS",
|
||||
ExternalAgentConfigMigrationItemType::Hooks => "HOOKS",
|
||||
ExternalAgentConfigMigrationItemType::Commands => "COMMANDS",
|
||||
ExternalAgentConfigMigrationItemType::Sessions => "SESSIONS",
|
||||
}
|
||||
}
|
||||
|
||||
async fn record_completed_import_notification(
|
||||
state_db: &StateDbHandle,
|
||||
notification: &ExternalAgentConfigImportCompletedNotification,
|
||||
) -> anyhow::Result<()> {
|
||||
let successes = notification
|
||||
.item_type_results
|
||||
.iter()
|
||||
.flat_map(|type_result| type_result.successes.iter())
|
||||
.map(|success| {
|
||||
Ok(ExternalAgentConfigImportSuccessRecord {
|
||||
item_type: serde_json::from_value(serde_json::to_value(success.item_type)?)?,
|
||||
cwd: success.cwd.clone(),
|
||||
source: success.source.clone(),
|
||||
target: success.target.clone(),
|
||||
})
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
let failures = notification
|
||||
.item_type_results
|
||||
.iter()
|
||||
.flat_map(|type_result| type_result.failures.iter())
|
||||
.map(|failure| {
|
||||
Ok(ExternalAgentConfigImportFailureRecord {
|
||||
item_type: serde_json::from_value(serde_json::to_value(failure.item_type)?)?,
|
||||
error_type: failure.error_type.clone(),
|
||||
failure_stage: failure.failure_stage.clone(),
|
||||
message: failure.message.clone(),
|
||||
cwd: failure.cwd.clone(),
|
||||
source: failure.source.clone(),
|
||||
})
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?;
|
||||
state_db
|
||||
.record_external_agent_config_import_completed(
|
||||
notification.import_id.as_str(),
|
||||
&successes,
|
||||
&failures,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn protocol_import_history(
|
||||
record: codex_state::ExternalAgentConfigImportHistoryRecord,
|
||||
) -> Result<ExternalAgentConfigImportHistory, JSONRPCErrorError> {
|
||||
let successes = record
|
||||
.successes
|
||||
.into_iter()
|
||||
.map(protocol_import_success_record)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let failures = record
|
||||
.failures
|
||||
.into_iter()
|
||||
.map(protocol_import_failure_record)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(ExternalAgentConfigImportHistory {
|
||||
import_id: record.import_id,
|
||||
completed_at_ms: record.completed_at_ms,
|
||||
successes,
|
||||
failures,
|
||||
})
|
||||
}
|
||||
|
||||
fn protocol_import_success_record(
|
||||
record: ExternalAgentConfigImportSuccessRecord,
|
||||
) -> Result<ProtocolImportSuccess, JSONRPCErrorError> {
|
||||
Ok(ProtocolImportSuccess {
|
||||
item_type: protocol_import_record_item_type(record.item_type)?,
|
||||
cwd: record.cwd,
|
||||
source: record.source,
|
||||
target: record.target,
|
||||
})
|
||||
}
|
||||
|
||||
fn protocol_import_failure_record(
|
||||
record: ExternalAgentConfigImportFailureRecord,
|
||||
) -> Result<ProtocolImportFailure, JSONRPCErrorError> {
|
||||
Ok(ProtocolImportFailure {
|
||||
item_type: protocol_import_record_item_type(record.item_type)?,
|
||||
error_type: record.error_type,
|
||||
failure_stage: record.failure_stage,
|
||||
message: record.message,
|
||||
cwd: record.cwd,
|
||||
source: record.source,
|
||||
})
|
||||
}
|
||||
|
||||
fn protocol_import_record_item_type(
|
||||
item_type: String,
|
||||
) -> Result<ExternalAgentConfigMigrationItemType, JSONRPCErrorError> {
|
||||
serde_json::from_value(serde_json::Value::String(item_type.clone())).map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to decode import item type {item_type}: {err}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn completed_notification(
|
||||
import_id: String,
|
||||
item_results: &[CoreImportItemResult],
|
||||
@@ -529,6 +802,22 @@ fn completed_notification(
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_import_type_result(item_result: &CoreImportItemResult) -> ProtocolImportTypeResult {
|
||||
ProtocolImportTypeResult {
|
||||
item_type: protocol_migration_item_type(item_result.item_type),
|
||||
successes: item_result
|
||||
.successes
|
||||
.iter()
|
||||
.map(protocol_import_success)
|
||||
.collect(),
|
||||
failures: item_result
|
||||
.raw_errors
|
||||
.iter()
|
||||
.map(protocol_import_raw_error)
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_import_success(
|
||||
success: &crate::config::external_agent_config::ExternalAgentConfigImportSuccess,
|
||||
) -> ProtocolImportSuccess {
|
||||
@@ -543,6 +832,7 @@ fn protocol_import_success(
|
||||
fn protocol_import_raw_error(raw_error: &CoreImportRawError) -> ProtocolImportFailure {
|
||||
ProtocolImportFailure {
|
||||
item_type: protocol_migration_item_type(raw_error.item_type),
|
||||
error_type: raw_error.error_type.clone(),
|
||||
failure_stage: raw_error.failure_stage.clone(),
|
||||
message: raw_error.message.clone(),
|
||||
cwd: raw_error.cwd.clone(),
|
||||
|
||||
@@ -18,9 +18,12 @@ use codex_core_plugins::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETP
|
||||
use codex_core_plugins::remote::RemoteAppTemplateUnavailableReason;
|
||||
use codex_core_plugins::remote::is_valid_remote_plugin_id;
|
||||
use codex_core_plugins::remote::validate_remote_plugin_id;
|
||||
use codex_core_plugins::remote_bundle::RemotePluginBundleInstallError;
|
||||
use codex_mcp::McpOAuthLoginSupport;
|
||||
use codex_mcp::oauth_login_support;
|
||||
use codex_mcp::should_retry_without_scopes;
|
||||
use codex_plugin::PluginId;
|
||||
use codex_plugin::PluginTelemetryMetadata;
|
||||
use codex_rmcp_client::perform_oauth_login_silent;
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -474,7 +477,7 @@ impl PluginRequestProcessor {
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
thread_manager.plugins_manager().clear_cache();
|
||||
thread_manager.skills_manager().clear_cache();
|
||||
thread_manager.skills_service().clear_cache();
|
||||
if thread_manager.list_thread_ids().await.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -484,7 +487,7 @@ impl PluginRequestProcessor {
|
||||
|
||||
fn clear_plugin_related_caches(&self) {
|
||||
self.thread_manager.plugins_manager().clear_cache();
|
||||
self.thread_manager.skills_manager().clear_cache();
|
||||
self.thread_manager.skills_service().clear_cache();
|
||||
}
|
||||
|
||||
async fn load_latest_config(
|
||||
@@ -1437,15 +1440,24 @@ impl PluginRequestProcessor {
|
||||
}
|
||||
|
||||
let plugins_manager = self.thread_manager.plugins_manager();
|
||||
let marketplace_display = marketplace_path.display().to_string();
|
||||
let plugin_name_for_log = plugin_name.clone();
|
||||
let request = PluginInstallRequest {
|
||||
plugin_name,
|
||||
marketplace_path,
|
||||
};
|
||||
|
||||
let result = plugins_manager
|
||||
.install_plugin(request)
|
||||
.await
|
||||
.map_err(Self::plugin_install_error)?;
|
||||
let result = match plugins_manager.install_plugin(request).await {
|
||||
Ok(result) => result,
|
||||
Err(err) => {
|
||||
warn!(
|
||||
marketplace = %marketplace_display,
|
||||
plugin_name = %plugin_name_for_log,
|
||||
"failed to install plugin: {err}"
|
||||
);
|
||||
return Err(Self::plugin_install_error(err));
|
||||
}
|
||||
};
|
||||
let config = match self.load_latest_config(config_cwd).await {
|
||||
Ok(config) => config,
|
||||
Err(err) => {
|
||||
@@ -1512,11 +1524,20 @@ impl PluginRequestProcessor {
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
let error_type = remote_plugin_catalog_error_type(&err);
|
||||
self.track_plugin_install_failed_for_remote_plugin(
|
||||
&remote_plugin_id,
|
||||
&remote_marketplace_name,
|
||||
error_type,
|
||||
err.to_string(),
|
||||
);
|
||||
remote_plugin_catalog_error_to_jsonrpc(
|
||||
err,
|
||||
"read remote plugin details before install",
|
||||
)
|
||||
})?;
|
||||
let actual_remote_marketplace_name = remote_detail.marketplace_name.clone();
|
||||
let remote_plugin_name = remote_detail.summary.name.clone();
|
||||
if remote_detail.summary.availability == PluginAvailability::DisabledByAdmin {
|
||||
return Err(invalid_request(format!(
|
||||
"remote plugin {remote_plugin_id} is disabled by admin"
|
||||
@@ -1527,31 +1548,48 @@ impl PluginRequestProcessor {
|
||||
"remote plugin {remote_plugin_id} is not available for install"
|
||||
)));
|
||||
}
|
||||
let actual_remote_marketplace_name = remote_detail.marketplace_name.clone();
|
||||
// Direct install writes the same cache tree that installed-plugin sync
|
||||
// prunes before the backend installed snapshot can include this plugin.
|
||||
let _remote_plugin_cache_mutation =
|
||||
codex_core_plugins::remote::mark_remote_plugin_cache_mutation_in_flight(
|
||||
config.codex_home.as_path(),
|
||||
&actual_remote_marketplace_name,
|
||||
&remote_detail.summary.name,
|
||||
&remote_plugin_name,
|
||||
);
|
||||
let validated_bundle = codex_core_plugins::remote_bundle::validate_remote_plugin_bundle(
|
||||
&remote_plugin_id,
|
||||
&actual_remote_marketplace_name,
|
||||
&remote_detail.summary.name,
|
||||
&remote_plugin_name,
|
||||
remote_detail.release_version.as_deref(),
|
||||
remote_detail.bundle_download_url.as_deref(),
|
||||
remote_detail.app_manifest.clone(),
|
||||
)
|
||||
.map_err(remote_plugin_bundle_install_error_to_jsonrpc)?;
|
||||
.map_err(|err| {
|
||||
let error_type = remote_plugin_bundle_install_error_type(&err);
|
||||
self.track_plugin_install_failed_for_remote_plugin(
|
||||
&remote_plugin_id,
|
||||
&actual_remote_marketplace_name,
|
||||
error_type,
|
||||
err.to_string(),
|
||||
);
|
||||
remote_plugin_bundle_install_error_to_jsonrpc(err)
|
||||
})?;
|
||||
|
||||
let result = codex_core_plugins::remote_bundle::download_and_install_remote_plugin_bundle(
|
||||
config.codex_home.to_path_buf(),
|
||||
validated_bundle,
|
||||
)
|
||||
.await
|
||||
.map_err(remote_plugin_bundle_install_error_to_jsonrpc)?;
|
||||
.map_err(|err| {
|
||||
let error_type = remote_plugin_bundle_install_error_type(&err);
|
||||
self.track_plugin_install_failed_for_remote_plugin(
|
||||
&remote_plugin_id,
|
||||
&actual_remote_marketplace_name,
|
||||
error_type,
|
||||
err.to_string(),
|
||||
);
|
||||
remote_plugin_bundle_install_error_to_jsonrpc(err)
|
||||
})?;
|
||||
|
||||
// Cache first so a backend install cannot succeed when local materialization fails.
|
||||
// If this backend call fails, the cache entry is harmless because remote installed state
|
||||
@@ -1563,7 +1601,16 @@ impl PluginRequestProcessor {
|
||||
&remote_plugin_id,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| remote_plugin_catalog_error_to_jsonrpc(err, "install remote plugin"))?;
|
||||
.map_err(|err| {
|
||||
let error_type = remote_plugin_catalog_error_type(&err);
|
||||
self.track_plugin_install_failed_for_remote_plugin(
|
||||
&remote_plugin_id,
|
||||
&actual_remote_marketplace_name,
|
||||
error_type,
|
||||
err.to_string(),
|
||||
);
|
||||
remote_plugin_catalog_error_to_jsonrpc(err, "install remote plugin")
|
||||
})?;
|
||||
|
||||
self.thread_manager
|
||||
.plugins_manager()
|
||||
@@ -1646,6 +1693,32 @@ impl PluginRequestProcessor {
|
||||
})
|
||||
}
|
||||
|
||||
fn track_plugin_install_failed_for_remote_plugin(
|
||||
&self,
|
||||
remote_plugin_id: &str,
|
||||
marketplace_name: &str,
|
||||
error_type: &'static str,
|
||||
error_message: String,
|
||||
) {
|
||||
tracing::warn!(
|
||||
remote_plugin_id = %remote_plugin_id,
|
||||
marketplace_name = %marketplace_name,
|
||||
error_type = %error_type,
|
||||
error = %error_message,
|
||||
"remote plugin install failed"
|
||||
);
|
||||
// The remote id is reported separately; this local name only satisfies
|
||||
// PluginId validation before remote details are available.
|
||||
let Ok(plugin_id) = PluginId::new("unknown".to_string(), marketplace_name.to_string())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut plugin = PluginTelemetryMetadata::from_plugin_id(&plugin_id);
|
||||
plugin.remote_plugin_id = Some(remote_plugin_id.to_string());
|
||||
self.analytics_events_client
|
||||
.track_plugin_install_failed(plugin, error_type.to_string());
|
||||
}
|
||||
|
||||
async fn plugin_apps_needing_auth_for_install(
|
||||
&self,
|
||||
config: &Config,
|
||||
@@ -2145,6 +2218,75 @@ fn remote_plugin_detail_to_info(
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_plugin_catalog_error_type(err: &RemotePluginCatalogError) -> &'static str {
|
||||
match err {
|
||||
RemotePluginCatalogError::AuthRequired => "remote_catalog_auth_required",
|
||||
RemotePluginCatalogError::UnsupportedAuthMode => "remote_catalog_unsupported_auth_mode",
|
||||
RemotePluginCatalogError::AuthToken(_) => "remote_catalog_auth_token",
|
||||
RemotePluginCatalogError::Request { .. } => "remote_catalog_request",
|
||||
RemotePluginCatalogError::UnexpectedStatus { .. } => "remote_catalog_unexpected_status",
|
||||
RemotePluginCatalogError::Decode { .. } => "remote_catalog_decode",
|
||||
RemotePluginCatalogError::InvalidBaseUrl(_) => "remote_catalog_invalid_base_url",
|
||||
RemotePluginCatalogError::InvalidBaseUrlPath => "remote_catalog_invalid_base_url_path",
|
||||
RemotePluginCatalogError::UnknownMarketplace { .. } => "remote_catalog_unknown_marketplace",
|
||||
RemotePluginCatalogError::UnexpectedPluginId { .. } => {
|
||||
"remote_catalog_unexpected_plugin_id"
|
||||
}
|
||||
RemotePluginCatalogError::UnexpectedSkillName { .. } => {
|
||||
"remote_catalog_unexpected_skill_name"
|
||||
}
|
||||
RemotePluginCatalogError::UnexpectedEnabledState { .. } => {
|
||||
"remote_catalog_unexpected_enabled_state"
|
||||
}
|
||||
RemotePluginCatalogError::InvalidPluginPath { .. } => "remote_catalog_invalid_plugin_path",
|
||||
RemotePluginCatalogError::PluginShareCheckoutNotAvailable { .. } => {
|
||||
"remote_catalog_plugin_share_checkout_not_available"
|
||||
}
|
||||
RemotePluginCatalogError::Archive { .. } => "remote_catalog_archive",
|
||||
RemotePluginCatalogError::ArchiveJoin(_) => "remote_catalog_archive_join",
|
||||
RemotePluginCatalogError::ArchiveTooLarge { .. } => "remote_catalog_archive_too_large",
|
||||
RemotePluginCatalogError::MissingUploadEtag => "remote_catalog_missing_upload_etag",
|
||||
RemotePluginCatalogError::UnexpectedResponse(_) => "remote_catalog_unexpected_response",
|
||||
RemotePluginCatalogError::CacheRemove(_) => "remote_catalog_cache_remove",
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_plugin_bundle_install_error_type(err: &RemotePluginBundleInstallError) -> &'static str {
|
||||
match err {
|
||||
RemotePluginBundleInstallError::MissingReleaseVersion { .. } => {
|
||||
"remote_bundle_missing_release_version"
|
||||
}
|
||||
RemotePluginBundleInstallError::InvalidReleaseVersion { .. } => {
|
||||
"remote_bundle_invalid_release_version"
|
||||
}
|
||||
RemotePluginBundleInstallError::MissingBundleDownloadUrl { .. } => {
|
||||
"remote_bundle_missing_download_url"
|
||||
}
|
||||
RemotePluginBundleInstallError::InvalidBundleDownloadUrl { .. } => {
|
||||
"remote_bundle_invalid_download_url"
|
||||
}
|
||||
RemotePluginBundleInstallError::UnsupportedBundleDownloadUrlScheme { .. } => {
|
||||
"remote_bundle_unsupported_download_url_scheme"
|
||||
}
|
||||
RemotePluginBundleInstallError::InvalidPluginId { .. } => "remote_bundle_invalid_plugin_id",
|
||||
RemotePluginBundleInstallError::DownloadRequest { .. } => "remote_bundle_download_request",
|
||||
RemotePluginBundleInstallError::DownloadStatus { .. } => "remote_bundle_download_status",
|
||||
RemotePluginBundleInstallError::DownloadBody { .. } => "remote_bundle_download_body",
|
||||
RemotePluginBundleInstallError::DownloadTooLarge { .. } => {
|
||||
"remote_bundle_download_too_large"
|
||||
}
|
||||
RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. } => {
|
||||
"remote_bundle_unsupported_download_final_url"
|
||||
}
|
||||
RemotePluginBundleInstallError::ExtractedBundleTooLarge { .. } => {
|
||||
"remote_bundle_extracted_too_large"
|
||||
}
|
||||
RemotePluginBundleInstallError::Io { .. } => "remote_bundle_io",
|
||||
RemotePluginBundleInstallError::InvalidBundle(_) => "remote_bundle_invalid_bundle",
|
||||
RemotePluginBundleInstallError::Store(_) => "remote_bundle_store",
|
||||
}
|
||||
}
|
||||
|
||||
fn remote_plugin_catalog_error_to_jsonrpc(
|
||||
err: RemotePluginCatalogError,
|
||||
context: &str,
|
||||
|
||||
@@ -4,7 +4,6 @@ use codex_app_server_protocol::SelectedCapabilityRoot;
|
||||
use codex_extension_api::ExtensionDataInit;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
|
||||
const THREAD_LIST_DEFAULT_LIMIT: usize = 25;
|
||||
const THREAD_LIST_MAX_LIMIT: usize = 100;
|
||||
@@ -906,7 +905,8 @@ impl ThreadRequestProcessor {
|
||||
"`permissions` cannot be combined with `sandbox`",
|
||||
));
|
||||
}
|
||||
let environment_selections = self.parse_environment_selections(environments)?;
|
||||
let environment_selections =
|
||||
resolve_turn_environment_selections(self.thread_manager.as_ref(), environments)?;
|
||||
let runtime_workspace_roots = runtime_workspace_roots.map(resolve_runtime_workspace_roots);
|
||||
let mut typesafe_overrides = self.build_thread_config_overrides(
|
||||
model,
|
||||
@@ -1311,27 +1311,6 @@ impl ThreadRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_environment_selections(
|
||||
&self,
|
||||
environments: Option<Vec<TurnEnvironmentParams>>,
|
||||
) -> Result<Option<Vec<TurnEnvironmentSelection>>, JSONRPCErrorError> {
|
||||
let environment_selections = environments.map(|environments| {
|
||||
environments
|
||||
.into_iter()
|
||||
.map(|environment| TurnEnvironmentSelection {
|
||||
environment_id: environment.environment_id,
|
||||
cwd: PathUri::from_abs_path(&environment.cwd),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
if let Some(environment_selections) = environment_selections.as_ref() {
|
||||
self.thread_manager
|
||||
.validate_environment_selections(environment_selections)
|
||||
.map_err(environment_selection_error)?;
|
||||
}
|
||||
Ok(environment_selections)
|
||||
}
|
||||
|
||||
async fn thread_archive_inner(
|
||||
&self,
|
||||
params: ThreadArchiveParams,
|
||||
@@ -1802,16 +1781,22 @@ impl ThreadRequestProcessor {
|
||||
.list_background_terminals()
|
||||
.await
|
||||
.into_iter()
|
||||
.map(|terminal| ThreadBackgroundTerminal {
|
||||
item_id: terminal.item_id,
|
||||
process_id: terminal.process_id,
|
||||
command: terminal.command,
|
||||
cwd: terminal.cwd,
|
||||
os_pid: None,
|
||||
cpu_percent: None,
|
||||
rss_kb: None,
|
||||
.map(|terminal| {
|
||||
// TODO(anp): Migrate ThreadBackgroundTerminal to PathUri.
|
||||
let cwd = terminal.cwd.to_abs_path().map_err(|err| {
|
||||
internal_error(format!("background terminal has invalid cwd: {err}"))
|
||||
})?;
|
||||
Ok(ThreadBackgroundTerminal {
|
||||
item_id: terminal.item_id,
|
||||
process_id: terminal.process_id,
|
||||
command: terminal.command,
|
||||
cwd,
|
||||
os_pid: None,
|
||||
cpu_percent: None,
|
||||
rss_kb: None,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
.collect::<Result<Vec<_>, JSONRPCErrorError>>()?;
|
||||
|
||||
let (data, next_cursor) = paginate_background_terminals(&terminals, cursor, limit)?;
|
||||
|
||||
@@ -1918,6 +1903,7 @@ impl ThreadRequestProcessor {
|
||||
let store_sort_key = match sort_key.unwrap_or(ThreadSortKey::CreatedAt) {
|
||||
ThreadSortKey::CreatedAt => StoreThreadSortKey::CreatedAt,
|
||||
ThreadSortKey::UpdatedAt => StoreThreadSortKey::UpdatedAt,
|
||||
ThreadSortKey::RecencyAt => StoreThreadSortKey::RecencyAt,
|
||||
};
|
||||
let sort_direction = sort_direction.unwrap_or(SortDirection::Desc);
|
||||
let (stored_threads, next_cursor) = self
|
||||
@@ -1999,6 +1985,7 @@ impl ThreadRequestProcessor {
|
||||
let store_sort_key = match sort_key.unwrap_or(ThreadSortKey::CreatedAt) {
|
||||
ThreadSortKey::CreatedAt => StoreThreadSortKey::CreatedAt,
|
||||
ThreadSortKey::UpdatedAt => StoreThreadSortKey::UpdatedAt,
|
||||
ThreadSortKey::RecencyAt => StoreThreadSortKey::RecencyAt,
|
||||
};
|
||||
let store_sort_direction = sort_direction.unwrap_or(SortDirection::Desc);
|
||||
let (allowed_sources, source_kind_filter) = compute_source_filters(source_kinds);
|
||||
@@ -3716,6 +3703,7 @@ fn thread_backwards_cursor_for_sort_key(
|
||||
let timestamp = match sort_key {
|
||||
StoreThreadSortKey::CreatedAt => thread.created_at,
|
||||
StoreThreadSortKey::UpdatedAt => thread.updated_at,
|
||||
StoreThreadSortKey::RecencyAt => thread.recency_at,
|
||||
};
|
||||
// The state DB stores unique millisecond timestamps. Offset the reverse cursor by one
|
||||
// millisecond so the opposite-direction query includes the page anchor.
|
||||
@@ -4160,6 +4148,7 @@ pub(crate) fn thread_from_stored_thread(
|
||||
},
|
||||
created_at: thread.created_at.timestamp(),
|
||||
updated_at: thread.updated_at.timestamp(),
|
||||
recency_at: Some(thread.recency_at.timestamp()),
|
||||
status: ThreadStatus::NotLoaded,
|
||||
path,
|
||||
cwd,
|
||||
@@ -4365,6 +4354,7 @@ fn build_thread_from_snapshot(
|
||||
model_provider: config_snapshot.model_provider_id.clone(),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
recency_at: Some(now),
|
||||
status: ThreadStatus::NotLoaded,
|
||||
path,
|
||||
cwd: config_snapshot.cwd().clone(),
|
||||
|
||||
@@ -478,6 +478,7 @@ mod thread_processor_behavior_tests {
|
||||
reasoning_effort: None,
|
||||
created_at: created_at.with_timezone(&Utc),
|
||||
updated_at: updated_at.with_timezone(&Utc),
|
||||
recency_at: updated_at.with_timezone(&Utc),
|
||||
archived_at: None,
|
||||
cwd: PathBuf::from("/tmp"),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
|
||||
@@ -178,6 +178,7 @@ mod tests {
|
||||
model_provider: "mock_provider".to_string(),
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
recency_at: Some(0),
|
||||
status: ThreadStatus::Idle,
|
||||
path: None,
|
||||
cwd: test_path_buf("/tmp").abs(),
|
||||
|
||||
@@ -320,6 +320,7 @@ pub(crate) fn summary_to_thread(
|
||||
model_provider,
|
||||
created_at: created_at.map(|dt| dt.timestamp()).unwrap_or(0),
|
||||
updated_at: updated_at.map(|dt| dt.timestamp()).unwrap_or(0),
|
||||
recency_at: updated_at.map(|dt| dt.timestamp()),
|
||||
status: ThreadStatus::NotLoaded,
|
||||
path: (!path.as_os_str().is_empty()).then_some(path),
|
||||
cwd,
|
||||
|
||||
@@ -4,7 +4,6 @@ use codex_protocol::protocol::AdditionalContextKind as CoreAdditionalContextKind
|
||||
use codex_protocol::protocol::MultiAgentVersion;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
|
||||
const DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR: &str =
|
||||
"direct app-server input is not allowed for multi-agent v2 sub-agents";
|
||||
@@ -341,27 +340,6 @@ impl TurnRequestProcessor {
|
||||
Ok((review_request, hint))
|
||||
}
|
||||
|
||||
fn parse_environment_selections(
|
||||
&self,
|
||||
environments: Option<Vec<TurnEnvironmentParams>>,
|
||||
) -> Result<Option<Vec<TurnEnvironmentSelection>>, JSONRPCErrorError> {
|
||||
let environment_selections = environments.map(|environments| {
|
||||
environments
|
||||
.into_iter()
|
||||
.map(|environment| TurnEnvironmentSelection {
|
||||
environment_id: environment.environment_id,
|
||||
cwd: PathUri::from_abs_path(&environment.cwd),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
if let Some(environment_selections) = environment_selections.as_ref() {
|
||||
self.thread_manager
|
||||
.validate_environment_selections(environment_selections)
|
||||
.map_err(environment_selection_error)?;
|
||||
}
|
||||
Ok(environment_selections)
|
||||
}
|
||||
|
||||
async fn request_trace_context(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
@@ -433,7 +411,8 @@ impl TurnRequestProcessor {
|
||||
self.track_error_response(&request_id, error, /*error_type*/ None);
|
||||
})?;
|
||||
|
||||
let environment_selections = self.parse_environment_selections(params.environments)?;
|
||||
let environment_selections =
|
||||
resolve_turn_environment_selections(self.thread_manager.as_ref(), params.environments)?;
|
||||
|
||||
// Map v2 input items to core input items.
|
||||
let mapped_items: Vec<CoreInputItem> = params
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user