Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,264 @@
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
use crate::auth::KnownPlan;
use crate::auth::PlanType as AuthPlanType;
#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq, Eq, JsonSchema, TS, Default)]
#[serde(rename_all = "lowercase")]
#[ts(rename_all = "lowercase")]
pub enum PlanType {
#[default]
Free,
Go,
Plus,
Pro,
ProLite,
ProMax,
Team,
#[serde(rename = "self_serve_business_prolite")]
#[ts(rename = "self_serve_business_prolite")]
SelfServeBusinessProLite,
#[serde(rename = "self_serve_business_usage_based")]
#[ts(rename = "self_serve_business_usage_based")]
SelfServeBusinessUsageBased,
Business,
Ent26,
#[serde(rename = "enterprise_cbp_automation")]
#[ts(rename = "enterprise_cbp_automation")]
EnterpriseCbpAutomation,
#[serde(rename = "enterprise_cbp_usage_based")]
#[ts(rename = "enterprise_cbp_usage_based")]
EnterpriseCbpUsageBased,
Enterprise,
Edu,
#[serde(rename = "edu_plus")]
#[ts(rename = "edu_plus")]
EduPlus,
#[serde(rename = "edu_pro")]
#[ts(rename = "edu_pro")]
EduPro,
Sci,
#[serde(rename = "sci_plus")]
#[ts(rename = "sci_plus")]
SciPlus,
#[serde(other)]
Unknown,
}
/// Account state returned by a model provider before it is adapted to an app-facing wire type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProviderAccount {
ApiKey,
}
impl PlanType {
pub fn is_team_like(self) -> bool {
matches!(
self,
Self::Team | Self::SelfServeBusinessProLite | Self::SelfServeBusinessUsageBased
)
}
pub fn is_business_like(self) -> bool {
matches!(
self,
Self::Business
| Self::Ent26
| Self::EnterpriseCbpAutomation
| Self::EnterpriseCbpUsageBased
)
}
/// Groups education plans by workspace capabilities without losing their SKU identity.
pub fn is_education_like(self) -> bool {
matches!(self, Self::Edu | Self::EduPlus | Self::EduPro)
}
pub fn is_workspace_account(self) -> bool {
self.is_team_like()
|| self.is_business_like()
|| self.is_education_like()
|| matches!(self, Self::Enterprise | Self::Sci | Self::SciPlus)
}
}
impl From<AuthPlanType> for PlanType {
fn from(plan_type: AuthPlanType) -> Self {
match plan_type {
AuthPlanType::Known(plan) => plan.into(),
AuthPlanType::Unknown(_) => Self::Unknown,
}
}
}
impl From<KnownPlan> for PlanType {
fn from(plan: KnownPlan) -> Self {
match plan {
KnownPlan::Free => Self::Free,
KnownPlan::Go => Self::Go,
KnownPlan::Plus => Self::Plus,
KnownPlan::Pro => Self::Pro,
KnownPlan::ProLite => Self::ProLite,
KnownPlan::ProMax => Self::ProMax,
KnownPlan::Team => Self::Team,
KnownPlan::SelfServeBusinessProLite => Self::SelfServeBusinessProLite,
KnownPlan::SelfServeBusinessUsageBased => Self::SelfServeBusinessUsageBased,
KnownPlan::Business => Self::Business,
KnownPlan::Ent26 => Self::Ent26,
KnownPlan::EnterpriseCbpAutomation => Self::EnterpriseCbpAutomation,
KnownPlan::EnterpriseCbpUsageBased => Self::EnterpriseCbpUsageBased,
KnownPlan::Enterprise => Self::Enterprise,
KnownPlan::Edu => Self::Edu,
KnownPlan::EduPlus => Self::EduPlus,
KnownPlan::EduPro => Self::EduPro,
KnownPlan::Sci => Self::Sci,
KnownPlan::SciPlus => Self::SciPlus,
}
}
}
#[cfg(test)]
mod tests {
use super::PlanType;
use crate::auth::KnownPlan;
use crate::auth::PlanType as AuthPlanType;
use pretty_assertions::assert_eq;
#[test]
fn business_plan_types_use_expected_wire_names() {
assert_eq!(
serde_json::to_string(&PlanType::SelfServeBusinessProLite)
.expect("self-serve business ProLite should serialize"),
"\"self_serve_business_prolite\""
);
assert_eq!(
serde_json::to_string(&PlanType::SelfServeBusinessUsageBased)
.expect("self-serve business usage based should serialize"),
"\"self_serve_business_usage_based\""
);
assert_eq!(
serde_json::to_string(&PlanType::EnterpriseCbpUsageBased)
.expect("enterprise cbp usage based should serialize"),
"\"enterprise_cbp_usage_based\""
);
assert_eq!(
serde_json::to_string(&PlanType::EnterpriseCbpAutomation)
.expect("enterprise cbp automation should serialize"),
"\"enterprise_cbp_automation\""
);
assert_eq!(
serde_json::to_string(&PlanType::Ent26).expect("ent26 should serialize"),
"\"ent26\""
);
assert_eq!(
serde_json::to_string(&PlanType::ProLite).expect("prolite should serialize"),
"\"prolite\""
);
assert_eq!(
serde_json::from_str::<PlanType>("\"self_serve_business_prolite\"")
.expect("self-serve business ProLite should deserialize"),
PlanType::SelfServeBusinessProLite
);
assert_eq!(
serde_json::from_str::<PlanType>("\"self_serve_business_usage_based\"")
.expect("self-serve business usage based should deserialize"),
PlanType::SelfServeBusinessUsageBased
);
assert_eq!(
serde_json::from_str::<PlanType>("\"prolite\"").expect("prolite should deserialize"),
PlanType::ProLite
);
assert_eq!(
serde_json::from_str::<PlanType>("\"enterprise_cbp_usage_based\"")
.expect("enterprise cbp usage based should deserialize"),
PlanType::EnterpriseCbpUsageBased
);
assert_eq!(
serde_json::from_str::<PlanType>("\"enterprise_cbp_automation\"")
.expect("enterprise cbp automation should deserialize"),
PlanType::EnterpriseCbpAutomation
);
assert_eq!(
serde_json::from_str::<PlanType>("\"ent26\"").expect("ent26 should deserialize"),
PlanType::Ent26
);
}
#[test]
fn plan_family_helpers_group_business_variants_with_existing_plans() {
assert_eq!(PlanType::Team.is_team_like(), true);
assert_eq!(PlanType::SelfServeBusinessProLite.is_team_like(), true);
assert_eq!(PlanType::SelfServeBusinessUsageBased.is_team_like(), true);
assert_eq!(PlanType::Business.is_team_like(), false);
assert_eq!(PlanType::Ent26.is_team_like(), false);
assert_eq!(PlanType::Business.is_business_like(), true);
assert_eq!(PlanType::Ent26.is_business_like(), true);
assert_eq!(PlanType::EnterpriseCbpAutomation.is_business_like(), true);
assert_eq!(PlanType::EnterpriseCbpUsageBased.is_business_like(), true);
assert_eq!(PlanType::Team.is_business_like(), false);
}
#[test]
fn workspace_account_helper_includes_business_workspace_plans() {
assert_eq!(PlanType::Team.is_workspace_account(), true);
assert_eq!(
PlanType::SelfServeBusinessProLite.is_workspace_account(),
true
);
assert_eq!(
PlanType::SelfServeBusinessUsageBased.is_workspace_account(),
true
);
assert_eq!(PlanType::Business.is_workspace_account(), true);
assert_eq!(PlanType::Ent26.is_workspace_account(), true);
assert_eq!(
PlanType::EnterpriseCbpAutomation.is_workspace_account(),
true
);
assert_eq!(
PlanType::EnterpriseCbpUsageBased.is_workspace_account(),
true
);
assert_eq!(PlanType::Enterprise.is_workspace_account(), true);
assert_eq!(PlanType::Edu.is_workspace_account(), true);
assert_eq!(PlanType::EduPlus.is_workspace_account(), true);
assert_eq!(PlanType::EduPro.is_workspace_account(), true);
for plan in [KnownPlan::Sci, KnownPlan::SciPlus] {
assert!(plan.is_workspace_account());
assert!(PlanType::from(plan).is_workspace_account());
}
assert_eq!(PlanType::Pro.is_workspace_account(), false);
}
#[test]
fn auth_plan_type_converts_to_account_plan_type() {
assert_eq!(
PlanType::from(AuthPlanType::Known(KnownPlan::SelfServeBusinessProLite)),
PlanType::SelfServeBusinessProLite
);
assert_eq!(
PlanType::from(AuthPlanType::Known(KnownPlan::EnterpriseCbpUsageBased)),
PlanType::EnterpriseCbpUsageBased
);
assert_eq!(
PlanType::from(AuthPlanType::Known(KnownPlan::EnterpriseCbpAutomation)),
PlanType::EnterpriseCbpAutomation
);
assert_eq!(
PlanType::from(AuthPlanType::Known(KnownPlan::Ent26)),
PlanType::Ent26
);
assert_eq!(
PlanType::from(AuthPlanType::Known(KnownPlan::Enterprise)),
PlanType::Enterprise
);
assert_eq!(
PlanType::from(AuthPlanType::Unknown("mystery-tier".to_string())),
PlanType::Unknown
);
}
}

View File

@@ -0,0 +1,32 @@
//! Bounded agent failure diagnostics, separate from error behavior and user-visible messages.
//! The first annotation wins so outer spawn stages preserve more precise failure origins.
use super::CodexErr;
/// A failure origin, or the spawn stage when no more precise origin is available.
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum_macros::IntoStaticStr)]
#[strum(serialize_all = "snake_case")]
pub enum AgentErrorContext {
ExecutionCapacity,
ResidencyCapacity,
RegistryCapacity,
DuplicatePath,
NicknameUnavailable,
ManagerUnavailable,
RuntimeShutdown,
ForkHistory,
ChildStartup,
InputAdmission,
}
impl CodexErr {
/// Attach bounded diagnostics without replacing a more precise inner annotation.
pub fn with_agent_context(mut self, context: AgentErrorContext) -> Self {
self.agent_context.get_or_insert(context);
self
}
pub fn agent_context(&self) -> Option<AgentErrorContext> {
self.agent_context
}
}

View File

@@ -0,0 +1,240 @@
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::fmt;
use std::ops::Deref;
use std::str::FromStr;
use ts_rs::TS;
#[derive(
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema, TS,
)]
#[serde(try_from = "String", into = "String")]
#[schemars(with = "String")]
#[ts(type = "string")]
pub struct AgentPath(String);
impl AgentPath {
pub const ROOT: &str = "/root";
pub const MORPHEUS: &str = "/morpheus";
const ROOT_SEGMENT: &str = "root";
pub fn root() -> Self {
Self(Self::ROOT.to_string())
}
pub fn morpheus() -> Self {
Self(Self::MORPHEUS.to_string())
}
pub fn from_string(path: String) -> Result<Self, String> {
validate_absolute_path(path.as_str())?;
Ok(Self(path))
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
pub fn is_root(&self) -> bool {
self.as_str() == Self::ROOT
}
pub fn name(&self) -> &str {
if self.is_root() {
return Self::ROOT_SEGMENT;
}
self.as_str()
.rsplit('/')
.next()
.filter(|segment| !segment.is_empty())
.unwrap_or(Self::ROOT_SEGMENT)
}
pub fn join(&self, agent_name: &str) -> Result<Self, String> {
validate_agent_name(agent_name)?;
Self::from_string(format!("{self}/{agent_name}"))
}
pub fn resolve(&self, reference: &str) -> Result<Self, String> {
if reference.is_empty() {
return Err("agent path must not be empty".to_string());
}
if reference == Self::ROOT {
return Ok(Self::root());
}
if reference.starts_with('/') {
return Self::try_from(reference);
}
validate_relative_reference(reference)?;
Self::from_string(format!("{self}/{reference}"))
}
}
impl TryFrom<String> for AgentPath {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_string(value)
}
}
impl TryFrom<&str> for AgentPath {
type Error = String;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::from_string(value.to_string())
}
}
impl From<AgentPath> for String {
fn from(value: AgentPath) -> Self {
value.0
}
}
impl FromStr for AgentPath {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl AsRef<str> for AgentPath {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Deref for AgentPath {
type Target = str;
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl fmt::Display for AgentPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
fn validate_agent_name(agent_name: &str) -> Result<(), String> {
if agent_name.is_empty() {
return Err("agent_name must not be empty".to_string());
}
if agent_name == AgentPath::ROOT_SEGMENT {
return Err("agent_name `root` is reserved".to_string());
}
if agent_name == "." || agent_name == ".." {
return Err(format!("agent_name `{agent_name}` is reserved"));
}
if agent_name.contains('/') {
return Err("agent_name must not contain `/`".to_string());
}
if !agent_name
.chars()
.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
{
return Err(
"agent_name must use only lowercase letters, digits, and underscores".to_string(),
);
}
Ok(())
}
fn validate_absolute_path(path: &str) -> Result<(), String> {
if path == AgentPath::MORPHEUS {
return Ok(());
}
let Some(stripped) = path.strip_prefix('/') else {
return Err("absolute agent paths must start with `/root` or be `/morpheus`".to_string());
};
let mut segments = stripped.split('/');
let Some(root) = segments.next() else {
return Err("absolute agent path must not be empty".to_string());
};
if root != AgentPath::ROOT_SEGMENT {
return Err("absolute agent paths must start with `/root` or be `/morpheus`".to_string());
}
if stripped.ends_with('/') {
return Err("absolute agent path must not end with `/`".to_string());
}
for segment in segments {
validate_agent_name(segment)?;
}
Ok(())
}
fn validate_relative_reference(reference: &str) -> Result<(), String> {
if reference.ends_with('/') {
return Err("relative agent path must not end with `/`".to_string());
}
for segment in reference.split('/') {
validate_agent_name(segment)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::AgentPath;
use pretty_assertions::assert_eq;
#[test]
fn root_has_expected_name() {
let root = AgentPath::root();
assert_eq!(root.as_str(), AgentPath::ROOT);
assert_eq!(root.name(), "root");
assert!(root.is_root());
}
#[test]
fn morpheus_has_expected_name() {
let morpheus = AgentPath::morpheus();
assert_eq!(morpheus.as_str(), AgentPath::MORPHEUS);
assert_eq!(morpheus.name(), "morpheus");
assert!(!morpheus.is_root());
}
#[test]
fn join_builds_child_paths() {
let root = AgentPath::root();
let child = root.join("researcher").expect("child path");
assert_eq!(child.as_str(), "/root/researcher");
assert_eq!(child.name(), "researcher");
}
#[test]
fn resolve_supports_relative_and_absolute_references() {
let current = AgentPath::try_from("/root/researcher").expect("path");
assert_eq!(
current.resolve("worker").expect("relative path"),
AgentPath::try_from("/root/researcher/worker").expect("path")
);
assert_eq!(
current.resolve("/root/other").expect("absolute path"),
AgentPath::try_from("/root/other").expect("path")
);
}
#[test]
fn invalid_names_and_paths_are_rejected() {
assert_eq!(
AgentPath::root().join("BadName"),
Err("agent_name must use only lowercase letters, digits, and underscores".to_string())
);
assert_eq!(
AgentPath::try_from("/not-root"),
Err("absolute agent paths must start with `/root` or be `/morpheus`".to_string())
);
assert_eq!(
AgentPath::root().resolve("../sibling"),
Err("agent_name `..` is reserved".to_string())
);
}
}

View File

@@ -0,0 +1,570 @@
use crate::mcp::RequestId;
use crate::models::AdditionalPermissionProfile;
use crate::models::PermissionProfile;
use crate::parse_command::ParsedCommand;
use crate::protocol::FileChange;
use crate::protocol::ReviewDecision;
use crate::request_permissions::RequestPermissionProfile;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::LegacyAppPathString;
use akode_utils_path_uri::PathUri;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::path::PathBuf;
use ts_rs::TS;
/// Fully resolved permissions for rerunning an intercepted child process.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedPermissionProfile {
pub permission_profile: PermissionProfile,
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EscalationPermissions {
/// Permissions to merge with the active turn permissions.
AdditionalPermissionProfile(AdditionalPermissionProfile),
/// Fully resolved permissions that should replace the active turn permissions.
ResolvedPermissionProfile(ResolvedPermissionProfile),
}
/// Proposed execpolicy change to allow commands starting with this prefix.
///
/// The `command` tokens form the prefix that would be added as an execpolicy
/// `prefix_rule(..., decision="allow")`, letting the agent bypass approval for
/// commands that start with this token sequence.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(transparent)]
#[ts(type = "Array<string>")]
pub struct ExecPolicyAmendment {
pub command: Vec<String>,
}
impl ExecPolicyAmendment {
pub fn new(command: Vec<String>) -> Self {
Self { command }
}
pub fn command(&self) -> &[String] {
&self.command
}
}
impl From<Vec<String>> for ExecPolicyAmendment {
fn from(command: Vec<String>) -> Self {
Self { command }
}
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub enum NetworkApprovalProtocol {
// TODO(viyatb): Add websocket protocol variants when managed proxy policy
// decisions expose websocket traffic as a distinct approval context.
Http,
#[serde(alias = "https_connect", alias = "http-connect")]
Https,
Socks5Tcp,
Socks5Udp,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
pub struct NetworkApprovalContext {
pub host: String,
pub protocol: NetworkApprovalProtocol,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub enum NetworkPolicyRuleAction {
Allow,
Deny,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
pub enum GuardianRiskLevel {
Low,
Medium,
High,
Critical,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
pub enum GuardianUserAuthorization {
Unknown,
Low,
Medium,
High,
}
/// Final allow/deny outcome returned by the guardian reviewer.
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
pub enum GuardianAssessmentOutcome {
Allow,
Deny,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub enum GuardianAssessmentStatus {
InProgress,
Approved,
Denied,
TimedOut,
Aborted,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub enum GuardianAssessmentDecisionSource {
Agent,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub enum GuardianCommandSource {
Shell,
UnifiedExec,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(tag = "type", rename_all = "snake_case")]
pub enum GuardianAssessmentAction {
Command {
source: GuardianCommandSource,
command: String,
cwd: LegacyAppPathString,
},
Execve {
source: GuardianCommandSource,
program: String,
argv: Vec<String>,
cwd: AbsolutePathBuf,
},
/// A child approval for input to an existing command execution item.
WriteStdin {
approval_id: String,
process_id: String,
stdin: String,
/// Launch directory of the existing terminal, not its current working directory.
cwd: PathUri,
},
ApplyPatch {
cwd: LegacyAppPathString,
files: Vec<LegacyAppPathString>,
},
NetworkAccess {
target: String,
host: String,
protocol: NetworkApprovalProtocol,
port: u16,
},
McpToolCall {
server: String,
tool_name: String,
connector_id: Option<String>,
connector_name: Option<String>,
tool_title: Option<String>,
},
RequestPermissions {
reason: Option<String>,
permissions: RequestPermissionProfile,
},
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
pub struct NetworkPolicyAmendment {
pub host: String,
pub action: NetworkPolicyRuleAction,
}
/// Why this approval needs a fresh Guardian assessment.
#[derive(
Debug,
Clone,
Copy,
Deserialize,
Serialize,
PartialEq,
Eq,
JsonSchema,
TS,
strum_macros::IntoStaticStr,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum GuardianReviewReason {
Policy,
FreshRequired,
MissingScore,
StaleScore,
InvalidScore,
IncompatibleCompaction,
ElevatedRisk,
ScoringFailure,
AuthorizationChanged,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)]
pub struct GuardianAssessmentEvent {
/// Request-scoped trigger; absent in events recorded by older clients.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub review_reason: Option<GuardianReviewReason>,
#[serde(skip)]
#[schemars(skip)]
#[ts(skip)]
pub model_context: Option<crate::items::ModelInvocationContext>,
/// Stable identifier for this guardian review lifecycle.
pub id: String,
/// Thread item being reviewed, when the review maps to a concrete item.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub target_item_id: Option<String>,
/// Trusted plugin attribution for command items synthesized from this review.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub plugin_id: Option<String>,
/// Safe plugin-relative path for command items synthesized from this review.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub script_path: Option<String>,
/// Turn ID that this assessment belongs to.
/// Uses `#[serde(default)]` for backwards compatibility.
#[serde(default)]
pub turn_id: String,
#[serde(default)]
#[ts(type = "number")]
pub started_at_ms: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional, type = "number")]
pub completed_at_ms: Option<i64>,
pub status: GuardianAssessmentStatus,
/// Coarse risk label. Omitted while the assessment is in progress.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub risk_level: Option<GuardianRiskLevel>,
/// How directly the transcript authorizes the reviewed action.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub user_authorization: Option<GuardianUserAuthorization>,
/// Human-readable explanation of the final assessment. Omitted while in progress.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub rationale: Option<String>,
/// Source that produced the terminal assessment decision.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub decision_source: Option<GuardianAssessmentDecisionSource>,
/// Canonical action payload that was reviewed.
pub action: GuardianAssessmentAction,
}
/// Distinguishes a command approval from input sent to an existing terminal.
#[derive(Debug, Default, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub enum ExecApprovalKind {
#[default]
Command,
/// Requires a fresh human decision; automated and reusable approvals are invalid.
HumanCommand,
WriteStdin,
}
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)]
pub struct ExecApprovalRequestEvent {
#[serde(skip)]
#[schemars(skip)]
#[ts(skip)]
pub model_context: Option<crate::items::ModelInvocationContext>,
/// Missing on older events, which retain command approval semantics.
#[serde(default)]
pub kind: ExecApprovalKind,
/// Identifier for the associated command execution item.
pub call_id: String,
/// Trusted plugin attribution for the command item, when available.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub plugin_id: Option<String>,
/// Safe plugin-relative path for the command item, when available.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub script_path: Option<String>,
/// Identifier for this specific approval callback.
///
/// When absent, the approval is for the command item itself (`call_id`).
/// This is present for subcommand approvals (via execve intercept) and stdin writes.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub approval_id: Option<String>,
/// Turn ID that this command belongs to.
/// Uses `#[serde(default)]` for backwards compatibility.
#[serde(default)]
pub turn_id: String,
/// Environment in which the command will run.
#[serde(
default,
rename = "environmentId",
alias = "environment_id",
skip_serializing_if = "Option::is_none"
)]
#[ts(optional)]
#[ts(rename = "environmentId")]
pub environment_id: Option<String>,
#[ts(type = "number")]
pub started_at_ms: i64,
/// The command to be executed.
pub command: Vec<String>,
/// The command's working directory, or the launch directory for terminal input.
pub cwd: LegacyAppPathString,
/// Optional human-readable reason for the approval (e.g. retry without sandbox).
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
/// Optional network context for a blocked request that can be approved.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub network_approval_context: Option<NetworkApprovalContext>,
/// Proposed execpolicy amendment that can be applied to allow future runs.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
/// Proposed network policy amendments (for example allow/deny this host in future).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub proposed_network_policy_amendments: Option<Vec<NetworkPolicyAmendment>>,
/// Optional additional filesystem permissions requested for this command.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub additional_permissions: Option<AdditionalPermissionProfile>,
/// Ordered list of decisions the client may present for this prompt.
///
/// When absent, clients should derive the legacy default set from the
/// other fields on this request.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub available_decisions: Option<Vec<ReviewDecision>>,
pub parsed_cmd: Vec<ParsedCommand>,
}
impl ExecApprovalRequestEvent {
pub fn effective_approval_id(&self) -> String {
self.approval_id
.clone()
.unwrap_or_else(|| self.call_id.clone())
}
pub fn effective_available_decisions(&self) -> Vec<ReviewDecision> {
// available_decisions is a new field that may not be populated by older
// senders, so we fall back to the legacy logic if it's not present.
match &self.available_decisions {
Some(decisions) => decisions.clone(),
None => Self::default_available_decisions(
self.network_approval_context.as_ref(),
self.proposed_execpolicy_amendment.as_ref(),
self.proposed_network_policy_amendments.as_deref(),
self.additional_permissions.as_ref(),
),
}
}
pub fn default_available_decisions(
network_approval_context: Option<&NetworkApprovalContext>,
proposed_execpolicy_amendment: Option<&ExecPolicyAmendment>,
proposed_network_policy_amendments: Option<&[NetworkPolicyAmendment]>,
additional_permissions: Option<&AdditionalPermissionProfile>,
) -> Vec<ReviewDecision> {
if network_approval_context.is_some() {
let mut decisions = vec![ReviewDecision::Approved, ReviewDecision::ApprovedForSession];
if let Some(amendment) = proposed_network_policy_amendments.and_then(|amendments| {
amendments
.iter()
.find(|amendment| amendment.action == NetworkPolicyRuleAction::Allow)
}) {
decisions.push(ReviewDecision::NetworkPolicyAmendment {
network_policy_amendment: amendment.clone(),
});
}
decisions.push(ReviewDecision::Abort);
return decisions;
}
if additional_permissions.is_some() {
return vec![ReviewDecision::Approved, ReviewDecision::Abort];
}
let mut decisions = vec![ReviewDecision::Approved];
if let Some(prefix) = proposed_execpolicy_amendment {
decisions.push(ReviewDecision::ApprovedExecpolicyAmendment {
proposed_execpolicy_amendment: prefix.clone(),
});
}
decisions.push(ReviewDecision::Abort);
decisions
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)]
#[serde(tag = "mode", rename_all = "snake_case")]
#[ts(tag = "mode")]
pub enum ElicitationRequest {
#[serde(rename = "openai/userVerification")]
#[ts(rename = "openai/userVerification")]
UserVerification {
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
#[ts(optional, rename = "_meta")]
meta: Option<JsonValue>,
title: String,
description: String,
challenge: String,
},
Form {
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
#[ts(optional, rename = "_meta")]
meta: Option<JsonValue>,
message: String,
requested_schema: JsonValue,
},
#[serde(rename = "openai/form")]
#[ts(rename = "openai/form")]
OpenAiForm {
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
#[ts(optional, rename = "_meta")]
meta: Option<JsonValue>,
message: String,
requested_schema: JsonValue,
},
#[serde(rename = "openaiForm")]
#[ts(rename = "openaiForm")]
OpenAiElicitationForm {
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
#[ts(optional, rename = "_meta")]
meta: Option<JsonValue>,
message: String,
requested_schema: JsonValue,
},
Url {
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
#[ts(optional, rename = "_meta")]
meta: Option<JsonValue>,
message: String,
url: String,
elicitation_id: String,
},
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)]
pub struct ElicitationAbandonedEvent {
pub server_name: String,
/// Original Core-generated response token of the unanswered request.
#[ts(type = "string | number")]
pub id: RequestId,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)]
pub struct ElicitationRequestEvent {
/// Turn ID that this elicitation belongs to, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub turn_id: Option<String>,
pub server_name: String,
#[ts(type = "string | number")]
pub id: RequestId,
pub request: ElicitationRequest,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
pub enum ElicitationAction {
Accept,
Decline,
Cancel,
}
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)]
pub struct ApplyPatchApprovalRequestEvent {
/// Responses API call id for the associated patch apply call, if available.
pub call_id: String,
/// Turn ID that this patch belongs to.
/// Uses `#[serde(default)]` for backwards compatibility with older senders.
#[serde(default)]
pub turn_id: String,
#[ts(type = "number")]
pub started_at_ms: i64,
pub changes: HashMap<PathBuf, FileChange>,
/// Optional explanatory reason (e.g. request for extra write access).
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
/// When set, the agent is asking the user to allow writes under this root for the remainder of the session.
#[serde(skip_serializing_if = "Option::is_none")]
pub grant_root: Option<PathBuf>,
}
#[cfg(test)]
mod tests {
use super::*;
use akode_utils_absolute_path::test_support::PathBufExt;
use akode_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
#[test]
fn guardian_assessment_action_deserializes_command_shape() {
let action: GuardianAssessmentAction = serde_json::from_value(serde_json::json!({
"type": "command",
"source": "shell",
"command": "rm -rf /tmp/guardian",
"cwd": test_path_buf("/tmp"),
}))
.expect("guardian action");
assert_eq!(
action,
GuardianAssessmentAction::Command {
source: GuardianCommandSource::Shell,
command: "rm -rf /tmp/guardian".to_string(),
cwd: test_path_buf("/tmp").abs().into(),
}
);
}
#[cfg(unix)]
#[test]
fn guardian_assessment_action_round_trips_execve_shape() {
let value = serde_json::json!({
"type": "execve",
"source": "shell",
"program": "/bin/rm",
"argv": ["/usr/bin/rm", "-f", "/tmp/file.sqlite"],
"cwd": "/tmp",
});
let action: GuardianAssessmentAction =
serde_json::from_value(value.clone()).expect("guardian action");
assert_eq!(
serde_json::to_value(&action).expect("serialize guardian action"),
value
);
assert_eq!(
action,
GuardianAssessmentAction::Execve {
source: GuardianCommandSource::Shell,
program: "/bin/rm".to_string(),
argv: vec![
"/usr/bin/rm".to_string(),
"-f".to_string(),
"/tmp/file.sqlite".to_string(),
],
cwd: test_path_buf("/tmp").abs(),
}
);
}
}

View File

@@ -0,0 +1,219 @@
use serde::Deserialize;
use serde::Serialize;
use strum_macros::Display;
use thiserror::Error;
/// Authentication mode for stored or host-supplied provider credentials.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Display, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AuthMode {
/// Provider API key supplied by the caller and stored by Codex.
ApiKey,
/// Provider auth supplied as request headers by a host application.
#[serde(rename = "headers")]
#[strum(serialize = "headers")]
Headers,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PlanType {
Known(KnownPlan),
Unknown(String),
}
impl PlanType {
pub fn from_raw_value(raw: &str) -> Self {
match raw.to_ascii_lowercase().as_str() {
"free" => Self::Known(KnownPlan::Free),
"go" => Self::Known(KnownPlan::Go),
"plus" => Self::Known(KnownPlan::Plus),
"pro" => Self::Known(KnownPlan::Pro),
"prolite" => Self::Known(KnownPlan::ProLite),
"promax" => Self::Known(KnownPlan::ProMax),
"team" => Self::Known(KnownPlan::Team),
"self_serve_business_prolite" => Self::Known(KnownPlan::SelfServeBusinessProLite),
"self_serve_business_usage_based" => {
Self::Known(KnownPlan::SelfServeBusinessUsageBased)
}
"business" => Self::Known(KnownPlan::Business),
"ent26" => Self::Known(KnownPlan::Ent26),
"enterprise_cbp_automation" => Self::Known(KnownPlan::EnterpriseCbpAutomation),
"enterprise_cbp_usage_based" => Self::Known(KnownPlan::EnterpriseCbpUsageBased),
"enterprise" | "hc" => Self::Known(KnownPlan::Enterprise),
"education" | "edu" => Self::Known(KnownPlan::Edu),
"edu_plus" => Self::Known(KnownPlan::EduPlus),
"edu_pro" => Self::Known(KnownPlan::EduPro),
"sci" => Self::Known(KnownPlan::Sci),
"sci_plus" => Self::Known(KnownPlan::SciPlus),
_ => Self::Unknown(raw.to_string()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KnownPlan {
Free,
Go,
Plus,
Pro,
ProLite,
ProMax,
Team,
#[serde(rename = "self_serve_business_prolite")]
SelfServeBusinessProLite,
#[serde(rename = "self_serve_business_usage_based")]
SelfServeBusinessUsageBased,
Business,
Ent26,
#[serde(rename = "enterprise_cbp_automation")]
EnterpriseCbpAutomation,
#[serde(rename = "enterprise_cbp_usage_based")]
EnterpriseCbpUsageBased,
#[serde(alias = "hc")]
Enterprise,
#[serde(alias = "education")]
Edu,
#[serde(rename = "edu_plus")]
EduPlus,
#[serde(rename = "edu_pro")]
EduPro,
Sci,
#[serde(rename = "sci_plus")]
SciPlus,
}
impl KnownPlan {
pub fn display_name(self) -> &'static str {
match self {
Self::Free => "Free",
Self::Go => "Go",
Self::Plus => "Plus",
Self::Pro => "Pro (More)",
Self::ProLite => "Pro",
Self::ProMax => "Pro (Max)",
Self::Team => "Team",
Self::SelfServeBusinessProLite => "Self Serve Business ProLite",
Self::SelfServeBusinessUsageBased => "Self Serve Business Usage Based",
Self::Business => "Business",
Self::Ent26 => "Enterprise",
Self::EnterpriseCbpAutomation => "Enterprise (Automation)",
Self::EnterpriseCbpUsageBased => "Enterprise CBP Usage Based",
Self::Enterprise => "Enterprise",
Self::Edu => "Edu",
Self::EduPlus => "Edu Plus",
Self::EduPro => "Edu Pro",
Self::Sci => "Academic Researchers",
Self::SciPlus => "Academic Researchers Plus",
}
}
pub fn raw_value(self) -> &'static str {
match self {
Self::Free => "free",
Self::Go => "go",
Self::Plus => "plus",
Self::Pro => "pro",
Self::ProLite => "prolite",
Self::ProMax => "promax",
Self::Team => "team",
Self::SelfServeBusinessProLite => "self_serve_business_prolite",
Self::SelfServeBusinessUsageBased => "self_serve_business_usage_based",
Self::Business => "business",
Self::Ent26 => "ent26",
Self::EnterpriseCbpAutomation => "enterprise_cbp_automation",
Self::EnterpriseCbpUsageBased => "enterprise_cbp_usage_based",
Self::Enterprise => "enterprise",
Self::Edu => "edu",
Self::EduPlus => "edu_plus",
Self::EduPro => "edu_pro",
Self::Sci => "sci",
Self::SciPlus => "sci_plus",
}
}
pub fn is_workspace_account(self) -> bool {
matches!(
self,
Self::Team
| Self::SelfServeBusinessProLite
| Self::SelfServeBusinessUsageBased
| Self::Business
| Self::Ent26
| Self::EnterpriseCbpAutomation
| Self::EnterpriseCbpUsageBased
| Self::Enterprise
| Self::Edu
| Self::EduPlus
| Self::EduPro
| Self::Sci
| Self::SciPlus
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("{message}")]
pub struct RefreshTokenFailedError {
pub reason: RefreshTokenFailedReason,
pub message: String,
}
impl RefreshTokenFailedError {
pub fn new(reason: RefreshTokenFailedReason, message: impl Into<String>) -> Self {
Self {
reason,
message: message.into(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefreshTokenFailedReason {
Expired,
Exhausted,
Revoked,
Other,
}
#[cfg(test)]
mod tests {
use super::KnownPlan;
use super::PlanType;
use pretty_assertions::assert_eq;
#[test]
fn plan_type_deserializes_raw_aliases() {
assert_eq!(
serde_json::from_str::<PlanType>("\"hc\"").expect("hc should deserialize"),
PlanType::Known(KnownPlan::Enterprise)
);
assert_eq!(
serde_json::from_str::<PlanType>("\"education\"")
.expect("education should deserialize"),
PlanType::Known(KnownPlan::Edu)
);
assert_eq!(
serde_json::from_str::<PlanType>("\"enterprise_cbp_automation\"")
.expect("enterprise cbp automation should deserialize"),
PlanType::Known(KnownPlan::EnterpriseCbpAutomation)
);
for (raw, known) in [
("promax", KnownPlan::ProMax),
("edu_plus", KnownPlan::EduPlus),
("edu_pro", KnownPlan::EduPro),
("sci", KnownPlan::Sci),
("sci_plus", KnownPlan::SciPlus),
] {
let expected = PlanType::Known(known);
assert_eq!(PlanType::from_raw_value(raw), expected);
assert_eq!(
serde_json::from_value::<PlanType>(serde_json::json!(raw))
.expect("plan should deserialize"),
expected
);
assert_eq!(known.raw_value(), raw);
}
}
}

View File

@@ -0,0 +1,89 @@
use akode_utils_path_uri::LegacyAppPathString;
use akode_utils_path_uri::PathUri;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::sync::Arc;
use ts_rs::TS;
/// A user-selected root that can expose one or more runtime capabilities.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct SelectedCapabilityRoot {
/// Stable identifier supplied by the capability selection platform.
pub id: String,
/// Where the selected root can be resolved.
pub location: CapabilityRootLocation,
}
/// Roots selected for one environment, retaining their order in the thread's root list.
///
/// The index is each root's position in the original thread list. Executor skills assign
/// aliases (`e0`, `e1`, ...) in root order. Keeping the index lets us split roots across
/// environments and combine them again without changing those aliases.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EnvironmentCapabilityRoots(Arc<[(usize, SelectedCapabilityRoot)]>);
impl EnvironmentCapabilityRoots {
/// Selects this environment's roots without losing their original positions.
pub fn for_environment(environment_id: &str, roots: &[SelectedCapabilityRoot]) -> Self {
let mut selected = Vec::new();
for (index, root) in roots.iter().enumerate() {
let CapabilityRootLocation::Environment {
environment_id: root_environment_id,
..
} = &root.location;
if root_environment_id == environment_id {
selected.push((index, root.clone()));
}
}
Self(selected.into())
}
/// Restores root order so changing environment order does not change skill aliases.
pub fn collect<'a>(
selections: impl IntoIterator<Item = &'a Self>,
) -> Vec<SelectedCapabilityRoot> {
let mut roots = Vec::new();
for selection in selections {
roots.extend(selection.0.iter());
}
roots.sort_by_key(|(index, _)| *index);
roots.into_iter().map(|(_, root)| root.clone()).collect()
}
}
/// Location used to resolve a selected capability root.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type")]
#[ts(export_to = "v2/")]
pub enum CapabilityRootLocation {
/// A path owned by an execution environment.
Environment {
#[serde(rename = "environmentId")]
#[ts(rename = "environmentId")]
environment_id: String,
/// Absolute path for the root in the selected environment.
#[serde(deserialize_with = "deserialize_path_uri_from_api_path")]
#[schemars(with = "String")]
#[ts(type = "string")]
path: PathUri,
},
}
fn deserialize_path_uri_from_api_path<'de, D>(deserializer: D) -> Result<PathUri, D::Error>
where
D: serde::Deserializer<'de>,
{
let path = LegacyAppPathString::deserialize(deserializer)?;
if let Ok(path_uri) = PathUri::parse(path.as_str()) {
return Ok(path_uri);
}
path.try_into().map_err(serde::de::Error::custom)
}
#[cfg(test)]
#[path = "capabilities_tests.rs"]
mod tests;

View File

@@ -0,0 +1,30 @@
use super::CapabilityRootLocation;
use super::SelectedCapabilityRoot;
use akode_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
#[test]
fn environment_capability_root_accepts_foreign_file_uri() {
let selected_root = serde_json::from_str::<SelectedCapabilityRoot>(
r#"{
"id": "selected-demo",
"location": {
"type": "environment",
"environmentId": "executor-test",
"path": "file:///C:/plugins/demo"
}
}"#,
)
.expect("file URI should deserialize");
assert_eq!(
selected_root,
SelectedCapabilityRoot {
id: "selected-demo".to_string(),
location: CapabilityRootLocation::Environment {
environment_id: "executor-test".to_string(),
path: PathUri::parse("file:///C:/plugins/demo").expect("path URI"),
},
}
);
}

View File

@@ -0,0 +1,88 @@
//! Decodes unknown error classifications as `Other` so enclosing records stay readable.
//! The wire definition keeps serialization exhaustive and known payload validation strict.
use crate::protocol::CodexErrorInfo;
use crate::protocol::NonSteerableTurnKind;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
use serde::de::Error as _;
use serde_json::Value;
#[derive(Serialize, Deserialize)]
#[serde(
remote = "CodexErrorInfo",
rename = "CodexErrorInfo",
rename_all = "snake_case"
)]
enum CodexErrorInfoWire {
ContextWindowExceeded,
SessionBudgetExceeded,
UsageLimitExceeded,
RateLimitExceeded,
FlexUnavailable,
ServerOverloaded,
ModelNotFound,
/// Capacity is unavailable on a route restricted by server policy.
PolicyCapacityUnavailable,
CyberPolicy,
BioPolicy,
MisalignmentPolicyViolation,
TooManyDenials,
HttpConnectionFailed {
http_status_code: Option<u16>,
},
ResponseStreamConnectionFailed {
http_status_code: Option<u16>,
},
InternalServerError,
Unauthorized,
BadRequest,
InvalidPrompt,
SandboxError,
ResponseStreamDisconnected {
http_status_code: Option<u16>,
},
ResponseTooManyFailedAttempts {
http_status_code: Option<u16>,
},
ActiveTurnNotSteerable {
turn_kind: NonSteerableTurnKind,
},
ThreadRollbackFailed,
#[serde(other)]
Other,
}
impl Serialize for CodexErrorInfo {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
CodexErrorInfoWire::serialize(self, serializer)
}
}
impl<'de> Deserialize<'de> for CodexErrorInfo {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = Value::deserialize(deserializer)?;
// Probe the tag first so only unknown payloads are discarded: `serde(other)`
// recognizes unknown tags, but its unit variant rejects their payloads.
if let Value::Object(fields) = &value
&& fields.len() == 1
&& let Some(kind) = fields.keys().next()
&& kind != "other"
&& matches!(
CodexErrorInfoWire::deserialize(Value::String(kind.clone())),
Ok(Self::Other)
)
{
return Ok(Self::Other);
}
CodexErrorInfoWire::deserialize(value).map_err(D::Error::custom)
}
}

View File

@@ -0,0 +1,980 @@
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_redacted_string::RedactedString;
use schemars::JsonSchema;
use schemars::r#gen::SchemaGenerator;
use schemars::schema::InstanceType;
use schemars::schema::Metadata;
use schemars::schema::Schema;
use schemars::schema::SchemaObject;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use std::collections::HashMap;
use std::fmt;
use std::num::NonZeroU64;
use std::ops::Deref;
use std::str::FromStr;
use std::time::Duration;
use strum_macros::Display;
use strum_macros::EnumIter;
use ts_rs::TS;
use wildmatch::WildMatchPattern;
use crate::openai_models::ReasoningEffort;
/// Limit for the text included in `codex.tool_result` log records.
/// This does not affect model-visible output. Raising it can expose more tool data to logs.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, JsonSchema)]
#[serde(default)]
pub struct ToolResultLogConfig {
/// Maximum UTF-8 bytes before the truncation notice. Defaults to 2048.
pub max_bytes: usize,
}
impl Default for ToolResultLogConfig {
fn default() -> Self {
Self {
max_bytes: 2 * 1024,
}
}
}
/// Selects which part of the active context is charged against
/// `model_auto_compact_token_limit`.
#[derive(
Debug, Serialize, Deserialize, Default, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum AutoCompactTokenLimitScope {
/// Count the full active context against the limit.
#[default]
Total,
/// Count sampled output and later growth after the carried window prefix.
BodyAfterPrefix,
}
/// A summary of the reasoning performed by the model. This can be useful for
/// debugging and understanding the model's reasoning process.
/// See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries
#[derive(
Debug, Serialize, Deserialize, Default, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum ReasoningSummary {
#[default]
Auto,
Concise,
Detailed,
/// Option to disable reasoning summaries.
None,
}
/// Controls output length/detail on GPT-5 models via the Responses API.
/// Serialized with lowercase values to match the OpenAI API.
#[derive(
Hash,
Debug,
Serialize,
Deserialize,
Default,
Clone,
Copy,
PartialEq,
Eq,
Display,
JsonSchema,
TS,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum Verbosity {
Low,
#[default]
Medium,
High,
}
#[derive(
Deserialize, Debug, Clone, Copy, PartialEq, Default, Serialize, Display, JsonSchema, TS,
)]
#[serde(rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
pub enum SandboxMode {
#[serde(rename = "read-only")]
#[default]
ReadOnly,
#[serde(rename = "workspace-write")]
WorkspaceWrite,
#[serde(rename = "danger-full-access")]
DangerFullAccess,
}
/// Validated plain profile-v2 name used to select `$AKODE_HOME/<name>.config.toml`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProfileV2Name(String);
impl ProfileV2Name {
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct ProfileV2NameParseError {
value: String,
}
impl fmt::Display for ProfileV2NameParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"invalid --profile value `{}`; pass a plain name such as `work`",
self.value
)
}
}
impl std::error::Error for ProfileV2NameParseError {}
impl FromStr for ProfileV2Name {
type Err = ProfileV2NameParseError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
if value.is_empty()
|| !value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
{
return Err(ProfileV2NameParseError {
value: value.to_string(),
});
}
Ok(Self(value.to_string()))
}
}
impl Deref for ProfileV2Name {
type Target = str;
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl fmt::Display for ProfileV2Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Display, TS)]
#[strum(serialize_all = "snake_case")]
#[ts(type = r#""user" | "auto_review" | "guardian_subagent""#)]
/// Configures who approval requests are routed to for review. Examples
/// include sandbox escapes, blocked network access, MCP approval prompts, and
/// ARC escalations. Defaults to `user`. `auto_review` uses a carefully
/// prompted subagent to gather relevant context and apply a risk-based
/// decision framework before approving or denying the request.
pub enum ApprovalsReviewer {
#[default]
#[serde(rename = "user")]
User,
#[serde(rename = "auto_review", alias = "guardian_subagent")]
#[strum(serialize = "auto_review")]
AutoReview,
}
impl JsonSchema for ApprovalsReviewer {
fn schema_name() -> String {
"ApprovalsReviewer".to_string()
}
fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
string_enum_schema_with_description(
&["user", "auto_review", "guardian_subagent"],
"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.",
)
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum ShellEnvironmentPolicyInherit {
/// "Core" environment variables for the platform. On UNIX, this would
/// include HOME, LOGNAME, PATH, SHELL, and USER, among others.
Core,
/// Inherits the full environment from the parent process.
#[default]
All,
/// Do not inherit any environment variables from the parent process.
None,
}
/// Assigns a shell environment variable pattern to the include-only or exclude
/// set. Includes do not re-add variables removed by another exclude pattern.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
#[ts(export_to = "v2/")]
pub enum ShellEnvironmentPolicyFilter {
Include,
Exclude,
}
pub type EnvironmentVariablePattern = WildMatchPattern<'*', '?'>;
/// Deriving the `env` based on this policy works as follows:
/// 1. Create an initial map based on the `inherit` policy.
/// 2. If `ignore_default_excludes` is false, filter the map using the default
/// exclude pattern(s), which are: `"*KEY*"`, `"*SECRET*"`, and `"*TOKEN*"`.
/// 3. If `exclude` is not empty, filter the map using the provided patterns.
/// 4. Insert any entries from `r#set` into the map.
/// 5. If non-empty, filter the map using the `include_only` patterns.
#[derive(Debug, Clone, PartialEq)]
pub struct ShellEnvironmentPolicy {
/// Starting point when building the environment.
pub inherit: ShellEnvironmentPolicyInherit,
/// True to skip the check to exclude default environment variables that
/// contain "KEY", "SECRET", or "TOKEN" in their name. Defaults to true.
pub ignore_default_excludes: bool,
/// Environment variable names to exclude from the environment.
pub exclude: Vec<EnvironmentVariablePattern>,
/// (key, value) pairs to insert in the environment.
pub r#set: HashMap<String, String>,
/// Environment variable names to retain in the environment.
pub include_only: Vec<EnvironmentVariablePattern>,
/// If true, the shell profile will be used to run the command.
pub use_profile: bool,
}
impl Default for ShellEnvironmentPolicy {
fn default() -> Self {
Self {
inherit: ShellEnvironmentPolicyInherit::All,
ignore_default_excludes: true,
exclude: Vec::new(),
r#set: HashMap::new(),
include_only: Vec::new(),
use_profile: false,
}
}
}
fn string_enum_schema_with_description(values: &[&str], description: &str) -> Schema {
let mut schema = SchemaObject {
instance_type: Some(InstanceType::String.into()),
metadata: Some(Box::new(Metadata {
description: Some(description.to_string()),
..Default::default()
})),
..Default::default()
};
schema.enum_values = Some(
values
.iter()
.map(|value| Value::String((*value).to_string()))
.collect(),
);
Schema::Object(schema)
}
#[derive(
Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Display, JsonSchema, TS,
)]
#[serde(rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
pub enum WindowsSandboxLevel {
#[default]
Disabled,
RestrictedToken,
Elevated,
}
/// Controls whether a Windows sandbox launch reconciles persistent proxy settings or preserves
/// the settings established by another launch.
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum WindowsSandboxProxySettingsMode {
#[default]
Reconcile,
Preserve,
}
/// Deprecated: `friendly` and `pragmatic` no longer select a style.
#[derive(
Debug,
Serialize,
Deserialize,
Clone,
Copy,
PartialEq,
Eq,
Display,
JsonSchema,
TS,
PartialOrd,
Ord,
EnumIter,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum Personality {
None,
Friendly,
Pragmatic,
}
/// Controls the effective multi-agent delegation instructions for a turn. `custom` means the
/// configured mode hint defines the policy instead of a built-in policy.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Display, JsonSchema, TS, Default)]
#[serde(rename_all = "camelCase", from = "MultiAgentModeWire")]
#[ts(rename_all = "camelCase")]
#[strum(serialize_all = "camelCase")]
pub enum MultiAgentMode {
Custom(String),
#[default]
ExplicitRequestOnly,
Proactive,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
enum MultiAgentModeWire {
None,
Custom(String),
ExplicitRequestOnly,
Proactive,
}
impl From<MultiAgentModeWire> for MultiAgentMode {
fn from(value: MultiAgentModeWire) -> Self {
match value {
MultiAgentModeWire::None => Self::Custom(String::new()),
MultiAgentModeWire::Custom(hint_text) => Self::Custom(hint_text),
MultiAgentModeWire::ExplicitRequestOnly => Self::ExplicitRequestOnly,
MultiAgentModeWire::Proactive => Self::Proactive,
}
}
}
#[derive(
Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS, Default,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum WebSearchMode {
Disabled,
#[default]
Cached,
Indexed,
Live,
}
impl WebSearchMode {
/// Restricts search to the access permitted by both modes.
pub fn restrict_to(self, requested: Self) -> Self {
match (self, requested) {
(Self::Disabled, _) | (_, Self::Disabled) => Self::Disabled,
(Self::Cached, _) | (_, Self::Cached) => Self::Cached,
(Self::Indexed, _) | (_, Self::Indexed) => Self::Indexed,
(Self::Live, Self::Live) => Self::Live,
}
}
}
/// A model-facing surface on which a tool can be exposed.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ToolExposureSurface {
/// Nested tools available to Code Mode scripts.
CodeMode,
/// Tools discovered later through tool search.
Deferred,
/// Tools present in the model's initial tool list.
Direct,
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum WebSearchContextSize {
Low,
Medium,
High,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[schemars(deny_unknown_fields)]
pub struct WebSearchLocation {
pub country: Option<String>,
pub region: Option<String>,
pub city: Option<String>,
pub timezone: Option<String>,
}
impl WebSearchLocation {
pub fn merge(&self, other: &Self) -> Self {
Self {
country: other.country.clone().or_else(|| self.country.clone()),
region: other.region.clone().or_else(|| self.region.clone()),
city: other.city.clone().or_else(|| self.city.clone()),
timezone: other.timezone.clone().or_else(|| self.timezone.clone()),
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[schemars(deny_unknown_fields)]
pub struct WebSearchToolConfig {
pub context_size: Option<WebSearchContextSize>,
pub allowed_domains: Option<Vec<String>>,
pub location: Option<WebSearchLocation>,
}
impl WebSearchToolConfig {
pub fn merge(&self, other: &Self) -> Self {
Self {
context_size: other.context_size.or(self.context_size),
allowed_domains: other
.allowed_domains
.clone()
.or_else(|| self.allowed_domains.clone()),
location: match (&self.location, &other.location) {
(Some(location), Some(other_location)) => Some(location.merge(other_location)),
(Some(location), None) => Some(location.clone()),
(None, Some(other_location)) => Some(other_location.clone()),
(None, None) => None,
},
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[schemars(deny_unknown_fields)]
pub struct WebSearchFilters {
pub allowed_domains: Option<Vec<String>>,
}
#[derive(
Debug, Serialize, Deserialize, Clone, Copy, Default, PartialEq, Eq, Display, JsonSchema, TS,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum WebSearchUserLocationType {
#[default]
Approximate,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[schemars(deny_unknown_fields)]
pub struct WebSearchUserLocation {
#[serde(default)]
pub r#type: WebSearchUserLocationType,
pub country: Option<String>,
pub region: Option<String>,
pub city: Option<String>,
pub timezone: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq, JsonSchema, TS)]
#[schemars(deny_unknown_fields)]
pub struct WebSearchConfig {
pub filters: Option<WebSearchFilters>,
pub user_location: Option<WebSearchUserLocation>,
pub search_context_size: Option<WebSearchContextSize>,
}
impl From<WebSearchLocation> for WebSearchUserLocation {
fn from(location: WebSearchLocation) -> Self {
Self {
r#type: WebSearchUserLocationType::Approximate,
country: location.country,
region: location.region,
city: location.city,
timezone: location.timezone,
}
}
}
impl From<WebSearchToolConfig> for WebSearchConfig {
fn from(config: WebSearchToolConfig) -> Self {
Self {
filters: config
.allowed_domains
.map(|allowed_domains| WebSearchFilters {
allowed_domains: Some(allowed_domains),
}),
user_location: config.location.map(Into::into),
search_context_size: config.context_size,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum ServiceTier {
Fast,
Flex,
}
/// Request/config sentinel for explicit standard routing.
///
/// This is not a catalog service tier id. It means the user intentionally
/// selected no service tier, so model catalog defaults should not apply.
pub const SERVICE_TIER_DEFAULT_REQUEST_VALUE: &str = "default";
impl ServiceTier {
pub const fn request_value(self) -> &'static str {
match self {
Self::Fast => "priority",
Self::Flex => "flex",
}
}
pub fn from_request_value(value: &str) -> Option<Self> {
match value {
"fast" | "priority" => Some(Self::Fast),
"flex" => Some(Self::Flex),
_ => None,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum ForcedLoginMethod {
Chatgpt,
Api,
}
const DEFAULT_PROVIDER_AUTH_TIMEOUT_MS: u64 = 5_000;
const DEFAULT_PROVIDER_AUTH_REFRESH_INTERVAL_MS: u64 = 300_000;
/// Configuration for obtaining a provider bearer token from a command.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ModelProviderAuthInfo {
/// Command to execute. Bare names are resolved via `PATH`; paths are resolved against `cwd`.
pub command: String,
/// Command arguments.
#[serde(default)]
pub args: Vec<RedactedString>,
/// Maximum time to wait for the token command to exit successfully.
#[serde(default = "default_provider_auth_timeout_ms")]
pub timeout_ms: NonZeroU64,
/// Maximum age for the cached token before rerunning the command.
/// Set to `0` to disable proactive refresh and only rerun after a 401 retry path.
#[serde(default = "default_provider_auth_refresh_interval_ms")]
pub refresh_interval_ms: u64,
/// Working directory used when running the token command.
#[serde(default = "default_provider_auth_cwd")]
#[schemars(skip_serializing_if = "is_default_provider_auth_cwd")]
pub cwd: AbsolutePathBuf,
}
impl ModelProviderAuthInfo {
pub fn timeout(&self) -> Duration {
Duration::from_millis(self.timeout_ms.get())
}
pub fn refresh_interval(&self) -> Option<Duration> {
NonZeroU64::new(self.refresh_interval_ms).map(|value| Duration::from_millis(value.get()))
}
}
fn default_provider_auth_timeout_ms() -> NonZeroU64 {
non_zero_u64(
DEFAULT_PROVIDER_AUTH_TIMEOUT_MS,
"model_providers.<id>.auth.timeout_ms",
)
}
fn default_provider_auth_refresh_interval_ms() -> u64 {
DEFAULT_PROVIDER_AUTH_REFRESH_INTERVAL_MS
}
fn non_zero_u64(value: u64, field_name: &str) -> NonZeroU64 {
match NonZeroU64::new(value) {
Some(value) => value,
None => panic!("{field_name} must be non-zero"),
}
}
fn default_provider_auth_cwd() -> AbsolutePathBuf {
let deserializer = serde::de::value::StrDeserializer::<serde::de::value::Error>::new(".");
if let Ok(cwd) = AbsolutePathBuf::deserialize(deserializer) {
return cwd;
}
match AbsolutePathBuf::current_dir() {
Ok(cwd) => cwd,
Err(err) => panic!("provider auth cwd must resolve: {err}"),
}
}
fn is_default_provider_auth_cwd(path: &AbsolutePathBuf) -> bool {
path == &default_provider_auth_cwd()
}
/// Represents the trust level for a project directory.
/// This determines the approval policy and sandbox mode applied.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum TrustLevel {
Trusted,
Untrusted,
}
/// Controls whether the TUI uses the terminal's alternate screen buffer.
///
/// - `auto` (default): Use alternate screen mode.
/// - `always`: Always use alternate screen mode.
/// - `never`: Never use alternate screen mode. Runs in inline mode, preserving scrollback.
///
/// The CLI flag `--no-alt-screen` can override this setting at runtime.
#[derive(
Debug, Serialize, Deserialize, Default, Clone, Copy, PartialEq, Eq, Display, JsonSchema, TS,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum AltScreenMode {
/// Use alternate screen mode.
#[default]
Auto,
/// Always use alternate screen mode.
Always,
/// Never use alternate screen (inline mode only).
Never,
}
/// Initial collaboration mode to use when the TUI starts.
#[derive(
Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, JsonSchema, TS, Default,
)]
#[serde(rename_all = "snake_case")]
pub enum ModeKind {
Plan,
#[default]
#[serde(
alias = "code",
alias = "pair_programming",
alias = "execute",
alias = "custom"
)]
Default,
}
pub const TUI_VISIBLE_COLLABORATION_MODES: [ModeKind; 2] = [ModeKind::Default, ModeKind::Plan];
impl ModeKind {
pub const fn display_name(self) -> &'static str {
match self {
Self::Plan => "Plan",
Self::Default => "Default",
}
}
pub const fn is_tui_visible(self) -> bool {
matches!(self, Self::Plan | Self::Default)
}
pub const fn allows_request_user_input(self) -> bool {
matches!(self, Self::Plan)
}
}
/// Collaboration mode for a Codex session.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize, JsonSchema, TS)]
#[serde(rename_all = "lowercase")]
pub struct CollaborationMode {
pub mode: ModeKind,
pub settings: Settings,
}
impl CollaborationMode {
/// Returns a reference to the settings.
fn settings_ref(&self) -> &Settings {
&self.settings
}
pub fn model(&self) -> &str {
self.settings_ref().model.as_str()
}
pub fn reasoning_effort(&self) -> Option<ReasoningEffort> {
self.settings_ref().reasoning_effort.clone()
}
/// Updates the collaboration mode with new model and/or effort values.
///
/// - `model`: `Some(s)` to update the model, `None` to keep the current model
/// - `effort`: `Some(Some(e))` to set effort to `e`, `Some(None)` to clear effort, `None` to keep current effort
/// - `developer_instructions`: `Some(Some(s))` to set instructions, `Some(None)` to clear them, `None` to keep current
///
/// Returns a new `CollaborationMode` with updated values, preserving the mode.
pub fn with_updates(
&self,
model: Option<String>,
effort: Option<Option<ReasoningEffort>>,
developer_instructions: Option<Option<String>>,
) -> Self {
let settings = self.settings_ref();
let updated_settings = Settings {
model: model.unwrap_or_else(|| settings.model.clone()),
reasoning_effort: effort.unwrap_or_else(|| settings.reasoning_effort.clone()),
developer_instructions: developer_instructions
.unwrap_or_else(|| settings.developer_instructions.clone()),
};
CollaborationMode {
mode: self.mode,
settings: updated_settings,
}
}
/// Applies a mask to this collaboration mode, returning a new collaboration mode
/// with the mask values applied. Fields in the mask that are `Some` will override
/// the corresponding fields, while `None` values will preserve the original values.
///
/// The `name` field in the mask is ignored as it's metadata for the mask itself.
pub fn apply_mask(&self, mask: &CollaborationModeMask) -> Self {
let settings = self.settings_ref();
CollaborationMode {
mode: mask.mode.unwrap_or(self.mode),
settings: Settings {
model: mask.model.clone().unwrap_or_else(|| settings.model.clone()),
reasoning_effort: mask
.reasoning_effort
.clone()
.unwrap_or_else(|| settings.reasoning_effort.clone()),
developer_instructions: mask
.developer_instructions
.clone()
.unwrap_or_else(|| settings.developer_instructions.clone()),
},
}
}
}
/// Settings for a collaboration mode.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize, JsonSchema, TS)]
pub struct Settings {
pub model: String,
pub reasoning_effort: Option<ReasoningEffort>,
pub developer_instructions: Option<String>,
}
/// A mask for collaboration mode settings, allowing partial updates.
/// All fields except `name` are optional, enabling selective updates.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize, JsonSchema, TS)]
pub struct CollaborationModeMask {
pub name: String,
pub mode: Option<ModeKind>,
pub model: Option<String>,
pub reasoning_effort: Option<Option<ReasoningEffort>>,
pub developer_instructions: Option<Option<String>>,
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn web_search_mode_restrictions_never_expand_either_mode() {
use WebSearchMode::Cached;
use WebSearchMode::Disabled;
use WebSearchMode::Indexed;
use WebSearchMode::Live;
let modes = [Disabled, Cached, Indexed, Live];
let expected = [
[Disabled, Disabled, Disabled, Disabled],
[Disabled, Cached, Cached, Cached],
[Disabled, Cached, Indexed, Indexed],
[Disabled, Cached, Indexed, Live],
];
for (parent_index, parent) in modes.into_iter().enumerate() {
for (requested_index, requested) in modes.into_iter().enumerate() {
assert_eq!(
parent.restrict_to(requested),
expected[parent_index][requested_index],
"parent: {parent:?}, requested: {requested:?}",
);
}
}
}
#[test]
fn apply_mask_can_clear_optional_fields() {
let mode = CollaborationMode {
mode: ModeKind::Default,
settings: Settings {
model: "gpt-5.2-codex".to_string(),
reasoning_effort: Some(ReasoningEffort::High),
developer_instructions: Some("stay focused".to_string()),
},
};
let mask = CollaborationModeMask {
name: "Clear".to_string(),
mode: None,
model: None,
reasoning_effort: Some(None),
developer_instructions: Some(None),
};
let expected = CollaborationMode {
mode: ModeKind::Default,
settings: Settings {
model: "gpt-5.2-codex".to_string(),
reasoning_effort: None,
developer_instructions: None,
},
};
assert_eq!(expected, mode.apply_mask(&mask));
}
#[test]
fn mode_kind_deserializes_alias_values_to_default() {
for alias in ["code", "pair_programming", "execute", "custom"] {
let json = format!("\"{alias}\"");
let mode: ModeKind = serde_json::from_str(&json).expect("deserialize mode");
assert_eq!(ModeKind::Default, mode);
}
}
#[test]
fn approvals_reviewer_serializes_auto_review_and_accepts_legacy_guardian_subagent() {
assert_eq!(ApprovalsReviewer::User.to_string(), "user");
assert_eq!(
serde_json::to_string(&ApprovalsReviewer::User).expect("serialize reviewer"),
"\"user\""
);
assert_eq!(
serde_json::to_string(&ApprovalsReviewer::AutoReview).expect("serialize reviewer"),
"\"auto_review\""
);
for value in ["user", "auto_review", "guardian_subagent"] {
let json = format!("\"{value}\"");
let reviewer: ApprovalsReviewer =
serde_json::from_str(&json).expect("deserialize reviewer");
let expected = if value == "user" {
ApprovalsReviewer::User
} else {
ApprovalsReviewer::AutoReview
};
assert_eq!(expected, reviewer);
}
}
#[test]
fn profile_v2_name_rejects_paths_and_empty_names() {
assert_eq!(
ProfileV2Name::from_str("../foo"),
Err(ProfileV2NameParseError {
value: "../foo".to_string(),
}),
"dots and slashes are disallowed to prevent reading arbitrary files"
);
assert_eq!(
ProfileV2Name::from_str(""),
Err(ProfileV2NameParseError {
value: String::new(),
}),
"profile name cannot be empty"
);
}
#[test]
fn tui_visible_collaboration_modes_match_mode_kind_visibility() {
let expected = [ModeKind::Default, ModeKind::Plan];
assert_eq!(expected, TUI_VISIBLE_COLLABORATION_MODES);
for mode in TUI_VISIBLE_COLLABORATION_MODES {
assert!(mode.is_tui_visible());
}
}
#[test]
fn web_search_location_merge_prefers_overlay_values() {
let base = WebSearchLocation {
country: Some("US".to_string()),
region: Some("CA".to_string()),
city: None,
timezone: Some("America/Los_Angeles".to_string()),
};
let overlay = WebSearchLocation {
country: None,
region: Some("WA".to_string()),
city: Some("Seattle".to_string()),
timezone: None,
};
let expected = WebSearchLocation {
country: Some("US".to_string()),
region: Some("WA".to_string()),
city: Some("Seattle".to_string()),
timezone: Some("America/Los_Angeles".to_string()),
};
assert_eq!(expected, base.merge(&overlay));
}
#[test]
fn web_search_tool_config_merge_prefers_overlay_values() {
let base = WebSearchToolConfig {
context_size: Some(WebSearchContextSize::Low),
allowed_domains: Some(vec!["openai.com".to_string()]),
location: Some(WebSearchLocation {
country: Some("US".to_string()),
region: Some("CA".to_string()),
city: None,
timezone: Some("America/Los_Angeles".to_string()),
}),
};
let overlay = WebSearchToolConfig {
context_size: Some(WebSearchContextSize::High),
allowed_domains: None,
location: Some(WebSearchLocation {
country: None,
region: Some("WA".to_string()),
city: Some("Seattle".to_string()),
timezone: None,
}),
};
let expected = WebSearchToolConfig {
context_size: Some(WebSearchContextSize::High),
allowed_domains: Some(vec!["openai.com".to_string()]),
location: Some(WebSearchLocation {
country: Some("US".to_string()),
region: Some("WA".to_string()),
city: Some("Seattle".to_string()),
timezone: Some("America/Los_Angeles".to_string()),
}),
};
assert_eq!(expected, base.merge(&overlay));
}
}

View File

@@ -0,0 +1,30 @@
//! Context window identity used for compaction, rollout restoration, and request metadata.
use serde::Serialize;
use std::fmt;
use uuid::Uuid;
#[derive(derive_more::Debug, Clone, PartialEq, Eq, Serialize)]
#[debug("{_0}")]
#[serde(transparent)]
pub struct ContextWindowId(String);
impl ContextWindowId {
pub fn new_uuid_v7() -> Self {
Self(Uuid::now_v7().to_string())
}
/// Reads a persisted window ID, ignoring IDs outside the supported format.
pub fn parse(value: &str) -> Option<Self> {
Uuid::parse_str(value)
.ok()
.filter(|uuid| uuid.get_version_num() == 7)
.map(|uuid| Self(uuid.to_string()))
}
}
impl fmt::Display for ContextWindowId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(formatter)
}
}

View File

@@ -0,0 +1,52 @@
//! Start diagnostics retain routing-independent metadata without exposing input content.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn realtime_start_debug_redacts_text_and_transport() {
let secret = "credential-bearing-content";
let mut params = ConversationStartParams {
client_managed_handoffs: false,
delegation_ack_filler: None,
flush_transcript_tail_on_session_end: false,
codex_responses_as_items: false,
codex_response_item_prefix: Some(secret.to_owned()),
codex_response_handoff_mode: Default::default(),
backend_reasoning_status: false,
codex_response_handoff_channel_prefixes: Some(BTreeMap::from([(
secret.to_owned(),
vec![secret.to_owned()],
)])),
model: Some(secret.to_owned()),
output_modality: RealtimeOutputModality::Audio,
include_startup_context: true,
initial_items: vec![ConversationTextParams {
role: ConversationTextRole::Developer,
text: secret.to_owned(),
}],
realtime_start_instructions: Some(secret.to_owned()),
realtime_end_instructions: Some(secret.to_owned()),
prompt: Some(Some(secret.to_owned())),
realtime_session_id: Some(secret.to_owned()),
voice_session_id: Some(secret.to_owned()),
transport: None,
version: Some(RealtimeConversationVersion::V3),
voice: None,
};
for transport in [
ConversationStartTransport::ExistingCall {
call_id: secret.to_owned(),
sideband_base_url: Some(format!("wss://example.test/?token={secret}")),
},
ConversationStartTransport::Webrtc {
sdp: secret.to_owned(),
},
] {
params.transport = Some(transport);
assert_eq!(
format!("{params:?}"),
"ConversationStartParams { output_modality: Audio, initial_items_count: 1, version: Some(V3), .. }"
);
}
}

View File

@@ -0,0 +1,175 @@
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::de::Error as _;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use ts_rs::TS;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type", export_to = "v2/")]
pub enum DynamicToolSpec {
Function(DynamicToolFunctionSpec),
Namespace(DynamicToolNamespaceSpec),
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct DynamicToolFunctionSpec {
pub name: String,
pub description: String,
pub input_schema: JsonValue,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub defer_loading: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct DynamicToolNamespaceSpec {
pub name: String,
pub description: String,
pub tools: Vec<DynamicToolNamespaceTool>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type", export_to = "v2/")]
pub enum DynamicToolNamespaceTool {
Function(DynamicToolFunctionSpec),
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct DynamicToolCallRequest {
pub call_id: String,
pub turn_id: String,
#[serde(default)]
pub started_at_ms: i64,
#[serde(default)]
pub namespace: Option<String>,
pub tool: String,
pub arguments: JsonValue,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct DynamicToolResponse {
pub content_items: Vec<DynamicToolCallOutputContentItem>,
pub success: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "camelCase")]
#[ts(tag = "type")]
pub enum DynamicToolCallOutputContentItem {
#[serde(rename_all = "camelCase")]
InputText { text: String },
#[serde(rename_all = "camelCase")]
InputImage { image_url: String },
#[serde(rename_all = "camelCase")]
InputAudio { audio_url: String },
}
/// Former flat `SessionMeta` shape, including the old `exposeToContext` flag.
/// Kept so new builds can resume sessions written before explicit namespaces.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct LegacyDynamicToolSpec {
namespace: Option<String>,
name: String,
description: String,
input_schema: JsonValue,
defer_loading: Option<bool>,
expose_to_context: Option<bool>,
}
pub fn normalize_dynamic_tool_specs(
values: Vec<JsonValue>,
) -> Result<Vec<DynamicToolSpec>, serde_json::Error> {
let has_legacy_fields = |value: &JsonValue| {
value.get("namespace").is_some()
|| value.get("exposeToContext").is_some()
|| value.get("type").is_none()
};
let has_legacy_format = values.iter().any(|value| {
has_legacy_fields(value)
|| value
.get("tools")
.and_then(JsonValue::as_array)
.is_some_and(|tools| tools.iter().any(&has_legacy_fields))
});
let has_canonical_format = values.iter().any(|value| value.get("type").is_some());
if has_legacy_format && has_canonical_format {
return Err(serde_json::Error::custom(
"dynamic tools must use either canonical or legacy format consistently",
));
}
if !has_legacy_format {
return values.into_iter().map(serde_json::from_value).collect();
}
let tools = values
.into_iter()
.map(|value| {
let tool: LegacyDynamicToolSpec = serde_json::from_value(value)?;
let function = DynamicToolFunctionSpec {
name: tool.name,
description: tool.description,
input_schema: tool.input_schema,
defer_loading: tool.defer_loading.unwrap_or_else(|| {
tool.expose_to_context
.map(|visible| !visible)
.unwrap_or(false)
}),
};
Ok((tool.namespace, function))
})
.collect::<Result<Vec<_>, serde_json::Error>>()?;
Ok(group_dynamic_tools_by_namespace(tools))
}
pub fn group_dynamic_tools_by_namespace(
tools: Vec<(Option<String>, DynamicToolFunctionSpec)>,
) -> Vec<DynamicToolSpec> {
let mut grouped_tools = Vec::with_capacity(tools.len());
let mut namespace_indices = HashMap::<String, usize>::new();
for (namespace, function) in tools {
let Some(namespace) = namespace else {
grouped_tools.push(DynamicToolSpec::Function(function));
continue;
};
let function = DynamicToolNamespaceTool::Function(function);
if let Some(index) = namespace_indices.get(&namespace).copied() {
let DynamicToolSpec::Namespace(namespace) = &mut grouped_tools[index] else {
unreachable!("namespace index must point to a namespace");
};
namespace.tools.push(function);
continue;
}
namespace_indices.insert(namespace.clone(), grouped_tools.len());
grouped_tools.push(DynamicToolSpec::Namespace(DynamicToolNamespaceSpec {
name: namespace,
description: String::new(),
tools: vec![function],
}));
}
grouped_tools
}
pub fn deserialize_dynamic_tool_specs<'de, D>(
deserializer: D,
) -> Result<Option<Vec<DynamicToolSpec>>, D::Error>
where
D: Deserializer<'de>,
{
let Some(values) = Option::<Vec<JsonValue>>::deserialize(deserializer)? else {
return Ok(None);
};
normalize_dynamic_tool_specs(values)
.map(Some)
.map_err(D::Error::custom)
}

View File

@@ -0,0 +1,237 @@
//! Environment requests, thread selections, and attachment authority.
//! Selections bind requests to the thread's capability roots before runtime use.
use crate::capabilities::EnvironmentCapabilityRoots;
use crate::capabilities::SelectedCapabilityRoot;
use crate::config_types::ShellEnvironmentPolicy;
use crate::config_types::WindowsSandboxLevel;
use crate::mcp_policy::EnvironmentMcpPolicy;
use crate::models::PermissionProfile;
use crate::models::PermissionProfileSnapshot;
use crate::protocol::AskForApproval;
use crate::sandbox::SandboxType;
use akode_execpolicy::RequirementsExecPolicy;
use akode_network_proxy::EnvironmentNetworkPolicy;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
/// An environment requested by a caller, before attaching the receiving thread's roots.
///
/// Callers choose the environment and paths, but startup may still need to load roots from
/// saved history or inherited attachments. Keeping this input separate lets the receiving
/// thread construct a complete selection instead of filling in missing roots later.
#[derive(Debug, Clone, PartialEq)]
pub struct TurnEnvironmentRequest {
pub environment_id: String,
pub cwd: PathUri,
pub workspace_roots: Vec<PathUri>,
pub config: EnvironmentConfigState,
}
/// An environment selected for a thread, with its capability roots already attached.
///
/// Runtime snapshots carry this value so capability discovery uses the roots captured
/// with the environment. Construct it from a request and the receiving thread's roots.
#[derive(Debug, Clone, PartialEq)]
pub struct TurnEnvironmentSelection {
pub environment_id: String,
pub cwd: PathUri,
pub workspace_roots: Vec<PathUri>,
pub config: EnvironmentConfigState,
/// Roots selected by the client for this environment when the thread started.
pub selected_capability_roots: EnvironmentCapabilityRoots,
}
impl TurnEnvironmentSelection {
/// Attaches this environment's roots before the selection enters runtime state.
/// The caller supplies the receiving thread's roots so reselection restores them and
/// reusing an environment from another thread does not reuse that thread's root choices.
pub fn new(request: TurnEnvironmentRequest, roots: &[SelectedCapabilityRoot]) -> Self {
Self {
selected_capability_roots: EnvironmentCapabilityRoots::for_environment(
&request.environment_id,
roots,
),
environment_id: request.environment_id,
cwd: request.cwd,
workspace_roots: request.workspace_roots,
config: request.config,
}
}
/// Whether these selections refer to the same environment and workspace.
/// Unlike full selection equality, this ignores configuration and capability roots:
/// those can differ between threads that follow the same owner's configuration.
pub fn has_same_workspace(&self, other: &Self) -> bool {
self.environment_id == other.environment_id
&& self.cwd == other.cwd
&& self.workspace_roots == other.workspace_roots
}
/// Requests this environment again; the receiving thread supplies its own roots.
/// This explicit conversion discards thread-owned state. Test inputs should instead
/// construct requests directly so they do not depend on runtime selection fields.
pub fn into_request(self) -> TurnEnvironmentRequest {
TurnEnvironmentRequest {
environment_id: self.environment_id,
cwd: self.cwd,
workspace_roots: self.workspace_roots,
config: self.config,
}
}
}
/// The environments captured by a thread and its fallback working directory.
#[derive(Debug, Clone, PartialEq)]
pub struct TurnEnvironmentSelections {
pub legacy_fallback_cwd: AbsolutePathBuf,
pub environments: Vec<TurnEnvironmentSelection>,
}
impl TurnEnvironmentSelections {
pub fn new(
legacy_fallback_cwd: AbsolutePathBuf,
environments: Vec<TurnEnvironmentSelection>,
) -> Self {
Self {
legacy_fallback_cwd,
environments,
}
}
/// Requests these environments again, leaving root choices to the receiving thread.
pub fn into_requests(self) -> TurnEnvironmentRequests {
TurnEnvironmentRequests {
legacy_fallback_cwd: self.legacy_fallback_cwd,
environment_requests: self
.environments
.into_iter()
.map(TurnEnvironmentSelection::into_request)
.collect(),
}
}
}
/// Environment input supplied together with its fallback working directory.
/// The receiving thread attaches roots in `select` before capturing these environments.
#[derive(Debug, Clone, PartialEq)]
pub struct TurnEnvironmentRequests {
pub legacy_fallback_cwd: AbsolutePathBuf,
pub environment_requests: Vec<TurnEnvironmentRequest>,
}
impl TurnEnvironmentRequests {
pub fn new(
legacy_fallback_cwd: AbsolutePathBuf,
environment_requests: Vec<TurnEnvironmentRequest>,
) -> Self {
Self {
legacy_fallback_cwd,
environment_requests,
}
}
/// Constructs selections with the receiving thread's roots, including roots retained
/// while an environment was deselected. Snapshots can then carry complete selections.
pub fn select(self, roots: &[SelectedCapabilityRoot]) -> TurnEnvironmentSelections {
TurnEnvironmentSelections {
legacy_fallback_cwd: self.legacy_fallback_cwd,
environments: self
.environment_requests
.into_iter()
.map(|request| TurnEnvironmentSelection::new(request, roots))
.collect(),
}
}
}
/// Configuration supplied for a thread's selected environment.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub enum EnvironmentConfigState {
/// Preserve the existing thread-derived environment configuration.
FromThread,
/// The owner will supply environment configuration later.
Pending,
/// The owner supplied configuration for this environment attachment.
Ready(EnvironmentConfig),
/// The owner could not supply configuration for this environment attachment.
Failed(String),
}
/// Full Access requires no approvals and unrestricted permissions everywhere selected.
/// Thread-owned attachments inherit the fallback profile; unresolved owner authority
/// is never Full Access. All approval and background-review paths use this decision.
pub fn has_full_access<'a>(
approval_policy: AskForApproval,
thread_profile: &PermissionProfile,
environments: impl IntoIterator<Item = &'a EnvironmentConfigState>,
) -> bool {
let mut environments = environments.into_iter().peekable();
approval_policy == AskForApproval::Never
&& if environments.peek().is_none() {
matches!(thread_profile, PermissionProfile::Disabled)
} else {
environments.all(|environment| match environment {
EnvironmentConfigState::FromThread => {
matches!(thread_profile, PermissionProfile::Disabled)
}
EnvironmentConfigState::Ready(config) => {
matches!(
config.permission_profile.permission_profile(),
PermissionProfile::Disabled
)
}
EnvironmentConfigState::Pending | EnvironmentConfigState::Failed(_) => false,
})
}
}
/// Resolved configuration for a thread/environment attachment.
#[derive(Clone, PartialEq)]
pub struct EnvironmentConfig {
/// Hooks from this environment's effective managed requirements.
pub environment_hooks: crate::hooks::HookEventsToml,
/// Whether shell tools may start login shells in this environment.
pub allow_login_shell: bool,
/// Effective workspace roots resolved for this environment attachment.
pub workspace_roots: Vec<PathUri>,
/// Resolved permissions for this thread's environment attachment.
pub permission_profile: PermissionProfileSnapshot,
/// Controls which environment variables shell commands may inherit.
pub shell_environment_policy: ShellEnvironmentPolicy,
/// Legacy Windows restricted-token setup level for this environment attachment.
pub windows_sandbox_level: WindowsSandboxLevel,
/// Concrete Windows sandbox backend selected for this environment attachment.
pub windows_sandbox_type: SandboxType,
/// Whether Linux sandbox processes use the legacy Landlock backend.
pub use_legacy_landlock: bool,
/// Additional managed command restrictions for this environment attachment.
pub exec_policy: Option<RequirementsExecPolicy>,
/// Additional managed MCP restrictions for this environment attachment.
pub mcp_policy: Option<EnvironmentMcpPolicy>,
/// Owner-provided traffic restrictions. `None` keeps the existing controller policy.
pub network_policy: Option<EnvironmentNetworkPolicy>,
/// Capability roots selected for this thread's environment attachment.
pub selected_capability_roots: Vec<SelectedCapabilityRoot>,
}
impl std::fmt::Debug for EnvironmentConfig {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("EnvironmentConfig")
.field("environment_hooks", &self.environment_hooks.handler_count())
.field("allow_login_shell", &self.allow_login_shell)
.field("workspace_roots", &self.workspace_roots)
.field("permission_profile", &self.permission_profile)
.field("shell_environment_policy", &"<redacted>")
.field("windows_sandbox_level", &self.windows_sandbox_level)
.field("windows_sandbox_type", &self.windows_sandbox_type)
.field("use_legacy_landlock", &self.use_legacy_landlock)
.field("exec_policy", &self.exec_policy)
.field("mcp_policy", &self.mcp_policy)
.field("network_policy", &self.network_policy)
.field("selected_capability_roots", &self.selected_capability_roots)
.finish()
}
}

View File

@@ -0,0 +1,963 @@
use crate::ThreadId;
use crate::auth::PlanType;
pub use crate::auth::RefreshTokenFailedError;
pub use crate::auth::RefreshTokenFailedReason;
use crate::exec_output::ExecToolCallOutput;
use crate::network_policy::NetworkPolicyDecisionPayload;
use crate::protocol::CodexErrorInfo;
use crate::protocol::ErrorEvent;
use crate::protocol::MisalignmentErrorDetails;
use crate::protocol::RateLimitReachedType;
use crate::protocol::RateLimitSnapshot;
use crate::protocol::TokenUsage;
use crate::protocol::TruncationPolicy;
use chrono::DateTime;
use chrono::Datelike;
use chrono::Local;
use chrono::Utc;
use akode_async_utils::CancelErr;
use akode_async_utils::backoff;
use akode_http_client::HttpError;
use akode_http_client::RetryAfter;
use akode_utils_string::truncate_middle_chars;
use akode_utils_string::truncate_middle_with_token_budget;
use http::StatusCode;
use serde_json;
use std::fmt;
use std::io;
use std::time::Duration;
use strum_macros::EnumDiscriminants;
use thiserror::Error;
use tokio::task::JoinError;
#[path = "agent_error.rs"]
mod agent;
pub use agent::AgentErrorContext;
pub type Result<T> = std::result::Result<T, CodexErr>;
/// Limit UI error messages to a reasonable size while keeping useful context.
const ERROR_MESSAGE_UI_MAX_BYTES: usize = 2 * 1024;
#[derive(Error, Debug)]
pub enum SandboxErr {
/// Error from sandbox execution
#[error(
"sandbox denied exec error, exit code: {}, stdout: {}, stderr: {}",
.output.exit_code, .output.stdout.text, .output.stderr.text
)]
Denied {
output: Box<ExecToolCallOutput>,
network_policy_decision: Option<NetworkPolicyDecisionPayload>,
},
/// Error from linux seccomp filter setup
#[cfg(target_os = "linux")]
#[error("seccomp setup error")]
SeccompInstall(#[from] seccompiler::Error),
/// Error from linux seccomp backend
#[cfg(target_os = "linux")]
#[error("seccomp backend error")]
SeccompBackend(#[from] seccompiler::BackendError),
/// Command timed out
#[error("command timed out")]
Timeout { output: Box<ExecToolCallOutput> },
/// Command was killed by a signal
#[error("command was killed by a signal")]
Signal(i32),
/// Error from linux landlock
#[error("Landlock was not able to fully enforce all sandbox rules")]
LandlockRestrict,
}
pub struct CodexErr {
details: CodexErrorDetails,
retry_after: Option<RetryAfter>,
agent_context: Option<AgentErrorContext>,
}
/// A terminal response that stopped before the model finished, with any reported usage.
/// Content-filter retries and explicit interruptions have separate handling.
#[derive(derive_more::Debug, Error, PartialEq, Eq)]
#[error("Incomplete response returned, reason: {reason}")]
pub struct ResponseIncompleteError {
/// Provider output items explicitly marked incomplete, retained for failed inference traces.
#[debug(skip)]
pub partial_output: Vec<serde_json::Value>,
pub reason: String,
pub response_id: Option<String>,
pub token_usage: Option<TokenUsage>,
}
/// The semantic category and diagnostic payload for a [`CodexErr`].
#[derive(Error, Debug, EnumDiscriminants)]
#[strum_discriminants(name(CodexErrKind))]
#[strum_discriminants(derive(serde::Serialize, strum_macros::IntoStaticStr))]
#[strum_discriminants(strum(serialize_all = "snake_case"))]
#[strum_discriminants(serde(rename_all = "snake_case"))]
#[strum_discriminants(doc = "The payload-free semantic category of the error.")]
pub enum CodexErrorDetails {
#[error("turn aborted. Something went wrong? Hit `/feedback` to report the issue.")]
TurnAborted,
#[error("budget reached")]
SessionBudgetExceeded,
/// Returned by ResponsesClient when the SSE stream disconnects or errors out **after** the HTTP
/// handshake has succeeded but **before** it finished emitting `response.completed`.
///
/// The Session loop treats this as a transient error and will automatically retry the turn.
#[error("stream disconnected before completion: {0}")]
Stream(String),
/// A response stopped by the content filter. Sampling retries need developer guidance.
#[error(
"stream disconnected before completion: Incomplete response returned, reason: content_filter"
)]
ContentFilter,
#[error(transparent)]
ResponseIncomplete(Box<ResponseIncompleteError>),
/// A retryable upstream rate limit received inside the response stream.
#[error("rate limit exceeded: {0}")]
RateLimitExceeded(String),
// The iOS input-limit classifier matches this message's ASCII prefix.
#[error(
"Codex ran out of room in the model's context window. Start a new thread or clear earlier history before retrying."
)]
ContextWindowExceeded,
#[error("no thread with id: {0}")]
ThreadNotFound(ThreadId),
#[error("agent thread limit reached")]
AgentLimitReached { max_threads: usize },
#[error("session configured event was not the first event in the stream")]
SessionConfiguredNotFirstEvent,
/// Returned by run_command_stream when the spawned child process timed out (10s).
#[error("timeout waiting for child process to exit")]
Timeout,
#[error("request timed out")]
RequestTimeout,
/// Returned by run_command_stream when the child could not be spawned (its stdout/stderr pipes
/// could not be captured). Analogous to the previous `CodexError::Spawn` variant.
#[error("spawn failed: child stdout/stderr not captured")]
Spawn,
/// Returned by run_command_stream when the user pressed Ctrl-C (SIGINT). Session uses this to
/// surface a polite FunctionCallOutput back to the model instead of crashing the CLI.
#[error("interrupted (Ctrl-C). Something went wrong? Hit `/feedback` to report the issue.")]
Interrupted,
/// Unexpected HTTP status code.
#[error("{0}")]
UnexpectedStatus(UnexpectedResponseError),
/// Invalid request.
#[error("{0}")]
InvalidRequest(String),
#[error("{message}")]
InvalidAudioInput {
message: String,
/// True when the provider rejected an individual clip, independent of request size.
per_recording: bool,
},
#[error("{message}")]
ModelNotFound {
message: String,
status: Option<StatusCode>,
},
#[error("{message}")]
InvalidPrompt { message: String },
/// Multiple registered tools share the same effective name.
#[error("duplicate tool: {0}")]
ToolCollision(String),
/// Invalid image.
#[error("Image poisoning")]
InvalidImageRequest(),
#[error("{0}")]
UsageLimitReached(UsageLimitReachedError),
#[error("Selected model is at capacity. Please try a different model.")]
ServerOverloaded,
/// Policy-restricted capacity follows the same retry advice as ordinary overloads.
#[error("Policy-restricted capacity is unavailable. Please try again later.")]
PolicyCapacityUnavailable,
#[error("Flex capacity unavailable.")]
FlexUnavailable,
#[error("{message}")]
CyberPolicy { message: String },
#[error("{message}")]
BioPolicy { message: String },
#[error("{message}")]
MisalignmentPolicyViolation {
message: String,
misalignment: Option<MisalignmentErrorDetails>,
},
#[error("{0}")]
ResponseStreamFailed(ResponseStreamFailed),
#[error("{0}")]
ConnectionFailed(ConnectionFailedError),
#[error("Quota exceeded. Check your plan and billing details.")]
QuotaExceeded,
#[error("Your model provider account does not include access to this model.")]
UsageNotIncluded,
#[error("We’re currently experiencing high demand, which may cause temporary errors.")]
InternalServerError,
/// Retry limit exceeded.
#[error("{0}")]
RetryLimit(RetryLimitReachedError),
/// Agent loop died unexpectedly
#[error("internal error; agent loop died unexpectedly")]
InternalAgentDied,
/// Sandbox error
#[error("sandbox error: {0}")]
Sandbox(#[from] SandboxErr),
#[error("akode-linux-sandbox was required but not provided")]
LandlockSandboxExecutableNotProvided,
#[error("unsupported operation: {0}")]
UnsupportedOperation(String),
#[error("{0}")]
RefreshTokenFailed(RefreshTokenFailedError),
/// Gateway credentials require user action before requests can resume.
#[error("{0}")]
GatewayLoginRequired(String),
#[error("Fatal error: {0}")]
Fatal(String),
// -----------------------------------------------------------------
// Automatic conversions for common external error types
// -----------------------------------------------------------------
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Json(#[from] serde_json::Error),
#[cfg(target_os = "linux")]
#[error(transparent)]
LandlockRuleset(#[from] landlock::RulesetError),
#[cfg(target_os = "linux")]
#[error(transparent)]
LandlockPathFd(#[from] landlock::PathFdError),
#[error(transparent)]
TokioJoin(#[from] JoinError),
#[error("{0}")]
EnvVar(EnvVarError),
}
impl From<&CodexErr> for CodexErrKind {
fn from(error: &CodexErr) -> Self {
error.details().into()
}
}
impl fmt::Debug for CodexErr {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.details {
CodexErrorDetails::Stream(message) => formatter
.debug_tuple("Stream")
.field(message)
.field(&self.server_retry_delay())
.finish(),
details => fmt::Debug::fmt(details, formatter),
}
}
}
impl fmt::Display for CodexErr {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.details, formatter)
}
}
impl std::error::Error for CodexErr {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.details.source()
}
}
impl From<CodexErrorDetails> for CodexErr {
fn from(details: CodexErrorDetails) -> Self {
Self {
details,
retry_after: None,
agent_context: None,
}
}
}
impl From<CancelErr> for CodexErr {
fn from(error: CancelErr) -> Self {
CodexErrorDetails::from(error).into()
}
}
impl From<SandboxErr> for CodexErr {
fn from(error: SandboxErr) -> Self {
CodexErrorDetails::from(error).into()
}
}
impl From<io::Error> for CodexErr {
fn from(error: io::Error) -> Self {
CodexErrorDetails::from(error).into()
}
}
impl From<serde_json::Error> for CodexErr {
fn from(error: serde_json::Error) -> Self {
CodexErrorDetails::from(error).into()
}
}
impl From<JoinError> for CodexErr {
fn from(error: JoinError) -> Self {
CodexErrorDetails::from(error).into()
}
}
#[cfg(target_os = "linux")]
impl From<landlock::RulesetError> for CodexErr {
fn from(error: landlock::RulesetError) -> Self {
CodexErrorDetails::from(error).into()
}
}
#[cfg(target_os = "linux")]
impl From<landlock::PathFdError> for CodexErr {
fn from(error: landlock::PathFdError) -> Self {
CodexErrorDetails::from(error).into()
}
}
impl From<CancelErr> for CodexErrorDetails {
fn from(_: CancelErr) -> Self {
CodexErrorDetails::TurnAborted
}
}
// TODO(anp): Remove this compatibility macro once callers construct
// `CodexErrorDetails` directly.
macro_rules! codex_err_unit_constructors {
($($variant:ident),* $(,)?) => {
$(
#[doc(hidden)]
#[allow(non_upper_case_globals)]
pub const $variant: Self = Self {
details: CodexErrorDetails::$variant,
retry_after: None,
agent_context: None,
};
)*
};
}
// TODO(anp): Remove this compatibility macro once callers construct
// `CodexErrorDetails` directly.
macro_rules! codex_err_tuple_constructors {
($($(#[$attr:meta])* $variant:ident($value:ident: $value_type:ty)),* $(,)?) => {
$(
$(#[$attr])*
#[doc(hidden)]
#[allow(non_snake_case)]
pub fn $variant($value: $value_type) -> Self {
CodexErrorDetails::$variant($value).into()
}
)*
};
}
impl CodexErr {
codex_err_unit_constructors!(
TurnAborted,
SessionBudgetExceeded,
ContextWindowExceeded,
SessionConfiguredNotFirstEvent,
Timeout,
RequestTimeout,
Spawn,
Interrupted,
ServerOverloaded,
QuotaExceeded,
UsageNotIncluded,
InternalServerError,
InternalAgentDied,
LandlockSandboxExecutableNotProvided,
);
codex_err_tuple_constructors!(
Stream(message: String),
ThreadNotFound(thread_id: ThreadId),
UnexpectedStatus(error: UnexpectedResponseError),
InvalidRequest(message: String),
UsageLimitReached(error: UsageLimitReachedError),
ResponseStreamFailed(error: ResponseStreamFailed),
ConnectionFailed(error: ConnectionFailedError),
RetryLimit(error: RetryLimitReachedError),
Sandbox(error: SandboxErr),
UnsupportedOperation(message: String),
RefreshTokenFailed(error: RefreshTokenFailedError),
Fatal(message: String),
Io(error: io::Error),
Json(error: serde_json::Error),
#[cfg(target_os = "linux")]
LandlockRuleset(error: landlock::RulesetError),
#[cfg(target_os = "linux")]
LandlockPathFd(error: landlock::PathFdError),
TokioJoin(error: JoinError),
EnvVar(error: EnvVarError),
);
// TODO(anp): Remove this compatibility constructor once callers construct
// `CodexErrorDetails` directly.
#[doc(hidden)]
#[allow(non_snake_case)]
pub fn InvalidImageRequest() -> Self {
CodexErrorDetails::InvalidImageRequest().into()
}
/// Creates an error with no server-provided retry delay.
pub fn new(details: CodexErrorDetails) -> Self {
details.into()
}
/// Returns the semantic failure and its diagnostic payload.
pub fn details(&self) -> &CodexErrorDetails {
&self.details
}
/// Returns the delay before the given retry attempt, or `None` for a terminal error.
///
/// The first retry is attempt one. Retryable errors use server advice when available and
/// otherwise use exponential backoff with jitter. Callers enforce their own retry budgets.
pub fn retry_delay(&self, retry_count: u64) -> Option<Duration> {
match self.details() {
CodexErrorDetails::UnexpectedStatus(error)
if is_runtime_auth_denial(
error.status,
&error.body,
error.identity_error_code.as_deref(),
) =>
{
None
}
CodexErrorDetails::TurnAborted
| CodexErrorDetails::SessionBudgetExceeded
| CodexErrorDetails::Interrupted
| CodexErrorDetails::EnvVar(_)
| CodexErrorDetails::Fatal(_)
| CodexErrorDetails::UsageNotIncluded
| CodexErrorDetails::QuotaExceeded
| CodexErrorDetails::InvalidImageRequest()
| CodexErrorDetails::InvalidRequest(_)
| CodexErrorDetails::InvalidAudioInput { .. }
| CodexErrorDetails::ResponseIncomplete(_)
| CodexErrorDetails::ModelNotFound { .. }
| CodexErrorDetails::InvalidPrompt { .. }
| CodexErrorDetails::ToolCollision(_)
| CodexErrorDetails::RefreshTokenFailed(_)
| CodexErrorDetails::GatewayLoginRequired(_)
| CodexErrorDetails::UnsupportedOperation(_)
| CodexErrorDetails::Sandbox(_)
| CodexErrorDetails::LandlockSandboxExecutableNotProvided
| CodexErrorDetails::ContextWindowExceeded
| CodexErrorDetails::ThreadNotFound(_)
| CodexErrorDetails::AgentLimitReached { .. }
| CodexErrorDetails::Spawn
| CodexErrorDetails::SessionConfiguredNotFirstEvent
| CodexErrorDetails::UsageLimitReached(_)
| CodexErrorDetails::FlexUnavailable
| CodexErrorDetails::CyberPolicy { .. }
| CodexErrorDetails::BioPolicy { .. }
| CodexErrorDetails::MisalignmentPolicyViolation { .. } => None,
CodexErrorDetails::ServerOverloaded
| CodexErrorDetails::PolicyCapacityUnavailable
| CodexErrorDetails::RetryLimit(_) => self.server_retry_delay(),
CodexErrorDetails::Stream(..)
| CodexErrorDetails::ContentFilter
| CodexErrorDetails::RateLimitExceeded(_)
| CodexErrorDetails::Timeout
| CodexErrorDetails::RequestTimeout
| CodexErrorDetails::UnexpectedStatus(_)
| CodexErrorDetails::ResponseStreamFailed(_)
| CodexErrorDetails::ConnectionFailed(_)
| CodexErrorDetails::InternalServerError
| CodexErrorDetails::InternalAgentDied
| CodexErrorDetails::Io(_)
| CodexErrorDetails::Json(_)
| CodexErrorDetails::TokioJoin(_) => Some(
self.server_retry_delay()
.unwrap_or_else(|| backoff(retry_count)),
),
#[cfg(target_os = "linux")]
CodexErrorDetails::LandlockRuleset(_) | CodexErrorDetails::LandlockPathFd(_) => None,
}
}
/// Returns the original server-advised instant for callers that pass the error on.
pub fn retry_after(&self) -> Option<RetryAfter> {
self.retry_after
}
/// Returns the remaining server-advised delay without applying local retry policy.
/// Expired advice stays present as zero instead of falling back to a local delay.
pub fn server_retry_delay(&self) -> Option<Duration> {
self.retry_after.map(RetryAfter::remaining_delay)
}
/// Retains an already captured server deadline without restarting it.
pub fn with_retry_after(mut self, retry_after: RetryAfter) -> Self {
self.retry_after = Some(retry_after);
self
}
/// Minimal shim so that existing `e.downcast_ref::<CodexErr>()` checks continue to compile
/// after replacing `anyhow::Error` in the return signature. This mirrors the behavior of
/// `anyhow::Error::downcast_ref` but works directly on our concrete error type.
pub fn downcast_ref<T: std::any::Any>(&self) -> Option<&T> {
(self as &dyn std::any::Any).downcast_ref::<T>()
}
/// Translate core error to client-facing protocol error.
pub fn to_codex_protocol_error(&self) -> CodexErrorInfo {
match &self.details {
CodexErrorDetails::ContextWindowExceeded => CodexErrorInfo::ContextWindowExceeded,
CodexErrorDetails::SessionBudgetExceeded => CodexErrorInfo::SessionBudgetExceeded,
CodexErrorDetails::RateLimitExceeded(_) => CodexErrorInfo::RateLimitExceeded,
CodexErrorDetails::UsageLimitReached(_)
| CodexErrorDetails::QuotaExceeded
| CodexErrorDetails::UsageNotIncluded => CodexErrorInfo::UsageLimitExceeded,
CodexErrorDetails::ServerOverloaded => CodexErrorInfo::ServerOverloaded,
CodexErrorDetails::PolicyCapacityUnavailable => {
CodexErrorInfo::PolicyCapacityUnavailable
}
CodexErrorDetails::FlexUnavailable => CodexErrorInfo::FlexUnavailable,
CodexErrorDetails::CyberPolicy { .. } => CodexErrorInfo::CyberPolicy,
CodexErrorDetails::BioPolicy { .. } => CodexErrorInfo::BioPolicy,
CodexErrorDetails::ModelNotFound { .. } => CodexErrorInfo::ModelNotFound,
CodexErrorDetails::InvalidPrompt { .. } => CodexErrorInfo::InvalidPrompt,
CodexErrorDetails::MisalignmentPolicyViolation { .. } => {
CodexErrorInfo::MisalignmentPolicyViolation
}
CodexErrorDetails::RetryLimit(_) => CodexErrorInfo::ResponseTooManyFailedAttempts {
http_status_code: self.http_status_code_value(),
},
CodexErrorDetails::ConnectionFailed(_) | CodexErrorDetails::UnexpectedStatus(_) => {
CodexErrorInfo::HttpConnectionFailed {
http_status_code: self.http_status_code_value(),
}
}
CodexErrorDetails::ResponseStreamFailed(_) => {
CodexErrorInfo::ResponseStreamConnectionFailed {
http_status_code: self.http_status_code_value(),
}
}
CodexErrorDetails::RefreshTokenFailed(_) => CodexErrorInfo::Unauthorized,
CodexErrorDetails::SessionConfiguredNotFirstEvent
| CodexErrorDetails::InternalServerError
| CodexErrorDetails::InternalAgentDied => CodexErrorInfo::InternalServerError,
CodexErrorDetails::InvalidAudioInput { .. }
| CodexErrorDetails::UnsupportedOperation(_)
| CodexErrorDetails::ThreadNotFound(_)
| CodexErrorDetails::AgentLimitReached { .. } => CodexErrorInfo::BadRequest,
CodexErrorDetails::Sandbox(_) => CodexErrorInfo::SandboxError,
_ => CodexErrorInfo::Other,
}
}
pub fn to_error_event(&self, message_prefix: Option<String>) -> ErrorEvent {
let error_message = self.to_string();
let message: String = match message_prefix {
Some(prefix) => format!("{prefix}: {error_message}"),
None => error_message,
};
ErrorEvent {
message,
codex_error_info: Some(self.to_codex_protocol_error()),
rejected_audio_file_ids: Vec::new(),
misalignment: match &self.details {
CodexErrorDetails::MisalignmentPolicyViolation { misalignment, .. } => {
misalignment.clone()
}
_ => None,
},
}
}
pub fn http_status_code_value(&self) -> Option<u16> {
let http_status_code = match &self.details {
CodexErrorDetails::FlexUnavailable => Some(StatusCode::TOO_MANY_REQUESTS),
CodexErrorDetails::ModelNotFound { status, .. } => *status,
CodexErrorDetails::RetryLimit(err) => Some(err.status),
CodexErrorDetails::UnexpectedStatus(err) => Some(err.status),
CodexErrorDetails::ConnectionFailed(err) => err.source.status(),
CodexErrorDetails::ResponseStreamFailed(err) => err.source.status(),
_ => None,
};
http_status_code.as_ref().map(StatusCode::as_u16)
}
}
#[derive(Debug)]
pub struct ConnectionFailedError {
pub source: HttpError,
}
impl std::fmt::Display for ConnectionFailedError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Connection failed: {}", self.source)
}
}
#[derive(Debug)]
pub struct ResponseStreamFailed {
pub source: HttpError,
pub request_id: Option<String>,
}
impl std::fmt::Display for ResponseStreamFailed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Error while reading the server response: {}{}",
self.source,
self.request_id
.as_ref()
.map(|id| format!(", request id: {id}"))
.unwrap_or_default()
)
}
}
#[derive(Clone, Debug)]
pub struct UnexpectedResponseError {
pub status: StatusCode,
pub body: String,
pub user_message: Option<String>,
pub url: Option<String>,
pub cf_ray: Option<String>,
pub request_id: Option<String>,
pub identity_authorization_error: Option<String>,
pub identity_error_code: Option<String>,
}
/// Runtime denial cannot be repaired by retrying the request or refreshing its original credential.
/// Keep unavailable verification state and ordinary credential errors on their existing paths.
pub fn is_runtime_auth_denial(
status: StatusCode,
body: &str,
identity_error_code: Option<&str>,
) -> bool {
if !matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) {
return false;
}
let is_terminal = |code| {
matches!(
code,
Some(
"runtime_assertion_invalid"
| "runtime_instance_paused"
| "runtime_instance_revoked"
| "invalid_agent_instance_assertion"
)
)
};
if is_terminal(identity_error_code) {
return true;
}
let Ok(body) = serde_json::from_str::<serde_json::Value>(body) else {
return false;
};
is_terminal(
body.pointer("/error/code")
.and_then(serde_json::Value::as_str),
)
}
const UNEXPECTED_RESPONSE_BODY_MAX_BYTES: usize = 1000;
impl UnexpectedResponseError {
fn display_body(&self) -> String {
if let Some(message) = self.extract_error_message() {
return message;
}
let trimmed_body = self.body.trim();
if trimmed_body.is_empty() {
return "Unknown error".to_string();
}
truncate_with_ellipsis(trimmed_body, UNEXPECTED_RESPONSE_BODY_MAX_BYTES)
}
/// Returns the provider message from a structured HTTP error body.
pub fn extract_error_message(&self) -> Option<String> {
let json = serde_json::from_str::<serde_json::Value>(&self.body).ok()?;
let message = json
.get("error")
.and_then(|error| error.get("message"))
.and_then(serde_json::Value::as_str)?;
let message = message.trim();
if message.is_empty() {
None
} else {
Some(message.to_string())
}
}
}
impl std::fmt::Display for UnexpectedResponseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut message = if let Some(user_message) = &self.user_message {
user_message.clone()
} else {
let status = self.status;
let body = self.display_body();
format!("unexpected status {status}: {body}")
};
if let Some(url) = &self.url {
message.push_str(&format!(", url: {url}"));
}
if let Some(cf_ray) = &self.cf_ray {
message.push_str(&format!(", cf-ray: {cf_ray}"));
}
if let Some(id) = &self.request_id {
message.push_str(&format!(", request id: {id}"));
}
if let Some(auth_error) = &self.identity_authorization_error {
message.push_str(&format!(", auth error: {auth_error}"));
}
if let Some(error_code) = &self.identity_error_code {
message.push_str(&format!(", auth error code: {error_code}"));
}
write!(f, "{message}")
}
}
impl std::error::Error for UnexpectedResponseError {}
fn truncate_with_ellipsis(text: &str, max_bytes: usize) -> String {
if text.len() <= max_bytes {
return text.to_string();
}
let mut cut = max_bytes;
while !text.is_char_boundary(cut) {
cut = cut.saturating_sub(1);
}
let mut truncated = text[..cut].to_string();
truncated.push_str("...");
truncated
}
fn truncate_text(content: &str, policy: TruncationPolicy) -> String {
match policy {
TruncationPolicy::Bytes(bytes) => truncate_middle_chars(content, bytes),
TruncationPolicy::Tokens(tokens) => truncate_middle_with_token_budget(content, tokens).0,
}
}
#[derive(Debug)]
pub struct RetryLimitReachedError {
pub status: StatusCode,
pub request_id: Option<String>,
}
impl std::fmt::Display for RetryLimitReachedError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"exceeded retry limit, last status: {}{}",
self.status,
self.request_id
.as_ref()
.map(|id| format!(", request id: {id}"))
.unwrap_or_default()
)
}
}
#[derive(Debug)]
pub struct UsageLimitReachedError {
pub plan_type: Option<PlanType>,
pub resets_at: Option<DateTime<Utc>>,
/// Server-selected window responsible for the limit, in minutes.
pub limit_window_minutes: Option<u16>,
pub rate_limits: Option<Box<RateLimitSnapshot>>,
pub promo_message: Option<String>,
pub rate_limit_reached_type: Option<RateLimitReachedType>,
}
impl std::fmt::Display for UsageLimitReachedError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Reserve is a fallback for exhausted ordinary usage, so keep the standard
// recovery copy below instead of suggesting another model.
if let Some(limit_name) = self
.rate_limits
.as_ref()
.and_then(|snapshot| snapshot.limit_name.as_deref())
.map(str::trim)
.filter(|name| !name.is_empty())
&& !limit_name.eq_ignore_ascii_case("codex")
&& !limit_name.eq_ignore_ascii_case("gpt-reserve")
{
return write!(
f,
"You’ve hit your usage limit for {limit_name}. Switch to another model now,{}",
retry_suffix_after_or(self.resets_at.as_ref())
);
}
if let Some(rate_limit_reached_type) = self.rate_limit_reached_type {
match rate_limit_reached_type {
RateLimitReachedType::WorkspaceOwnerCreditsDepleted => {
return write!(
f,
"Your workspace is out of credits. Add credits to continue."
);
}
RateLimitReachedType::WorkspaceMemberCreditsDepleted => {
return write!(
f,
"Your workspace is out of credits. Ask your workspace owner to refill in order to continue."
);
}
RateLimitReachedType::WorkspaceOwnerUsageLimitReached => {
return write!(
f,
"You hit your spend cap set in your workspace. Increase your spend cap to continue."
);
}
RateLimitReachedType::WorkspaceMemberUsageLimitReached => {
return write!(
f,
"You hit your spend cap set by the owner of your workspace. Ask an owner to increase your spend cap to continue."
);
}
RateLimitReachedType::RateLimitReached => {
// Generic limits use the neutral copy below.
}
}
}
// Plan upsells and server promo copy are ChatGPT-specific; keep the message neutral.
let message = format!(
"You’ve hit your usage limit with the model provider.{}",
retry_suffix(self.resets_at.as_ref())
);
write!(f, "{message}")
}
}
fn retry_suffix(resets_at: Option<&DateTime<Utc>>) -> String {
if let Some(resets_at) = resets_at {
let formatted = format_retry_timestamp(resets_at);
format!(" Try again at {formatted}.")
} else {
" Try again later.".to_string()
}
}
fn retry_suffix_after_or(resets_at: Option<&DateTime<Utc>>) -> String {
if let Some(resets_at) = resets_at {
let formatted = format_retry_timestamp(resets_at);
format!(" or try again at {formatted}.")
} else {
" or try again later.".to_string()
}
}
fn format_retry_timestamp(resets_at: &DateTime<Utc>) -> String {
let local_reset = resets_at.with_timezone(&Local);
let local_now = now_for_retry().with_timezone(&Local);
if local_reset.date_naive() == local_now.date_naive() {
local_reset.format("%-I:%M %p").to_string()
} else {
let suffix = day_suffix(local_reset.day());
local_reset
.format(&format!("%b %-d{suffix}, %Y %-I:%M %p"))
.to_string()
}
}
fn day_suffix(day: u32) -> &'static str {
match day {
11..=13 => "th",
_ => match day % 10 {
1 => "st",
2 => "nd", // codespell:ignore
3 => "rd",
_ => "th",
},
}
}
#[cfg(test)]
thread_local! {
static NOW_OVERRIDE: std::cell::RefCell<Option<DateTime<Utc>>> =
const { std::cell::RefCell::new(None) };
}
fn now_for_retry() -> DateTime<Utc> {
#[cfg(test)]
{
if let Some(now) = NOW_OVERRIDE.with(|cell| *cell.borrow()) {
return now;
}
}
Utc::now()
}
#[derive(Debug)]
pub struct EnvVarError {
/// Name of the environment variable that is missing.
pub var: String,
/// Optional instructions to help the user get a valid value for the
/// variable and set it.
pub instructions: Option<String>,
}
impl std::fmt::Display for EnvVarError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Missing environment variable: `{}`.", self.var)?;
if let Some(instructions) = &self.instructions {
write!(f, " {instructions}")?;
}
Ok(())
}
}
pub fn get_error_message_ui(e: &CodexErr) -> String {
let message = match e.details() {
CodexErrorDetails::Sandbox(SandboxErr::Denied { output, .. }) => {
let aggregated = output.aggregated_output.text.trim();
if !aggregated.is_empty() {
output.aggregated_output.text.clone()
} else {
let stderr = output.stderr.text.trim();
let stdout = output.stdout.text.trim();
match (stderr.is_empty(), stdout.is_empty()) {
(false, false) => format!("{stderr}\n{stdout}"),
(false, true) => output.stderr.text.clone(),
(true, false) => output.stdout.text.clone(),
(true, true) => format!(
"command failed inside sandbox with exit code {}",
output.exit_code
),
}
}
}
// Timeouts are not sandbox errors from a UX perspective; present them plainly.
CodexErrorDetails::Sandbox(SandboxErr::Timeout { output }) => {
format!(
"error: command timed out after {} ms",
output.duration.as_millis()
)
}
_ => e.to_string(),
};
truncate_text(
&message,
TruncationPolicy::Bytes(ERROR_MESSAGE_UI_MAX_BYTES),
)
}
#[cfg(test)]
#[path = "error_tests.rs"]
mod tests;

View File

@@ -0,0 +1,762 @@
use super::*;
use crate::auth::KnownPlan;
use crate::exec_output::StreamOutput;
use crate::protocol::RateLimitWindow;
use chrono::DateTime;
use chrono::Duration as ChronoDuration;
use chrono::TimeZone;
use chrono::Utc;
use akode_http_client::HttpResponse;
use http::Response as RawHttpResponse;
use http::StatusCode;
use pretty_assertions::assert_eq;
use std::time::Duration;
#[tokio::test(start_paused = true)]
async fn codex_err_debug_preserves_legacy_shape() {
let actual = [
CodexErr::Timeout,
CodexErr::Stream("disconnected".to_string()),
CodexErr::Stream("retry later".to_string()).with_retry_after(
RetryAfter::from_delay(Duration::from_secs(2)).expect("retry deadline"),
),
CodexErr::InternalServerError.with_retry_after(
RetryAfter::from_delay(Duration::from_secs(3)).expect("retry deadline"),
),
]
.map(|err| format!("{err:?}"));
assert_eq!(
actual,
[
"Timeout".to_string(),
"Stream(\"disconnected\", None)".to_string(),
"Stream(\"retry later\", Some(2s))".to_string(),
"InternalServerError".to_string(),
]
);
}
#[test]
fn retryability_preserves_error_details_distinctions() {
let errors = [
(CodexErr::ServerOverloaded, false),
(CodexErr::new(CodexErrorDetails::ContentFilter), true),
(
CodexErr::new(CodexErrorDetails::RateLimitExceeded("retry later".into())),
true,
),
(
CodexErr::RetryLimit(RetryLimitReachedError {
status: StatusCode::TOO_MANY_REQUESTS,
request_id: None,
}),
false,
),
(
CodexErr::UnexpectedStatus(UnexpectedResponseError {
status: StatusCode::TOO_MANY_REQUESTS,
body: String::new(),
user_message: None,
url: None,
cf_ray: None,
request_id: None,
identity_authorization_error: None,
identity_error_code: None,
}),
true,
),
(
CodexErrorDetails::ToolCollision("functions.update_plan".to_string()).into(),
false,
),
(CodexErr::InternalServerError, true),
];
for (err, expected) in errors {
assert_eq!(
err.retry_delay(/*retry_count*/ 1).is_some(),
expected,
"unexpected retryability for {err:?}"
);
}
}
/// Retryable errors prefer server advice and otherwise back off by attempt; advice does not
/// make a terminal error retryable.
#[test]
fn retry_delay_distinguishes_server_advice_backoff_and_terminal_errors() {
let error = CodexErr::InternalServerError;
for (retry_count, expected_millis) in [(1, 180..220), (3, 720..880)] {
let delay = error.retry_delay(retry_count).expect("retryable error");
assert!(expected_millis.contains(&delay.as_millis()));
}
assert_eq!(error.server_retry_delay(), None);
let advice = Duration::ZERO;
let retry_after = RetryAfter::from_delay(advice).expect("retry deadline");
let error = error.with_retry_after(retry_after);
assert_eq!(
(
error.retry_delay(/*retry_count*/ 1),
error.retry_delay(/*retry_count*/ 3),
error.server_retry_delay(),
),
(Some(advice), Some(advice), Some(advice)),
);
let error = CodexErr::QuotaExceeded.with_retry_after(retry_after);
assert_eq!(
(
error.retry_delay(/*retry_count*/ 1),
error.server_retry_delay(),
),
(None, Some(advice)),
);
}
fn rate_limit_snapshot() -> RateLimitSnapshot {
let primary_reset_at = Utc
.with_ymd_and_hms(2024, 1, 1, 1, 0, 0)
.unwrap()
.timestamp();
let secondary_reset_at = Utc
.with_ymd_and_hms(2024, 1, 1, 2, 0, 0)
.unwrap()
.timestamp();
RateLimitSnapshot {
limit_id: None,
limit_name: None,
normal_model_slug: None,
primary: Some(RateLimitWindow {
used_percent: 50.0,
window_minutes: Some(60),
resets_at: Some(primary_reset_at),
}),
secondary: Some(RateLimitWindow {
used_percent: 30.0,
window_minutes: Some(120),
resets_at: Some(secondary_reset_at),
}),
credits: None,
individual_limit: None,
spend_control_reached: None,
plan_type: None,
rate_limit_reached_type: None,
}
}
fn with_now_override<T>(now: DateTime<Utc>, f: impl FnOnce() -> T) -> T {
NOW_OVERRIDE.with(|cell| {
*cell.borrow_mut() = Some(now);
let result = f();
*cell.borrow_mut() = None;
result
})
}
#[test]
fn usage_limit_reached_error_formats_plus_plan() {
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(KnownPlan::Plus)),
resets_at: None,
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
assert_eq!(
err.to_string(),
"You’ve hit your usage limit with the model provider. Try again later."
);
}
#[test]
fn usage_limit_reached_error_formats_rate_limit_reached_types() {
let cases = [
(
RateLimitReachedType::RateLimitReached,
"You’ve hit your usage limit with the model provider. Try again later.",
),
(
RateLimitReachedType::WorkspaceOwnerCreditsDepleted,
"Your workspace is out of credits. Add credits to continue.",
),
(
RateLimitReachedType::WorkspaceMemberCreditsDepleted,
"Your workspace is out of credits. Ask your workspace owner to refill in order to continue.",
),
(
RateLimitReachedType::WorkspaceOwnerUsageLimitReached,
"You hit your spend cap set in your workspace. Increase your spend cap to continue.",
),
(
RateLimitReachedType::WorkspaceMemberUsageLimitReached,
"You hit your spend cap set by the owner of your workspace. Ask an owner to increase your spend cap to continue.",
),
];
for (rate_limit_reached_type, expected) in cases {
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(KnownPlan::Plus)),
resets_at: None,
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: Some(rate_limit_reached_type),
};
assert_eq!(err.to_string(), expected);
}
}
#[test]
fn server_overloaded_maps_to_protocol() {
let err = CodexErr::ServerOverloaded;
assert_eq!(
err.to_codex_protocol_error(),
CodexErrorInfo::ServerOverloaded
);
}
#[test]
fn sandbox_denied_uses_aggregated_output_when_stderr_empty() {
let output = ExecToolCallOutput {
exit_code: 77,
stdout: StreamOutput::new(String::new()),
stderr: StreamOutput::new(String::new()),
aggregated_output: StreamOutput::new("aggregate detail".to_string()),
duration: Duration::from_millis(10),
timed_out: false,
};
let err = CodexErr::Sandbox(SandboxErr::Denied {
output: Box::new(output),
network_policy_decision: None,
});
assert_eq!(get_error_message_ui(&err), "aggregate detail");
}
#[test]
fn sandbox_denied_reports_both_streams_when_available() {
let output = ExecToolCallOutput {
exit_code: 9,
stdout: StreamOutput::new("stdout detail".to_string()),
stderr: StreamOutput::new("stderr detail".to_string()),
aggregated_output: StreamOutput::new(String::new()),
duration: Duration::from_millis(10),
timed_out: false,
};
let err = CodexErr::Sandbox(SandboxErr::Denied {
output: Box::new(output),
network_policy_decision: None,
});
assert_eq!(get_error_message_ui(&err), "stderr detail\nstdout detail");
}
#[test]
fn sandbox_denied_reports_stdout_when_no_stderr() {
let output = ExecToolCallOutput {
exit_code: 11,
stdout: StreamOutput::new("stdout only".to_string()),
stderr: StreamOutput::new(String::new()),
aggregated_output: StreamOutput::new(String::new()),
duration: Duration::from_millis(8),
timed_out: false,
};
let err = CodexErr::Sandbox(SandboxErr::Denied {
output: Box::new(output),
network_policy_decision: None,
});
assert_eq!(get_error_message_ui(&err), "stdout only");
}
#[test]
fn to_error_event_handles_response_stream_failed() {
let response = RawHttpResponse::builder()
.status(StatusCode::TOO_MANY_REQUESTS)
.body("")
.unwrap();
let mut source = HttpResponse::from(response)
.error_for_status_ref()
.unwrap_err();
*source.url_mut().unwrap() = "http://example.com".parse().unwrap();
let err = CodexErr::ResponseStreamFailed(ResponseStreamFailed {
source,
request_id: Some("req-123".to_string()),
});
let event = err.to_error_event(Some("prefix".to_string()));
assert_eq!(
event.message,
"prefix: Error while reading the server response: HTTP status client error (429 Too Many Requests) for url (http://example.com/), request id: req-123"
);
assert_eq!(
event.codex_error_info,
Some(CodexErrorInfo::ResponseStreamConnectionFailed {
http_status_code: Some(429)
})
);
}
#[test]
fn sandbox_denied_reports_exit_code_when_no_output_available() {
let output = ExecToolCallOutput {
exit_code: 13,
stdout: StreamOutput::new(String::new()),
stderr: StreamOutput::new(String::new()),
aggregated_output: StreamOutput::new(String::new()),
duration: Duration::from_millis(5),
timed_out: false,
};
let err = CodexErr::Sandbox(SandboxErr::Denied {
output: Box::new(output),
network_policy_decision: None,
});
assert_eq!(
get_error_message_ui(&err),
"command failed inside sandbox with exit code 13"
);
}
#[test]
fn usage_limit_reached_error_formats_free_plan() {
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(KnownPlan::Free)),
resets_at: None,
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
assert_eq!(
err.to_string(),
"You’ve hit your usage limit with the model provider. Try again later."
);
}
#[test]
fn usage_limit_reached_error_formats_go_plan() {
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(KnownPlan::Go)),
resets_at: None,
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
assert_eq!(
err.to_string(),
"You’ve hit your usage limit with the model provider. Try again later."
);
}
#[test]
fn usage_limit_reached_error_formats_default_when_none() {
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: None,
resets_at: None,
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
assert_eq!(
err.to_string(),
"You’ve hit your usage limit with the model provider. Try again later."
);
}
#[test]
fn usage_limit_reached_error_formats_team_plan() {
let base = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
let resets_at = base + ChronoDuration::hours(1);
with_now_override(base, move || {
let expected_time = format_retry_timestamp(&resets_at);
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(KnownPlan::Team)),
resets_at: Some(resets_at),
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
let expected = format!(
"You’ve hit your usage limit with the model provider. Try again at {expected_time}."
);
assert_eq!(err.to_string(), expected);
});
}
#[test]
fn usage_limit_reached_error_formats_business_plan_without_reset() {
for plan in [
KnownPlan::Business,
KnownPlan::Ent26,
KnownPlan::EnterpriseCbpAutomation,
] {
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(plan)),
resets_at: None,
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
assert_eq!(
err.to_string(),
"You’ve hit your usage limit with the model provider. Try again later."
);
}
}
#[test]
fn usage_limit_reached_error_formats_self_serve_business_prolite_plan() {
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(KnownPlan::SelfServeBusinessProLite)),
resets_at: None,
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
assert_eq!(
err.to_string(),
"You’ve hit your usage limit with the model provider. Try again later."
);
}
#[test]
fn usage_limit_reached_error_formats_self_serve_business_usage_based_plan() {
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(KnownPlan::SelfServeBusinessUsageBased)),
resets_at: None,
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
assert_eq!(
err.to_string(),
"You’ve hit your usage limit with the model provider. Try again later."
);
}
#[test]
fn usage_limit_reached_error_formats_enterprise_cbp_usage_based_plan() {
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(KnownPlan::EnterpriseCbpUsageBased)),
resets_at: None,
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
assert_eq!(
err.to_string(),
"You’ve hit your usage limit with the model provider. Try again later."
);
}
#[test]
fn usage_limit_reached_error_formats_default_for_other_plans() {
for plan in [
KnownPlan::Enterprise,
KnownPlan::Edu,
KnownPlan::EduPlus,
KnownPlan::EduPro,
] {
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(plan)),
resets_at: None,
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
assert_eq!(
err.to_string(),
"You’ve hit your usage limit with the model provider. Try again later."
);
}
}
#[test]
fn usage_limit_reached_error_formats_pro_plan_with_reset() {
let base = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
let resets_at = base + ChronoDuration::hours(1);
with_now_override(base, move || {
let expected_time = format_retry_timestamp(&resets_at);
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(KnownPlan::Pro)),
resets_at: Some(resets_at),
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
let expected = format!(
"You’ve hit your usage limit with the model provider. Try again at {expected_time}."
);
assert_eq!(err.to_string(), expected);
});
}
#[test]
fn usage_limit_reached_error_hides_upsell_for_non_codex_limit_name() {
let base = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
let resets_at = base + ChronoDuration::hours(1);
with_now_override(base, move || {
let expected_time = format_retry_timestamp(&resets_at);
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(KnownPlan::Plus)),
resets_at: Some(resets_at),
rate_limits: Some(Box::new(RateLimitSnapshot {
limit_id: Some("codex_other".to_string()),
limit_name: Some("codex_other".to_string()),
..rate_limit_snapshot()
})),
promo_message: Some("Server promo copy".to_string()),
rate_limit_reached_type: None,
};
let expected = format!(
"You’ve hit your usage limit for codex_other. Switch to another model now, or try again at {expected_time}."
);
assert_eq!(err.to_string(), expected);
});
}
#[test]
fn usage_limit_reached_includes_minutes_when_available() {
let base = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
let resets_at = base + ChronoDuration::minutes(5);
with_now_override(base, move || {
let expected_time = format_retry_timestamp(&resets_at);
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: None,
resets_at: Some(resets_at),
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
let expected = format!(
"You’ve hit your usage limit with the model provider. Try again at {expected_time}."
);
assert_eq!(err.to_string(), expected);
});
}
#[test]
fn unexpected_status_non_html_is_unchanged() {
let err = UnexpectedResponseError {
status: StatusCode::FORBIDDEN,
body: "plain text error".to_string(),
user_message: None,
url: Some("http://example.com/plain".to_string()),
cf_ray: None,
request_id: None,
identity_authorization_error: None,
identity_error_code: None,
};
let status = StatusCode::FORBIDDEN.to_string();
let url = "http://example.com/plain";
assert_eq!(
err.to_string(),
format!("unexpected status {status}: plain text error, url: {url}")
);
}
#[test]
fn unexpected_status_uses_user_message_and_preserves_response_context() {
let err = UnexpectedResponseError {
status: StatusCode::UNAUTHORIZED,
body: "provider-specific response".to_string(),
user_message: Some("Provider-specific guidance".to_string()),
url: Some("https://example.com/v1/responses".to_string()),
cf_ray: None,
request_id: Some("req-provider".to_string()),
identity_authorization_error: None,
identity_error_code: None,
};
assert_eq!(
err.to_string(),
"Provider-specific guidance, url: https://example.com/v1/responses, request id: req-provider"
);
}
#[test]
fn unexpected_status_prefers_error_message_when_present() {
let err = UnexpectedResponseError {
status: StatusCode::UNAUTHORIZED,
body: r#"{"error":{"message":"Workspace is not authorized in this region."},"status":401}"#
.to_string(),
user_message: None,
url: Some("https://api.example.com/v1/responses".to_string()),
cf_ray: None,
request_id: Some("req-123".to_string()),
identity_authorization_error: None,
identity_error_code: None,
};
let status = StatusCode::UNAUTHORIZED.to_string();
assert_eq!(
err.to_string(),
format!(
"unexpected status {status}: Workspace is not authorized in this region., url: https://api.example.com/v1/responses, request id: req-123"
)
);
}
#[test]
fn unexpected_status_truncates_long_body_with_ellipsis() {
let long_body = "x".repeat(UNEXPECTED_RESPONSE_BODY_MAX_BYTES + 10);
let err = UnexpectedResponseError {
status: StatusCode::BAD_GATEWAY,
body: long_body,
user_message: None,
url: Some("http://example.com/long".to_string()),
cf_ray: None,
request_id: Some("req-long".to_string()),
identity_authorization_error: None,
identity_error_code: None,
};
let status = StatusCode::BAD_GATEWAY.to_string();
let expected_body = format!("{}...", "x".repeat(UNEXPECTED_RESPONSE_BODY_MAX_BYTES));
assert_eq!(
err.to_string(),
format!(
"unexpected status {status}: {expected_body}, url: http://example.com/long, request id: req-long"
)
);
}
#[test]
fn unexpected_status_includes_cf_ray_and_request_id() {
let err = UnexpectedResponseError {
status: StatusCode::UNAUTHORIZED,
body: "plain text error".to_string(),
user_message: None,
url: Some("https://api.example.com/v1/responses".to_string()),
cf_ray: Some("9c81f9f18f2fa49d-LHR".to_string()),
request_id: Some("req-xyz".to_string()),
identity_authorization_error: None,
identity_error_code: None,
};
let status = StatusCode::UNAUTHORIZED.to_string();
assert_eq!(
err.to_string(),
format!(
"unexpected status {status}: plain text error, url: https://api.example.com/v1/responses, cf-ray: 9c81f9f18f2fa49d-LHR, request id: req-xyz"
)
);
}
#[test]
fn unexpected_status_includes_identity_auth_details() {
let err = UnexpectedResponseError {
status: StatusCode::UNAUTHORIZED,
body: "plain text error".to_string(),
user_message: None,
url: Some("https://api.example.com/v1/models".to_string()),
cf_ray: Some("cf-ray-auth-401-test".to_string()),
request_id: Some("req-auth".to_string()),
identity_authorization_error: Some("missing_authorization_header".to_string()),
identity_error_code: Some("token_expired".to_string()),
};
let status = StatusCode::UNAUTHORIZED.to_string();
assert_eq!(
err.to_string(),
format!(
"unexpected status {status}: plain text error, url: https://api.example.com/v1/models, cf-ray: cf-ray-auth-401-test, request id: req-auth, auth error: missing_authorization_header, auth error code: token_expired"
)
);
}
#[test]
fn usage_limit_reached_includes_hours_and_minutes() {
let base = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
let resets_at = base + ChronoDuration::hours(3) + ChronoDuration::minutes(32);
with_now_override(base, move || {
let expected_time = format_retry_timestamp(&resets_at);
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: Some(PlanType::Known(KnownPlan::Plus)),
resets_at: Some(resets_at),
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
let expected = format!(
"You’ve hit your usage limit with the model provider. Try again at {expected_time}."
);
assert_eq!(err.to_string(), expected);
});
}
#[test]
fn usage_limit_reached_includes_days_hours_minutes() {
let base = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
let resets_at =
base + ChronoDuration::days(2) + ChronoDuration::hours(3) + ChronoDuration::minutes(5);
with_now_override(base, move || {
let expected_time = format_retry_timestamp(&resets_at);
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: None,
resets_at: Some(resets_at),
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
let expected = format!(
"You’ve hit your usage limit with the model provider. Try again at {expected_time}."
);
assert_eq!(err.to_string(), expected);
});
}
#[test]
fn usage_limit_reached_less_than_minute() {
let base = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
let resets_at = base + ChronoDuration::seconds(30);
with_now_override(base, move || {
let expected_time = format_retry_timestamp(&resets_at);
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: None,
resets_at: Some(resets_at),
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: None,
rate_limit_reached_type: None,
};
let expected = format!(
"You’ve hit your usage limit with the model provider. Try again at {expected_time}."
);
assert_eq!(err.to_string(), expected);
});
}
#[test]
fn usage_limit_reached_ignores_server_promo_message() {
let base = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
let resets_at = base + ChronoDuration::seconds(30);
with_now_override(base, move || {
let expected_time = format_retry_timestamp(&resets_at);
let err = UsageLimitReachedError {
limit_window_minutes: None,
plan_type: None,
resets_at: Some(resets_at),
rate_limits: Some(Box::new(rate_limit_snapshot())),
promo_message: Some(
"To continue using Codex, start a free trial of <PLAN> today".to_string(),
),
rate_limit_reached_type: None,
};
let expected = format!(
"You’ve hit your usage limit with the model provider. Try again at {expected_time}."
);
assert_eq!(err.to_string(), expected);
});
}

View File

@@ -0,0 +1,169 @@
//! Text encoding detection and conversion utilities for shell output.
//!
//! Windows users frequently run into code pages such as CP1251 or CP866 when invoking commands
//! through VS Code. Those bytes show up as invalid UTF-8 and used to be replaced with the standard
//! Unicode replacement character. We now lean on `chardetng` and `encoding_rs` so we can
//! automatically detect and decode the vast majority of legacy encodings before falling back to
//! lossy UTF-8 decoding.
use chardetng::EncodingDetector;
use encoding_rs::Encoding;
use encoding_rs::IBM866;
use encoding_rs::WINDOWS_1252;
use std::time::Duration;
#[derive(Debug, Clone)]
pub struct StreamOutput<T: Clone> {
pub text: T,
pub truncated_after_lines: Option<u32>,
}
impl StreamOutput<String> {
pub fn new(text: String) -> Self {
Self {
text,
truncated_after_lines: None,
}
}
}
impl StreamOutput<Vec<u8>> {
pub fn from_utf8_lossy(&self) -> StreamOutput<String> {
StreamOutput {
text: bytes_to_string_smart(&self.text),
truncated_after_lines: self.truncated_after_lines,
}
}
}
#[derive(Clone, Debug)]
pub struct ExecToolCallOutput {
pub exit_code: i32,
pub stdout: StreamOutput<String>,
pub stderr: StreamOutput<String>,
pub aggregated_output: StreamOutput<String>,
pub duration: Duration,
pub timed_out: bool,
}
impl Default for ExecToolCallOutput {
fn default() -> Self {
Self {
exit_code: 0,
stdout: StreamOutput::new(String::new()),
stderr: StreamOutput::new(String::new()),
aggregated_output: StreamOutput::new(String::new()),
duration: Duration::ZERO,
timed_out: false,
}
}
}
/// Attempts to convert arbitrary bytes to UTF-8 with best-effort encoding detection.
pub fn bytes_to_string_smart(bytes: &[u8]) -> String {
if bytes.is_empty() {
return String::new();
}
if let Ok(utf8_str) = std::str::from_utf8(bytes) {
return utf8_str.to_owned();
}
let encoding = detect_encoding(bytes);
decode_bytes(bytes, encoding)
}
// Windows-1252 reassigns a handful of 0x80-0x9F slots to smart punctuation (curly quotes, dashes,
// ™). CP866 uses those *same byte values* for uppercase Cyrillic letters. When chardetng sees shell
// snippets that mix these bytes with ASCII it sometimes guesses IBM866, so “smart quotes” render as
// Cyrillic garbage (“УФЦ”) in VS Code. However, CP866 uppercase tokens are perfectly valid output
// (e.g., `ПРИ test`) so we cannot flip every 0x80-0x9F byte to Windows-1252 either. The compromise
// is to only coerce IBM866 to Windows-1252 when (a) the high bytes are exclusively the punctuation
// values listed below and (b) we spot adjacent ASCII. This targets the real failure case without
// clobbering legitimate Cyrillic text. If another code page has a similar collision, introduce a
// dedicated allowlist (like this one) plus unit tests that capture the actual shell output we want
// to preserve. Windows-1252 byte values for smart punctuation.
const WINDOWS_1252_PUNCT_BYTES: [u8; 8] = [
0x91, // ‘ (left single quotation mark)
0x92, // ’ (right single quotation mark)
0x93, // “ (left double quotation mark)
0x94, // ” (right double quotation mark)
0x95, // • (bullet)
0x96, // – (en dash)
0x97, // — (em dash)
0x99, // ™ (trade mark sign)
];
fn detect_encoding(bytes: &[u8]) -> &'static Encoding {
let mut detector = EncodingDetector::new();
detector.feed(bytes, true);
let (encoding, _is_confident) = detector.guess_assess(None, true);
// chardetng occasionally reports IBM866 for short strings that only contain Windows-1252 “smart
// punctuation” bytes (0x80-0x9F) because that range maps to Cyrillic letters in IBM866. When
// those bytes show up alongside an ASCII word (typical shell output: `"“`test), we know the
// intent was likely CP1252 quotes/dashes. Prefer WINDOWS_1252 in that specific situation so we
// render the characters users expect instead of Cyrillic junk. References:
// - Windows-1252 reserving 0x80-0x9F for curly quotes/dashes:
// https://en.wikipedia.org/wiki/Windows-1252
// - CP866 mapping 0x93/0x94/0x96 to Cyrillic letters, so the same bytes show up as “УФЦ” when
// mis-decoded: https://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/PC/CP866.TXT
if encoding == IBM866 && looks_like_windows_1252_punctuation(bytes) {
return WINDOWS_1252;
}
encoding
}
fn decode_bytes(bytes: &[u8], encoding: &'static Encoding) -> String {
let (decoded, _, had_errors) = encoding.decode(bytes);
if had_errors {
return String::from_utf8_lossy(bytes).into_owned();
}
decoded.into_owned()
}
/// Detect whether the byte stream looks like Windows-1252 “smart punctuation” wrapped around
/// otherwise-ASCII text.
///
/// Context: IBM866 and Windows-1252 share the 0x80-0x9F slot range. In IBM866 these bytes decode to
/// Cyrillic letters, whereas Windows-1252 maps them to curly quotes and dashes. chardetng can guess
/// IBM866 for short snippets that only contain those bytes, which turns shell output such as
/// `“test”` into unreadable Cyrillic. To avoid that, we treat inputs comprising a handful of bytes
/// from the problematic range plus ASCII letters as CP1252 punctuation. We deliberately do *not*
/// cap how many of those punctuation bytes we accept: VS Code frequently prints several quoted
/// phrases (e.g., `"foo" - "bar"`), and truncating the count would once again mis-decode those as
/// Cyrillic. If we discover additional encodings with overlapping byte ranges, prefer adding
/// encoding-specific byte allowlists like `WINDOWS_1252_PUNCT` and tests that exercise real-world
/// shell snippets.
fn looks_like_windows_1252_punctuation(bytes: &[u8]) -> bool {
let mut saw_extended_punctuation = false;
let mut saw_ascii_word = false;
for &byte in bytes {
if byte >= 0xA0 {
return false;
}
if (0x80..=0x9F).contains(&byte) {
if !is_windows_1252_punct(byte) {
return false;
}
saw_extended_punctuation = true;
}
if byte.is_ascii_alphabetic() {
saw_ascii_word = true;
}
}
saw_extended_punctuation && saw_ascii_word
}
fn is_windows_1252_punct(byte: u8) -> bool {
WINDOWS_1252_PUNCT_BYTES.contains(&byte)
}
#[cfg(test)]
#[path = "exec_output_tests.rs"]
mod tests;

View File

@@ -0,0 +1,77 @@
//! Integration test for the text encoding fix for issue #6178.
//!
//! These tests simulate VSCode's shell preview on Windows/WSL where the output
//! may be encoded with a legacy code page before it reaches Codex.
use super::StreamOutput;
use pretty_assertions::assert_eq;
#[test]
fn test_utf8_shell_output() {
// Baseline: UTF-8 output should bypass the detector and remain unchanged.
assert_eq!(decode_shell_output("пример".as_bytes()), "пример");
}
#[test]
fn test_cp1251_shell_output() {
// VS Code shells on Windows frequently surface CP1251 bytes for Cyrillic text.
assert_eq!(decode_shell_output(b"\xEF\xF0\xE8\xEC\xE5\xF0"), "пример");
}
#[test]
fn test_cp866_shell_output() {
// Native cmd.exe still defaults to CP866; make sure we recognize that too.
assert_eq!(decode_shell_output(b"\xAF\xE0\xA8\xAC\xA5\xE0"), "пример");
}
#[test]
fn test_windows_1252_smart_decoding() {
// Smart detection should turn fancy quotes/dashes into the proper Unicode glyphs.
assert_eq!(
decode_shell_output(b"\x93\x94 test \x96 dash"),
"\u{201C}\u{201D} test \u{2013} dash"
);
}
#[test]
fn test_smart_decoding_improves_over_lossy_utf8() {
// Regression guard: String::from_utf8_lossy() alone used to emit replacement chars here.
let bytes = b"\x93\x94 test \x96 dash";
assert!(
String::from_utf8_lossy(bytes).contains('\u{FFFD}'),
"lossy UTF-8 should inject replacement chars"
);
assert_eq!(
decode_shell_output(bytes),
"\u{201C}\u{201D} test \u{2013} dash",
"smart decoding should keep curly quotes intact"
);
}
#[test]
fn test_mixed_ascii_and_legacy_encoding() {
// Commands tend to mix ASCII status text with Latin-1 bytes (e.g. café).
assert_eq!(decode_shell_output(b"Output: caf\xE9"), "Output: café"); // codespell:ignore caf
}
#[test]
fn test_pure_latin1_shell_output() {
// Latin-1 by itself should still decode correctly (regression coverage for the older tests).
assert_eq!(decode_shell_output(b"caf\xE9"), "café"); // codespell:ignore caf
}
#[test]
fn test_invalid_bytes_still_fall_back_to_lossy() {
// If detection fails, we still want the user to see replacement characters.
let bytes = b"\xFF\xFE\xFD";
assert_eq!(decode_shell_output(bytes), String::from_utf8_lossy(bytes));
}
fn decode_shell_output(bytes: &[u8]) -> String {
StreamOutput {
text: bytes.to_vec(),
truncated_after_lines: None,
}
.from_utf8_lossy()
.text
}

View File

@@ -0,0 +1,16 @@
//! Shared Guardian transcript encoding selected by configuration and used by evidence consumers.
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
/// Transcript encoding shared by rendering, provenance instructions and budget recovery.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TranscriptFormat {
/// Numbered entries with a role prefix and unescaped text.
#[default]
Line,
/// Host-owned metadata with message text escaped as a JSON string.
Json,
}

View File

@@ -0,0 +1,213 @@
//! Shared hook handler configuration for local and owner-managed environment sources.
use crate::protocol::HookEventName;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct HookEventsToml {
#[serde(rename = "PreModelRequest", default)]
pub pre_model_request: Vec<MatcherGroup>,
#[serde(rename = "PostModelRequest", default)]
pub post_model_request: Vec<MatcherGroup>,
#[serde(rename = "PreToolUse", default)]
pub pre_tool_use: Vec<MatcherGroup>,
#[serde(rename = "PermissionRequest", default)]
pub permission_request: Vec<MatcherGroup>,
#[serde(rename = "PostToolUse", default)]
pub post_tool_use: Vec<MatcherGroup>,
#[serde(rename = "PreCompact", default)]
pub pre_compact: Vec<MatcherGroup>,
#[serde(rename = "PostCompact", default)]
pub post_compact: Vec<MatcherGroup>,
#[serde(rename = "SessionStart", default)]
pub session_start: Vec<MatcherGroup>,
#[serde(rename = "SessionEnd", default)]
pub session_end: Vec<MatcherGroup>,
#[serde(rename = "UserPromptSubmit", default)]
pub user_prompt_submit: Vec<MatcherGroup>,
#[serde(rename = "SubagentStart", default)]
pub subagent_start: Vec<MatcherGroup>,
#[serde(rename = "SubagentStop", default)]
pub subagent_stop: Vec<MatcherGroup>,
#[serde(rename = "Stop", default)]
pub stop: Vec<MatcherGroup>,
#[serde(rename = "Interrupt", default)]
pub interrupt: Vec<MatcherGroup>,
}
impl HookEventsToml {
pub fn is_empty(&self) -> bool {
let Self {
pre_model_request,
post_model_request,
pre_tool_use,
permission_request,
post_tool_use,
pre_compact,
post_compact,
session_start,
session_end,
user_prompt_submit,
subagent_start,
subagent_stop,
stop,
interrupt,
} = self;
pre_model_request.is_empty()
&& post_model_request.is_empty()
&& pre_tool_use.is_empty()
&& permission_request.is_empty()
&& post_tool_use.is_empty()
&& pre_compact.is_empty()
&& post_compact.is_empty()
&& session_start.is_empty()
&& session_end.is_empty()
&& user_prompt_submit.is_empty()
&& subagent_start.is_empty()
&& subagent_stop.is_empty()
&& stop.is_empty()
&& interrupt.is_empty()
}
pub fn handler_count(&self) -> usize {
let Self {
pre_model_request,
post_model_request,
pre_tool_use,
permission_request,
post_tool_use,
pre_compact,
post_compact,
session_start,
session_end,
user_prompt_submit,
subagent_start,
subagent_stop,
stop,
interrupt,
} = self;
[
pre_model_request,
post_model_request,
pre_tool_use,
permission_request,
post_tool_use,
pre_compact,
post_compact,
session_start,
session_end,
user_prompt_submit,
subagent_start,
subagent_stop,
stop,
interrupt,
]
.into_iter()
.flatten()
.map(|group| group.hooks.len())
.sum()
}
pub fn into_matcher_groups(mut self) -> [(HookEventName, Vec<MatcherGroup>); 14] {
self.matcher_groups_mut()
.map(|(event, groups)| (event, std::mem::take(groups)))
}
pub fn matcher_groups_mut(&mut self) -> [(HookEventName, &mut Vec<MatcherGroup>); 14] {
use HookEventName as Event;
[
(Event::PreModelRequest, &mut self.pre_model_request),
(Event::PostModelRequest, &mut self.post_model_request),
(Event::PreToolUse, &mut self.pre_tool_use),
(Event::PermissionRequest, &mut self.permission_request),
(Event::PostToolUse, &mut self.post_tool_use),
(Event::PreCompact, &mut self.pre_compact),
(Event::PostCompact, &mut self.post_compact),
(Event::SessionStart, &mut self.session_start),
(Event::SessionEnd, &mut self.session_end),
(Event::UserPromptSubmit, &mut self.user_prompt_submit),
(Event::SubagentStart, &mut self.subagent_start),
(Event::SubagentStop, &mut self.subagent_stop),
(Event::Stop, &mut self.stop),
(Event::Interrupt, &mut self.interrupt),
]
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MatcherGroup {
#[serde(default)]
pub matcher: Option<String>,
#[serde(default)]
pub hooks: Vec<HookHandlerConfig>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type")]
pub enum HookHandlerConfig {
#[serde(rename = "command")]
Command {
command: String,
#[serde(default, rename = "commandWindows", alias = "command_windows")]
command_windows: Option<String>,
#[serde(default, rename = "timeout")]
timeout_sec: Option<u64>,
#[serde(default)]
r#async: bool,
#[serde(default, rename = "statusMessage")]
status_message: Option<String>,
/// Approximate token threshold for spilling this hook's `additionalContext` to disk.
/// Unset uses 2,500 tokens; `0` disables spilling for this hook. The threshold is
/// evaluated against the original context; a spilled preview also includes recovery
/// metadata.
#[serde(
default,
rename = "additionalContextLimit",
skip_serializing_if = "Option::is_none"
)]
additional_context_limit: Option<usize>,
},
#[serde(rename = "mcp_tool")]
McpTool {
server: String,
tool: String,
#[serde(default, deserialize_with = "deserialize_mcp_tool_input")]
input: serde_json::Map<String, serde_json::Value>,
#[serde(default, rename = "timeout")]
timeout_sec: Option<u64>,
#[serde(default, rename = "statusMessage")]
status_message: Option<String>,
},
#[serde(rename = "prompt")]
Prompt {},
#[serde(rename = "agent")]
Agent {},
}
// Reject values such as null that cannot be represented in TOML for trust hashing.
fn deserialize_mcp_tool_input<'de, D>(
deserializer: D,
) -> Result<serde_json::Map<String, serde_json::Value>, D::Error>
where
D: serde::Deserializer<'de>,
{
let input = serde_json::Map::deserialize(deserializer)?;
fn representable(value: &serde_json::Value) -> bool {
match value {
serde_json::Value::Null => false,
serde_json::Value::Number(n) => !n.is_u64() || n.as_i64().is_some(),
serde_json::Value::Array(items) => items.iter().all(representable),
serde_json::Value::Object(items) => items.values().all(representable),
serde_json::Value::Bool(_) | serde_json::Value::String(_) => true,
}
}
if !input.values().all(representable) {
return Err(serde::de::Error::custom(
"MCP hook input must be representable as TOML",
));
}
Ok(input)
}

View File

@@ -0,0 +1,12 @@
//! Response item ID generation shared by sessions and their consumers.
use crate::ResponseItemId;
use std::sync::Arc;
/// Generates response item IDs from a type prefix for an owning session. Clones share the same callable.
pub type ItemIdGenerator = Arc<dyn Fn(&str) -> ResponseItemId + Send + Sync>;
#[cfg(test)]
pub(super) fn uuid_v7_item_id_generator_for_test() -> ItemIdGenerator {
Arc::new(|prefix| ResponseItemId::with_suffix(prefix, uuid::Uuid::now_v7()))
}

View File

@@ -0,0 +1,981 @@
use crate::AgentPath;
use crate::ItemIdGenerator;
use crate::ThreadId;
use crate::dynamic_tools::DynamicToolCallOutputContentItem;
use crate::mcp::CallToolResult;
use crate::memory_citation::MemoryCitation;
use crate::models::AudioReference;
use crate::models::ContentItem;
use crate::models::ContentItemMetadata;
use crate::models::FunctionCallOutputBody;
use crate::models::ImageDetail;
use crate::models::ImageReference;
use crate::models::InternalChatMessageMetadataPassthrough;
use crate::models::MessagePhase;
use crate::models::ResponseItem;
use crate::models::WebSearchAction;
use crate::openai_models::ReasoningEffort as ReasoningEffortConfig;
use crate::parse_command::ParsedCommand;
use crate::protocol::AgentStatus;
use crate::protocol::CollabAgentRef;
use crate::protocol::ExecCommandSource;
use crate::protocol::ExecCommandStatus;
use crate::protocol::FileChange;
use crate::protocol::PatchApplyStatus;
use crate::protocol::ReviewOutputEvent;
use crate::protocol::ReviewTarget;
use crate::protocol::SubAgentActivityKind;
use crate::protocol::UserMessageAudioKind;
use crate::user_input::ByteRange;
use crate::user_input::TextElement;
use crate::user_input::UserInput;
use akode_extension_items::ExtensionItem;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use quick_xml::de::from_str as from_xml_str;
use quick_xml::se::to_string as to_xml_string;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;
use ts_rs::TS;
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)]
#[serde(tag = "type")]
#[ts(tag = "type")]
pub enum TurnItem {
UserMessage(UserMessageItem),
FunctionCallOutput(FunctionCallOutputItem),
HookPrompt(HookPromptItem),
AgentMessage(AgentMessageItem),
Plan(PlanItem),
Reasoning(ReasoningItem),
CommandExecution(CommandExecutionItem),
DynamicToolCall(DynamicToolCallItem),
CollabAgentToolCall(CollabAgentToolCallItem),
SubAgentActivity(SubAgentActivityItem),
/// Hosted Responses API web-search item handled directly by core.
///
/// Standalone web search uses Self::Extension instead because its display
/// schema is owned by the web-search extension.
WebSearch(WebSearchItem),
ImageView(ImageViewItem),
/// Item whose schema and lifecycle details are owned by an extension.
///
/// Standalone image generation, sleep, and web search use this path.
/// App-server wraps the same typed items in their public variants.
Extension(ExtensionItem),
/// Hosted Responses API image-generation item handled directly by core.
///
/// This remains separate from [`Self::Extension`] because core still owns
/// hosted image persistence and legacy-event fanout.
ImageGeneration(ImageGenerationItem),
EnteredReviewMode(EnteredReviewModeItem),
ExitedReviewMode(ExitedReviewModeItem),
FileChange(FileChangeItem),
McpToolCall(McpToolCallItem),
ContextCompaction(ContextCompactionItem),
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)]
pub struct UserMessageItem {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub client_id: Option<String>,
pub content: Vec<UserInput>,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)]
pub struct FunctionCallOutputItem {
pub id: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub namespace: Option<String>,
pub output: FunctionCallOutputBody,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
pub struct HookPromptItem {
pub id: String,
pub fragments: Vec<HookPromptFragment>,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
pub struct HookPromptFragment {
pub text: String,
pub hook_run_id: String,
/// Emission-time attribution; persisted on the ResponseItem, not the UI hook fragment.
#[serde(skip)]
#[ts(skip)]
#[schemars(skip)]
pub metadata: ContentItemMetadata,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename = "hook_prompt")]
struct HookPromptXml {
#[serde(rename = "@hook_run_id")]
hook_run_id: String,
#[serde(rename = "$text")]
text: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)]
#[serde(tag = "type")]
#[ts(tag = "type")]
pub enum AgentMessageContent {
Text { text: String },
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum AgentMessageDelivery {
Async,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "v2/")]
pub struct AsyncUserInputQuestion {
pub title: String,
pub options: Option<Vec<String>>,
}
/// A presentation instruction for Chat to apply to this answer when recovering history.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, TS, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct AgentMessageDisplay {
/// Unknown actions must be left for the producing client to handle.
pub action: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub block_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub check_trusted_contacts: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, TS, JsonSchema)]
pub struct AgentMessageModeration {
pub moderated: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub display: Option<AgentMessageDisplay>,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)]
/// Assistant-authored message payload used in turn-item streams.
///
/// `phase` is optional because not all providers/models emit it. Consumers
/// should use it when present, but retain legacy completion semantics when it
/// is `None`.
pub struct AgentMessageItem {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub moderation: Option<AgentMessageModeration>,
pub id: String,
pub content: Vec<AgentMessageContent>,
/// Optional phase metadata carried through from `ResponseItem::Message`.
///
/// This is currently used by TUI rendering to distinguish mid-turn
/// commentary from a final answer and avoid status-indicator jitter.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub phase: Option<MessagePhase>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub memory_citation: Option<MemoryCitation>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub delivery: Option<AgentMessageDelivery>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub questions: Option<Vec<AsyncUserInputQuestion>>,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)]
pub struct EnteredReviewModeItem {
pub id: String,
pub target: ReviewTarget,
pub user_facing_hint: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)]
pub struct ExitedReviewModeItem {
pub id: String,
pub review_output: Option<ReviewOutputEvent>,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)]
pub struct PlanItem {
pub id: String,
pub text: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)]
pub struct ReasoningItem {
pub id: String,
pub summary_text: Vec<String>,
#[serde(default)]
pub raw_content: Vec<String>,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CommandExecutionStatus {
InProgress,
Completed,
Failed,
Declined,
}
impl From<ExecCommandStatus> for CommandExecutionStatus {
fn from(value: ExecCommandStatus) -> Self {
match value {
ExecCommandStatus::Completed => Self::Completed,
ExecCommandStatus::Failed => Self::Failed,
ExecCommandStatus::Declined => Self::Declined,
}
}
}
/// Returns whether a path is safe to serialize as a trusted plugin-relative path.
///
/// This validates the cross-platform wire shape only. The trusted plugin resolver
/// remains responsible for establishing that the path actually came from a plugin root.
pub fn is_safe_plugin_relative_path(path: &str) -> bool {
!path.is_empty()
&& !path.starts_with('/')
&& !path.contains('\\')
&& path.split('/').all(|component| {
!component.is_empty()
&& !matches!(component, "." | "..")
&& !matches!(
component.as_bytes(),
[drive, b':', ..] if drive.is_ascii_alphabetic()
)
})
}
/// Immutable model labels carried within command lifecycle events.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelInvocationContext {
pub model_slug: String,
pub reasoning_effort: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)]
pub struct CommandExecutionItem {
/// Observed process backend; None means unknown or not launched.
#[serde(skip)]
#[schemars(skip)]
#[ts(skip)]
pub sandbox_type: Option<crate::sandbox::SandboxType>,
#[serde(skip)]
#[schemars(skip)]
#[ts(skip)]
pub model_context: Option<ModelInvocationContext>,
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub plugin_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub script_path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub process_id: Option<String>,
pub command: Vec<String>,
pub cwd: PathUri,
pub parsed_cmd: Vec<ParsedCommand>,
pub source: ExecCommandSource,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub interaction_input: Option<String>,
pub status: CommandExecutionStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub aggregated_output: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub exit_code: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(type = "string", optional)]
pub duration: Option<Duration>,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DynamicToolCallStatus {
InProgress,
Completed,
Failed,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)]
pub struct DynamicToolCallItem {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub namespace: Option<String>,
pub tool: String,
pub arguments: serde_json::Value,
pub status: DynamicToolCallStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub content_items: Option<Vec<DynamicToolCallOutputContentItem>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub success: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub error: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(type = "string", optional)]
pub duration: Option<Duration>,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CollabAgentTool {
SpawnAgent,
SendInput,
ResumeAgent,
Wait,
CloseAgent,
SendMessage,
FollowupTask,
InterruptAgent,
ListAgents,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CollabAgentToolCallStatus {
InProgress,
Completed,
Failed,
Interrupted,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)]
pub struct CollabAgentToolCallItem {
pub id: String,
pub tool: CollabAgentTool,
pub status: CollabAgentToolCallStatus,
pub sender_thread_id: ThreadId,
#[serde(default)]
pub receiver_thread_ids: Vec<ThreadId>,
#[serde(default)]
pub receiver_agents: Vec<CollabAgentRef>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub prompt: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub model: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub reasoning_effort: Option<ReasoningEffortConfig>,
#[serde(default)]
pub agents_states: HashMap<ThreadId, AgentStatus>,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
pub struct SubAgentActivityItem {
/// Resolved model at sub-agent creation; absent from older records and other activities.
pub model: Option<String>,
/// Resolved reasoning effort at sub-agent creation, when known.
pub reasoning_effort: Option<ReasoningEffortConfig>,
pub id: String,
pub kind: SubAgentActivityKind,
pub agent_thread_id: ThreadId,
pub agent_path: AgentPath,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)]
pub struct WebSearchItem {
pub id: String,
pub query: String,
pub action: WebSearchAction,
/// Structured search results returned out-of-band by standalone web search.
///
/// These stay as opaque JSON at the Codex transport boundary so new result
/// fields and result types can pass through without changing model-visible
/// context or requiring a Codex release.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub results: Option<Vec<JsonValue>>,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)]
pub struct ImageViewItem {
pub id: String,
/// Path resolved within the selected execution environment.
///
/// This core protocol type is not exposed directly in the app-server API.
/// App-server converts the path to `LegacyAppPathString` at its boundary.
pub path: PathUri,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)]
pub struct ImageGenerationItem {
pub id: String,
pub status: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub revised_prompt: Option<String>,
pub result: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub saved_path: Option<AbsolutePathBuf>,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)]
pub struct FileChangeItem {
pub id: String,
pub changes: HashMap<PathBuf, FileChange>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub status: Option<PatchApplyStatus>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub auto_approved: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub stdout: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub stderr: Option<String>,
}
/// UI resource and display preference for model invocations, captured from the tool descriptor.
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct McpAppUi {
pub resource_uri: String,
pub preferred_model_display_mode: McpAppDisplayMode,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum McpAppDisplayMode {
Inline,
Fullscreen,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
pub struct McpToolCallItem {
pub id: String,
pub server: String,
pub tool: String,
pub arguments: serde_json::Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub connector_id: Option<String>,
/// Legacy compatibility field; prefer `mcp_app_ui.resource_uri` when available.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub mcp_app_resource_uri: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub mcp_app_ui: Option<McpAppUi>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub link_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub app_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub action_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub plugin_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub read_only_hint: Option<bool>,
pub status: McpToolCallStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub result: Option<CallToolResult>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub error: Option<McpToolCallError>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(type = "string", optional)]
pub duration: Option<Duration>,
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
pub enum McpToolCallStatus {
InProgress,
Completed,
Failed,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
pub struct McpToolCallError {
pub message: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)]
pub struct ContextCompactionItem {
pub id: String,
}
fn new_item_id() -> String {
uuid::Uuid::now_v7().to_string()
}
impl ContextCompactionItem {
pub fn new() -> Self {
Self { id: new_item_id() }
}
}
impl Default for ContextCompactionItem {
fn default() -> Self {
Self::new()
}
}
impl UserMessageItem {
pub fn new(content: &[UserInput]) -> Self {
Self {
id: new_item_id(),
client_id: None,
content: content.to_vec(),
}
}
pub fn message(&self) -> String {
self.content
.iter()
.map(|c| match c {
UserInput::Text { text, .. } => text.clone(),
_ => String::new(),
})
.collect::<Vec<String>>()
.join("")
}
pub fn text_elements(&self) -> Vec<TextElement> {
let mut out = Vec::new();
let mut offset = 0usize;
for input in &self.content {
if let UserInput::Text {
text,
text_elements,
..
} = input
{
// Text element ranges are relative to each text chunk; offset them so they align
// with the concatenated message returned by `message()`.
for elem in text_elements {
let byte_range = ByteRange {
start: offset + elem.byte_range.start,
end: offset + elem.byte_range.end,
};
out.push(TextElement::new(
byte_range,
elem.placeholder(text).map(str::to_string),
));
}
offset += text.len();
}
}
out
}
pub fn image_urls(&self) -> Vec<String> {
self.content
.iter()
.filter_map(|c| match c {
UserInput::Image {
image: ImageReference::Inline { image_url },
..
} => Some(image_url.clone()),
_ => None,
})
.collect()
}
pub fn image_details(&self) -> Vec<Option<ImageDetail>> {
trim_trailing_default_image_details(
self.content
.iter()
.filter_map(|c| match c {
UserInput::Image {
image: ImageReference::Inline { .. },
detail,
} => Some(*detail),
_ => None,
})
.collect(),
)
}
pub fn local_image_paths(&self) -> Vec<std::path::PathBuf> {
self.content
.iter()
.filter_map(|c| match c {
UserInput::LocalImage { path, .. } => Some(path.clone()),
_ => None,
})
.collect()
}
pub fn local_image_details(&self) -> Vec<Option<ImageDetail>> {
trim_trailing_default_image_details(
self.content
.iter()
.filter_map(|c| match c {
UserInput::LocalImage { detail, .. } => Some(*detail),
_ => None,
})
.collect(),
)
}
pub fn audio_urls(&self) -> Vec<String> {
self.content
.iter()
.filter_map(|c| match c {
UserInput::Audio {
audio: AudioReference::Inline { audio_url },
} => Some(audio_url.clone()),
_ => None,
})
.collect()
}
/// Returns file-backed audio references when the message includes an upload.
/// Inline payloads remain exclusively in the legacy `audio` field.
pub fn audio_references(&self) -> Option<Vec<AudioReference>> {
let audio = self
.content
.iter()
.filter_map(|content| match content {
UserInput::Audio {
audio: audio @ AudioReference::File { .. },
} => Some(audio.clone()),
_ => None,
})
.collect::<Vec<_>>();
(!audio.is_empty()).then_some(audio)
}
/// Returns the original inline/file ordering when uploaded audio is present.
pub fn audio_order(&self) -> Vec<UserMessageAudioKind> {
if !self.content.iter().any(|content| {
matches!(
content,
UserInput::Audio {
audio: AudioReference::File { .. }
}
)
}) {
return Vec::new();
}
self.content
.iter()
.filter_map(|content| match content {
UserInput::Audio {
audio: AudioReference::Inline { .. },
} => Some(UserMessageAudioKind::Inline),
UserInput::Audio {
audio: AudioReference::File { .. },
} => Some(UserMessageAudioKind::File),
_ => None,
})
.collect()
}
pub fn local_audio_paths(&self) -> Vec<std::path::PathBuf> {
self.content
.iter()
.filter_map(|c| match c {
UserInput::LocalAudio { path } => Some(path.clone()),
_ => None,
})
.collect()
}
}
pub(crate) fn trim_trailing_default_image_details(
mut details: Vec<Option<ImageDetail>>,
) -> Vec<Option<ImageDetail>> {
while matches!(details.last(), Some(None)) {
details.pop();
}
details
}
impl HookPromptItem {
pub fn from_fragments(id: Option<&str>, fragments: Vec<HookPromptFragment>) -> Self {
Self {
id: id.map(str::to_string).unwrap_or_else(new_item_id),
fragments,
}
}
}
impl HookPromptFragment {
pub fn from_single_hook(text: impl Into<String>, hook_run_id: impl Into<String>) -> Self {
Self {
text: text.into(),
hook_run_id: hook_run_id.into(),
metadata: ContentItemMetadata::default(),
}
}
}
pub fn build_hook_prompt_message(
fragments: &[HookPromptFragment],
item_id_generator: &ItemIdGenerator,
) -> Option<ResponseItem> {
let mut content = Vec::new();
let mut metadata = Vec::new();
for fragment in fragments {
if let Some(text) = serialize_hook_prompt_fragment(&fragment.text, &fragment.hook_run_id) {
content.push(ContentItem::InputText { text });
metadata.push(fragment.metadata.clone());
}
}
if content.is_empty() {
return None;
}
Some(ResponseItem::Message {
status: None,
encrypted_content: None,
id: Some(item_id_generator("msg")),
role: "user".to_string(),
content,
phase: None,
internal_chat_message_metadata_passthrough: metadata
.iter()
.any(|part| part != &ContentItemMetadata::default())
.then_some(InternalChatMessageMetadataPassthrough {
content_item_metadata: Some(metadata),
..Default::default()
}),
})
}
pub fn parse_hook_prompt_message(
id: Option<&str>,
content: &[ContentItem],
) -> Option<HookPromptItem> {
let fragments = content
.iter()
.map(|content_item| {
let ContentItem::InputText { text } = content_item else {
return None;
};
parse_hook_prompt_fragment(text)
})
.collect::<Option<Vec<_>>>()?;
if fragments.is_empty() {
return None;
}
Some(HookPromptItem::from_fragments(id, fragments))
}
pub fn parse_hook_prompt_fragment(text: &str) -> Option<HookPromptFragment> {
let trimmed = text.trim();
let HookPromptXml { text, hook_run_id } = from_xml_str::<HookPromptXml>(trimmed).ok()?;
if hook_run_id.trim().is_empty() {
return None;
}
Some(HookPromptFragment::from_single_hook(text, hook_run_id))
}
fn serialize_hook_prompt_fragment(text: &str, hook_run_id: &str) -> Option<String> {
if hook_run_id.trim().is_empty() {
return None;
}
to_xml_string(&HookPromptXml {
text: text.to_string(),
hook_run_id: hook_run_id.to_string(),
})
.ok()
}
impl TurnItem {
pub fn id(&self) -> String {
match self {
TurnItem::UserMessage(item) => item.id.clone(),
TurnItem::FunctionCallOutput(item) => item.id.clone(),
TurnItem::HookPrompt(item) => item.id.clone(),
TurnItem::AgentMessage(item) => item.id.clone(),
TurnItem::Plan(item) => item.id.clone(),
TurnItem::Reasoning(item) => item.id.clone(),
TurnItem::CommandExecution(item) => item.id.clone(),
TurnItem::DynamicToolCall(item) => item.id.clone(),
TurnItem::CollabAgentToolCall(item) => item.id.clone(),
TurnItem::SubAgentActivity(item) => item.id.clone(),
TurnItem::WebSearch(item) => item.id.clone(),
TurnItem::ImageView(item) => item.id.clone(),
TurnItem::Extension(item) => item.id().to_string(),
TurnItem::ImageGeneration(item) => item.id.clone(),
TurnItem::EnteredReviewMode(item) => item.id.clone(),
TurnItem::ExitedReviewMode(item) => item.id.clone(),
TurnItem::FileChange(item) => item.id.clone(),
TurnItem::McpToolCall(item) => item.id.clone(),
TurnItem::ContextCompaction(item) => item.id.clone(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use akode_extension_items::sleep::SleepItem;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn sleep_extension_item_preserves_type_and_kind() {
let item = TurnItem::Extension(ExtensionItem::Sleep(SleepItem {
id: "sleep-1".to_string(),
duration_ms: 1_000,
}));
assert_eq!(
serde_json::to_value(item).expect("serialize sleep extension item"),
json!({
"type": "Extension",
"kind": "clock.sleep",
"id": "sleep-1",
"durationMs": 1_000,
})
);
}
#[test]
fn user_message_item_extracts_audio_attachments() {
let item = UserMessageItem::new(&[
UserInput::Text {
text: "transcribe these".to_string(),
text_elements: Vec::new(),
},
UserInput::Audio {
audio: AudioReference::Inline {
audio_url: "https://example.com/remote.mp3".to_string(),
},
},
UserInput::Audio {
audio: AudioReference::File {
file_id: "file_audio".to_string(),
},
},
UserInput::LocalAudio {
path: std::path::PathBuf::from("local.wav"),
},
]);
assert_eq!(
(item.audio_urls(), item.local_audio_paths()),
(
vec!["https://example.com/remote.mp3".to_string()],
vec![std::path::PathBuf::from("local.wav")],
)
);
assert_eq!(
item.audio_references(),
Some(vec![AudioReference::File {
file_id: "file_audio".to_string(),
}])
);
assert_eq!(
item.audio_order(),
vec![UserMessageAudioKind::Inline, UserMessageAudioKind::File]
);
}
#[test]
fn plugin_relative_paths_use_safe_wire_shape() {
assert!(is_safe_plugin_relative_path("scripts/run.py"));
for path in [
"",
"/home/user/.akode/plugins/cache/sample/scripts/run.py",
"C:/Users/user/.akode/plugins/cache/sample/scripts/run.py",
"scripts/C:/run.py",
r"\\server\share\sample\scripts\run.py",
r"scripts\run.py",
"scripts//run.py",
"scripts/./run.py",
"scripts/../run.py",
] {
assert!(
!is_safe_plugin_relative_path(path),
"unsafe plugin-relative path should be rejected: {path:?}"
);
}
}
#[test]
fn hook_prompt_roundtrips_multiple_fragments() {
let original = vec![
HookPromptFragment::from_single_hook("Retry with care & joy.", "hook-run-1"),
HookPromptFragment::from_single_hook("Then summarize cleanly.", "hook-run-2"),
];
let message =
build_hook_prompt_message(&original, &crate::uuid_v7_item_id_generator_for_test())
.expect("hook prompt");
let ResponseItem::Message { id, content, .. } = message else {
panic!("expected hook prompt message");
};
assert!(id.is_some_and(|id| id.starts_with("msg_")));
let parsed = parse_hook_prompt_message(/*id*/ None, &content).expect("parsed hook prompt");
assert_eq!(parsed.fragments, original);
}
#[test]
fn hook_prompt_parses_legacy_single_hook_run_id() {
let parsed = parse_hook_prompt_fragment(
r#"<hook_prompt hook_run_id="hook-run-1">Retry with tests.</hook_prompt>"#,
)
.expect("legacy hook prompt");
assert_eq!(
parsed,
HookPromptFragment {
text: "Retry with tests.".to_string(),
hook_run_id: "hook-run-1".to_string(),
metadata: Default::default(),
}
);
}
}

View File

@@ -0,0 +1,704 @@
use crate::ThreadId;
use crate::dynamic_tools::DynamicToolCallRequest;
use crate::items::AgentMessageContent;
use crate::items::AgentMessageItem;
use crate::items::CollabAgentTool;
use crate::items::CollabAgentToolCallItem;
use crate::items::CollabAgentToolCallStatus;
use crate::items::CommandExecutionItem;
use crate::items::CommandExecutionStatus;
use crate::items::ContextCompactionItem;
use crate::items::DynamicToolCallItem;
use crate::items::DynamicToolCallStatus;
use crate::items::EnteredReviewModeItem;
use crate::items::ExitedReviewModeItem;
use crate::items::FileChangeItem;
use crate::items::ImageGenerationItem;
use crate::items::McpToolCallItem;
use crate::items::ReasoningItem;
use crate::items::SubAgentActivityItem;
use crate::items::TurnItem;
use crate::items::UserMessageItem;
use crate::items::WebSearchItem;
use crate::items::trim_trailing_default_image_details;
use crate::models::ImageReference;
use crate::protocol::AgentMessageContentDeltaEvent;
use crate::protocol::AgentMessageEvent;
use crate::protocol::AgentReasoningEvent;
use crate::protocol::AgentReasoningRawContentEvent;
use crate::protocol::AgentStatus;
use crate::protocol::CollabAgentInteractionBeginEvent;
use crate::protocol::CollabAgentInteractionEndEvent;
use crate::protocol::CollabAgentSpawnBeginEvent;
use crate::protocol::CollabAgentSpawnEndEvent;
use crate::protocol::CollabAgentStatusEntry;
use crate::protocol::CollabCloseBeginEvent;
use crate::protocol::CollabCloseEndEvent;
use crate::protocol::CollabResumeBeginEvent;
use crate::protocol::CollabResumeEndEvent;
use crate::protocol::CollabWaitingBeginEvent;
use crate::protocol::CollabWaitingEndEvent;
use crate::protocol::ContextCompactedEvent;
use crate::protocol::DynamicToolCallResponseEvent;
use crate::protocol::EnteredReviewModeEvent;
use crate::protocol::EventMsg;
use crate::protocol::ExecCommandBeginEvent;
use crate::protocol::ExecCommandEndEvent;
use crate::protocol::ExecCommandStatus;
use crate::protocol::ExitedReviewModeEvent;
use crate::protocol::ImageGenerationBeginEvent;
use crate::protocol::ImageGenerationEndEvent;
use crate::protocol::ItemCompletedEvent;
use crate::protocol::ItemStartedEvent;
use crate::protocol::McpInvocation;
use crate::protocol::McpToolCallBeginEvent;
use crate::protocol::McpToolCallEndEvent;
use crate::protocol::PatchApplyBeginEvent;
use crate::protocol::PatchApplyEndEvent;
use crate::protocol::PatchApplyStatus;
use crate::protocol::ReasoningContentDeltaEvent;
use crate::protocol::ReasoningRawContentDeltaEvent;
use crate::protocol::SubAgentActivityEvent;
use crate::protocol::UserMessageEvent;
use crate::protocol::UserMessageImageKind;
use crate::protocol::ViewImageToolCallEvent;
use crate::protocol::WebSearchBeginEvent;
use crate::protocol::WebSearchEndEvent;
use crate::user_input::UserInput;
use akode_extension_items::image_generation::GeneratedImageRef;
/// Converts canonical item lifecycle events back into the legacy raw event stream used by
/// compatibility consumers that have not migrated to `TurnItem`.
pub trait HasLegacyEvent {
fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec<EventMsg>;
}
impl ContextCompactionItem {
pub fn as_legacy_event(&self) -> EventMsg {
EventMsg::ContextCompacted(ContextCompactedEvent {})
}
}
impl UserMessageItem {
pub fn as_legacy_user_message_event(&self) -> UserMessageEvent {
// Legacy user-message events flatten only text inputs into `message` and
// rebase text element ranges onto that concatenated text.
let mut file_ids = Vec::new();
let mut file_id_details = Vec::new();
let mut image_order = Vec::new();
for input in &self.content {
if let UserInput::Image { image, detail } = input {
match image {
ImageReference::Inline { .. } => {
image_order.push(UserMessageImageKind::Inline);
}
ImageReference::File { file_id } => {
image_order.push(UserMessageImageKind::File);
file_ids.push(file_id.clone());
file_id_details.push(*detail);
}
}
}
}
let file_id_details = trim_trailing_default_image_details(file_id_details);
UserMessageEvent {
client_id: self.client_id.clone(),
message: self.message(),
images: Some(self.image_urls()),
image_details: self.image_details(),
file_ids: (!file_ids.is_empty()).then_some(file_ids),
file_id_details,
image_order,
local_images: self.local_image_paths(),
local_image_details: self.local_image_details(),
audio: Some(self.audio_urls()),
audio_references: self.audio_references(),
audio_order: self.audio_order(),
local_audio: self.local_audio_paths(),
text_elements: self.text_elements(),
}
}
pub fn as_legacy_event(&self) -> EventMsg {
EventMsg::UserMessage(self.as_legacy_user_message_event())
}
}
impl AgentMessageItem {
pub fn as_legacy_events(&self) -> Vec<EventMsg> {
let texts = self.content.iter().map(|part| match part {
AgentMessageContent::Text { text } => text.as_str(),
});
let event = |message, moderation| {
EventMsg::AgentMessage(AgentMessageEvent {
message,
moderation,
phase: self.phase.clone(),
memory_citation: self.memory_citation.clone(),
delivery: self.delivery,
questions: self.questions.clone(),
})
};
if let Some(decision) = &self.moderation {
// The canonical answer has one ID even when the model supplied multiple text parts.
return vec![event(
texts.collect(),
Some(crate::protocol::TargetedAnswerModeration {
item_id: self.id.clone(),
moderated: decision.moderated,
display: decision.display.clone(),
}),
)];
}
texts.map(|text| event(text.to_owned(), None)).collect()
}
}
impl EnteredReviewModeItem {
pub fn as_legacy_event(&self, turn_id: String) -> EventMsg {
EventMsg::EnteredReviewMode(EnteredReviewModeEvent {
target: self.target.clone(),
user_facing_hint: Some(self.user_facing_hint.clone()),
turn_id: Some(turn_id),
item_id: Some(self.id.clone()),
})
}
}
impl ExitedReviewModeItem {
pub fn as_legacy_event(&self, turn_id: String) -> EventMsg {
EventMsg::ExitedReviewMode(ExitedReviewModeEvent {
turn_id: Some(turn_id),
item_id: Some(self.id.clone()),
review_output: self.review_output.clone(),
})
}
}
impl ReasoningItem {
pub fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec<EventMsg> {
let mut events = Vec::new();
for summary in &self.summary_text {
events.push(EventMsg::AgentReasoning(AgentReasoningEvent {
text: summary.clone(),
}));
}
if show_raw_agent_reasoning {
for entry in &self.raw_content {
events.push(EventMsg::AgentReasoningRawContent(
AgentReasoningRawContentEvent {
text: entry.clone(),
},
));
}
}
events
}
}
impl CommandExecutionItem {
pub(crate) fn as_legacy_begin_event(&self, turn_id: String, started_at_ms: i64) -> EventMsg {
EventMsg::ExecCommandBegin(ExecCommandBeginEvent {
call_id: self.id.clone(),
plugin_id: self.plugin_id.clone(),
script_path: self.script_path.clone(),
process_id: self.process_id.clone(),
turn_id,
started_at_ms,
command: self.command.clone(),
cwd: self.cwd.clone(),
parsed_cmd: self.parsed_cmd.clone(),
source: self.source,
interaction_input: self.interaction_input.clone(),
})
}
pub(crate) fn as_legacy_end_event(
&self,
turn_id: String,
completed_at_ms: i64,
) -> Option<EventMsg> {
let status = match self.status {
CommandExecutionStatus::InProgress => return None,
CommandExecutionStatus::Completed => ExecCommandStatus::Completed,
CommandExecutionStatus::Failed => ExecCommandStatus::Failed,
CommandExecutionStatus::Declined => ExecCommandStatus::Declined,
};
Some(EventMsg::ExecCommandEnd(ExecCommandEndEvent {
call_id: self.id.clone(),
plugin_id: self.plugin_id.clone(),
script_path: self.script_path.clone(),
process_id: self.process_id.clone(),
turn_id,
completed_at_ms,
command: self.command.clone(),
cwd: self.cwd.clone(),
parsed_cmd: self.parsed_cmd.clone(),
source: self.source,
interaction_input: self.interaction_input.clone(),
aggregated_output: self.aggregated_output.clone().unwrap_or_default(),
exit_code: self.exit_code.unwrap_or_default(),
duration: self.duration.unwrap_or_default(),
status,
}))
}
}
impl DynamicToolCallItem {
pub(crate) fn as_legacy_request_event(&self, turn_id: String, started_at_ms: i64) -> EventMsg {
EventMsg::DynamicToolCallRequest(DynamicToolCallRequest {
call_id: self.id.clone(),
turn_id,
started_at_ms,
namespace: self.namespace.clone(),
tool: self.tool.clone(),
arguments: self.arguments.clone(),
})
}
pub(crate) fn as_legacy_response_event(
&self,
turn_id: String,
completed_at_ms: i64,
) -> Option<EventMsg> {
if matches!(self.status, DynamicToolCallStatus::InProgress) {
return None;
}
Some(EventMsg::DynamicToolCallResponse(
DynamicToolCallResponseEvent {
call_id: self.id.clone(),
turn_id,
completed_at_ms,
namespace: self.namespace.clone(),
tool: self.tool.clone(),
arguments: self.arguments.clone(),
content_items: self.content_items.clone().unwrap_or_default(),
success: self.success.unwrap_or(false),
error: self.error.clone(),
duration: self.duration.unwrap_or_default(),
},
))
}
}
impl CollabAgentToolCallItem {
pub(crate) fn as_legacy_begin_event(&self, started_at_ms: i64) -> Option<EventMsg> {
let receiver_thread_id = self.receiver_thread_ids.first().copied();
match self.tool {
// V2 records these tool items privately, not as legacy UI events.
CollabAgentTool::SendMessage
| CollabAgentTool::FollowupTask
| CollabAgentTool::InterruptAgent
| CollabAgentTool::ListAgents => None,
CollabAgentTool::SpawnAgent => Some(EventMsg::CollabAgentSpawnBegin(
CollabAgentSpawnBeginEvent {
call_id: self.id.clone(),
started_at_ms,
sender_thread_id: self.sender_thread_id,
prompt: self.prompt.clone().unwrap_or_default(),
model: self.model.clone().unwrap_or_default(),
reasoning_effort: self.reasoning_effort.clone().unwrap_or_default(),
},
)),
CollabAgentTool::SendInput => receiver_thread_id.map(|receiver_thread_id| {
EventMsg::CollabAgentInteractionBegin(CollabAgentInteractionBeginEvent {
call_id: self.id.clone(),
started_at_ms,
sender_thread_id: self.sender_thread_id,
receiver_thread_id,
prompt: self.prompt.clone().unwrap_or_default(),
})
}),
CollabAgentTool::ResumeAgent => receiver_thread_id.map(|receiver_thread_id| {
let (receiver_agent_nickname, receiver_agent_role) =
self.receiver_agent_identity(receiver_thread_id);
EventMsg::CollabResumeBegin(CollabResumeBeginEvent {
call_id: self.id.clone(),
started_at_ms,
sender_thread_id: self.sender_thread_id,
receiver_thread_id,
receiver_agent_nickname,
receiver_agent_role,
})
}),
CollabAgentTool::Wait => Some(EventMsg::CollabWaitingBegin(CollabWaitingBeginEvent {
started_at_ms,
sender_thread_id: self.sender_thread_id,
receiver_thread_ids: self.receiver_thread_ids.clone(),
receiver_agents: self.receiver_agents.clone(),
call_id: self.id.clone(),
})),
CollabAgentTool::CloseAgent => receiver_thread_id.map(|receiver_thread_id| {
EventMsg::CollabCloseBegin(CollabCloseBeginEvent {
call_id: self.id.clone(),
started_at_ms,
sender_thread_id: self.sender_thread_id,
receiver_thread_id,
})
}),
}
}
pub(crate) fn as_legacy_end_event(&self, completed_at_ms: i64) -> Option<EventMsg> {
if matches!(self.status, CollabAgentToolCallStatus::InProgress) {
return None;
}
let receiver_thread_id = self.receiver_thread_ids.first().copied();
match self.tool {
CollabAgentTool::SendMessage
| CollabAgentTool::FollowupTask
| CollabAgentTool::InterruptAgent
| CollabAgentTool::ListAgents => None,
CollabAgentTool::SpawnAgent => {
let (new_agent_nickname, new_agent_role) = receiver_thread_id
.map(|thread_id| self.receiver_agent_identity(thread_id))
.unwrap_or_default();
Some(EventMsg::CollabAgentSpawnEnd(CollabAgentSpawnEndEvent {
call_id: self.id.clone(),
completed_at_ms,
sender_thread_id: self.sender_thread_id,
new_thread_id: receiver_thread_id,
new_agent_nickname,
new_agent_role,
prompt: self.prompt.clone().unwrap_or_default(),
model: self.model.clone().unwrap_or_default(),
reasoning_effort: self.reasoning_effort.clone().unwrap_or_default(),
status: receiver_thread_id
.map(|thread_id| self.agent_status(thread_id))
.unwrap_or(AgentStatus::NotFound),
}))
}
CollabAgentTool::SendInput => receiver_thread_id.map(|receiver_thread_id| {
let (receiver_agent_nickname, receiver_agent_role) =
self.receiver_agent_identity(receiver_thread_id);
EventMsg::CollabAgentInteractionEnd(CollabAgentInteractionEndEvent {
call_id: self.id.clone(),
completed_at_ms,
sender_thread_id: self.sender_thread_id,
receiver_thread_id,
receiver_agent_nickname,
receiver_agent_role,
prompt: self.prompt.clone().unwrap_or_default(),
status: self.agent_status(receiver_thread_id),
})
}),
CollabAgentTool::ResumeAgent => receiver_thread_id.map(|receiver_thread_id| {
let (receiver_agent_nickname, receiver_agent_role) =
self.receiver_agent_identity(receiver_thread_id);
EventMsg::CollabResumeEnd(CollabResumeEndEvent {
call_id: self.id.clone(),
completed_at_ms,
sender_thread_id: self.sender_thread_id,
receiver_thread_id,
receiver_agent_nickname,
receiver_agent_role,
status: self.agent_status(receiver_thread_id),
})
}),
CollabAgentTool::Wait => Some(EventMsg::CollabWaitingEnd(CollabWaitingEndEvent {
sender_thread_id: self.sender_thread_id,
call_id: self.id.clone(),
completed_at_ms,
agent_statuses: self
.receiver_agents
.iter()
.map(|agent| CollabAgentStatusEntry {
thread_id: agent.thread_id,
agent_nickname: agent.agent_nickname.clone(),
agent_role: agent.agent_role.clone(),
status: self.agent_status(agent.thread_id),
})
.collect(),
statuses: self.agents_states.clone(),
})),
CollabAgentTool::CloseAgent => receiver_thread_id.map(|receiver_thread_id| {
let (receiver_agent_nickname, receiver_agent_role) =
self.receiver_agent_identity(receiver_thread_id);
EventMsg::CollabCloseEnd(CollabCloseEndEvent {
call_id: self.id.clone(),
completed_at_ms,
sender_thread_id: self.sender_thread_id,
receiver_thread_id,
receiver_agent_nickname,
receiver_agent_role,
status: self.agent_status(receiver_thread_id),
})
}),
}
}
fn receiver_agent_identity(&self, thread_id: ThreadId) -> (Option<String>, Option<String>) {
let receiver_agent = self
.receiver_agents
.iter()
.find(|agent| agent.thread_id == thread_id);
(
receiver_agent.and_then(|agent| agent.agent_nickname.clone()),
receiver_agent.and_then(|agent| agent.agent_role.clone()),
)
}
fn agent_status(&self, thread_id: ThreadId) -> AgentStatus {
self.agents_states
.get(&thread_id)
.cloned()
.unwrap_or(AgentStatus::NotFound)
}
}
impl SubAgentActivityItem {
pub(crate) fn as_legacy_event(&self, occurred_at_ms: i64) -> EventMsg {
EventMsg::SubAgentActivity(SubAgentActivityEvent {
model: self.model.clone(),
reasoning_effort: self.reasoning_effort.clone(),
event_id: self.id.clone(),
occurred_at_ms,
agent_thread_id: self.agent_thread_id,
agent_path: self.agent_path.clone(),
kind: self.kind,
})
}
}
impl WebSearchItem {
pub fn as_legacy_event(&self) -> EventMsg {
EventMsg::WebSearchEnd(WebSearchEndEvent {
call_id: self.id.clone(),
query: self.query.clone(),
action: self.action.clone(),
results: self.results.clone(),
})
}
}
impl ImageGenerationItem {
pub fn as_legacy_event(&self) -> EventMsg {
EventMsg::ImageGenerationEnd(ImageGenerationEndEvent {
call_id: self.id.clone(),
status: self.status.clone(),
revised_prompt: self.revised_prompt.clone(),
image: GeneratedImageRef::Inline {
result: self.result.clone(),
},
transparent_background: None,
failure: None,
saved_path: self.saved_path.clone(),
input_images: Vec::new(),
generation_id: None,
})
}
}
impl FileChangeItem {
pub fn as_legacy_begin_event(&self, turn_id: String) -> EventMsg {
EventMsg::PatchApplyBegin(PatchApplyBeginEvent {
call_id: self.id.clone(),
turn_id,
auto_approved: self.auto_approved.unwrap_or(false),
changes: self.changes.clone(),
})
}
pub fn as_legacy_end_event(&self, turn_id: String) -> Option<EventMsg> {
let status = self.status.clone()?;
Some(EventMsg::PatchApplyEnd(PatchApplyEndEvent {
call_id: self.id.clone(),
turn_id,
stdout: self.stdout.clone().unwrap_or_default(),
stderr: self.stderr.clone().unwrap_or_default(),
success: status == PatchApplyStatus::Completed,
changes: self.changes.clone(),
status,
}))
}
}
impl McpToolCallItem {
pub fn as_legacy_begin_event(&self, turn_id: String) -> EventMsg {
EventMsg::McpToolCallBegin(McpToolCallBeginEvent {
call_id: self.id.clone(),
turn_id,
invocation: McpInvocation {
server: self.server.clone(),
tool: self.tool.clone(),
arguments: (!self.arguments.is_null()).then(|| self.arguments.clone()),
},
connector_id: self.connector_id.clone(),
mcp_app_resource_uri: self.mcp_app_resource_uri.clone(),
mcp_app_ui: self.mcp_app_ui.clone(),
link_id: self.link_id.clone(),
app_name: self.app_name.clone(),
action_name: self.action_name.clone(),
plugin_id: self.plugin_id.clone(),
read_only_hint: self.read_only_hint,
})
}
pub fn as_legacy_end_event(&self, turn_id: String) -> Option<EventMsg> {
let result = match (&self.result, &self.error) {
(Some(result), _) => Ok(result.clone()),
(None, Some(error)) => Err(error.message.clone()),
(None, None) => return None,
};
Some(EventMsg::McpToolCallEnd(McpToolCallEndEvent {
call_id: self.id.clone(),
turn_id,
invocation: McpInvocation {
server: self.server.clone(),
tool: self.tool.clone(),
arguments: (!self.arguments.is_null()).then(|| self.arguments.clone()),
},
mcp_app_resource_uri: self.mcp_app_resource_uri.clone(),
mcp_app_ui: self.mcp_app_ui.clone(),
connector_id: self.connector_id.clone(),
link_id: self.link_id.clone(),
app_name: self.app_name.clone(),
action_name: self.action_name.clone(),
plugin_id: self.plugin_id.clone(),
read_only_hint: self.read_only_hint,
duration: self.duration?,
result,
}))
}
}
impl TurnItem {
pub fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec<EventMsg> {
match self {
TurnItem::UserMessage(item) => vec![item.as_legacy_event()],
TurnItem::FunctionCallOutput(_) | TurnItem::HookPrompt(_) => Vec::new(),
TurnItem::AgentMessage(item) => item.as_legacy_events(),
TurnItem::Plan(_) => Vec::new(),
TurnItem::CommandExecution(_)
| TurnItem::DynamicToolCall(_)
| TurnItem::CollabAgentToolCall(_) => Vec::new(),
TurnItem::SubAgentActivity(_) => Vec::new(),
TurnItem::WebSearch(item) => vec![item.as_legacy_event()],
TurnItem::ImageView(item) => {
vec![EventMsg::ViewImageToolCall(ViewImageToolCallEvent {
call_id: item.id.clone(),
path: item.path.clone(),
})]
}
TurnItem::Extension(_) => Vec::new(),
TurnItem::ImageGeneration(item) => vec![item.as_legacy_event()],
TurnItem::EnteredReviewMode(_) | TurnItem::ExitedReviewMode(_) => Vec::new(),
TurnItem::FileChange(item) => item
.as_legacy_end_event(String::new())
.into_iter()
.collect(),
TurnItem::McpToolCall(item) => item
.as_legacy_end_event(String::new())
.into_iter()
.collect(),
TurnItem::Reasoning(item) => item.as_legacy_events(show_raw_agent_reasoning),
TurnItem::ContextCompaction(item) => vec![item.as_legacy_event()],
}
}
}
impl HasLegacyEvent for ItemStartedEvent {
fn as_legacy_events(&self, _: bool) -> Vec<EventMsg> {
match &self.item {
TurnItem::WebSearch(item) => vec![EventMsg::WebSearchBegin(WebSearchBeginEvent {
call_id: item.id.clone(),
})],
TurnItem::ImageView(_) => Vec::new(),
TurnItem::ImageGeneration(item) => {
vec![EventMsg::ImageGenerationBegin(ImageGenerationBeginEvent {
call_id: item.id.clone(),
})]
}
TurnItem::FileChange(item) => vec![item.as_legacy_begin_event(self.turn_id.clone())],
TurnItem::McpToolCall(item) => vec![item.as_legacy_begin_event(self.turn_id.clone())],
TurnItem::CommandExecution(item) => {
vec![item.as_legacy_begin_event(self.turn_id.clone(), self.started_at_ms)]
}
TurnItem::DynamicToolCall(item) => {
vec![item.as_legacy_request_event(self.turn_id.clone(), self.started_at_ms)]
}
TurnItem::CollabAgentToolCall(item) => item
.as_legacy_begin_event(self.started_at_ms)
.into_iter()
.collect(),
_ => Vec::new(),
}
}
}
impl HasLegacyEvent for ItemCompletedEvent {
fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec<EventMsg> {
match &self.item {
TurnItem::McpToolCall(item) => item
.as_legacy_end_event(self.turn_id.clone())
.into_iter()
.collect(),
TurnItem::FileChange(item) => item
.as_legacy_end_event(self.turn_id.clone())
.into_iter()
.collect(),
TurnItem::CommandExecution(item) => item
.as_legacy_end_event(self.turn_id.clone(), self.completed_at_ms)
.into_iter()
.collect(),
TurnItem::DynamicToolCall(item) => item
.as_legacy_response_event(self.turn_id.clone(), self.completed_at_ms)
.into_iter()
.collect(),
TurnItem::CollabAgentToolCall(item) => item
.as_legacy_end_event(self.completed_at_ms)
.into_iter()
.collect(),
TurnItem::SubAgentActivity(item) => {
vec![item.as_legacy_event(self.completed_at_ms)]
}
TurnItem::EnteredReviewMode(item) => {
vec![item.as_legacy_event(self.turn_id.clone())]
}
TurnItem::ExitedReviewMode(item) => {
vec![item.as_legacy_event(self.turn_id.clone())]
}
_ => self.item.as_legacy_events(show_raw_agent_reasoning),
}
}
}
impl HasLegacyEvent for AgentMessageContentDeltaEvent {
fn as_legacy_events(&self, _: bool) -> Vec<EventMsg> {
Vec::new()
}
}
impl HasLegacyEvent for ReasoningContentDeltaEvent {
fn as_legacy_events(&self, _: bool) -> Vec<EventMsg> {
Vec::new()
}
}
impl HasLegacyEvent for ReasoningRawContentDeltaEvent {
fn as_legacy_events(&self, _: bool) -> Vec<EventMsg> {
Vec::new()
}
}
impl HasLegacyEvent for EventMsg {
fn as_legacy_events(&self, show_raw_agent_reasoning: bool) -> Vec<EventMsg> {
match self {
EventMsg::ItemStarted(event) => event.as_legacy_events(show_raw_agent_reasoning),
EventMsg::ItemCompleted(event) => event.as_legacy_events(show_raw_agent_reasoning),
EventMsg::AgentMessageContentDelta(event) => {
event.as_legacy_events(show_raw_agent_reasoning)
}
EventMsg::ReasoningContentDelta(event) => {
event.as_legacy_events(show_raw_agent_reasoning)
}
EventMsg::ReasoningRawContentDelta(event) => {
event.as_legacy_events(show_raw_agent_reasoning)
}
_ => Vec::new(),
}
}
}

View File

@@ -0,0 +1,65 @@
pub mod account;
mod agent_path;
pub mod auth;
mod context_window_id;
mod item_id_generator;
mod response_item_id;
mod response_usage;
mod sanitized_git_url;
mod session_id;
mod thread_id;
mod tool_name;
pub use agent_path::AgentPath;
pub use context_window_id::ContextWindowId;
pub use item_id_generator::ItemIdGenerator;
#[cfg(test)]
use item_id_generator::uuid_v7_item_id_generator_for_test;
pub use permission_profile_intersection::PermissionIntersectionError;
pub use permission_profile_intersection::intersect_effective_permission_profiles;
pub use response_item_id::ResponseItemId;
pub use response_usage::ResponseUsageMetadata;
pub use sanitized_git_url::SanitizedGitUrl;
pub use session_id::SessionId;
pub use thread_id::RolloutId;
pub use thread_id::ThreadId;
pub use tool_name::DEFAULT_FUNCTION_NAMESPACE;
pub use tool_name::ToolName;
pub mod approvals;
pub mod capabilities;
mod codex_error_info;
pub mod config_types;
mod guardian_transcript;
pub use guardian_transcript::TranscriptFormat;
pub mod dynamic_tools;
mod environment;
pub mod error;
pub mod exec_output;
pub mod hooks;
pub mod items;
mod legacy_events;
pub mod local_media;
pub mod mcp;
pub mod mcp_approval_meta;
pub mod mcp_policy;
pub mod memory_citation;
mod memory_version;
pub use memory_version::MemoryVersion;
pub mod models;
pub mod network_policy;
pub mod num_format;
pub mod openai_models;
pub mod parse_command;
mod permission_profile_intersection;
mod permission_profile_snapshot;
pub mod permissions;
pub mod plan_tool;
pub mod protocol;
pub mod realtime;
pub mod request_permissions;
pub mod request_user_input;
pub mod review_format;
pub mod sandbox;
pub mod security_risk;
pub mod shell_environment;
pub mod turn_input;
pub mod user_input;

View File

@@ -0,0 +1,99 @@
use std::io;
use std::io::Read;
use std::path::Path;
use akode_utils_image::MAX_PROMPT_IMAGE_INPUT_BYTES;
use akode_utils_image::PromptImageMode;
use akode_utils_image::data_url_from_bytes;
use akode_utils_image::load_for_prompt_bytes;
use crate::models::AudioReference;
use crate::models::ImageDetail;
use crate::models::ImageReference;
use crate::user_input::UserInput;
/// Maximum accepted decoded byte length for prompt audio inputs.
///
/// This matches the Responses API audio input limit.
pub const MAX_PROMPT_AUDIO_INPUT_BYTES: usize = 50 * 1024 * 1024;
/// Snapshots local image and audio input into portable, validated data URLs.
pub fn snapshot_local_user_input(input: &mut UserInput) -> io::Result<()> {
match input {
UserInput::LocalImage { path, detail } => {
let image_detail = *detail;
let mode = match image_detail {
Some(ImageDetail::Original) => PromptImageMode::Original,
Some(ImageDetail::Auto | ImageDetail::Low | ImageDetail::High) | None => {
PromptImageMode::ResizeToFit
}
};
let file_bytes = read_bounded_local_media(path, MAX_PROMPT_IMAGE_INPUT_BYTES, "image")?;
let image = load_for_prompt_bytes(path, file_bytes, mode).map_err(io::Error::other)?;
*input = UserInput::Image {
image: ImageReference::Inline {
image_url: image.into_data_url(),
},
detail: image_detail,
};
}
UserInput::LocalAudio { path } => {
let mime = audio_mime_for_path(path).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "unsupported audio format")
})?;
let file_bytes = read_bounded_local_media(path, MAX_PROMPT_AUDIO_INPUT_BYTES, "audio")?;
*input = UserInput::Audio {
audio: AudioReference::Inline {
audio_url: data_url_from_bytes(mime, &file_bytes),
},
};
}
UserInput::Text { .. }
| UserInput::Image { .. }
| UserInput::Audio { .. }
| UserInput::Skill { .. }
| UserInput::Mention { .. } => {}
}
Ok(())
}
fn read_bounded_local_media(path: &Path, max_bytes: usize, kind: &str) -> io::Result<Vec<u8>> {
let file = std::fs::File::open(path)?;
if file.metadata()?.len() > max_bytes as u64 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("{kind} input exceeds {max_bytes} bytes"),
));
}
let mut bytes = Vec::new();
file.take(max_bytes as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > max_bytes {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("{kind} input exceeds {max_bytes} bytes"),
));
}
Ok(bytes)
}
pub(crate) fn audio_mime_for_path(path: &Path) -> Option<&'static str> {
let extension = path.extension()?.to_str()?;
if extension.eq_ignore_ascii_case("wav") {
Some("audio/wav")
} else if extension.eq_ignore_ascii_case("mp3") {
Some("audio/mpeg")
} else if extension.eq_ignore_ascii_case("m4a") {
Some("audio/mp4")
} else if extension.eq_ignore_ascii_case("webm") {
Some("audio/webm")
} else if extension.eq_ignore_ascii_case("ogg") {
Some("audio/ogg")
} else {
None
}
}
#[cfg(test)]
#[path = "local_media_tests.rs"]
mod tests;

View File

@@ -0,0 +1,132 @@
use super::*;
use anyhow::Result;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
const TINY_PNG_BYTES: &[u8] = &[
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0,
0, 0, 31, 21, 196, 137, 0, 0, 0, 11, 73, 68, 65, 84, 120, 156, 99, 96, 0, 2, 0, 0, 5, 0, 1,
122, 94, 171, 63, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
];
#[test]
fn snapshots_local_image_user_input_with_requested_detail() -> Result<()> {
let temp_dir = tempdir()?;
let image_path = temp_dir.path().join("sample.png");
std::fs::write(&image_path, TINY_PNG_BYTES)?;
for detail in [
None,
Some(ImageDetail::Auto),
Some(ImageDetail::Low),
Some(ImageDetail::High),
Some(ImageDetail::Original),
] {
let mut input = UserInput::LocalImage {
path: image_path.clone(),
detail,
};
snapshot_local_user_input(&mut input)?;
assert_eq!(
UserInput::Image {
image: crate::models::ImageReference::Inline {
image_url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII="
.to_string(),
},
detail,
},
input
);
}
Ok(())
}
#[test]
fn snapshots_local_audio_user_input_with_supported_mime_types() -> Result<()> {
let temp_dir = tempdir()?;
for (extension, mime) in [
("wav", "audio/wav"),
("MP3", "audio/mpeg"),
("m4a", "audio/mp4"),
("webm", "audio/webm"),
("ogg", "audio/ogg"),
] {
let audio_path = temp_dir.path().join(format!("sample.{extension}"));
std::fs::write(&audio_path, b"audio")?;
let mut input = UserInput::LocalAudio { path: audio_path };
snapshot_local_user_input(&mut input)?;
assert_eq!(
UserInput::Audio {
audio: AudioReference::Inline {
audio_url: format!("data:{mime};base64,YXVkaW8=")
},
},
input
);
}
Ok(())
}
#[test]
fn rejects_invalid_local_media_without_changing_user_input() -> Result<()> {
let temp_dir = tempdir()?;
let invalid_image_path = temp_dir.path().join("invalid.png");
let unsupported_audio_path = temp_dir.path().join("unsupported.flac");
std::fs::write(&invalid_image_path, b"invalid image")?;
std::fs::write(&unsupported_audio_path, b"audio")?;
let mut invalid_image = UserInput::LocalImage {
path: invalid_image_path,
detail: Some(ImageDetail::Original),
};
let original_image = invalid_image.clone();
let image_error = snapshot_local_user_input(&mut invalid_image)
.expect_err("an invalid local image must be rejected");
assert_eq!(io::ErrorKind::Other, image_error.kind());
assert_eq!(original_image, invalid_image);
let mut unsupported_audio = UserInput::LocalAudio {
path: unsupported_audio_path,
};
let original_audio = unsupported_audio.clone();
let audio_error = snapshot_local_user_input(&mut unsupported_audio)
.expect_err("an unsupported local audio format must be rejected");
assert_eq!(io::ErrorKind::InvalidData, audio_error.kind());
assert_eq!(original_audio, unsupported_audio);
Ok(())
}
#[test]
fn rejects_oversized_local_media_without_reading_it() -> Result<()> {
let temp_dir = tempdir()?;
for (name, limit, is_image) in [
("oversized.png", MAX_PROMPT_IMAGE_INPUT_BYTES, true),
("oversized.mp3", MAX_PROMPT_AUDIO_INPUT_BYTES, false),
] {
let path = temp_dir.path().join(name);
std::fs::File::create(&path)?.set_len(limit as u64 + 1)?;
let mut input = if is_image {
UserInput::LocalImage { path, detail: None }
} else {
UserInput::LocalAudio { path }
};
let original = input.clone();
let error = snapshot_local_user_input(&mut input)
.expect_err("oversized local media must be rejected before it is read");
assert_eq!(io::ErrorKind::InvalidData, error.kind());
assert_eq!(original, input);
}
Ok(())
}

View File

@@ -0,0 +1,627 @@
//! Types used when representing Model Context Protocol (MCP) values inside the
//! Codex protocol.
//!
//! We intentionally keep these types TS/JSON-schema friendly (via `ts-rs` and
//! `schemars`) so they can be embedded in Codex's own protocol structures.
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use std::collections::HashMap;
use ts_rs::TS;
/// Observed state of an MCP connection in a published thread runtime.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
pub enum McpServerConnectionStatus {
NotStarted,
Starting,
Connected,
AuthenticationRequired,
Failed,
Cancelled,
Disabled,
}
/// Extension ID for OpenAI elicitation modes.
pub const OPENAI_ELICITATION_EXTENSION_ID: &str = "openai/elicitation";
/// Extension ID for legacy OpenAI form elicitation.
pub const OPENAI_FORM_EXTENSION_ID: &str = "openai/form";
/// Extension ID for standard MCP form elicitations that require user-entered input.
pub const OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID: &str = "openai/standard-form-input";
/// Extension ID for MCP App UI rendering.
pub const MCP_APP_UI_EXTENSION_ID: &str = "io.modelcontextprotocol/ui";
/// Host-supplied confirmation-policy documents for Node REPL-backed actor calls.
pub const CONFIRMATION_POLICIES_META_KEY: &str = "openai/confirmation_policies";
/// Returns whether a raw MCP server name identifies a Node REPL-backed server.
pub fn is_node_repl_backed_server(server: &str) -> bool {
matches!(server, "node_repl" | "cua_repl")
}
/// Recognizes Node REPL-backed tools in model-visible MCP namespaces or legacy
/// flat tool names. An explicit namespace takes precedence over the tool name.
pub fn is_node_repl_backed_tool(name: &str, namespace: Option<&str>) -> bool {
if let Some(namespace) = namespace {
let namespace = namespace.strip_prefix("mcp__").unwrap_or(namespace);
return is_node_repl_backed_server(namespace.strip_suffix("__").unwrap_or(namespace));
}
let name = name.strip_prefix("mcp__").unwrap_or(name);
name.split_once("__")
.is_some_and(|(server, _)| is_node_repl_backed_server(server))
}
/// Producer-reported completeness of the thread's MCP tools/call attribution.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum McpAttributionStatus {
#[default]
None,
Complete,
AttributionError,
}
/// Bounded diagnostics for an attribution error, never a policy decision.
///
/// Recorder reasons identify the first observed error and survive checkpoints.
/// Payload reasons describe a request-serialization fallback and are not checkpointed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum McpAttributionErrorReason {
HistoryMissingCheckpoint,
CheckpointInvalid,
CheckpointSourceConflict,
SourceInvalid,
RecorderPoisoned,
/// An earlier error checkpoint did not retain its cause.
RestoredErrorUnknown,
PayloadTooLarge,
SerializationFailed,
#[serde(other)]
Unknown,
}
/// One source and the first runtime turn in which Codex recorded it.
///
/// Server and tool names are retained when no stable identifier is available;
/// they are not guaranteed to be globally unique or independently authenticated.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct McpAttributionSource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub connector_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub plugin_id: Option<String>,
pub server_name: String,
pub tool_name: String,
pub first_turn_id: String,
}
/// Cumulative, model-invisible attribution reported on Responses API requests.
/// This is provenance data, not a training-eligibility decision or attestation.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct McpAttribution {
pub status: McpAttributionStatus,
/// First observed attribution error, absent for non-error states.
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_mcp_attribution_error_reason"
)]
pub error_reason: Option<McpAttributionErrorReason>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sources: Vec<McpAttributionSource>,
}
fn deserialize_mcp_attribution_error_reason<'de, D>(
deserializer: D,
) -> Result<Option<McpAttributionErrorReason>, D::Error>
where
D: Deserializer<'de>,
{
let value = serde_json::Value::deserialize(deserializer)?;
Ok(serde_json::from_value(value).ok())
}
/// Bounded app-resource provenance retained across a compaction checkpoint.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct McpResourceOriginCheckpoint {
pub origins: Vec<McpResourceOrigin>,
pub turns: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub current_turn_id: Option<String>,
}
/// The original app, account, tool, and URI that authorize one widget read.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct McpResourceOrigin {
pub call_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub turn_id: Option<String>,
pub tool: String,
pub connector_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub link_id: Option<String>,
pub uri: String,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub ambiguous_account: bool,
}
/// Client extensions that must not be advertised to MCP servers.
const MCP_CLIENT_ONLY_EXTENSION_IDS: [&str; 1] = [OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID];
/// MCP extensions supplied by the client that created a Codex session.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ClientMcpExtensions {
extensions: HashMap<String, serde_json::Value>,
}
impl ClientMcpExtensions {
/// Creates a session extension set from trusted client declarations.
pub fn new(extensions: impl IntoIterator<Item = (String, serde_json::Value)>) -> Self {
Self {
extensions: extensions.into_iter().collect(),
}
}
/// Returns whether the client declared the given extension.
pub fn contains(&self, extension_id: &str) -> bool {
self.extensions.contains_key(extension_id)
}
/// Returns the client's settings for the given extension.
pub fn get(&self, extension_id: &str) -> Option<&serde_json::Value> {
self.extensions.get(extension_id)
}
/// Returns only client extensions that should be advertised to MCP servers.
pub fn for_mcp_servers(&self) -> Self {
Self::new(
self.extensions
.iter()
.filter(|(id, _)| !MCP_CLIENT_ONLY_EXTENSION_IDS.contains(&id.as_str()))
.map(|(id, settings)| (id.clone(), settings.clone())),
)
}
/// Iterates over the extensions and their settings.
pub fn iter(&self) -> impl Iterator<Item = (&str, &serde_json::Value)> {
self.extensions
.iter()
.map(|(id, settings)| (id.as_str(), settings))
}
}
/// ID of a request, which can be either a string or an integer.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, TS)]
#[serde(untagged)]
pub enum RequestId {
String(String),
#[ts(type = "number")]
Integer(i64),
}
impl std::fmt::Display for RequestId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RequestId::String(s) => f.write_str(s),
RequestId::Integer(i) => i.fmt(f),
}
}
}
/// Presentation metadata advertised by an initialized MCP server.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct McpServerInfo {
pub name: String,
pub title: Option<String>,
pub version: String,
pub description: Option<String>,
pub icons: Option<Vec<serde_json::Value>>,
pub website_url: Option<String>,
}
/// Definition for a tool the client can call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct Tool {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub title: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub description: Option<String>,
pub input_schema: serde_json::Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub output_schema: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub annotations: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub icons: Option<Vec<serde_json::Value>>,
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub meta: Option<serde_json::Value>,
}
/// A known resource that the server is capable of reading.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub annotations: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub mime_type: Option<String>,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
#[ts(type = "number")]
pub size: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub title: Option<String>,
pub uri: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub icons: Option<Vec<serde_json::Value>>,
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub meta: Option<serde_json::Value>,
}
/// Contents returned when reading a resource from an MCP server.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, TS)]
#[serde(untagged)]
pub enum ResourceContent {
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
Text {
/// The URI of this resource.
uri: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
mime_type: Option<String>,
text: String,
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
meta: Option<serde_json::Value>,
},
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
Blob {
/// The URI of this resource.
uri: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
mime_type: Option<String>,
blob: String,
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
meta: Option<serde_json::Value>,
},
}
/// A template description for resources available on the server.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct ResourceTemplate {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub annotations: Option<serde_json::Value>,
pub uri_template: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub title: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub mime_type: Option<String>,
}
/// The server's response to a tool call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct CallToolResult {
pub content: Vec<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub structured_content: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub is_error: Option<bool>,
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub meta: Option<serde_json::Value>,
}
// === Adapter helpers ===
//
// These types and conversions intentionally live in `akode-protocol` so other crates can convert
// “wire-shaped” MCP JSON (typically coming from rmcp model structs serialized with serde) into our
// TS/JsonSchema-friendly protocol types without depending on `mcp-types`.
fn deserialize_lossy_opt_i64<'de, D>(deserializer: D) -> Result<Option<i64>, D::Error>
where
D: serde::Deserializer<'de>,
{
match Option::<serde_json::Number>::deserialize(deserializer)? {
Some(number) => {
if let Some(v) = number.as_i64() {
Ok(Some(v))
} else if let Some(v) = number.as_u64() {
Ok(i64::try_from(v).ok())
} else {
Ok(None)
}
}
None => Ok(None),
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ToolSerde {
name: String,
#[serde(default)]
title: Option<String>,
#[serde(default)]
description: Option<String>,
#[serde(default, rename = "inputSchema", alias = "input_schema")]
input_schema: serde_json::Value,
#[serde(default, rename = "outputSchema", alias = "output_schema")]
output_schema: Option<serde_json::Value>,
#[serde(default)]
annotations: Option<serde_json::Value>,
#[serde(default)]
icons: Option<Vec<serde_json::Value>>,
#[serde(rename = "_meta", default)]
meta: Option<serde_json::Value>,
}
impl From<ToolSerde> for Tool {
fn from(value: ToolSerde) -> Self {
let ToolSerde {
name,
title,
description,
input_schema,
output_schema,
annotations,
icons,
meta,
} = value;
Self {
name,
title,
description,
input_schema,
output_schema,
annotations,
icons,
meta,
}
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ResourceSerde {
#[serde(default)]
annotations: Option<serde_json::Value>,
#[serde(default)]
description: Option<String>,
#[serde(rename = "mimeType", alias = "mime_type", default)]
mime_type: Option<String>,
name: String,
#[serde(default, deserialize_with = "deserialize_lossy_opt_i64")]
size: Option<i64>,
#[serde(default)]
title: Option<String>,
uri: String,
#[serde(default)]
icons: Option<Vec<serde_json::Value>>,
#[serde(rename = "_meta", default)]
meta: Option<serde_json::Value>,
}
impl From<ResourceSerde> for Resource {
fn from(value: ResourceSerde) -> Self {
let ResourceSerde {
annotations,
description,
mime_type,
name,
size,
title,
uri,
icons,
meta,
} = value;
Self {
annotations,
description,
mime_type,
name,
size,
title,
uri,
icons,
meta,
}
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ResourceTemplateSerde {
#[serde(default)]
annotations: Option<serde_json::Value>,
#[serde(rename = "uriTemplate", alias = "uri_template")]
uri_template: String,
name: String,
#[serde(default)]
title: Option<String>,
#[serde(default)]
description: Option<String>,
#[serde(rename = "mimeType", alias = "mime_type", default)]
mime_type: Option<String>,
}
impl From<ResourceTemplateSerde> for ResourceTemplate {
fn from(value: ResourceTemplateSerde) -> Self {
let ResourceTemplateSerde {
annotations,
uri_template,
name,
title,
description,
mime_type,
} = value;
Self {
annotations,
uri_template,
name,
title,
description,
mime_type,
}
}
}
impl Tool {
pub fn from_mcp_value(value: serde_json::Value) -> Result<Self, serde_json::Error> {
Ok(serde_json::from_value::<ToolSerde>(value)?.into())
}
}
impl Resource {
pub fn from_mcp_value(value: serde_json::Value) -> Result<Self, serde_json::Error> {
Ok(serde_json::from_value::<ResourceSerde>(value)?.into())
}
}
impl ResourceTemplate {
pub fn from_mcp_value(value: serde_json::Value) -> Result<Self, serde_json::Error> {
Ok(serde_json::from_value::<ResourceTemplateSerde>(value)?.into())
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn node_repl_backed_tool_recognizes_namespaces_and_legacy_names() {
for (name, namespace, expected) in [
("read_file", Some("mcp__node_repl"), true),
("read_file", Some("mcp__node_repl__"), true),
("read_file", Some("node_repl"), true),
("read_file", Some("node_repl__"), true),
("read_file", Some("mcp__cua_repl"), true),
("read_file", Some("mcp__cua_repl__"), true),
("read_file", Some("cua_repl"), true),
("read_file", Some("cua_repl__"), true),
("read_file", Some("node_repl_"), false),
("read_file", Some("cua_repl_"), false),
("read_file", Some("mcp__node_repl____"), false),
("read_file", Some("mcp__cua_repl____"), false),
("mcp__node_repl__js", None, true),
("node_repl__js", None, true),
("mcp__cua_repl__js", None, true),
("cua_repl__js", None, true),
("mcp__node_repl__js", Some("other"), false),
("mcp__cua_repl__js", Some("other"), false),
("mcp__node_repl_other__js", None, false),
("mcp__cua_repl_other__js", None, false),
] {
assert_eq!(
is_node_repl_backed_tool(name, namespace),
expected,
"tool {name} in namespace {namespace:?}"
);
}
}
#[test]
fn client_mcp_extensions_for_mcp_servers_excludes_client_only_extensions() {
let openai_form_settings = serde_json::json!({ "version": 1 });
let app_ui_settings = serde_json::json!({ "mimeTypes": ["text/html"] });
let future_server_extension_settings = serde_json::json!({ "version": 2 });
let extensions = ClientMcpExtensions::new([
(
OPENAI_FORM_EXTENSION_ID.to_string(),
openai_form_settings.clone(),
),
(MCP_APP_UI_EXTENSION_ID.to_string(), app_ui_settings.clone()),
(
OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID.to_string(),
serde_json::json!({}),
),
(
"example/future-server-extension".to_string(),
future_server_extension_settings.clone(),
),
]);
assert_eq!(
extensions.for_mcp_servers(),
ClientMcpExtensions::new([
(OPENAI_FORM_EXTENSION_ID.to_string(), openai_form_settings),
(MCP_APP_UI_EXTENSION_ID.to_string(), app_ui_settings),
(
"example/future-server-extension".to_string(),
future_server_extension_settings,
),
])
);
}
#[test]
fn resource_size_deserializes_without_narrowing() {
let resource = serde_json::json!({
"name": "big",
"uri": "file:///tmp/big",
"size": 5_000_000_000u64,
});
let parsed = Resource::from_mcp_value(resource).expect("should deserialize");
assert_eq!(parsed.size, Some(5_000_000_000));
let resource = serde_json::json!({
"name": "negative",
"uri": "file:///tmp/negative",
"size": -1,
});
let parsed = Resource::from_mcp_value(resource).expect("should deserialize");
assert_eq!(parsed.size, Some(-1));
let resource = serde_json::json!({
"name": "too_big_for_i64",
"uri": "file:///tmp/too_big_for_i64",
"size": 18446744073709551615u64,
});
let parsed = Resource::from_mcp_value(resource).expect("should deserialize");
assert_eq!(parsed.size, None);
}
}

View File

@@ -0,0 +1,42 @@
/// Identifies privileged Codex approvals. Changing this key or adding another
/// privileged discriminator requires updating the MCP elicitation router's
/// form-forwarding safeguards.
pub const APPROVAL_KIND_KEY: &str = "codex_approval_kind";
pub const APPROVAL_KIND_MCP_TOOL_CALL: &str = "mcp_tool_call";
pub const APPROVAL_KIND_BROWSER_AUTH: &str = "browser_auth";
pub const APPROVAL_KIND_TOOL_SUGGESTION: &str = "tool_suggestion";
/// Marks requests that need user input even when their form schema is empty.
pub const REQUIRES_USER_INPUT_KEY: &str = "codex_requires_user_input";
pub const REQUEST_TYPE_KEY: &str = "codex_request_type";
pub const REQUEST_TYPE_APPROVAL_REQUEST: &str = "approval_request";
pub const STRICT_AUTO_REVIEW_KEY: &str = "codex_strict_auto_review";
/// Marks a sensitive action requiring synchronous review when routed to automatic review.
/// Absent or false preserves the existing approval path; this does not opt into review.
pub const SENSITIVE_ACTION_KEY: &str = "codex_sensitive_action";
pub const APPROVALS_REVIEWER_KEY: &str = "approvals_reviewer";
pub const PERSIST_KEY: &str = "persist";
pub const PERSIST_SESSION: &str = "session";
pub const PERSIST_ALWAYS: &str = "always";
/// Set where cancellation originates, before user actions and runtime failures
/// are flattened into the same elicitation action. Absence means unknown.
pub const CANCELLATION_REASON_KEY: &str = "codex_approval_cancellation_reason";
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum McpApprovalCancellationReason {
User,
Interrupted,
NonInteractive,
}
pub const SOURCE_KEY: &str = "source";
pub const SOURCE_CONNECTOR: &str = "connector";
pub const CONNECTOR_ID_KEY: &str = "connector_id";
pub const CONNECTOR_NAME_KEY: &str = "connector_name";
pub const CONNECTOR_DESCRIPTION_KEY: &str = "connector_description";
pub const TOOL_NAME_KEY: &str = "tool_name";
pub const TOOL_ANNOTATIONS_KEY: &str = "tool_annotations";
pub const TOOL_TITLE_KEY: &str = "tool_title";
pub const TOOL_DESCRIPTION_KEY: &str = "tool_description";
pub const TOOL_PARAMS_KEY: &str = "tool_params";
pub const TOOL_PARAMS_DISPLAY_KEY: &str = "tool_params_display";

View File

@@ -0,0 +1,96 @@
use serde::Deserialize;
use std::collections::BTreeMap;
/// Additional managed MCP restrictions supplied by an environment owner.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EnvironmentMcpPolicy {
pub servers: Option<BTreeMap<String, McpServerRequirement>>,
pub plugins: Option<BTreeMap<String, PluginMcpRequirements>>,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(untagged)]
pub enum McpServerIdentity {
Command { command: String },
Url { url: String },
}
/// String matching operations available to managed MCP server matchers.
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(tag = "match", rename_all = "snake_case", deny_unknown_fields)]
pub enum McpServerValueMatcher {
Exact { value: String },
Prefix { value: String },
Regex { expression: String },
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct McpServerCommandMatcher {
pub executable: String,
pub args: Vec<McpServerValueMatcher>,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
struct RawMcpServerCommandIdentity {
command: McpServerCommandMatcher,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
struct RawMcpServerUrlIdentity {
url: McpServerValueMatcher,
}
/// A requirement for one named MCP server.
///
/// The `Identity` variant preserves the released exact-match contract. The
/// command and URL variants are the normalized matcher-based forms accepted
/// under the `identity` key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum McpServerRequirement {
Identity { identity: McpServerIdentity },
Command(McpServerCommandMatcher),
Url(McpServerValueMatcher),
}
#[derive(Deserialize)]
struct RawMcpServerRequirement {
identity: RawMcpServerIdentity,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum RawMcpServerIdentity {
Exact(McpServerIdentity),
Command(RawMcpServerCommandIdentity),
Url(RawMcpServerUrlIdentity),
}
impl<'de> Deserialize<'de> for McpServerRequirement {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let RawMcpServerRequirement { identity } =
RawMcpServerRequirement::deserialize(deserializer)?;
match identity {
RawMcpServerIdentity::Exact(identity) => Ok(Self::Identity { identity }),
RawMcpServerIdentity::Command(matcher) => Ok(Self::Command(matcher.command)),
RawMcpServerIdentity::Url(matcher) => Ok(Self::Url(matcher.url)),
}
}
}
/// Managed MCP server requirements for one plugin.
#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct PluginMcpRequirements {
pub mcp_servers: Option<BTreeMap<String, McpServerRequirement>>,
}
impl PluginMcpRequirements {
pub fn is_empty(&self) -> bool {
self.mcp_servers.as_ref().is_none_or(BTreeMap::is_empty)
}
}

View File

@@ -0,0 +1,20 @@
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct MemoryCitation {
pub entries: Vec<MemoryCitationEntry>,
pub rollout_ids: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
pub struct MemoryCitationEntry {
pub path: String,
pub line_start: u32,
pub line_end: u32,
pub note: String,
}

View File

@@ -0,0 +1,23 @@
//! Selects a coherent memory pipeline and its generated-artifact namespace.
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum MemoryVersion {
#[default]
V1,
V2,
}
impl MemoryVersion {
/// Sibling roots keep v1 cleanup and rollback independent of v2 artifacts.
pub fn directory_name(self) -> &'static str {
match self {
Self::V1 => "memories",
Self::V2 => "memories_v2",
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,17 @@
//! Typed reasoning settings for a durable Responses API configuration update.
use crate::openai_models::ReasoningEffort;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
/// Reasoning settings interpreted by the backend for the routed model.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema, TS)]
pub struct ConfigurationReasoning {
pub effort: ReasoningEffort,
}
#[cfg(test)]
#[path = "configuration_update_tests.rs"]
mod tests;

View File

@@ -0,0 +1,51 @@
use super::ConfigurationReasoning;
use crate::models::ResponseItem;
use crate::openai_models::ReasoningEffort;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn configuration_update_round_trips_without_message_fields() {
let value = json!({
"type": "configuration_update",
"reasoning": { "effort": "high" }
});
let mut item: ResponseItem = serde_json::from_value(value.clone()).unwrap();
assert_eq!(
item,
ResponseItem::ConfigurationUpdate {
reasoning: ConfigurationReasoning {
effort: ReasoningEffort::High,
},
}
);
item.set_id(Some(crate::uuid_v7_item_id_generator_for_test()(
"configuration-id",
)));
item.set_turn_id_if_missing("turn-id");
item.set_create_time_if_missing(serde_json::Number::from(123));
assert_eq!(
(item.id(), item.id_prefix(), item.turn_id()),
(None, None, None)
);
assert_eq!(serde_json::to_value(item).unwrap(), value);
}
#[test]
fn configuration_update_preserves_model_defined_effort() {
let value = json!({
"type": "configuration_update",
"reasoning": { "effort": "model-specific" }
});
let item: ResponseItem = serde_json::from_value(value.clone()).unwrap();
assert_eq!(
item,
ResponseItem::ConfigurationUpdate {
reasoning: ConfigurationReasoning {
effort: ReasoningEffort::Custom("model-specific".to_string()),
},
}
);
assert_eq!(serde_json::to_value(item).unwrap(), value);
}

View File

@@ -0,0 +1,877 @@
use std::collections::HashSet;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
use super::InternalChatMessageMetadataPassthrough;
use super::ResponseItem;
/// Maximum distinct result sources retained for one tool invocation.
const MAX_TOOL_RESULT_SOURCES: usize = 32;
/// Maximum UTF-8 bytes for each source's `type` and `id` separately, not the source list.
pub const MAX_TOOL_RESULT_SOURCE_FIELD_BYTES: usize = 128;
const RESOURCE_ACCESS_METADATA_KEY: &str = "openai/resource_access";
const EXECUTED_TOOL_CALL_METADATA_FIELD_BYTES: usize = b"\"executed_tool_calls\":".len();
const INTERNAL_CHAT_MESSAGE_METADATA_PASSTHROUGH_FIELD_BYTES: usize =
b"\"internal_chat_message_metadata_passthrough\":".len();
fn executed_tool_call_metadata_field_bytes(
metadata: &InternalChatMessageMetadataPassthrough,
) -> usize {
let fields = InternalChatMessageMetadataPassthrough {
cell_id: metadata.cell_id.clone(),
tool_calls_complete: metadata.tool_calls_complete,
..Default::default()
};
let mut bytes =
serde_json::to_vec(&fields).map_or(usize::MAX, |fields| fields.len().saturating_sub(2));
if metadata.executed_tool_calls.is_some() {
bytes = bytes
.saturating_add(usize::from(bytes > 0))
.saturating_add(EXECUTED_TOOL_CALL_METADATA_FIELD_BYTES);
}
if bytes == 0 {
0
} else if metadata.turn_id.is_some()
|| metadata.create_time.is_some()
|| metadata.content_item_kinds.is_some()
|| metadata.content_item_metadata.is_some()
{
bytes + 1
} else {
bytes + INTERNAL_CHAT_MESSAGE_METADATA_PASSTHROUGH_FIELD_BYTES + 3
}
}
/// Returns the exact serialized wire size of an item's attempted-tool metadata.
pub fn executed_tool_call_metadata_bytes(item: &ResponseItem) -> usize {
let Some(metadata) = item.executed_tool_call_metadata() else {
return 0;
};
metadata
.executed_tool_calls
.as_ref()
.map_or(0, |calls| {
serde_json::to_vec(calls)
.map(|calls| calls.len())
.unwrap_or(usize::MAX)
})
.saturating_add(executed_tool_call_metadata_field_bytes(metadata))
}
impl InternalChatMessageMetadataPassthrough {
/// Compares call order, names and arguments, ignoring optional result metadata.
pub fn has_same_tool_calls(&self, calls: &[ExecutedToolCall]) -> bool {
self.executed_tool_calls.as_ref().is_some_and(|recorded| {
recorded.len() == calls.len()
&& recorded.iter().zip(calls).all(|(recorded, call)| {
recorded.name == call.name && recorded.arguments() == call.arguments()
})
})
}
/// Compares the complete ordered call inventory, independently of recorded arguments.
pub fn has_same_tool_call_inventory(&self, calls: &[ExecutedToolCall]) -> bool {
self.executed_tool_calls.as_ref().is_some_and(|recorded| {
recorded.len() == calls.len()
&& recorded.iter().zip(calls).all(|(recorded, call)| {
recorded.name == call.name
&& recorded.has_complete_inventory()
&& call.has_complete_inventory()
})
})
}
}
/// Clears completion across a cell when recorded calls or tool names were lost.
/// Argument truncation preserves inventory completeness; arguments and outputs are unchanged.
pub fn normalize_executed_tool_call_completeness(items: &mut [ResponseItem]) {
let mut damaged_cells = HashSet::new();
for item in items.iter_mut() {
let Some(metadata) = item
.internal_chat_message_metadata_passthrough_mut()
.and_then(Option::as_mut)
else {
continue;
};
if metadata
.executed_tool_calls
.iter()
.flatten()
.any(|call| !call.has_complete_inventory())
{
metadata.tool_calls_complete = None;
damaged_cells.extend(metadata.cell_id.clone());
}
}
clear_damaged_cell_completeness(items, &damaged_cells);
}
/// Bounds optional observations to the space left in the actual outgoing message.
/// Ordinary output and unrelated item metadata are never changed.
pub fn bound_executed_tool_calls_for_message(
items: &mut [ResponseItem],
max_metadata_bytes: usize,
) {
let mut damaged_cells = HashSet::new();
let total_metadata_bytes = metadata_bytes(items);
if total_metadata_bytes <= max_metadata_bytes {
return;
}
let mut remaining_bytes =
shed_generic_result_metadata(items, max_metadata_bytes, total_metadata_bytes);
// Shed optional sources and recorded arguments before resource-access evidence.
if metadata_bytes(items) > max_metadata_bytes {
let overage_bytes = shed_result_sources(items, max_metadata_bytes);
if overage_bytes > 0 {
truncate_call_arguments_to_fit(items, max_metadata_bytes, overage_bytes);
}
remaining_bytes = metadata_bytes(items);
}
shed_remaining_result_metadata(items, max_metadata_bytes, remaining_bytes);
// Recheck the serialized request rather than relying on the incremental size accounting.
if metadata_bytes(items) <= max_metadata_bytes {
return;
}
// Omission markers are optional too; keep the original call budget if they cannot fit.
for item in items.iter_mut() {
item.clear_tool_result_metadata();
}
if metadata_bytes(items) <= max_metadata_bytes {
return;
}
distribute_remaining_budget(items, max_metadata_bytes, &mut damaged_cells);
clear_damaged_cell_completeness(items, &damaged_cells);
}
fn metadata_bytes(items: &[ResponseItem]) -> usize {
items.iter().fold(0_usize, |bytes, item| {
bytes.saturating_add(executed_tool_call_metadata_bytes(item))
})
}
type ResultMetadataEntry<'a> = (usize, usize, usize, &'a mut ToolResultMetadata);
fn result_metadata_by_size(items: &mut [ResponseItem]) -> Vec<ResultMetadataEntry<'_>> {
let mut result_metadata = Vec::new();
for (item_index, item) in items.iter_mut().enumerate() {
if let Some(metadata) = item
.internal_chat_message_metadata_passthrough_mut()
.and_then(Option::as_mut)
{
for (call_index, call) in metadata
.executed_tool_calls
.iter_mut()
.flatten()
.enumerate()
{
if call.tool_result_metadata.is_some() {
let bytes = serde_json::to_vec(&call.tool_result_metadata)
.map_or(usize::MAX, |value| value.len());
result_metadata.push((
bytes,
item_index,
call_index,
&mut call.tool_result_metadata,
));
}
}
}
}
result_metadata.sort_by_key(|(bytes, order, call_index, _)| {
(std::cmp::Reverse(*bytes), *order, *call_index)
});
result_metadata
}
fn shed_generic_result_metadata(
items: &mut [ResponseItem],
max_metadata_bytes: usize,
mut total_metadata_bytes: usize,
) -> usize {
// Shed the largest values first so one large result does not discard unrelated small results.
let mut result_metadata = result_metadata_by_size(items);
for (bytes, _, _, metadata) in &mut result_metadata {
if total_metadata_bytes <= max_metadata_bytes {
break;
}
if metadata.retain_resource_access() {
let retained_bytes =
serde_json::to_vec(&**metadata).map_or(usize::MAX, |value| value.len());
total_metadata_bytes =
total_metadata_bytes.saturating_sub(bytes.saturating_sub(retained_bytes));
*bytes = retained_bytes;
} else {
let retained_bytes =
metadata.omit_if_smaller(*bytes, total_metadata_bytes - max_metadata_bytes);
total_metadata_bytes = total_metadata_bytes.saturating_sub(*bytes - retained_bytes);
*bytes = retained_bytes;
}
}
// Tiny generic values and markers can be cheaper than replacing them with a
// new marker. Remove their complete fields before sacrificing resource evidence.
for (bytes, _, _, metadata) in &mut result_metadata {
if total_metadata_bytes <= max_metadata_bytes {
break;
}
if metadata.retain_resource_access() {
continue;
}
**metadata = ToolResultMetadata::default();
total_metadata_bytes = total_metadata_bytes
.saturating_sub(bytes.saturating_add(b",\"tool_result_metadata\":".len()));
*bytes = 0;
}
total_metadata_bytes
}
fn shed_remaining_result_metadata(
items: &mut [ResponseItem],
max_metadata_bytes: usize,
mut total_metadata_bytes: usize,
) {
let mut result_metadata = result_metadata_by_size(items);
// Resource evidence is optional too; it must not displace the call inventory.
for (bytes, _, _, metadata) in &mut result_metadata {
if total_metadata_bytes <= max_metadata_bytes {
break;
}
// An omission marker can be larger than a small object, including an empty `_meta`.
let retained_bytes =
metadata.omit_if_smaller(*bytes, total_metadata_bytes - max_metadata_bytes);
total_metadata_bytes = total_metadata_bytes.saturating_sub(*bytes - retained_bytes);
*bytes = retained_bytes;
}
// Use the updated sizes: markers should be removed before smaller provider metadata.
result_metadata.sort_by_key(|(bytes, order, call_index, metadata)| {
(
!metadata.is_omitted_due_to_size_limit(),
std::cmp::Reverse(*bytes),
*order,
*call_index,
)
});
for (bytes, _, _, metadata) in result_metadata {
if total_metadata_bytes <= max_metadata_bytes {
break;
}
if metadata.is_none() {
continue;
}
*metadata = ToolResultMetadata::default();
// The required name and arguments always precede this optional serialized field.
total_metadata_bytes = total_metadata_bytes
.saturating_sub(bytes.saturating_add(b",\"tool_result_metadata\":".len()));
}
}
fn shed_result_sources(items: &mut [ResponseItem], max_metadata_bytes: usize) -> usize {
// Source evidence is optional; dropping it must not discard calls or their completion proof.
let mut overage_bytes = metadata_bytes(items).saturating_sub(max_metadata_bytes);
for item in items.iter_mut() {
if let Some(metadata) = item
.internal_chat_message_metadata_passthrough_mut()
.and_then(Option::as_mut)
{
for call in metadata.executed_tool_calls.iter_mut().flatten() {
if overage_bytes == 0 {
break;
}
if let Some(sources) = call.tool_result_sources.take() {
let bytes =
serde_json::to_vec(&sources).map_or(usize::MAX, |value| value.len());
overage_bytes = overage_bytes
.saturating_sub(bytes.saturating_add(b",\"tool_result_sources\":".len()));
}
}
}
}
overage_bytes
}
fn truncate_call_arguments_to_fit(
items: &mut [ResponseItem],
max_metadata_bytes: usize,
mut overage_bytes: usize,
) {
// A large outgoing message should not lose the other tool names in a
// cell when replacing one call's arguments is enough to make it fit.
for index in 0..items.len() {
while overage_bytes > 0 {
let Some(metadata) = items[index]
.internal_chat_message_metadata_passthrough_mut()
.and_then(Option::as_mut)
else {
break;
};
let mut arguments_changed = false;
for call in metadata.executed_tool_calls.iter_mut().flatten() {
if call.truncation().is_some() {
continue;
}
let original_bytes =
serde_json::to_vec(&call.arguments).map_or(usize::MAX, |value| value.len());
let truncated = ExecutedToolCallArguments::Truncated {
truncation: ExecutedToolCallTruncation {
original_bytes,
max_bytes: original_bytes.saturating_sub(overage_bytes),
omitted_calls: None,
original_name_bytes: None,
},
};
let truncated_bytes =
serde_json::to_vec(&truncated).map_or(usize::MAX, |value| value.len());
if truncated_bytes < original_bytes {
call.arguments = truncated;
arguments_changed = true;
break;
}
}
if !arguments_changed {
break;
}
overage_bytes = metadata_bytes(items).saturating_sub(max_metadata_bytes);
}
}
}
fn distribute_remaining_budget(
items: &mut [ResponseItem],
max_metadata_bytes: usize,
damaged_cells: &mut HashSet<String>,
) {
let mut remaining_items = items
.iter()
.filter(|item| executed_tool_call_metadata_bytes(item) > 0)
.count();
let mut remaining_bytes = max_metadata_bytes;
for item in items.iter_mut() {
let item_bytes = executed_tool_call_metadata_bytes(item);
if item_bytes == 0 {
continue;
}
let item_budget = remaining_bytes / remaining_items;
if item_bytes > item_budget {
// Remember the cell before a too-small share removes its metadata entirely.
let cell_id = item
.executed_tool_call_metadata()
.and_then(|metadata| metadata.cell_id.clone());
item.bound_executed_tool_calls_with_budget(item_budget);
if item.executed_tool_call_metadata().is_none_or(|metadata| {
metadata
.executed_tool_calls
.as_ref()
.is_none_or(|calls| !calls.iter().all(ExecutedToolCall::has_complete_inventory))
}) {
item.clear_tool_calls_complete();
damaged_cells.extend(cell_id);
}
}
remaining_bytes = remaining_bytes.saturating_sub(executed_tool_call_metadata_bytes(item));
remaining_items -= 1;
}
}
fn clear_damaged_cell_completeness(items: &mut [ResponseItem], damaged_cells: &HashSet<String>) {
for item in items {
if item.executed_tool_call_metadata().is_some_and(|metadata| {
metadata
.cell_id
.as_ref()
.is_some_and(|cell_id| damaged_cells.contains(cell_id))
}) {
item.clear_tool_calls_complete();
}
}
}
/// Raw model arguments or trusted truncation metadata for an attempted tool call.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(untagged)]
pub enum ExecutedToolCallArguments {
Raw(serde_json::Value),
#[serde(skip_deserializing)]
Truncated {
#[serde(rename = "_codex_executed_tool_call_truncated")]
truncation: ExecutedToolCallTruncation,
},
}
/// A model-attempted Codex tool invocation captured at the shared runtime boundary.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema, TS)]
pub struct ExecutedToolCall {
pub name: String,
#[ts(type = "unknown")]
arguments: ExecutedToolCallArguments,
/// Host-generated only: ignore input JSON rather than accepting caller-supplied
/// evidence, and keep this out of public schemas and generated clients.
#[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")]
#[schemars(skip)]
#[ts(skip)]
tool_result_sources: Option<Vec<ToolResultSource>>,
/// Raw MCP result metadata is host-recorded only, never trusted from input JSON or exposed
/// in public schemas. Its Debug implementation also prevents raw values reaching logs.
#[serde(
default,
skip_deserializing,
skip_serializing_if = "ToolResultMetadata::is_none"
)]
#[schemars(skip)]
#[ts(skip)]
tool_result_metadata: ToolResultMetadata,
}
/// MCP result metadata, optionally reduced to resource evidence, or a size-omission marker.
#[derive(Clone, Default, Serialize, PartialEq, Eq)]
#[serde(transparent)]
pub struct ToolResultMetadata(Option<serde_json::Value>);
impl std::fmt::Debug for ToolResultMetadata {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("ToolResultMetadata([redacted])")
}
}
impl ToolResultMetadata {
/// Captures the complete result; retention and outgoing-request budgets apply later.
pub fn new(metadata: &serde_json::Value) -> Self {
Self(Some(metadata.clone()))
}
/// Leaves generic metadata unchanged when it has no resource-access field.
fn retain_resource_access(&mut self) -> bool {
let Some(serde_json::Value::Object(metadata)) = self.0.as_mut() else {
return false;
};
if !metadata.contains_key(RESOURCE_ACCESS_METADATA_KEY) {
return false;
}
metadata.retain(|key, _| key == RESOURCE_ACCESS_METADATA_KEY);
true
}
fn omitted_due_to_size_limit(overage_bytes: usize) -> Self {
// MCP `_meta` is an object; this string is a harness omission status, not provider data.
Self(Some(serde_json::Value::String(format!(
"omitted_due_to_size_limit (overage_bytes={overage_bytes})"
))))
}
fn is_omitted_due_to_size_limit(&self) -> bool {
let Some(serde_json::Value::String(value)) = self.0.as_ref() else {
return false;
};
value == "omitted_due_to_size_limit"
|| value
.strip_prefix("omitted_due_to_size_limit (overage_bytes=")
.and_then(|value| value.strip_suffix(')'))
.is_some_and(|value| value.parse::<usize>().is_ok())
}
fn omit_if_smaller(&mut self, original_bytes: usize, overage_bytes: usize) -> usize {
if self.is_none() || self.is_omitted_due_to_size_limit() {
return original_bytes;
}
let omitted = Self::omitted_due_to_size_limit(overage_bytes);
let omitted_bytes = serde_json::to_vec(&omitted).map_or(usize::MAX, |value| value.len());
if omitted_bytes < original_bytes {
*self = omitted;
omitted_bytes
} else {
original_bytes
}
}
/// Whether there is no captured result metadata.
fn is_none(&self) -> bool {
self.0.is_none()
}
/// Whether the captured snapshot contains metadata or an omission marker.
pub fn is_some(&self) -> bool {
self.0.is_some()
}
}
/// A bounded capture update. Omitted updates still clear any previously recorded evidence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolResultSources(Option<Vec<ToolResultSource>>);
impl ToolResultSources {
/// Deduplicates a captured snapshot, discarding all sources if it exceeds a limit.
/// Capture rules determine coverage; this is not a resource or permission inventory.
pub fn new(sources: Vec<ToolResultSource>) -> Self {
let mut unique_sources = Vec::new();
for source in sources {
if unique_sources.contains(&source) {
continue;
}
if unique_sources.len() == MAX_TOOL_RESULT_SOURCES
|| source.r#type.len() > MAX_TOOL_RESULT_SOURCE_FIELD_BYTES
|| source.id.len() > MAX_TOOL_RESULT_SOURCE_FIELD_BYTES
{
return Self(None);
}
unique_sources.push(source);
}
Self(Some(unique_sources))
}
/// Records a failed parse using the receiver's existing array-of-sources shape.
/// `parse_failed` is a status marker, not a resource type; the required ID is empty.
pub fn parse_failed() -> Self {
Self(Some(vec![ToolResultSource {
r#type: "parse_failed".to_string(),
id: String::new(),
}]))
}
}
/// A captured source ID, or a `parse_failed` status marker with an empty ID.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct ToolResultSource {
#[serde(rename = "type")]
pub r#type: String,
pub id: String,
}
/// Trusted truncation details generated locally for an oversized attempted tool call.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema, TS)]
pub struct ExecutedToolCallTruncation {
original_bytes: usize,
max_bytes: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
omitted_calls: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
original_name_bytes: Option<usize>,
}
impl ExecutedToolCall {
/// Creates a recorded call without treating model-provided JSON as trusted metadata.
pub fn new(name: String, arguments: serde_json::Value) -> Self {
let arguments = if arguments
.as_object()
.is_some_and(|object| object.contains_key("_codex_executed_tool_call_truncated"))
{
serde_json::json!({ "_codex_executed_tool_call_raw": arguments })
} else {
arguments
};
Self {
name,
arguments: ExecutedToolCallArguments::Raw(arguments),
tool_result_sources: None,
tool_result_metadata: ToolResultMetadata::default(),
}
}
/// Replaces oversized arguments with internally generated truncation metadata.
pub fn truncated(name: String, original_bytes: usize, max_bytes: usize) -> Self {
let mut call = Self::new(name, serde_json::Value::Null);
call.set_truncation(original_bytes, max_bytes, /*omitted_calls*/ None);
call
}
/// Returns the raw arguments or locally generated truncation payload.
pub fn arguments(&self) -> &ExecutedToolCallArguments {
&self.arguments
}
/// Whether this call has result metadata or an omission marker.
pub fn has_tool_result_metadata(&self) -> bool {
self.tool_result_metadata.is_some()
}
/// Replaces this invocation's capture outcome, including clearing omitted evidence.
pub fn set_tool_result_sources(&mut self, sources: ToolResultSources) -> bool {
self.tool_result_sources = sources.0;
self.tool_result_sources.is_some()
}
/// Replaces the entire captured `_meta` snapshot.
pub fn set_tool_result_metadata(&mut self, metadata: ToolResultMetadata) {
self.tool_result_metadata = metadata;
}
fn truncation(&self) -> Option<&ExecutedToolCallTruncation> {
match &self.arguments {
ExecutedToolCallArguments::Raw(_) => None,
ExecutedToolCallArguments::Truncated { truncation } => Some(truncation),
}
}
/// Whether this entry retains its invocation and full tool name, regardless of arguments.
pub fn has_complete_inventory(&self) -> bool {
self.truncation().is_none_or(|truncation| {
truncation.omitted_calls.unwrap_or_default() == 0
&& truncation.original_name_bytes.is_none()
})
}
fn set_truncation(
&mut self,
original_bytes: usize,
max_bytes: usize,
omitted_calls: Option<usize>,
) {
self.set_truncation_with_name(
original_bytes,
max_bytes,
omitted_calls,
/*original_name_bytes*/ None,
);
}
fn set_truncation_with_name(
&mut self,
original_bytes: usize,
max_bytes: usize,
omitted_calls: Option<usize>,
original_name_bytes: Option<usize>,
) {
self.arguments = ExecutedToolCallArguments::Truncated {
truncation: ExecutedToolCallTruncation {
original_bytes,
max_bytes,
omitted_calls,
original_name_bytes,
},
};
}
}
impl ResponseItem {
fn ensure_tool_call_metadata(&mut self) -> Option<&mut InternalChatMessageMetadataPassthrough> {
self.internal_chat_message_metadata_passthrough_mut()
.map(Option::get_or_insert_default)
}
/// Associates host-recorded calls and completeness with their Code Mode cell.
pub fn set_tool_call_cell_id(&mut self, cell_id: &str) {
if let Some(metadata) = self.ensure_tool_call_metadata() {
metadata.cell_id = Some(cell_id.to_string());
}
}
/// Attaches model-attempted tool invocations without replacing existing item metadata.
pub fn append_executed_tool_calls(&mut self, calls: Vec<ExecutedToolCall>) {
if calls.is_empty() {
return;
}
let Some(metadata) = self.ensure_tool_call_metadata() else {
return;
};
metadata
.executed_tool_calls
.get_or_insert_with(Vec::new)
.extend(calls);
}
/// Marks a host-owned direct invocation or Code Mode cell's call inventory as complete.
/// Always includes this output's call list, which can be an empty delta for a terminal wait.
pub fn mark_tool_calls_complete(&mut self) {
if let Some(metadata) = self.ensure_tool_call_metadata() {
metadata.executed_tool_calls.get_or_insert_default();
metadata.tool_calls_complete = Some(true);
}
}
/// Discards a completion claim when the host cannot retain the full call inventory.
pub fn clear_tool_calls_complete(&mut self) {
if let Some(metadata) = self
.internal_chat_message_metadata_passthrough_mut()
.and_then(Option::as_mut)
{
metadata.tool_calls_complete = None;
}
}
/// Returns warehouse-only attempted-tool metadata for any supported item variant.
pub fn executed_tool_call_metadata(&self) -> Option<&InternalChatMessageMetadataPassthrough> {
self.internal_chat_message_metadata_passthrough()
}
/// Compares raw result metadata and its call bindings, ignoring other internal metadata.
pub fn has_same_tool_result_metadata(&self, other: &Self) -> bool {
fn result_metadata(
item: &ResponseItem,
) -> impl Iterator<Item = (usize, &str, &ExecutedToolCallArguments, &ToolResultMetadata)>
{
item.executed_tool_call_metadata()
.and_then(|metadata| metadata.executed_tool_calls.as_ref())
.into_iter()
.flatten()
.enumerate()
.filter(|(_, call)| call.tool_result_metadata.is_some())
.map(|(index, call)| {
(
index,
call.name.as_str(),
call.arguments(),
&call.tool_result_metadata,
)
})
}
result_metadata(self).eq(result_metadata(other))
}
/// Whether an output carries raw result metadata or a harness omission marker.
pub fn has_tool_result_metadata(&self) -> bool {
self.executed_tool_call_metadata().is_some_and(|metadata| {
metadata
.executed_tool_calls
.iter()
.flatten()
.any(|call| call.tool_result_metadata.is_some())
})
}
/// Omits raw tool results without changing existing call, source or completion metadata.
pub fn clear_tool_result_metadata(&mut self) {
if let Some(metadata) = self
.internal_chat_message_metadata_passthrough_mut()
.and_then(Option::as_mut)
{
for call in metadata.executed_tool_calls.iter_mut().flatten() {
call.tool_result_metadata = ToolResultMetadata::default();
}
}
}
/// Marks larger raw results with the full request's overage, preserving existing markers.
pub fn omit_tool_result_metadata(&mut self, overage_bytes: usize) {
if let Some(metadata) = self
.internal_chat_message_metadata_passthrough_mut()
.and_then(Option::as_mut)
{
for call in metadata.executed_tool_calls.iter_mut().flatten() {
let result = &mut call.tool_result_metadata;
let bytes = serde_json::to_vec(result).map_or(usize::MAX, |value| value.len());
result.omit_if_smaller(bytes, overage_bytes);
}
}
}
/// Preserves complete resource evidence, marking other large results with request overage.
pub fn retain_tool_resource_access_or_omit_metadata(&mut self, overage_bytes: usize) {
if let Some(metadata) = self
.internal_chat_message_metadata_passthrough_mut()
.and_then(Option::as_mut)
{
for call in metadata.executed_tool_calls.iter_mut().flatten() {
let result = &mut call.tool_result_metadata;
if !result.retain_resource_access() {
let bytes = serde_json::to_vec(result).map_or(usize::MAX, |value| value.len());
result.omit_if_smaller(bytes, overage_bytes);
}
}
}
}
/// Reduces optional results to resource evidence before considering call-inventory loss.
pub fn retain_tool_resource_access(&mut self) {
if let Some(metadata) = self
.internal_chat_message_metadata_passthrough_mut()
.and_then(Option::as_mut)
{
for call in metadata.executed_tool_calls.iter_mut().flatten() {
if !call.tool_result_metadata.retain_resource_access() {
call.tool_result_metadata = ToolResultMetadata::default();
}
}
}
}
/// Replaces an over-budget output's calls with its own omission marker.
fn bound_executed_tool_calls_with_budget(&mut self, max_metadata_bytes: usize) {
let Some(metadata) = self.executed_tool_call_metadata() else {
return;
};
let max_call_bytes =
max_metadata_bytes.saturating_sub(executed_tool_call_metadata_field_bytes(metadata));
let Some(calls) = self
.internal_chat_message_metadata_passthrough_mut()
.and_then(Option::as_mut)
.and_then(|metadata| metadata.executed_tool_calls.as_mut())
.filter(|calls| !calls.is_empty())
else {
self.clear_executed_tool_calls();
return;
};
let represented_calls = calls.iter().fold(0_usize, |count, call| {
count.saturating_add(1).saturating_add(
call.truncation()
.and_then(|truncation| truncation.omitted_calls)
.unwrap_or_default(),
)
});
calls.truncate(1);
let call = &mut calls[0];
let original_bytes = call
.truncation()
.map(|truncation| truncation.original_bytes)
.unwrap_or_else(|| {
serde_json::to_vec(&call.arguments)
.map(|bytes| bytes.len())
.unwrap_or(usize::MAX)
});
let original_name_bytes = call
.truncation()
.and_then(|truncation| truncation.original_name_bytes);
let omitted_calls = (represented_calls > 1).then_some(represented_calls - 1);
call.set_truncation_with_name(
original_bytes,
max_call_bytes,
omitted_calls,
original_name_bytes,
);
let serialized_bytes = |calls: &[ExecutedToolCall]| {
serde_json::to_vec(calls)
.map(|bytes| bytes.len())
.unwrap_or(usize::MAX)
};
if serialized_bytes(calls) > max_call_bytes {
let call = &mut calls[0];
call.set_truncation_with_name(
original_bytes,
max_call_bytes,
omitted_calls,
Some(original_name_bytes.unwrap_or(call.name.len())),
);
// Removing UTF-8 name bytes saves at least that many serialized JSON bytes.
let excess_bytes = serialized_bytes(calls).saturating_sub(max_call_bytes);
let name = &mut calls[0].name;
name.truncate(name.floor_char_boundary(name.len().saturating_sub(excess_bytes)));
}
if serialized_bytes(calls) > max_call_bytes {
self.clear_executed_tool_calls();
}
}
/// Removes untrusted warehouse-only tool records without changing the turn ID.
pub fn clear_executed_tool_calls(&mut self) {
let Some(metadata) = self.internal_chat_message_metadata_passthrough_mut() else {
return;
};
let Some(passthrough) = metadata.as_mut() else {
return;
};
passthrough.cell_id = None;
passthrough.executed_tool_calls = None;
passthrough.tool_calls_complete = None;
if *passthrough == InternalChatMessageMetadataPassthrough::default() {
*metadata = None;
}
}
}
#[cfg(test)]
#[path = "executed_tool_calls_tests.rs"]
mod tests;

View File

@@ -0,0 +1,697 @@
use anyhow::Result;
use pretty_assertions::assert_eq;
use super::super::FunctionCallOutputPayload;
use super::super::ResponseInputItem;
use super::*;
fn passthrough_metadata(turn_id: &str) -> InternalChatMessageMetadataPassthrough {
InternalChatMessageMetadataPassthrough {
turn_id: Some(turn_id.to_string()),
..Default::default()
}
}
fn output(call_id: &str) -> ResponseItem {
ResponseItem::from(ResponseInputItem::FunctionCallOutput {
call_id: call_id.to_string(),
output: FunctionCallOutputPayload::from_text(String::new()),
})
}
fn first_executed_tool_call(item: &mut ResponseItem) -> Option<&mut ExecutedToolCall> {
item.internal_chat_message_metadata_passthrough_mut()
.and_then(Option::as_mut)
.and_then(|metadata| metadata.executed_tool_calls.as_mut())
.and_then(|calls| calls.first_mut())
}
#[test]
fn result_metadata_comparison_tracks_raw_values_and_call_bindings() {
let empty = output("output");
let mut without_metadata = empty.clone();
without_metadata.append_executed_tool_calls(vec![ExecutedToolCall::new(
"apps_tool".to_string(),
serde_json::json!({ "query": "same" }),
)]);
assert!(empty.has_same_tool_result_metadata(&without_metadata));
let mut with_metadata = without_metadata.clone();
first_executed_tool_call(&mut with_metadata)
.unwrap()
.set_tool_result_metadata(ToolResultMetadata::new(
&serde_json::json!({ "id": "first" }),
));
assert!(!without_metadata.has_same_tool_result_metadata(&with_metadata));
assert!(!with_metadata.has_same_tool_result_metadata(&without_metadata));
assert!(with_metadata.has_same_tool_result_metadata(&with_metadata.clone()));
let mut changed = with_metadata.clone();
first_executed_tool_call(&mut changed)
.unwrap()
.set_tool_result_metadata(ToolResultMetadata::new(
&serde_json::json!({ "id": "second" }),
));
assert!(!with_metadata.has_same_tool_result_metadata(&changed));
changed.clear_tool_result_metadata();
assert!(without_metadata.has_same_tool_result_metadata(&changed));
let mut ordinary_metadata = with_metadata.clone();
ordinary_metadata.set_turn_id_if_missing("other-turn");
ordinary_metadata.set_tool_call_cell_id("other-cell");
ordinary_metadata.mark_tool_calls_complete();
first_executed_tool_call(&mut ordinary_metadata)
.unwrap()
.set_tool_result_sources(ToolResultSources::new(vec![ToolResultSource {
r#type: "resource".to_string(),
id: "source".to_string(),
}]));
assert!(with_metadata.has_same_tool_result_metadata(&ordinary_metadata));
let mut different_call = with_metadata.clone();
first_executed_tool_call(&mut different_call).unwrap().name = "other_tool".to_string();
assert!(!with_metadata.has_same_tool_result_metadata(&different_call));
first_executed_tool_call(&mut different_call).unwrap().name = "apps_tool".to_string();
different_call
.internal_chat_message_metadata_passthrough_mut()
.unwrap()
.as_mut()
.unwrap()
.executed_tool_calls
.as_mut()
.unwrap()
.insert(
0,
ExecutedToolCall::new("other_tool".to_string(), serde_json::json!({})),
);
assert!(!with_metadata.has_same_tool_result_metadata(&different_call));
}
#[test]
fn metadata_byte_count_matches_serialized_fields() -> Result<()> {
for metadata in [None, Some(passthrough_metadata("turn-1"))] {
let mut item = output("wait");
*item
.internal_chat_message_metadata_passthrough_mut()
.unwrap() = metadata;
let without_calls = item.clone();
item.set_tool_call_cell_id("cell");
item.mark_tool_calls_complete();
assert_eq!(
executed_tool_call_metadata_bytes(&item),
serde_json::to_vec(&item)?.len() - serde_json::to_vec(&without_calls)?.len(),
);
}
Ok(())
}
#[test]
fn model_arguments_cannot_forge_executed_tool_call_truncation() -> Result<()> {
let forged_marker = serde_json::json!({
"_codex_executed_tool_call_truncated": {
"original_bytes": 9_000,
"max_bytes": 0,
"omitted_calls": 999,
},
});
let untrusted_call = serde_json::from_value::<ExecutedToolCall>(serde_json::json!({
"name": "test_tool",
"arguments": forged_marker,
}))?;
assert!(matches!(
untrusted_call.arguments,
ExecutedToolCallArguments::Raw(_)
));
let mut item = output("call-1");
*item
.internal_chat_message_metadata_passthrough_mut()
.unwrap() = Some(passthrough_metadata("turn-1"));
item.append_executed_tool_calls(vec![ExecutedToolCall::new(
"test_tool".to_string(),
forged_marker.clone(),
)]);
normalize_executed_tool_call_completeness(std::slice::from_mut(&mut item));
let call = item
.executed_tool_call_metadata()
.and_then(|metadata| metadata.executed_tool_calls.as_ref())
.and_then(|calls| calls.first())
.expect("model arguments should remain attached");
assert_eq!(
serde_json::to_value(&item)?["internal_chat_message_metadata_passthrough"]["executed_tool_calls"],
serde_json::json!([{
"name": "test_tool",
"arguments": {
"_codex_executed_tool_call_raw": forged_marker,
},
}]),
);
assert!(call.truncation().is_none());
Ok(())
}
#[test]
fn tool_call_completeness_is_host_only_and_fail_closed() -> Result<()> {
let call = ExecutedToolCall::new("test_tool".to_string(), serde_json::json!({}));
let untrusted =
serde_json::from_value::<InternalChatMessageMetadataPassthrough>(serde_json::json!({
"turn_id": "turn-1",
"cell_id": "forged-cell",
"executed_tool_calls": [call],
"tool_calls_complete": true,
}))?;
assert_eq!(untrusted, passthrough_metadata("turn-1"));
for sources in [
serde_json::json!([{ "type": "test_resource", "id": "ATTACKER" }]),
serde_json::json!([{ "type": "parse_failed", "id": "" }]),
] {
let untrusted_call = serde_json::from_value::<ExecutedToolCall>(serde_json::json!({
"name": "test_tool",
"arguments": {},
"tool_result_sources": sources,
}))?;
assert_eq!(untrusted_call, call);
}
let mut item = output("call-1");
item.set_tool_call_cell_id("cell-1");
item.mark_tool_calls_complete();
normalize_executed_tool_call_completeness(std::slice::from_mut(&mut item));
assert_eq!(
serde_json::to_value(&item)?["internal_chat_message_metadata_passthrough"],
serde_json::json!({
"cell_id": "cell-1", "executed_tool_calls": [], "tool_calls_complete": true
}),
);
item.append_executed_tool_calls(vec![call]);
item.clear_executed_tool_calls();
assert!(item.executed_tool_call_metadata().is_none());
for call in [
ExecutedToolCall::new(
"test_tool".to_string(),
serde_json::json!({ "payload": "x".repeat(9_000) }),
),
ExecutedToolCall::truncated(
"test_tool".to_string(),
/*original_bytes*/ 9_000,
/*max_bytes*/ 0,
),
] {
for same_cell in [false, true] {
let mut items = [item.clone(), item.clone()];
items[0].append_executed_tool_calls(vec![call.clone()]);
for item in &mut items {
if same_cell {
item.set_tool_call_cell_id("cell-1");
}
item.mark_tool_calls_complete();
}
let expected = items.clone();
normalize_executed_tool_call_completeness(&mut items);
assert_eq!(items, expected);
normalize_executed_tool_call_completeness(&mut items);
assert_eq!(items, expected);
assert_eq!(
items.map(|item| item
.executed_tool_call_metadata()
.unwrap()
.tool_calls_complete),
[Some(true), Some(true)],
);
}
}
Ok(())
}
#[test]
fn tool_result_source_snapshots_replace_atomically() -> Result<()> {
let source = |kind: &str, id: &str| ToolResultSource {
r#type: kind.to_string(),
id: id.to_string(),
};
let mut call = ExecutedToolCall::new("test_tool".to_string(), serde_json::json!({}));
let mut sources = (0..MAX_TOOL_RESULT_SOURCES - 1)
.map(|index| source("test_resource", &format!("R{index}")))
.collect::<Vec<_>>();
sources.push(source("other_resource", "R0"));
sources.push(sources[0].clone());
let capture = ToolResultSources::new(sources.clone());
sources.truncate(MAX_TOOL_RESULT_SOURCES);
assert_eq!(capture, ToolResultSources(Some(sources.clone())));
assert!(call.set_tool_result_sources(capture));
sources.push(source("test_resource", "OVERFLOW"));
let capture = ToolResultSources::new(sources);
assert_eq!(capture, ToolResultSources(None));
assert!(!call.set_tool_result_sources(capture));
assert!(
serde_json::to_value(&call)?
.get("tool_result_sources")
.is_none()
);
// Measure UTF-8 bytes, and clear old evidence instead of keeping a partial replacement.
let field = format!(
"é{}",
"x".repeat(MAX_TOOL_RESULT_SOURCE_FIELD_BYTES - "é".len())
);
let bounded = source(&field, &field);
let oversized = format!("{field}x");
for invalid in [
source(&oversized, "R1"),
source("test_resource", &oversized),
] {
assert!(call.set_tool_result_sources(ToolResultSources::new(vec![bounded.clone()])));
assert_eq!(call.tool_result_sources, Some(vec![bounded.clone()]));
let capture = ToolResultSources::new(vec![source("test_resource", "R1"), invalid]);
assert_eq!(capture, ToolResultSources(None));
assert!(!call.set_tool_result_sources(capture));
assert_eq!(call.tool_result_sources, None);
}
assert!(call.set_tool_result_sources(ToolResultSources::new(vec![bounded])));
assert!(call.set_tool_result_sources(ToolResultSources::parse_failed()));
assert_eq!(
serde_json::to_value(&call)?,
serde_json::json!({
"name": "test_tool",
"arguments": {},
"tool_result_sources": [{ "type": "parse_failed", "id": "" }],
})
);
assert!(call.set_tool_result_sources(ToolResultSources::new(Vec::new())));
assert_eq!(
serde_json::to_value(&call)?["tool_result_sources"],
serde_json::json!([])
);
Ok(())
}
#[test]
fn tool_result_metadata_is_host_only_and_redacted_without_a_per_result_limit() -> Result<()> {
let mut call = ExecutedToolCall::new("test_tool".to_string(), serde_json::json!({}));
let without_metadata = call.clone();
for metadata in [
serde_json::json!({
"arbitrary-key": { "secret": "not-for-debug", "ids": [1, "é", null] },
"other": false,
}),
serde_json::json!({
"openai/resource_access": {
"resource_coverage": "complete",
"resources": ["not-for-debug", "x".repeat(40 * 1024)],
},
"other": "preserved along with resource_access",
}),
// Capture preserves the original value even when serialization escapes increase its size.
serde_json::json!({ "value": "\0".repeat(32 * 1024) }),
serde_json::json!({}),
serde_json::json!(null),
] {
let capture = ToolResultMetadata::new(&metadata);
assert_eq!(format!("{capture:?}"), "ToolResultMetadata([redacted])");
assert!(capture.is_some());
call.set_tool_result_metadata(capture);
let wire = serde_json::to_value(&call)?;
assert_eq!(
wire,
serde_json::json!({
"name": "test_tool",
"arguments": {},
"tool_result_metadata": metadata,
})
);
assert!(!format!("{call:?}").contains("not-for-debug"));
assert_eq!(
serde_json::from_value::<ExecutedToolCall>(wire)?,
without_metadata
);
}
Ok(())
}
#[test]
fn wire_budget_helpers_preserve_resource_evidence_markers_and_small_values() {
let resource_only = serde_json::json!({
"openai/resource_access": { "resource_coverage": "complete", "resources": [] },
});
let mut item = output("exec");
assert!(!item.has_tool_result_metadata());
item.append_executed_tool_calls(
[
ToolResultMetadata::new(&serde_json::json!({
"openai/resource_access": resource_only["openai/resource_access"],
"payload": "x".repeat(512),
})),
ToolResultMetadata::new(&serde_json::json!({
"omitted_due_to_size_limit": { "overage_bytes": 1 },
"payload": "x".repeat(512),
})),
ToolResultMetadata::new(&serde_json::json!({})),
ToolResultMetadata::new(&serde_json::json!("omitted_due_to_size_limit")),
ToolResultMetadata::omitted_due_to_size_limit(/*overage_bytes*/ 123_456),
ToolResultMetadata::default(),
]
.into_iter()
.map(|metadata| {
let mut call = ExecutedToolCall::new("test_tool".to_string(), serde_json::json!({}));
call.set_tool_result_metadata(metadata);
call.set_tool_result_sources(ToolResultSources::parse_failed());
call
})
.collect(),
);
item.set_tool_call_cell_id("exec");
item.mark_tool_calls_complete();
assert!(item.has_tool_result_metadata());
let mut expected = item.clone();
let calls = expected
.ensure_tool_call_metadata()
.unwrap()
.executed_tool_calls
.as_mut()
.unwrap();
calls[0].set_tool_result_metadata(ToolResultMetadata::new(&resource_only));
calls[1].set_tool_result_metadata(ToolResultMetadata::omitted_due_to_size_limit(
/*overage_bytes*/ 77,
));
item.retain_tool_resource_access_or_omit_metadata(/*overage_bytes*/ 77);
assert_eq!(item, expected);
item.retain_tool_resource_access_or_omit_metadata(/*overage_bytes*/ 1_234);
assert_eq!(item, expected);
first_executed_tool_call(&mut expected)
.unwrap()
.set_tool_result_metadata(ToolResultMetadata::omitted_due_to_size_limit(
/*overage_bytes*/ 1,
));
item.omit_tool_result_metadata(/*overage_bytes*/ 1);
assert_eq!(item, expected);
item.omit_tool_result_metadata(/*overage_bytes*/ 99_999);
assert_eq!(item, expected);
item.clear_tool_result_metadata();
assert!(!item.has_tool_result_metadata());
}
#[test]
fn message_budget_keeps_smaller_resource_evidence_when_larger_evidence_must_be_shed() {
for (sizes, larger_index) in [([1024, 512], 0), ([512, 1024], 1)] {
let mut items = sizes.map(|size| {
let mut item = ResponseItem::from(ResponseInputItem::FunctionCallOutput {
call_id: format!("call-{size}"),
output: FunctionCallOutputPayload::from_text("unchanged output".to_string()),
});
let mut call =
ExecutedToolCall::new(format!("tool_{size}"), serde_json::json!({"query": "kept"}));
call.set_tool_result_sources(ToolResultSources::new(vec![ToolResultSource {
r#type: "test_resource".to_string(),
id: format!("resource-{size}"),
}]));
call.set_tool_result_metadata(ToolResultMetadata::new(&serde_json::json!({
"openai/resource_access": {"opaque": "é".repeat(size)},
})));
item.append_executed_tool_calls(vec![call]);
item.set_tool_call_cell_id(&format!("cell-{size}"));
item.mark_tool_calls_complete();
item
});
let mut expected = items.clone();
for item in &mut expected {
first_executed_tool_call(item).unwrap().tool_result_sources = None;
}
let budget = expected
.iter()
.map(executed_tool_call_metadata_bytes)
.sum::<usize>()
- 128;
first_executed_tool_call(&mut expected[larger_index])
.unwrap()
.set_tool_result_metadata(ToolResultMetadata::omitted_due_to_size_limit(
/*overage_bytes*/ 128,
));
bound_executed_tool_calls_for_message(&mut items, budget);
assert_eq!(items, expected);
assert!(
items
.iter()
.map(executed_tool_call_metadata_bytes)
.sum::<usize>()
<= budget
);
bound_executed_tool_calls_for_message(&mut items, budget);
assert_eq!(items, expected);
}
}
#[test]
fn message_budget_drops_only_the_sources_needed_to_fit() {
let mut items = ["first", "second"].map(|id| {
let mut item = ResponseItem::from(ResponseInputItem::FunctionCallOutput {
call_id: id.to_string(),
output: FunctionCallOutputPayload::from_text("unchanged output".to_string()),
});
let mut call =
ExecutedToolCall::new(format!("tool_{id}"), serde_json::json!({"query": "kept"}));
call.set_tool_result_sources(ToolResultSources::new(vec![ToolResultSource {
r#type: "test_resource".to_string(),
id: id.to_string(),
}]));
call.set_tool_result_metadata(ToolResultMetadata::new(&serde_json::json!({
"openai/resource_access": {"resource_coverage": "complete", "resources": []},
})));
item.append_executed_tool_calls(vec![call]);
item.set_tool_call_cell_id(id);
item.mark_tool_calls_complete();
item
});
let mut expected = items.clone();
first_executed_tool_call(&mut expected[0])
.unwrap()
.tool_result_sources = None;
let budget = expected
.iter()
.map(executed_tool_call_metadata_bytes)
.sum::<usize>();
assert!(
items
.iter()
.map(executed_tool_call_metadata_bytes)
.sum::<usize>()
> budget
);
bound_executed_tool_calls_for_message(&mut items, budget);
assert_eq!(items, expected);
bound_executed_tool_calls_for_message(&mut items, budget);
assert_eq!(items, expected);
}
#[test]
fn message_budget_removes_generic_fields_before_resources_in_the_same_output() {
for generic in [
serde_json::json!({}),
serde_json::json!(null),
serde_json::json!("omitted_due_to_size_limit"),
] {
let mut item = output("exec");
for metadata in [
serde_json::json!({"openai/resource_access": {"opaque": "é".repeat(256)}}),
generic.clone(),
generic,
] {
let mut call = ExecutedToolCall::new("read".to_string(), serde_json::json!({}));
call.set_tool_result_metadata(ToolResultMetadata::new(&metadata));
item.append_executed_tool_calls(vec![call]);
}
item.set_tool_call_cell_id("cell");
item.mark_tool_calls_complete();
let mut expected = item.clone();
expected
.ensure_tool_call_metadata()
.unwrap()
.executed_tool_calls
.as_mut()
.unwrap()[1]
.set_tool_result_metadata(ToolResultMetadata::default());
let budget = executed_tool_call_metadata_bytes(&expected);
bound_executed_tool_calls_for_message(std::slice::from_mut(&mut item), budget);
assert_eq!(item, expected);
}
}
#[test]
fn message_budget_preserves_call_inventory_when_arguments_are_truncated() {
let arguments = serde_json::json!({"payload": "é".repeat(256)});
let argument_bytes = serde_json::to_vec(&arguments).unwrap().len();
let mut exec = output("exec");
exec.append_executed_tool_calls(vec![
ExecutedToolCall::new("first_é\"".to_string(), arguments.clone()),
ExecutedToolCall::new("second".to_string(), arguments),
]);
first_executed_tool_call(&mut exec)
.unwrap()
.set_tool_result_metadata(ToolResultMetadata::new(&serde_json::json!({
"openai/resource_access": {"resources": ["R1"]}
})));
let mut wait = output("wait");
for item in [&mut exec, &mut wait] {
item.set_tool_call_cell_id("cell_é\"");
item.mark_tool_calls_complete();
let metadata = item.ensure_tool_call_metadata().unwrap();
metadata.turn_id = Some("turn_é\"".to_string());
metadata.create_time = Some(serde_json::Number::from(123));
}
let original = vec![exec, wait];
let original_metadata_bytes = original
.iter()
.map(executed_tool_call_metadata_bytes)
.sum::<usize>();
// The first two cases fit after truncating only the first call's arguments;
// the second call's arguments and both completion claims must survive.
for budget in [
original_metadata_bytes - 64,
original_metadata_bytes - (argument_bytes - 128),
0,
] {
let mut items = original.clone();
let mut expected = original.clone();
if budget == 0 {
for item in &mut expected {
item.clear_executed_tool_calls();
}
} else {
first_executed_tool_call(&mut expected[0])
.unwrap()
.set_truncation(
argument_bytes,
argument_bytes - (original_metadata_bytes - budget),
/*omitted_calls*/ None,
);
}
bound_executed_tool_calls_for_message(&mut items, budget);
assert_eq!(items, expected);
let bounded_metadata_bytes = items
.iter()
.map(executed_tool_call_metadata_bytes)
.sum::<usize>();
assert!(bounded_metadata_bytes <= budget);
assert_eq!(
serde_json::to_vec(&original).unwrap().len()
- serde_json::to_vec(&items).unwrap().len(),
original_metadata_bytes - bounded_metadata_bytes,
);
}
}
#[test]
fn inventory_loss_still_clears_completeness() {
for (omitted_calls, original_name_bytes) in [(Some(1), None), (None, Some(20))] {
let mut call = ExecutedToolCall::new("test_tool".to_string(), serde_json::json!({}));
call.set_truncation_with_name(
/*original_bytes*/ 9_000,
/*max_bytes*/ 0,
omitted_calls,
original_name_bytes,
);
let mut item = output("call");
item.append_executed_tool_calls(vec![call]);
item.mark_tool_calls_complete();
normalize_executed_tool_call_completeness(std::slice::from_mut(&mut item));
assert_eq!(
item.executed_tool_call_metadata()
.unwrap()
.tool_calls_complete,
None
);
}
}
#[test]
fn result_metadata_shedding_keeps_smaller_results_within_one_output() {
let budget = 2 * 1024 * 1024;
let resource_only = serde_json::json!({
"openai/resource_access": { "resource_coverage": "complete", "resources": [] },
});
for (metadata, reduced_index, replacement) in [
(
[
serde_json::json!({}),
serde_json::json!({ "value": "é".repeat(10_000) }),
serde_json::json!({ "value": "é".repeat(10_000) }),
],
1,
None,
),
(
[
serde_json::json!({}),
serde_json::json!({ "value": "x".repeat(8_000) }),
serde_json::json!({ "value": "\0".repeat(4_500) }),
],
2,
None,
),
(
[
serde_json::json!({}),
serde_json::json!({ "value": "x".repeat(8_000) }),
serde_json::json!({
"value": "\0".repeat(4_500),
"openai/resource_access": resource_only["openai/resource_access"],
}),
],
2,
Some(ToolResultMetadata::new(&resource_only)),
),
] {
let mut metadata = metadata.to_vec();
metadata.extend(vec![
serde_json::json!({ "padding": "x".repeat(17_000) });
6
]);
let name_padding = (budget - 128 * 1024) / metadata.len();
let mut item = output("exec");
item.append_executed_tool_calls(
metadata
.iter()
.enumerate()
.map(|(index, metadata)| {
let mut call = ExecutedToolCall::new(
format!("tool_{index}{}", "x".repeat(name_padding)),
serde_json::json!({ "argument": index }),
);
call.set_tool_result_sources(ToolResultSources::new(vec![ToolResultSource {
r#type: "test_resource".to_string(),
id: format!("R{index}"),
}]));
call.set_tool_result_metadata(ToolResultMetadata::new(metadata));
call
})
.collect(),
);
item.set_tool_call_cell_id("exec");
item.mark_tool_calls_complete();
assert!(executed_tool_call_metadata_bytes(&item) > budget);
let replacement = replacement.unwrap_or_else(|| {
ToolResultMetadata::omitted_due_to_size_limit(
executed_tool_call_metadata_bytes(&item) - budget,
)
});
let mut expected = item.clone();
expected
.ensure_tool_call_metadata()
.unwrap()
.executed_tool_calls
.as_mut()
.unwrap()[reduced_index]
.set_tool_result_metadata(replacement);
let mut bounded = item.clone();
bound_executed_tool_calls_for_message(std::slice::from_mut(&mut bounded), budget);
assert_eq!(bounded, expected);
assert!(executed_tool_call_metadata_bytes(&bounded) <= budget);
bound_executed_tool_calls_for_message(std::slice::from_mut(&mut bounded), budget);
assert_eq!(bounded, expected);
}
}

View File

@@ -0,0 +1,164 @@
//! Per-part context sources, independent of message role, visibility, and trust.
use serde::Deserialize;
use serde::Serialize;
/// Harness-owned classification for one position in an item's content array.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(transparent)]
pub struct ContentItemKind(pub String);
impl ContentItemKind {
pub fn as_str(&self) -> &str {
&self.0
}
}
/// A callable namespace. Built-ins are typed; configured and MCP namespaces stay open.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(from = "String", into = "String")]
pub enum ContentItemNamespace {
Clock,
Functions,
ToolSearch,
Collaboration,
MultiAgentV1,
Other(String),
}
impl From<String> for ContentItemNamespace {
fn from(namespace: String) -> Self {
match namespace.as_str() {
"clock" => Self::Clock,
"functions" => Self::Functions,
"tool_search" => Self::ToolSearch,
"collaboration" => Self::Collaboration,
"multi_agent_v1" => Self::MultiAgentV1,
_ => Self::Other(namespace),
}
}
}
impl From<ContentItemNamespace> for String {
fn from(namespace: ContentItemNamespace) -> Self {
match namespace {
ContentItemNamespace::Clock => "clock".to_string(),
ContentItemNamespace::Functions => "functions".to_string(),
ContentItemNamespace::ToolSearch => "tool_search".to_string(),
ContentItemNamespace::Collaboration => "collaboration".to_string(),
ContentItemNamespace::MultiAgentV1 => "multi_agent_v1".to_string(),
ContentItemNamespace::Other(namespace) => namespace,
}
}
}
/// Who supplied a part. Tool-related context remains Tool even when the harness writes it.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentItemProvenance {
/// History saved before attribution, or content whose source is not known.
#[default]
#[serde(alias = "user_configured")]
Unknown,
/// The regular developer-instruction slot or additional requirements-layer instructions.
DeveloperInstructions { from_additional_requirements: bool },
/// Skill catalogs, usage guidance, and selected skill contents.
Skills,
/// Instructions loaded from AGENTS.md.
AgentsMd,
/// Harness-managed context; command-hook output is distinguished from built-in context.
Harness {
#[serde(default)]
hook: bool,
},
/// A tool result or tool-specific context; an unlisted tool can have no known namespace.
Tool {
#[serde(default, skip_serializing_if = "Option::is_none")]
namespace: Option<ContentItemNamespace>,
},
/// Ordinary user input, not an injected instruction fragment with a user role.
User,
}
/// Attribution for one position in a harness-emitted item's content array.
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
pub struct ContentItemMetadata {
pub provenance: ContentItemProvenance,
}
impl<'de> Deserialize<'de> for ContentItemMetadata {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
// Older records may lack attribution. Neither the old user_configured category
// nor a bare harness_injected:false identifies a source precisely enough.
#[derive(Deserialize)]
struct StoredMetadata {
#[serde(default)]
provenance: Option<ContentItemProvenance>,
#[serde(default)]
harness_injected: Option<bool>,
#[serde(default)]
source_tool_namespace: Option<String>,
}
let stored = StoredMetadata::deserialize(deserializer)?;
let provenance = stored.provenance.unwrap_or_else(|| {
match (stored.source_tool_namespace, stored.harness_injected) {
(Some(namespace), _) => ContentItemProvenance::Tool {
namespace: Some(namespace.into()),
},
(None, Some(true)) => ContentItemProvenance::Harness { hook: false },
(None, Some(false) | None) => ContentItemProvenance::Unknown,
}
});
Ok(Self { provenance })
}
}
impl ContentItemMetadata {
pub fn harness() -> Self {
Self {
provenance: ContentItemProvenance::Harness { hook: false },
}
}
pub fn command_hook() -> Self {
Self {
provenance: ContentItemProvenance::Harness { hook: true },
}
}
pub fn developer_instructions(from_additional_requirements: bool) -> Self {
Self {
provenance: ContentItemProvenance::DeveloperInstructions {
from_additional_requirements,
},
}
}
pub fn skills() -> Self {
Self {
provenance: ContentItemProvenance::Skills,
}
}
pub fn agents_md() -> Self {
Self {
provenance: ContentItemProvenance::AgentsMd,
}
}
pub fn user() -> Self {
Self {
provenance: ContentItemProvenance::User,
}
}
pub fn tool(namespace: Option<ContentItemNamespace>) -> Self {
Self {
provenance: ContentItemProvenance::Tool { namespace },
}
}
}
#[cfg(test)]
#[path = "item_metadata_tests.rs"]
mod tests;

View File

@@ -0,0 +1,116 @@
use super::ContentItemKind;
use crate::models::ContentItem;
use crate::models::InternalChatMessageMetadataPassthrough;
use crate::models::ResponseItem;
use anyhow::Result;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
#[test]
fn content_kinds_round_trip_without_restricting_future_values() -> Result<()> {
let item = response_item(InternalChatMessageMetadataPassthrough {
turn_id: Some("turn-1".to_string()),
content_item_kinds: Some(vec![ContentItemKind("future_content_kind".to_string())]),
..Default::default()
});
let serialized = serde_json::to_value(&item)?;
assert_eq!(
serialized,
json!({
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "hello"}],
"internal_chat_message_metadata_passthrough": {
"turn_id": "turn-1",
"content_item_kinds": ["future_content_kind"],
},
})
);
assert_eq!(serde_json::from_value::<ResponseItem>(serialized)?, item);
Ok(())
}
#[test]
fn malformed_content_kinds_do_not_prevent_loading_response_item() -> Result<()> {
for malformed_kinds in [
json!("user_text"),
json!({"kind": "user_text"}),
json!(["user_text", 123]),
] {
let item = serde_json::from_value::<ResponseItem>(response_item_json(json!({
"turn_id": "turn-1",
"content_item_kinds": malformed_kinds,
})))?;
assert_eq!(
item,
response_item(InternalChatMessageMetadataPassthrough {
turn_id: Some("turn-1".to_string()),
..Default::default()
})
);
}
Ok(())
}
#[test]
fn malformed_content_token_counts_do_not_prevent_loading_response_item() -> Result<()> {
for value in [json!(-1), json!(true), json!(1.5), json!("4"), json!(null)] {
let item: ResponseItem = serde_json::from_value(response_item_json(json!({
"content_token_count": value,
})))?;
assert_eq!(
item,
response_item(InternalChatMessageMetadataPassthrough::default())
);
}
Ok(())
}
#[test]
fn content_token_counts_are_not_replayed_into_requests() -> Result<()> {
let item: ResponseItem = serde_json::from_value(response_item_json(json!({
"turn_id": "turn-1", "content_token_count": 23,
})))?;
let ResponseItem::Message {
internal_chat_message_metadata_passthrough: Some(ref metadata),
..
} = item
else {
panic!("expected message metadata");
};
assert_eq!(metadata.content_token_count, Some(23));
let encoded = serde_json::to_value(item)?;
assert_eq!(
encoded["internal_chat_message_metadata_passthrough"],
json!({"turn_id": "turn-1"})
);
Ok(())
}
fn response_item(metadata: InternalChatMessageMetadataPassthrough) -> ResponseItem {
ResponseItem::Message {
status: None,
encrypted_content: None,
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: "hello".to_string(),
}],
phase: None,
internal_chat_message_metadata_passthrough: Some(metadata),
}
}
fn response_item_json(metadata: Value) -> Value {
json!({
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "hello"}],
"internal_chat_message_metadata_passthrough": metadata,
})
}

View File

@@ -0,0 +1,22 @@
use crate::approvals::NetworkApprovalProtocol;
use akode_network_proxy::NetworkDecisionSource;
use akode_network_proxy::NetworkPolicyDecision;
use serde::Deserialize;
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct NetworkPolicyDecisionPayload {
pub decision: NetworkPolicyDecision,
pub source: NetworkDecisionSource,
#[serde(default)]
pub protocol: Option<NetworkApprovalProtocol>,
pub host: Option<String>,
pub reason: Option<String>,
pub port: Option<u16>,
}
impl NetworkPolicyDecisionPayload {
pub fn is_ask_from_decider(&self) -> bool {
self.decision == NetworkPolicyDecision::Ask && self.source == NetworkDecisionSource::Decider
}
}

View File

@@ -0,0 +1,29 @@
use std::sync::OnceLock;
use icu_decimal::DecimalFormatter;
use icu_decimal::input::Decimal;
use icu_decimal::options::DecimalFormatterOptions;
use icu_locale_core::Locale;
fn make_local_formatter() -> Option<DecimalFormatter> {
let loc: Locale = sys_locale::get_locale()?.parse().ok()?;
DecimalFormatter::try_new(loc.into(), DecimalFormatterOptions::default()).ok()
}
fn make_en_us_formatter() -> DecimalFormatter {
#![allow(clippy::expect_used)]
let loc: Locale = "en-US".parse().expect("en-US wasn't a valid locale");
DecimalFormatter::try_new(loc.into(), DecimalFormatterOptions::default())
.expect("en-US wasn't a valid locale")
}
fn formatter() -> &'static DecimalFormatter {
static FORMATTER: OnceLock<DecimalFormatter> = OnceLock::new();
FORMATTER.get_or_init(|| make_local_formatter().unwrap_or_else(make_en_us_formatter))
}
/// Format an i64 with locale-aware digit separators (e.g. "12345" -> "12,345"
/// for en-US).
pub fn format_with_separators(n: i64) -> String {
formatter().format(&Decimal::from(n)).to_string()
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,200 @@
//! Model-owned Guardian coverage. Missing policy preserves legacy behavior;
//! unknown modes retain synchronous review and never enable the fast path.
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
use super::ModelInfo;
use crate::ToolName;
use crate::mcp::is_node_repl_backed_server;
use crate::mcp::is_node_repl_backed_tool;
/// How Guardian handles an action when the user selects automatic approval.
#[derive(Debug, Default, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum GuardianReviewMode {
#[default]
Disabled,
Synchronous,
/// Use a current low-risk score; otherwise run synchronous review.
Adaptive,
#[serde(other)]
Unknown,
}
/// How actions outside adaptive coverage affect cached classification evidence.
#[derive(Debug, Default, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum GuardianUnscoredAction {
Ignore,
AgeScore,
#[default]
#[serde(other)]
InvalidateScore,
}
/// A complete model policy. Omitted scopes are disabled; unknown fields are ignored.
/// Code Mode wrappers have no approval scope; their nested tools follow this policy.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct GuardianModelPolicy {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub computer_use: Option<GuardianReviewMode>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub shell: Option<GuardianReviewMode>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file_changes: Option<GuardianReviewMode>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mcp: Option<GuardianReviewMode>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub network: Option<GuardianReviewMode>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub permissions: Option<GuardianReviewMode>,
/// Coverage for tools without an approval category.
#[serde(default)]
pub other_tools: GuardianReviewMode,
#[serde(default)]
pub unscored_action: GuardianUnscoredAction,
/// Omission retains the existing allowance for adaptive computer use.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub initial_cua_call: Option<bool>,
/// Whether adaptive shell coverage includes ordinary sandboxed commands.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sandboxed_exec_commands: Option<bool>,
}
impl GuardianModelPolicy {
pub fn review_mode(&self, scope: GuardianScope) -> GuardianReviewMode {
match scope {
GuardianScope::ComputerUse => self.computer_use,
GuardianScope::Shell => self.shell,
GuardianScope::FileChanges => self.file_changes,
GuardianScope::Mcp => self.mcp,
GuardianScope::Network => self.network,
GuardianScope::Permissions => self.permissions,
GuardianScope::NativeTool => Some(GuardianReviewMode::Synchronous),
}
.unwrap_or(GuardianReviewMode::Disabled)
}
pub fn scoring_enabled(&self) -> bool {
[
self.computer_use,
self.shell,
self.file_changes,
self.mcp,
self.network,
self.permissions,
]
.contains(&Some(GuardianReviewMode::Adaptive))
}
pub fn disable_scoring(&mut self) {
for mode in [
&mut self.computer_use,
&mut self.shell,
&mut self.file_changes,
&mut self.mcp,
&mut self.network,
&mut self.permissions,
] {
if *mode == Some(GuardianReviewMode::Adaptive) {
*mode = Some(GuardianReviewMode::Synchronous);
}
}
self.other_tools = GuardianReviewMode::Synchronous;
}
pub fn allows_initial_cua_call(&self) -> bool {
self.initial_cua_call
.unwrap_or(self.computer_use == Some(GuardianReviewMode::Adaptive))
}
}
/// Approval categories understood by this client. Future catalog keys are ignored.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GuardianScope {
ComputerUse,
Shell,
FileChanges,
Mcp,
Network,
Permissions,
NativeTool,
}
impl GuardianScope {
pub fn for_mcp_server(server: &str) -> Self {
if is_node_repl_backed_server(server) {
Self::ComputerUse
} else {
Self::Mcp
}
}
/// Classifies state-changing MAv2 calls in the configured namespace.
/// An absent namespace accepts the default namespace spellings; callers gate this lookup.
pub fn for_multi_agent_tool(tool: &ToolName, namespace: Option<&str>) -> Option<Self> {
let matches_namespace = match namespace {
Some(namespace) => tool.namespace.as_deref() == Some(namespace),
None => tool.is_default_namespace(),
};
if matches_namespace
&& matches!(
tool.name.as_str(),
"spawn_agent" | "send_message" | "followup_task" | "interrupt_agent"
)
{
Some(Self::NativeTool)
} else {
None
}
}
pub fn for_tool(tool: &ToolName) -> Option<Self> {
if is_node_repl_backed_tool(&tool.name, tool.namespace.as_deref()) {
return Some(Self::ComputerUse);
}
if tool
.namespace
.as_deref()
.is_some_and(|namespace| namespace.starts_with("mcp__"))
|| tool.name.starts_with("mcp__")
{
return Some(Self::Mcp);
}
if !tool.is_default_namespace() {
return None;
}
match tool.name.as_str() {
"shell" | "shell_command" | "exec_command" | "write_stdin" | "execve" => {
Some(Self::Shell)
}
"apply_patch" => Some(Self::FileChanges),
"request_permissions" => Some(Self::Permissions),
_ => None,
}
}
}
impl ModelInfo {
/// An absent map uses legacy config; an omitted scope in a supplied map is disabled.
pub fn guardian_review_mode(&self, scope: GuardianScope) -> Option<GuardianReviewMode> {
self.guardian
.as_ref()
.map(|policy| policy.review_mode(scope))
}
/// The legacy metadata bit remains the transport understood by older CUA servers.
pub fn computer_use_review_required(&self) -> bool {
self.guardian_review_mode(GuardianScope::ComputerUse)
.map_or(self.node_repl_auto_review_required, |mode| {
mode != GuardianReviewMode::Disabled
})
}
}
#[cfg(test)]
#[path = "guardian_tests.rs"]
mod tests;

View File

@@ -0,0 +1,48 @@
use super::super::tests::test_model;
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn guardian_policy_is_optional_and_tolerates_future_config() -> anyhow::Result<()> {
let model = test_model(/*spec*/ None);
let mut wire = serde_json::to_value(&model)?;
assert!(
!wire
.as_object()
.expect("model object")
.contains_key("guardian")
);
assert_eq!(serde_json::from_value::<ModelInfo>(wire.clone())?, model);
wire["guardian"] = serde_json::json!({
"computer_use": "adaptive", "shell": "future_mode", "future_scope": {"version": 2},
"mcp": null, "permissions": "adaptive",
});
let model: ModelInfo = serde_json::from_value(wire)?;
assert_eq!(
model.guardian,
Some(GuardianModelPolicy {
computer_use: Some(GuardianReviewMode::Adaptive),
shell: Some(GuardianReviewMode::Unknown),
permissions: Some(GuardianReviewMode::Adaptive),
..Default::default()
})
);
assert!(model.computer_use_review_required());
assert_eq!(
model.guardian_review_mode(GuardianScope::Mcp),
Some(GuardianReviewMode::Disabled)
);
Ok(())
}
#[test]
fn guardian_policy_overrides_the_legacy_cua_bit_only_when_present() {
let mut model = test_model(/*spec*/ None);
model.node_repl_auto_review_required = true;
assert!(model.computer_use_review_required());
model.guardian = Some(GuardianModelPolicy::default());
assert!(!model.computer_use_review_required());
model.guardian.as_mut().expect("policy").computer_use = Some(GuardianReviewMode::Synchronous);
assert!(model.computer_use_review_required());
}

View File

@@ -0,0 +1,64 @@
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
use super::ReasoningEffort;
/// Legacy classifier modes retained for configuration and model-catalog compatibility.
#[derive(Debug, Default, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)]
#[serde(rename_all = "snake_case")]
#[ts(rename_all = "snake_case")]
pub enum AsyncClassifierMode {
Snapshot,
#[default]
Conversation,
}
/// Optional model-owned defaults for Guardian v2 classification experiments.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct GuardianV2ModelConfig {
/// Deprecated and ignored; asynchronous classification always uses conversations.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub async_classifier_mode: Option<AsyncClassifierMode>,
/// Reset retained async history when the next request exceeds this token estimate.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub async_classifier_conversation_token_limit: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub classifier_instructions: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub review_threshold_basis_points: Option<u16>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_tool_call_lag: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reasoning_effort: Option<ReasoningEffort>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub transcript: Option<GuardianV2TranscriptModelConfig>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_action_tokens: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_classifier_instruction_tokens: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reuse_parent_compaction: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_parent_compaction_tokens: Option<usize>,
}
/// Optional model-owned defaults for selecting and bounding Guardian v2 history.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct GuardianV2TranscriptModelConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sources: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub include_images: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_message_entry_tokens: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_tool_entry_tokens: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_message_transcript_tokens: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_tool_transcript_tokens: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_recent_non_user_entries: Option<usize>,
}

View File

@@ -0,0 +1,30 @@
//! Optional model-catalog overrides for harness-owned incremental tool notices.
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
/// Incremental tool notice overrides; missing/null or >512-byte values use bundled defaults.
/// Empty strings omit static text but retain runtime names and instructions.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct IncrementalToolMessages {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool_update_hint: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub removed_tools_header: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub removed_namespaces_header: Option<String>,
/// Prefix supporting `{name}`; the namespace instructions are appended verbatim.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespace_instructions_prefix: Option<String>,
/// Message supporting `{name}` when a namespace's instructions are cleared.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespace_instructions_cleared: Option<String>,
/// Literal hint before changed Code Mode tool definitions and namespace instructions.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exec_tools_update_hint: Option<String>,
/// Literal header before removed Code Mode tool and namespace-instruction identities.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exec_tools_removed_definitions_header: Option<String>,
}

View File

@@ -0,0 +1,52 @@
//! Sparse Memento V2 tool definitions. Runtime data remains with consumers.
use super::ToolMessage;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
/// Model-owned history namespace and public tool definitions.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct HistoryToolMessages {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespace_description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub list_windows: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub list_items: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub read_item: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub search_contents: Option<ToolMessage>,
}
/// Model-owned notes namespace and public tool definitions.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct NotesToolMessages {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespace_description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub list_files_by_prefix: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub read_file: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub search_contents: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub append_to_file: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub write_file: Option<ToolMessage>,
}
/// Model-owned context-window control tool definitions.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ContextManagementToolMessages {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub new_context: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub get_context_remaining: Option<ToolMessage>,
}
#[cfg(test)]
#[path = "memento_v2_tests.rs"]
mod tests;

View File

@@ -0,0 +1,18 @@
use crate::openai_models::ModelMessages;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn memento_catalog_round_trip_preserves_sparse_tools_and_explicit_empty() {
for tools in [
json!({}),
json!({
"history": {"namespace_description": "", "read_item": {"description": "", "parameters": "not JSON"}},
"notes": {"read_file": {"parameters": "{}"}},
"context_management": {"new_context": {"description": "catalog"}}
}),
] {
let messages: ModelMessages = serde_json::from_value(json!({"tools": tools})).unwrap();
assert_eq!(serde_json::to_value(messages.tools).unwrap(), tools);
}
}

View File

@@ -0,0 +1,66 @@
//! Sparse model-catalog wording for generic, selected, and recommended plugins.
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
/// Sparse plugin wording families, independent of runtime availability and authorization.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct PluginMessages {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub generic: Option<GenericPluginMessages>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub selected: Option<SelectedPluginMessages>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recommendations: Option<PluginRecommendationMessages>,
}
/// Literal generic plugin wording. Missing, null, blank, or invalid values use bundled text.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct GenericPluginMessages {
/// Literal text, up to 500 UTF-8 bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub intro: Option<String>,
/// Up to 2,000 UTF-8 bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage_instructions: Option<String>,
}
/// Selected-plugin wording. Fact-bearing fields require exactly one documented placeholder.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct SelectedPluginMessages {
/// Up to 500 UTF-8 bytes. Selected intro requires `{{ plugin_name }}`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub intro: Option<String>,
/// Up to 500 UTF-8 bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub search_tools: Option<String>,
/// Up to 500 UTF-8 bytes; requires `{{ skill_namespace }}`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skill_namespace: Option<String>,
/// Up to 500 UTF-8 bytes; requires `{{ apps }}`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub apps: Option<String>,
/// Up to 500 UTF-8 bytes; requires `{{ mcp_servers }}`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mcp_servers: Option<String>,
/// Up to 500 UTF-8 bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub closing: Option<String>,
/// Nonblank omission notice, up to 500 UTF-8 bytes, including any desired separator.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub omitted: Option<String>,
}
/// Literal recommendation introduction; plugin identities remain supplied by the harness.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct PluginRecommendationMessages {
/// Literal text, up to 500 UTF-8 bytes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub intro: Option<String>,
}
#[cfg(test)]
#[path = "plugins_tests.rs"]
mod tests;

View File

@@ -0,0 +1,34 @@
#![cfg(test)]
use crate::openai_models::ModelMessages;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn plugin_messages_preserve_sparse_nested_and_literal_wire_values() {
for plugins in [
serde_json::Value::Null,
json!({}),
json!({"generic": {}, "selected": {}, "recommendations": {}}),
json!({
"generic": {"intro": "", "usage_instructions": " \r\n\t"},
"selected": {
"intro": " {{ plugin_name }}\r\n",
"search_tools": "literal {{braces}}",
"skill_namespace": "{{ skill_namespace }}",
"apps": "{{ apps }}",
"mcp_servers": "{{ mcp_servers }}",
"closing": "é".repeat(251),
"omitted": "omitted"
},
"recommendations": {"intro": "recommendations"}
}),
] {
let messages: ModelMessages = serde_json::from_value(json!({"plugins": plugins})).unwrap();
let mut expected = serde_json::to_value(ModelMessages::default()).unwrap();
if !plugins.is_null() {
expected["plugins"] = plugins;
}
assert_eq!(serde_json::to_value(messages).unwrap(), expected);
}
}

View File

@@ -0,0 +1,44 @@
//! Model-owned effort normalization shared by native requests and configuration update items.
//!
//! UI aliases resolve through the same model defaults and fallbacks in both paths.
use super::ModelInfo;
use super::ReasoningEffort;
impl ModelInfo {
/// Resolves a selected effort to the value sent in an ordinary inference request.
pub fn resolve_reasoning_effort(&self, effort: ReasoningEffort) -> ReasoningEffort {
match effort {
ReasoningEffort::Ultra => self
.multi_agent_reasoning_effort
.as_ref()
.filter(|effort| {
*effort != &ReasoningEffort::Ultra
&& self
.supported_reasoning_levels
.iter()
.any(|preset| &preset.effort == *effort)
})
.cloned()
.or_else(|| {
self.supported_reasoning_levels
.iter()
.find(|preset| preset.effort == ReasoningEffort::Max)
.or_else(|| {
self.supported_reasoning_levels
.iter()
.rev()
.find(|preset| preset.effort != ReasoningEffort::Ultra)
})
.map(|preset| preset.effort.clone())
})
.unwrap_or(ReasoningEffort::Medium),
// Keep "persistent" in local settings; the Responses API calls it "disabled".
ReasoningEffort::Persistent => ReasoningEffort::Custom("disabled".to_string()),
effort => effort,
}
}
}
#[cfg(test)]
#[path = "reasoning_effort_tests.rs"]
mod tests;

View File

@@ -0,0 +1,52 @@
use super::super::ReasoningEffortPreset;
use super::super::tests::test_model;
use super::ReasoningEffort;
use pretty_assertions::assert_eq;
#[test]
fn resolves_ultra_using_model_override_and_supported_fallbacks() {
use ReasoningEffort::High;
use ReasoningEffort::Low;
use ReasoningEffort::Max;
use ReasoningEffort::Medium;
use ReasoningEffort::Ultra;
use ReasoningEffort::XHigh;
for (supported, multi_agent_effort, expected) in [
(vec![High, Max, Ultra], Some(High), High),
(vec![High, Max, Ultra], None, Max),
(vec![High, XHigh, Ultra], None, XHigh),
(vec![High, XHigh, Ultra], Some(Ultra), XHigh),
(vec![High, XHigh, Ultra], Some(Low), XHigh),
(vec![], None, Medium),
] {
let mut model = test_model(/*spec*/ None);
model.supported_reasoning_levels = supported
.into_iter()
.map(|effort| ReasoningEffortPreset {
effort,
description: String::new(),
})
.collect();
model.multi_agent_reasoning_effort = multi_agent_effort;
assert_eq!(model.resolve_reasoning_effort(Ultra), expected);
}
}
#[test]
fn preserves_native_efforts_and_translates_persistent_mode() {
let model = test_model(/*spec*/ None);
for effort in [
ReasoningEffort::Low,
ReasoningEffort::Medium,
ReasoningEffort::High,
ReasoningEffort::Max,
ReasoningEffort::Custom("future-effort".to_string()),
] {
assert_eq!(model.resolve_reasoning_effort(effort.clone()), effort);
}
assert_eq!(
model.resolve_reasoning_effort(ReasoningEffort::Persistent),
ReasoningEffort::Custom("disabled".to_string()),
);
}

View File

@@ -0,0 +1,31 @@
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::path::PathBuf;
use ts_rs::TS;
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ParsedCommand {
Read {
cmd: String,
name: String,
/// (Best effort) Path to the file being read by the command. When
/// possible, this is an absolute path, though when relative, it should
/// be resolved against the `cwd`` that will be used to run the command
/// to derive the absolute path.
path: PathBuf,
},
ListFiles {
cmd: String,
path: Option<String>,
},
Search {
cmd: String,
query: Option<String>,
path: Option<String>,
},
Unknown {
cmd: String,
},
}

View File

@@ -0,0 +1,425 @@
use std::path::Path;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_absolute_path::canonicalize_preserving_symlinks;
use thiserror::Error;
use crate::models::PermissionProfile;
use crate::permissions::FileSystemAccessMode;
use crate::permissions::FileSystemPath;
use crate::permissions::FileSystemSandboxEntry;
use crate::permissions::FileSystemSandboxKind;
use crate::permissions::FileSystemSandboxPolicy;
use crate::permissions::FileSystemSpecialPath;
use crate::permissions::NetworkSandboxPolicy;
use crate::permissions::PROTECTED_METADATA_PATH_NAMES;
use crate::permissions::ReadDenyMatcher;
use crate::permissions::default_read_only_subpaths_for_writable_root;
use crate::permissions::project_roots_glob_pattern;
/// A policy cannot be intersected without weakening either input.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub enum PermissionIntersectionError {
#[error("externally enforced filesystem permissions cannot be intersected safely")]
ExternalSandbox,
#[error("platform-default filesystem permissions cannot be intersected safely")]
PlatformDefaults,
#[error("unsupported permission path: {0}")]
UnsupportedPath(String),
}
/// Intersects already-effective filesystem permissions and network access.
///
/// Both profiles must already be materialized for the same local executor and
/// cwd. Concrete grant paths are canonicalized before comparison and in the
/// result, so symlinks cannot acquire authority beyond either input.
/// Unsupported policy shapes fail closed.
pub fn intersect_effective_permission_profiles(
authority: &PermissionProfile,
requested: &PermissionProfile,
cwd: &Path,
) -> Result<PermissionProfile, PermissionIntersectionError> {
if matches!(authority, PermissionProfile::External { .. })
|| matches!(requested, PermissionProfile::External { .. })
{
return Err(PermissionIntersectionError::ExternalSandbox);
}
AbsolutePathBuf::from_absolute_path_checked(cwd)
.map_err(|error| PermissionIntersectionError::UnsupportedPath(error.to_string()))?;
for profile in [authority, requested] {
for entry in profile.file_system_sandbox_policy().entries {
match entry.path {
FileSystemPath::Path { path } => {
path.to_abs_path().map_err(|error| {
PermissionIntersectionError::UnsupportedPath(error.to_string())
})?;
}
FileSystemPath::Special {
value: FileSystemSpecialPath::ProjectRoots { .. },
} => {
return Err(PermissionIntersectionError::UnsupportedPath(
"workspace permissions must already be materialized".to_string(),
));
}
FileSystemPath::GlobPattern { pattern }
if pattern.starts_with(&project_roots_glob_pattern(Path::new(""))) =>
{
return Err(PermissionIntersectionError::UnsupportedPath(pattern));
}
FileSystemPath::GlobPattern { .. } | FileSystemPath::Special { .. } => {}
}
}
}
let mut authority_policy = authority.file_system_sandbox_policy();
let mut requested_policy = requested.file_system_sandbox_policy();
let root_path = FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
};
let network = if authority.network_sandbox_policy().is_enabled()
&& requested.network_sandbox_policy().is_enabled()
{
NetworkSandboxPolicy::Enabled
} else {
NetworkSandboxPolicy::Restricted
};
if matches!(authority, PermissionProfile::Disabled)
&& matches!(requested, PermissionProfile::Disabled)
{
return Ok(PermissionProfile::Disabled);
}
if authority_policy == requested_policy {
return Ok(PermissionProfile::from_runtime_permissions(
&authority_policy,
network,
));
}
if matches!(authority_policy.kind, FileSystemSandboxKind::Unrestricted) {
return Ok(PermissionProfile::from_runtime_permissions(
&requested_policy,
network,
));
}
if matches!(requested_policy.kind, FileSystemSandboxKind::Unrestricted) {
return Ok(PermissionProfile::from_runtime_permissions(
&authority_policy,
network,
));
}
normalize_policy(&mut authority_policy)?;
normalize_policy(&mut requested_policy)?;
let tmpdir = FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
};
let temp_entries = [&authority_policy, &requested_policy].map(|policy| {
policy
.entries
.iter()
.filter(|entry| entry.path == tmpdir)
.collect::<Vec<_>>()
});
let common_temp = match (temp_entries[0].as_slice(), temp_entries[1].as_slice()) {
([left], [right])
if [left, right]
.into_iter()
.all(|entry| entry.access.can_write() && !entry.skips_missing_path()) =>
{
Some(FileSystemSandboxEntry::new(tmpdir.clone(), left.access))
}
([], []) => None,
([entry], []) | ([], [entry])
if entry.access.can_write() && !entry.skips_missing_path() =>
{
None
}
_ => {
return Err(PermissionIntersectionError::UnsupportedPath(
":tmpdir restrictions require executor-local bindings".to_string(),
));
}
};
for policy in [&mut authority_policy, &mut requested_policy] {
policy.entries.retain(|entry| entry.path != tmpdir);
}
let authority_denies = ReadDenyMatcher::try_new_for_local_paths(&authority_policy, cwd)
.map_err(PermissionIntersectionError::UnsupportedPath)?;
let requested_denies = ReadDenyMatcher::try_new_for_local_paths(&requested_policy, cwd)
.map_err(PermissionIntersectionError::UnsupportedPath)?;
let sources = [
(&authority_policy, authority_denies.as_ref()),
(&requested_policy, requested_denies.as_ref()),
];
let mut paths = Vec::new();
let mut denies = Vec::new();
let mut glob_depth: Option<Option<usize>> = None;
for (policy, _) in sources {
let writable_roots = policy.get_writable_roots_with_cwd(cwd);
for entry in &policy.entries {
if entry.access == FileSystemAccessMode::Deny && !denies.contains(entry) {
denies.push(entry.clone());
}
if matches!(entry.path, FileSystemPath::GlobPattern { .. }) {
glob_depth = Some(match glob_depth {
None => policy.glob_scan_max_depth,
Some(Some(previous)) => {
policy.glob_scan_max_depth.map(|depth| previous.max(depth))
}
Some(None) => None,
});
}
let Some(path) = entry_path(entry, cwd)? else {
continue;
};
if entry.skips_missing_path()
&& (entry.access != FileSystemAccessMode::Read
|| !writable_roots.iter().any(|root| {
root.read_only_subpaths.contains(&path)
|| default_read_only_subpaths_for_writable_root(
&root.root, /*protect_missing_dot_codex*/ false,
)
.contains(&path)
|| path.parent().as_ref() == Some(&root.root)
&& PROTECTED_METADATA_PATH_NAMES.iter().any(|name| {
path.as_path().file_name() == Some(std::ffi::OsStr::new(name))
})
}))
{
return Err(PermissionIntersectionError::UnsupportedPath(
"non-metadata optional permissions".to_string(),
));
}
paths.push(path);
}
paths.extend(policy.get_readable_roots_with_cwd(cwd));
for root in writable_roots {
paths.push(root.root.clone());
paths.extend(
PROTECTED_METADATA_PATH_NAMES
.iter()
.map(|name| root.root.join(name)),
);
paths.extend(root.read_only_subpaths);
}
}
paths.sort_by(|left, right| {
left.as_path()
.components()
.count()
.cmp(&right.as_path().components().count())
.then_with(|| left.as_path().cmp(right.as_path()))
});
paths.dedup();
denies.sort_by_cached_key(|entry| format!("{:?}", entry.path));
let mut intersection = FileSystemSandboxPolicy::restricted(denies);
intersection.glob_scan_max_depth = glob_depth.flatten();
let intersection_denies = ReadDenyMatcher::try_new_for_local_paths(&intersection, cwd)
.map_err(PermissionIntersectionError::UnsupportedPath)?;
for path in paths {
let [left, right] =
sources.map(|(policy, denies)| effective_access(policy, denies, path.as_path(), cwd));
let access = intersect_access(left, right);
let current = effective_access(
&intersection,
intersection_denies.as_ref(),
path.as_path(),
cwd,
);
let optional_metadata = sources.into_iter().any(|(policy, _)| {
policy.entries.iter().any(|entry| {
entry.skips_missing_path()
&& entry_path(entry, cwd).ok().flatten().as_ref() == Some(&path)
})
});
let required_restriction = sources.into_iter().any(|(policy, _)| {
policy.entries.iter().any(|entry| {
!entry.skips_missing_path()
&& !entry.access.can_write()
&& entry_path(entry, cwd).ok().flatten().as_ref() == Some(&path)
})
});
if access == current && !optional_metadata && !required_restriction {
continue;
}
let path = if path.as_path().parent().is_none()
&& cwd.starts_with(path.as_path())
&& sources
.into_iter()
.all(|(policy, _)| policy.entries.iter().any(|entry| entry.path == root_path))
{
root_path.clone()
} else {
path.into()
};
let entry =
if optional_metadata && !required_restriction && access == FileSystemAccessMode::Read {
FileSystemSandboxEntry::skip_missing_path(path, access)
} else {
FileSystemSandboxEntry::new(path, access)
};
if !intersection.entries.contains(&entry) {
intersection.entries.push(entry);
}
}
if let Some(temp) = common_temp {
intersection.entries.push(temp);
}
Ok(PermissionProfile::from_runtime_permissions(
&intersection,
network,
))
}
fn normalize_policy(
policy: &mut FileSystemSandboxPolicy,
) -> Result<(), PermissionIntersectionError> {
if policy.include_platform_defaults() {
return Err(PermissionIntersectionError::PlatformDefaults);
}
for entry in &mut policy.entries {
match &entry.path {
FileSystemPath::Path { path } => {
let path = path.to_abs_path().map_err(|error| {
PermissionIntersectionError::UnsupportedPath(error.to_string())
})?;
let physical = if entry.access.can_write()
|| entry.access == FileSystemAccessMode::Read && !entry.skips_missing_path()
{
path.canonicalize().map_err(|error| {
PermissionIntersectionError::UnsupportedPath(format!(
"{}: {error}",
path.as_path().display()
))
})?
} else {
physical_path(&path)?
};
let logical = path.ancestors().find_map(|ancestor| {
std::fs::symlink_metadata(ancestor.as_path()).ok()?;
let preserved = canonicalize_preserving_symlinks(ancestor.as_path()).ok()?;
let suffix = path.as_path().strip_prefix(ancestor.as_path()).ok()?;
Some(
AbsolutePathBuf::from_absolute_path_checked(preserved)
.ok()?
.join(suffix),
)
});
if !entry.access.can_write() && logical.as_ref() != Some(&physical) {
return Err(PermissionIntersectionError::UnsupportedPath(format!(
"symlinked restriction: {}",
path.as_path().display()
)));
}
entry.path = physical.into();
}
FileSystemPath::GlobPattern { pattern }
if entry.access != FileSystemAccessMode::Deny || entry.skips_missing_path() =>
{
return Err(PermissionIntersectionError::UnsupportedPath(format!(
"glob permissions: {pattern}"
)));
}
FileSystemPath::GlobPattern { .. } => {}
FileSystemPath::Special {
value: FileSystemSpecialPath::Root | FileSystemSpecialPath::Tmpdir,
} => {}
FileSystemPath::Special {
value: FileSystemSpecialPath::SlashTmp,
} => {
if cfg!(unix) {
entry.path = physical_path(
&AbsolutePathBuf::from_absolute_path_checked("/tmp").map_err(|error| {
PermissionIntersectionError::UnsupportedPath(error.to_string())
})?,
)?
.into();
}
}
FileSystemPath::Special {
value: FileSystemSpecialPath::Minimal,
} => return Err(PermissionIntersectionError::PlatformDefaults),
FileSystemPath::Special { value } => {
return Err(PermissionIntersectionError::UnsupportedPath(format!(
"{value:?}"
)));
}
}
}
Ok(())
}
fn entry_path(
entry: &FileSystemSandboxEntry,
cwd: &Path,
) -> Result<Option<AbsolutePathBuf>, PermissionIntersectionError> {
match &entry.path {
FileSystemPath::Path { path } => path
.to_abs_path()
.map(Some)
.map_err(|error| PermissionIntersectionError::UnsupportedPath(error.to_string())),
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
} => cwd
.ancestors()
.last()
.and_then(|root| AbsolutePathBuf::from_absolute_path_checked(root).ok())
.map(Some)
.ok_or_else(|| PermissionIntersectionError::UnsupportedPath(cwd.display().to_string())),
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir | FileSystemSpecialPath::SlashTmp,
} => Ok(None),
FileSystemPath::Special { value } => Err(PermissionIntersectionError::UnsupportedPath(
format!("{value:?}"),
)),
FileSystemPath::GlobPattern { .. } => Ok(None),
}
}
fn physical_path(path: &AbsolutePathBuf) -> Result<AbsolutePathBuf, PermissionIntersectionError> {
for ancestor in path.ancestors() {
if let Ok(physical) = ancestor.canonicalize()
&& let Ok(suffix) = path.as_path().strip_prefix(ancestor.as_path())
{
return Ok(physical.join(suffix));
}
}
Err(PermissionIntersectionError::UnsupportedPath(
path.as_path().display().to_string(),
))
}
fn effective_access(
policy: &FileSystemSandboxPolicy,
denies: Option<&ReadDenyMatcher>,
path: &Path,
cwd: &Path,
) -> FileSystemAccessMode {
if denies.is_some_and(|matcher| matcher.is_local_path_read_denied(path)) {
FileSystemAccessMode::Deny
} else if policy.can_write_local_path_with_cwd(path, cwd) {
FileSystemAccessMode::Write
} else if policy.can_read_local_path_with_cwd(path, cwd) {
FileSystemAccessMode::Read
} else {
FileSystemAccessMode::Deny
}
}
fn intersect_access(
left: FileSystemAccessMode,
right: FileSystemAccessMode,
) -> FileSystemAccessMode {
match (left, right) {
(FileSystemAccessMode::Deny, _) | (_, FileSystemAccessMode::Deny) => {
FileSystemAccessMode::Deny
}
(FileSystemAccessMode::Write, FileSystemAccessMode::Write) => FileSystemAccessMode::Write,
(FileSystemAccessMode::Read | FileSystemAccessMode::Write, _) => FileSystemAccessMode::Read,
}
}
#[cfg(test)]
#[path = "permission_profile_intersection_tests.rs"]
mod tests;

View File

@@ -0,0 +1,386 @@
use std::path::Path;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use super::PermissionIntersectionError;
use super::intersect_effective_permission_profiles;
use crate::models::PermissionProfile;
use crate::permissions::FileSystemAccessMode;
use crate::permissions::FileSystemAccessMode::Deny;
use crate::permissions::FileSystemAccessMode::Read;
use crate::permissions::FileSystemAccessMode::Write;
use crate::permissions::FileSystemPath;
use crate::permissions::FileSystemSandboxEntry;
use crate::permissions::FileSystemSandboxPolicy;
use crate::permissions::FileSystemSandboxPolicyContext;
use crate::permissions::FileSystemSpecialPath;
use crate::permissions::FileSystemSpecialPath::Minimal;
use crate::permissions::FileSystemSpecialPath::Tmpdir;
use crate::permissions::NetworkSandboxPolicy;
use crate::permissions::NetworkSandboxPolicy::Enabled;
use crate::permissions::NetworkSandboxPolicy::Restricted;
use crate::permissions::ReadDenyMatcher;
use crate::permissions::project_roots_glob_pattern;
fn absolute(path: &Path) -> AbsolutePathBuf {
AbsolutePathBuf::from_absolute_path(path).expect("absolute test path")
}
fn canonical(temp: &TempDir) -> AbsolutePathBuf {
absolute(temp.path())
.canonicalize()
.expect("canonical root")
}
fn managed(entries: Vec<FileSystemSandboxEntry>) -> PermissionProfile {
PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(entries),
Restricted,
)
}
fn entry(path: &Path, access: FileSystemAccessMode) -> FileSystemSandboxEntry {
FileSystemSandboxEntry::new(absolute(path).into(), access)
}
fn special(value: FileSystemSpecialPath, access: FileSystemAccessMode) -> FileSystemSandboxEntry {
FileSystemSandboxEntry::new(FileSystemPath::Special { value }, access)
}
fn skipped(path: FileSystemPath, access: FileSystemAccessMode) -> FileSystemSandboxEntry {
FileSystemSandboxEntry::skip_missing_path(path, access)
}
fn deny_glob(pattern: &str) -> FileSystemSandboxEntry {
FileSystemSandboxEntry::new(
FileSystemPath::GlobPattern {
pattern: pattern.into(),
},
Deny,
)
}
fn root_read() -> FileSystemSandboxEntry {
FileSystemSandboxPolicy::read_only().entries[0].clone()
}
fn rooted(
root: &AbsolutePathBuf,
access: FileSystemAccessMode,
entries: impl IntoIterator<Item = FileSystemSandboxEntry>,
) -> PermissionProfile {
let mut all_entries = vec![root_read(), entry(root.as_path(), access)];
all_entries.extend(entries);
managed(all_entries)
}
fn workspace(root: &AbsolutePathBuf, network: NetworkSandboxPolicy) -> PermissionProfile {
PermissionProfile::workspace_write_with(
&[],
network,
/*exclude_tmpdir_env_var*/ false,
/*exclude_slash_tmp*/ true,
)
.materialize_project_roots_with_workspace_roots(std::slice::from_ref(root))
}
fn intersection(
left: &PermissionProfile,
right: &PermissionProfile,
cwd: &AbsolutePathBuf,
) -> PermissionProfile {
intersect_effective_permission_profiles(left, right, cwd.as_path()).expect("safe intersection")
}
#[test]
fn effective_workspace_intersection_preserves_network_metadata_and_temp() {
let temp = TempDir::new().expect("workspace");
let root = canonical(&temp);
let project = root.join("project");
std::fs::create_dir(project.as_path()).expect("project directory");
let gitdir = root.join("external-gitdir");
std::fs::create_dir(gitdir.as_path()).expect("worktree gitdir");
std::fs::write(
project.join(".git").as_path(),
format!("gitdir: {}", gitdir.as_path().display()),
)
.expect("worktree git pointer");
let authority = workspace(&root, Enabled);
let mut requested_policy = workspace(&project, Restricted).file_system_sandbox_policy();
requested_policy
.entries
.push(skipped(gitdir.clone().into(), Read));
let requested = PermissionProfile::from_runtime_permissions(&requested_policy, Restricted);
let result = intersection(&authority, &requested, &project);
let policy = result.file_system_sandbox_policy();
// Keep :tmpdir independent of the workspace fixtures, which themselves live
// under the host's temporary directory.
let scratch = TempDir::new().expect("temporary directory grant");
let scratch_root = canonical(&scratch);
let cwd = PathUri::from_abs_path(&root);
let temporary_directories = [PathUri::from_abs_path(&scratch_root)];
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: std::slice::from_ref(&cwd),
user_home_dir: None,
temporary_directories: Some(&temporary_directories),
};
assert_eq!(
[&root, &project, &scratch_root]
.map(|path| policy.resolve_access(&PathUri::from_abs_path(path), &context)),
[Read, Write, Write]
);
assert_eq!(result.network_sandbox_policy(), Restricted);
assert!(policy.entries.contains(&special(Tmpdir, Write)));
for name in [".git", ".agents", ".akode", ".aws"] {
let protected = project.join(name);
assert!(!policy.can_write_local_path_with_cwd(protected.as_path(), root.as_path()));
assert!(policy.entries.contains(&skipped(protected.into(), Read)));
}
assert!(policy.entries.contains(&skipped(gitdir.into(), Read)));
let strict = rooted(
&project,
Write,
[entry(project.join(".git").as_path(), Read)],
);
let strict = intersection(&requested, &strict, &project).file_system_sandbox_policy();
let git_protection = entry(project.join(".git").as_path(), Read);
assert!(strict.entries.contains(&git_protection));
}
#[test]
fn exact_denies_nested_read_carveouts_and_reopened_writes_are_preserved() {
let temp = TempDir::new().expect("workspace");
let root = canonical(&temp);
let shared = root.join("shared");
let editable = shared.join("editable");
let left_secret = root.join("left-secret.env");
let right_secret = root.join("right-secret.token");
for directory in [&editable, &left_secret, &right_secret] {
std::fs::create_dir_all(directory.as_path()).expect("policy directory");
}
let left = rooted(
&root,
Write,
[
entry(shared.as_path(), Read),
entry(editable.as_path(), Write),
entry(left_secret.as_path(), Deny),
deny_glob("**/*.env"),
],
);
let mut left_policy = left.file_system_sandbox_policy();
left_policy.glob_scan_max_depth = Some(2);
let left = PermissionProfile::from_runtime_permissions(&left_policy, Restricted);
let right = rooted(
&root,
Write,
[
entry(shared.as_path(), Write),
entry(editable.as_path(), Write),
entry(right_secret.as_path(), Deny),
deny_glob("**/*.token"),
],
);
let mut right_policy = right.file_system_sandbox_policy();
right_policy.glob_scan_max_depth = Some(4);
let right = PermissionProfile::from_runtime_permissions(&right_policy, Restricted);
let result = intersection(&left, &right, &root);
let policy = result.file_system_sandbox_policy();
let denies = ReadDenyMatcher::try_new_for_local_paths(&policy, root.as_path())
.expect("valid merged deny globs")
.expect("merged denies");
assert_eq!(
[&root, &shared, &editable]
.map(|path| policy
.resolve_access_for_local_path_with_cwd(path.as_path(), root.as_path())),
[Write, Read, Write]
);
assert_eq!(
[
&left_secret,
&right_secret,
&root.join("credentials.env"),
&root.join("credentials.token"),
]
.map(|path| denies.is_local_path_read_denied(path.as_path())),
[true, true, true, true]
);
assert_eq!(policy.glob_scan_max_depth, Some(4));
assert!(policy.entries.contains(&entry(left_secret.as_path(), Deny)));
assert_eq!(result, intersection(&right, &left, &root));
let unbounded = rooted(&root, Write, [deny_glob("**/*.key")]);
assert_eq!(
intersection(&left, &unbounded, &root)
.file_system_sandbox_policy()
.glob_scan_max_depth,
None
);
}
#[test]
fn temporary_directory_restrictions_fail_closed() {
let temp = TempDir::new().expect("workspace");
let root = canonical(&temp);
let writable = workspace(&root, Restricted);
for access in [Read, Deny] {
let restricted = rooted(&root, Write, [special(Tmpdir, access)]);
assert!(matches!(
intersect_effective_permission_profiles(&restricted, &writable, root.as_path()),
Err(PermissionIntersectionError::UnsupportedPath(_))
));
}
}
#[test]
fn identical_unrestricted_and_disabled_profiles_keep_existing_enforcement() {
let temp = TempDir::new().expect("workspace");
let root = absolute(temp.path());
let readonly = PermissionProfile::read_only();
let disabled = PermissionProfile::Disabled;
assert_eq!(intersection(&disabled, &readonly, &root), readonly);
assert_eq!(intersection(&readonly, &disabled, &root), readonly);
assert_eq!(intersection(&disabled, &disabled, &root), disabled);
let unrestricted = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::unrestricted(),
Enabled,
);
assert_eq!(intersection(&unrestricted, &readonly, &root), readonly);
let minimal = managed(vec![special(Minimal, Read)]);
assert_eq!(intersection(&minimal, &minimal, &root), minimal);
let filesystem_root = root.as_path().ancestors().last().unwrap();
let explicit = managed(vec![entry(filesystem_root, Read)]);
assert!(
!intersection(&explicit, &explicit, &root)
.file_system_sandbox_policy()
.has_full_disk_read_access()
);
}
#[test]
fn unsupported_unresolved_and_optional_policy_shapes_fail_closed() {
let temp = TempDir::new().expect("workspace");
let root = canonical(&temp);
let readonly = PermissionProfile::read_only();
let external = PermissionProfile::External { network: Enabled };
for (left, right) in [(&external, &readonly), (&readonly, &external)] {
assert_eq!(
intersect_effective_permission_profiles(left, right, root.as_path()),
Err(PermissionIntersectionError::ExternalSandbox)
);
}
let unmaterialized = PermissionProfile::workspace_write();
assert!(matches!(
intersect_effective_permission_profiles(&unmaterialized, &readonly, root.as_path()),
Err(PermissionIntersectionError::UnsupportedPath(_))
));
let minimal = managed(vec![special(Minimal, Read)]);
assert_eq!(
intersect_effective_permission_profiles(&minimal, &readonly, root.as_path()),
Err(PermissionIntersectionError::PlatformDefaults)
);
let optional_write = rooted(&root, Write, [skipped(root.clone().into(), Write)]);
let invalid_glob = rooted(&root, Write, [deny_glob("**/[z-a]")]);
let optional_glob = rooted(&root, Write, [skipped(deny_glob("**/*.env").path, Deny)]);
let unresolved_pattern = project_roots_glob_pattern(Path::new("**/*.env"));
let unresolved_glob = rooted(&root, Write, [deny_glob(&unresolved_pattern)]);
let duplicate_tmpdir = managed(vec![
root_read(),
special(Tmpdir, Read),
skipped(FileSystemPath::Special { value: Tmpdir }, Write),
]);
for unsupported in [
&optional_write,
&invalid_glob,
&optional_glob,
&unresolved_glob,
&duplicate_tmpdir,
] {
assert!(matches!(
intersect_effective_permission_profiles(unsupported, &readonly, root.as_path()),
Err(PermissionIntersectionError::UnsupportedPath(_))
));
}
assert!(matches!(
intersect_effective_permission_profiles(
&readonly,
&readonly,
Path::new("relative/workspace")
),
Err(PermissionIntersectionError::UnsupportedPath(_))
));
}
#[cfg(unix)]
#[test]
fn canonical_grants_cannot_escape_through_readable_or_writable_symlinks() {
let temp = TempDir::new().expect("workspace");
let root = canonical(&temp);
let outside_temp = TempDir::new().expect("outside workspace");
let outside = canonical(&outside_temp);
let escaped = root.join("escaped");
let inside = root.join("inside");
let internal_alias = root.join("internal-alias");
std::fs::create_dir(inside.as_path()).expect("inside directory");
std::os::unix::fs::symlink(outside.as_path(), escaped.as_path()).expect("outside symlink");
std::os::unix::fs::symlink(inside.as_path(), internal_alias.as_path()).expect("inside symlink");
let parent = rooted(&root, Write, []);
let child = rooted(&escaped, Write, []);
let policy = intersection(&parent, &child, &root).file_system_sandbox_policy();
assert!(!policy.can_write_local_path_with_cwd(outside.as_path(), root.as_path()));
let parent = managed(vec![entry(root.as_path(), Read)]);
let child = managed(vec![entry(escaped.as_path(), Read)]);
assert!(matches!(
intersect_effective_permission_profiles(&parent, &child, root.as_path()),
Err(PermissionIntersectionError::UnsupportedPath(_))
));
let parent = rooted(&root, Write, []);
let child = rooted(&internal_alias, Write, []);
let policy = intersection(&parent, &child, &root).file_system_sandbox_policy();
assert!(policy.can_write_local_path_with_cwd(inside.as_path(), root.as_path()));
assert!(
!policy
.entries
.contains(&entry(internal_alias.as_path(), Write))
);
}
#[cfg(target_os = "macos")]
#[test]
fn macos_system_path_aliases_share_the_same_physical_permissions() {
let temp = TempDir::new_in("/tmp").expect("workspace under system path alias");
let canonical = canonical(&temp);
let alias = absolute(
&Path::new("/").join(
canonical
.as_path()
.strip_prefix("/private")
.expect("macOS alias"),
),
);
for access in [Read, Write] {
let left = managed(vec![entry(alias.as_path(), access)]);
let right = managed(vec![entry(canonical.as_path(), access)]);
let policy = intersection(&left, &right, &canonical).file_system_sandbox_policy();
assert_eq!(
policy.resolve_access_for_local_path_with_cwd(canonical.as_path(), canonical.as_path()),
access
);
}
let policy = intersection(
&workspace(&alias, Enabled),
&workspace(&canonical, Restricted),
&canonical,
)
.file_system_sandbox_policy();
assert!(policy.can_write_local_path_with_cwd(canonical.as_path(), canonical.as_path()));
}

View File

@@ -0,0 +1,128 @@
//! Trusted permission state keeps local and remote profile roots as executor path URIs.
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use crate::models::ActivePermissionProfile;
use crate::models::PermissionProfile;
/// A profile-declared root, separate from turn-scoped runtime workspace roots.
///
/// Local and remote roots share the same URI representation. Snapshot equality
/// compares the stored URI spelling without folding Windows case, so a spelling
/// change still propagates through settings.
#[derive(Debug, Clone, Eq)]
pub struct ProfileWorkspaceRoot(PathUri);
impl PartialEq for ProfileWorkspaceRoot {
fn eq(&self, other: &Self) -> bool {
self.0.to_string() == other.0.to_string()
}
}
impl ProfileWorkspaceRoot {
/// Borrow the resolved URI without projecting it onto the current host.
pub fn as_uri(&self) -> &PathUri {
&self.0
}
}
impl From<AbsolutePathBuf> for ProfileWorkspaceRoot {
fn from(path: AbsolutePathBuf) -> Self {
Self(PathUri::from_abs_path(&path))
}
}
impl From<PathUri> for ProfileWorkspaceRoot {
fn from(path: PathUri) -> Self {
Self(path)
}
}
/// Trusted snapshot of a resolved permission profile.
///
/// Keeps the concrete permissions, optional active profile identity, and
/// profile-defined workspace roots together for atomic installation. Callers
/// handling user-selected profile ids must resolve those ids before
/// constructing a snapshot.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PermissionProfileSnapshot {
permission_profile: PermissionProfile,
active_permission_profile: Option<ActivePermissionProfile>,
profile_workspace_roots: Vec<ProfileWorkspaceRoot>,
}
impl PermissionProfileSnapshot {
/// Create a snapshot with no active profile identity.
///
/// Use this only for legacy data or local overrides that genuinely do not
/// have a named or built-in profile identity.
pub fn legacy(permission_profile: PermissionProfile) -> Self {
Self {
permission_profile,
active_permission_profile: None,
profile_workspace_roots: Vec::new(),
}
}
/// Create a snapshot for an already-resolved active profile.
pub fn active(
permission_profile: PermissionProfile,
active_permission_profile: ActivePermissionProfile,
) -> Self {
Self::active_with_profile_workspace_roots(
permission_profile,
active_permission_profile,
Vec::new(),
)
}
/// Create a snapshot for an active profile and its declared roots.
///
/// Profile roots remain distinct from turn-scoped runtime workspace roots.
/// The supplied profile must already contain their compiled permissions;
/// storing roots here does not itself grant access or materialize rules.
pub fn active_with_profile_workspace_roots(
permission_profile: PermissionProfile,
active_permission_profile: ActivePermissionProfile,
profile_workspace_roots: Vec<ProfileWorkspaceRoot>,
) -> Self {
Self {
permission_profile,
active_permission_profile: Some(active_permission_profile),
profile_workspace_roots,
}
}
/// Reconstruct a trusted snapshot from already-resolved session state.
pub fn from_session_snapshot(
permission_profile: PermissionProfile,
active_permission_profile: Option<ActivePermissionProfile>,
) -> Self {
match active_permission_profile {
Some(active_permission_profile) => {
Self::active(permission_profile, active_permission_profile)
}
None => Self::legacy(permission_profile),
}
}
/// Borrow the concrete permissions captured in this snapshot.
pub fn permission_profile(&self) -> &PermissionProfile {
&self.permission_profile
}
/// Return the active profile identity captured in this snapshot, if any.
pub fn active_permission_profile(&self) -> Option<ActivePermissionProfile> {
self.active_permission_profile.clone()
}
/// Borrow profile-declared workspace roots captured in this snapshot.
pub fn profile_workspace_roots(&self) -> &[ProfileWorkspaceRoot] {
&self.profile_workspace_roots
}
}
#[cfg(test)]
#[path = "permission_profile_snapshot_tests.rs"]
mod tests;

View File

@@ -0,0 +1,20 @@
//! Profile-root spelling changes must propagate through settings snapshots.
use super::*;
#[test]
fn executor_profile_root_case_changes_update_snapshot() {
for (first, second) in [
("file:///C:/Work/Project", "file:///C:/work/project"),
("file://server/share/Project", "file://server/share/project"),
] {
let snapshot = |root| {
PermissionProfileSnapshot::active_with_profile_workspace_roots(
PermissionProfile::read_only(),
ActivePermissionProfile::new("executor"),
vec![PathUri::parse(root).unwrap().into()],
)
};
assert_ne!(snapshot(first), snapshot(second));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,102 @@
//! Core's mandatory-denial validation, shared without resolving paths on the controller.
//! Checks raw concrete grants; policy application and sandbox enforcement remain caller-owned.
use super::FileSystemAccessMode;
use super::FileSystemPath;
use super::FileSystemSandboxEntry;
use super::FileSystemSandboxKind;
use super::FileSystemSandboxPolicy;
use super::FileSystemSandboxPolicyContext;
use super::FileSystemSpecialPath;
use super::InvalidDenyReadGlobBehavior;
use super::PreparedReadDenyMatcher;
use akode_utils_path_uri::PathConvention;
use akode_utils_path_uri::PathUri;
/// Prepared mandatory rules reused when a caller replaces its selected profile.
pub struct DenyReadValidator {
required_entries: Vec<FileSystemSandboxEntry>,
matcher: Option<PreparedReadDenyMatcher>,
}
/// Details needed to retain the caller's existing sourced constraint diagnostics.
#[derive(Debug, PartialEq, Eq)]
pub enum DenyReadViolation {
MissingRequiredDeny,
ReadablePath(PathUri),
}
impl DenyReadValidator {
/// Prepares the strict matcher once, using the supplied executor facts.
pub fn new(
required: &FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Result<Self, String> {
let matcher = has_context_read_denials(required, context)
.then(|| {
required
.prepare_deny_read_matcher(context, InvalidDenyReadGlobBehavior::ReturnError)
})
.transpose()?;
Ok(Self {
required_entries: required.entries.clone(),
matcher,
})
}
/// Preserves Core's entry-presence and raw readable-path checks.
///
/// Symbolic entries are not expanded. An equally specific deny does not
/// exempt a concrete readable grant from this validation. Native callers
/// retain their native-path conversion boundary before passing the policy.
pub fn validate(
&self,
selected: &FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Result<(), DenyReadViolation> {
let missing_required_deny = self
.required_entries
.iter()
.any(|entry| !selected.entries.contains(entry));
let violating_root = selected
.entries
.iter()
.filter(|entry| entry.access.can_read())
.find_map(|entry| {
let FileSystemPath::Path { path } = &entry.path else {
return None;
};
if path.infer_path_convention() != context.cwd.infer_path_convention() {
return None;
}
self.matcher
.as_ref()
.is_some_and(|matcher| {
FileSystemSandboxPolicy::matches_prepared_read_deny(path, context, matcher)
})
.then_some(path)
});
// Core reports the first conflicting path even when a required entry is missing too.
if let Some(path) = violating_root {
return Err(DenyReadViolation::ReadablePath(path.clone()));
}
if missing_required_deny {
return Err(DenyReadViolation::MissingRequiredDeny);
}
Ok(())
}
}
pub(super) fn has_context_read_denials(
policy: &FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'_>,
) -> bool {
policy.kind == FileSystemSandboxKind::Restricted
&& policy.entries.iter().any(|entry| {
entry.access == FileSystemAccessMode::Deny
&& !matches!(&entry.path,
FileSystemPath::Special { value: FileSystemSpecialPath::SlashTmp }
if context.cwd.infer_path_convention() != Some(PathConvention::Posix)
)
})
}

View File

@@ -0,0 +1,91 @@
//! Projects filesystem permissions for each sandbox, preserving mutable paths where the backend binds them.
use super::FileSystemSandboxPolicy;
use super::LocalPolicyContext;
use super::normalize_effective_absolute_path;
use crate::protocol::WritableRoot;
use akode_utils_absolute_path::AbsolutePathBuf;
use std::io;
use std::path::Path;
/// How a sandbox binds filesystem roots after access and precedence are resolved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FileSystemPolicyProjection {
/// Resolve roots and carveouts to their effective native paths.
Native,
/// Normalize trusted system aliases, leaving mutable components for the sandbox to bind.
PreserveMutableRoots,
/// Inherit root metadata writes from the root mount and retain literal paths for read denials.
LinuxMounts,
}
impl FileSystemPolicyProjection {
pub(super) fn resolve_writable_path(self, path: AbsolutePathBuf) -> AbsolutePathBuf {
match self {
Self::Native | Self::LinuxMounts => normalize_effective_absolute_path(path),
Self::PreserveMutableRoots => path.normalize_system_aliases().unwrap_or(path),
}
}
}
/// Filesystem permissions resolved on the host that will enforce them.
///
/// Roots retain policy order. Deny globs remain patterns for the sandbox to enforce or expand.
/// Resolving these paths does not pin their targets; the sandbox still binds them at launch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedFileSystemPermissions {
pub has_full_disk_read_access: bool,
pub has_full_disk_write_access: bool,
pub include_platform_defaults: bool,
pub readable_roots: Vec<AbsolutePathBuf>,
pub writable_roots: Vec<WritableRoot>,
pub unreadable_roots: Vec<AbsolutePathBuf>,
pub unreadable_globs: Vec<String>,
pub glob_scan_max_depth: Option<usize>,
}
impl FileSystemSandboxPolicy {
/// Resolve the roots for one enforcement operation after binding executor-owned paths.
pub fn resolve_for_enforcement(
&self,
cwd: &Path,
projection: FileSystemPolicyProjection,
) -> io::Result<ResolvedFileSystemPermissions> {
let mut resolved = ResolvedFileSystemPermissions {
has_full_disk_read_access: self.has_full_disk_read_access(),
has_full_disk_write_access: self.has_full_disk_write_access(),
include_platform_defaults: self.include_platform_defaults(),
readable_roots: Vec::new(),
writable_roots: Vec::new(),
unreadable_roots: Vec::new(),
unreadable_globs: self.get_unreadable_globs_with_cwd(cwd),
glob_scan_max_depth: self.glob_scan_max_depth,
};
if resolved.has_full_disk_read_access && resolved.has_full_disk_write_access {
return Ok(resolved);
}
let entries = self.resolved_entries_with_cwd(cwd);
if entries.is_empty() {
return Ok(resolved);
}
let context = LocalPolicyContext::new(cwd);
let matching = context
.as_ref()
.and_then(|context| self.prepare_local_matching(&context.as_context()).ok());
if let Some(matching) = &matching {
if !resolved.has_full_disk_read_access {
resolved.readable_roots = Self::readable_roots(&entries, matching);
}
if !resolved.has_full_disk_write_access
&& entries.iter().any(|entry| entry.access.can_write())
{
resolved.writable_roots = Self::writable_roots(cwd, &entries, matching, projection);
}
}
// If the matcher couldn't be prepared, withhold grants but keep explicit denials.
resolved.unreadable_roots =
Self::unreadable_roots(cwd, &entries, matching.as_ref(), projection);
Ok(resolved)
}
}

View File

@@ -0,0 +1,260 @@
//! Prepare local policy paths in the sandbox's trusted system-alias namespace.
//! Normalize grants and restrictions once per operation without resolving mutable symlinks.
//! Check native macOS ASCII aliases before approving protected metadata writes.
//! Borrow unchanged policies and return normalization failures to fallible callers.
use super::FileSystemAccessMode;
use super::FileSystemPath;
use super::FileSystemSandboxEntry;
use super::FileSystemSandboxPolicy;
use super::FileSystemSandboxPolicyContext;
use super::FileSystemSpecialPath;
#[cfg(target_os = "macos")]
use super::PROTECTED_METADATA_PATH_NAMES;
use super::local_temporary_directories;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use std::borrow::Cow;
#[cfg(target_os = "macos")]
use std::ffi::CString;
use std::io;
#[cfg(target_os = "macos")]
use std::os::unix::ffi::OsStrExt;
#[cfg(target_os = "macos")]
use std::path::Component;
use std::path::Path;
#[cfg(target_os = "macos")]
use std::path::PathBuf;
/// Owns native environment bindings so one matcher can serve a whole root calculation.
pub(super) struct LocalPolicyContext {
cwd: PathUri,
user_home_dir: Option<PathUri>,
temporary_directories: Vec<PathUri>,
}
impl LocalPolicyContext {
pub(super) fn new(cwd: &Path) -> Option<Self> {
Some(Self {
cwd: PathUri::from(AbsolutePathBuf::from_absolute_path(cwd).ok()?),
user_home_dir: PathUri::from_host_native_path("~").ok(),
temporary_directories: local_temporary_directories(),
})
}
pub(super) fn as_context(&self) -> FileSystemSandboxPolicyContext<'_> {
FileSystemSandboxPolicyContext {
cwd: &self.cwd,
workspace_roots: std::slice::from_ref(&self.cwd),
user_home_dir: self.user_home_dir.as_ref(),
temporary_directories: Some(&self.temporary_directories),
}
}
}
/// An operation-scoped view of a configured policy with local roots resolved.
/// Reuse it for each target in the operation; prepare again when policy or
/// environment bindings change. Metadata checks also account for native ASCII
/// case aliases without changing executor-independent path comparisons.
pub struct LocalFileSystemPolicyMatcher<'a> {
policy: Cow<'a, FileSystemSandboxPolicy>,
context: FileSystemSandboxPolicyContext<'a>,
}
impl FileSystemSandboxPolicy {
/// Prepare local permission matching, resolving trusted aliases on macOS.
/// Borrows the configured policy on platforms that do not need normalization.
/// Remote paths must use `can_write_path` instead: the controller's
/// filesystem cannot establish aliases on another host.
pub fn prepare_local_matching<'a>(
&'a self,
context: &FileSystemSandboxPolicyContext<'a>,
) -> io::Result<LocalFileSystemPolicyMatcher<'a>> {
let mut policy = Cow::Borrowed(self);
if cfg!(target_os = "macos") {
let policy = policy.to_mut();
// Preserve non-path entries, including globs that constrain full-disk
// grants. Materialize symbolic roots using the selected environment.
policy.entries.retain(|entry| {
matches!(
entry.path,
FileSystemPath::GlobPattern { .. }
| FileSystemPath::Special {
value: FileSystemSpecialPath::Root
| FileSystemSpecialPath::Minimal
| FileSystemSpecialPath::Unknown { .. }
}
)
});
for (root, access) in self.resolved_entries(context) {
if root.is_opaque() {
continue;
}
let normalized =
root.to_abs_path()?
.normalize_system_aliases()
.map_err(|error| {
io::Error::new(
error.kind(),
format!("failed to normalize {root}: {error}"),
)
})?;
policy
.entries
.push(FileSystemSandboxEntry::new(normalized.into(), access));
}
}
Ok(LocalFileSystemPolicyMatcher {
policy,
context: *context,
})
}
}
impl LocalFileSystemPolicyMatcher<'_> {
/// Check write access, preserving failures to establish native path equivalence.
pub fn can_write_path(&self, path: &PathUri) -> io::Result<bool> {
self.with_path(path, |path| -> io::Result<bool> {
let writable = self.policy.can_write_path(path, &self.context);
#[cfg(target_os = "macos")]
if writable
&& !self
.policy
.has_full_disk_write_access_with_context(&self.context)
{
let native_path = path.to_abs_path()?;
for (root, access) in self.policy.resolved_entries(&self.context) {
if !access.can_write() || root.is_opaque() {
continue;
}
let root = root.to_abs_path()?;
let Some(candidate) = normalize_metadata_case_alias(&native_path, &root)?
else {
continue;
};
// This second policy view may only deny an already allowed write.
// Normalize both candidate and entries so explicit metadata grants
// and narrower restrictions keep their precedence.
let mut policy = self.policy.clone().into_owned();
for entry in &mut policy.entries {
if let FileSystemPath::Path { path } = &mut entry.path
&& let Some(normalized) =
normalize_metadata_case_alias(&path.to_abs_path()?, &root)?
{
*path = PathUri::from(normalized);
}
}
if !policy.can_write_path(&PathUri::from(candidate), &self.context) {
return Ok(false);
}
}
}
Ok(writable)
})?
}
pub(super) fn resolve_access(&self, path: &PathUri) -> FileSystemAccessMode {
self.with_path(path, |path| self.policy.resolve_access(path, &self.context))
.unwrap_or(FileSystemAccessMode::Deny)
}
fn with_path<T>(&self, path: &PathUri, evaluate: impl FnOnce(&PathUri) -> T) -> io::Result<T> {
let path = if cfg!(target_os = "macos") {
Cow::Owned(PathUri::from(
path.to_abs_path()?
.normalize_system_aliases()
.map_err(|error| {
io::Error::new(error.kind(), format!("failed to normalize {path}: {error}"))
})?,
))
} else {
Cow::Borrowed(path)
};
Ok(evaluate(&path))
}
}
// Match only ASCII case aliases leading to protected metadata. Each differing
// component is checked against its containing filesystem, including ancestors
// above mount points. Mutable symlink targets are never substituted into paths.
#[cfg(target_os = "macos")]
fn normalize_metadata_case_alias(
path: &AbsolutePathBuf,
root: &AbsolutePathBuf,
) -> io::Result<Option<AbsolutePathBuf>> {
let mut relative = path.components();
let Some(Component::Normal(name)) = relative.nth(root.components().count()) else {
return Ok(None);
};
let Some(metadata_name) = PROTECTED_METADATA_PATH_NAMES
.iter()
.find(|metadata| name.as_bytes().eq_ignore_ascii_case(metadata.as_bytes()))
else {
return Ok(None);
};
let mut parent = PathBuf::new();
for (expected, actual) in root.components().zip(path.components()) {
if expected != actual
&& (!expected
.as_os_str()
.as_bytes()
.eq_ignore_ascii_case(actual.as_os_str().as_bytes())
|| !is_case_insensitive_filesystem(&parent)?)
{
return Ok(None);
}
parent.push(expected.as_os_str());
}
// Exact metadata names still need root alias normalization even when the
// metadata's own filesystem is case-sensitive.
if name.as_bytes() != metadata_name.as_bytes()
&& !is_case_insensitive_filesystem(root.as_path())?
{
return Ok(None);
}
Ok(Some(root.join(*metadata_name).join(relative.as_path())))
}
#[cfg(target_os = "macos")]
fn is_case_insensitive_filesystem(path: &Path) -> io::Result<bool> {
// Missing paths inherit their nearest existing ancestor's semantics.
// An unknown result must never authorize a protected metadata write.
for ancestor in path.ancestors() {
let path = CString::new(ancestor.as_os_str().as_bytes())?;
// SAFETY: path is NUL-terminated and __error points to this thread's
// errno. Reset it to distinguish an unavailable value from a failure.
let sensitivity = unsafe {
*libc::__error() = 0;
libc::pathconf(path.as_ptr(), libc::_PC_CASE_SENSITIVE)
};
match sensitivity {
0 => return Ok(true),
1 => return Ok(false),
-1 => {
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(0) {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"filesystem case sensitivity is unavailable",
));
}
if error.kind() != io::ErrorKind::NotFound {
return Err(error);
}
}
value => {
return Err(io::Error::other(format!(
"unexpected filesystem case sensitivity: {value}",
)));
}
}
}
Err(io::Error::new(
io::ErrorKind::NotFound,
"no existing metadata parent",
))
}
#[cfg(all(test, target_os = "macos"))]
#[path = "local_aliases_tests.rs"]
mod tests;

View File

@@ -0,0 +1,163 @@
use super::*;
use crate::permissions::FileSystemAccessMode;
use pretty_assertions::assert_eq;
#[test]
fn local_aliases_keep_read_only_and_deny_overrides() -> anyhow::Result<()> {
let directory = tempfile::tempdir_in("/tmp")?;
let logical = PathUri::from_host_native_path(directory.path())?;
let physical = PathUri::from_host_native_path(directory.path().canonicalize()?)?;
let context = FileSystemSandboxPolicyContext {
cwd: &physical,
workspace_roots: std::slice::from_ref(&physical),
user_home_dir: None,
temporary_directories: None,
};
for writable in [&logical, &physical] {
for restricted in [&logical, &physical] {
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Deny] {
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
writable.clone().into(),
FileSystemAccessMode::Write,
),
FileSystemSandboxEntry::new(restricted.join("protected")?.into(), access),
]);
let matching = policy.prepare_local_matching(&context)?;
for spelling in [&logical, &physical] {
let protected = spelling.join("protected/missing/file")?;
assert_eq!(
(
matching.can_write_path(&spelling.join("missing/file")?)?,
matching.can_write_path(&protected)?,
policy.resolve_access_for_local_path_with_cwd(
protected.to_abs_path()?.as_path(),
directory.path(),
),
matching.can_write_path(&spelling.join(".akode/config.toml")?)?,
),
(true, false, access, false),
);
}
}
}
}
Ok(())
}
#[test]
fn equivalent_alias_entries_keep_restrictive_precedence() -> anyhow::Result<()> {
let directory = tempfile::tempdir_in("/tmp")?;
let logical = PathUri::from_host_native_path(directory.path())?;
let physical = PathUri::from_host_native_path(directory.path().canonicalize()?)?;
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(physical.clone().into(), FileSystemAccessMode::Write),
FileSystemSandboxEntry::new(logical.into(), FileSystemAccessMode::Deny),
]);
assert_eq!(
policy.resolve_access_for_local_path_with_cwd(
physical.join("missing")?.to_abs_path()?.as_path(),
directory.path(),
),
FileSystemAccessMode::Deny,
);
Ok(())
}
#[test]
fn local_metadata_case_aliases_respect_filesystem_and_explicit_grants() -> anyhow::Result<()> {
let directory = tempfile::tempdir()?;
let parent = PathUri::from_host_native_path(directory.path().canonicalize()?)?;
let workspace = parent.join("workspace")?.to_abs_path()?;
std::fs::create_dir(&workspace)?;
std::fs::create_dir(workspace.join(".git"))?;
let case_insensitive = workspace.join(".GIT").exists();
let root = PathUri::from_host_native_path(&workspace)?;
let context = FileSystemSandboxPolicyContext {
cwd: &root,
workspace_roots: std::slice::from_ref(&root),
user_home_dir: None,
temporary_directories: None,
};
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(parent.clone().into(), FileSystemAccessMode::Write),
FileSystemSandboxEntry::new(root.clone().into(), FileSystemAccessMode::Write),
]);
let matching = policy.prepare_local_matching(&context)?;
for relative in [
".GIT/config",
".CoDeX/config.toml",
".AGENTS/new",
".AWS/config",
] {
let path = root.join(relative)?;
assert_eq!(
(
matching.can_write_path(&path)?,
policy.can_write_path(&path, &context),
),
(!case_insensitive, true),
"local aliases must not change executor-independent matching: {relative}",
);
}
let root_alias = parent.join("WORKSPACE")?;
for relative in [".GIT/config", ".git/config", ".CoDeX/config.toml"] {
let path = root_alias.join(relative)?;
assert_eq!(
(
matching.can_write_path(&path)?,
policy.can_write_path(&path, &context),
),
(!case_insensitive, true),
"a broader grant must not bypass metadata protection via a root alias: {relative}",
);
}
for name in [".git", ".GIT"] {
let mut explicitly_writable = policy.clone();
explicitly_writable
.entries
.push(FileSystemSandboxEntry::new(
root.join(name)?.into(),
FileSystemAccessMode::Write,
));
let matching = explicitly_writable.prepare_local_matching(&context)?;
for spelling in [&root, &root_alias] {
assert!(
matching.can_write_path(&spelling.join(".GIT/config")?)?,
"explicit metadata grant must remain effective: {name}",
);
}
}
for (grant, restriction, candidate) in [
(".git", ".GIT/private", ".git/private"),
(".GIT", ".git/private", ".GIT/private"),
] {
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Deny] {
let mut restricted = policy.clone();
restricted.entries.extend([
FileSystemSandboxEntry::new(root.join(grant)?.into(), FileSystemAccessMode::Write),
FileSystemSandboxEntry::new(root.join(restriction)?.into(), access),
]);
assert_eq!(
restricted
.prepare_local_matching(&context)?
.can_write_path(&root.join(candidate)?)?,
!case_insensitive,
"narrower metadata restrictions must retain precedence: {restriction}",
);
}
}
let missing_root = root.join("missing")?;
let missing_policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry::new(
missing_root.clone().into(),
FileSystemAccessMode::Write,
)]);
assert_eq!(
missing_policy
.prepare_local_matching(&context)?
.can_write_path(&missing_root.join(".GIT/config")?)?,
!case_insensitive,
);
assert!(matching.can_write_path(&root.join("nested/.GIT/config")?)?);
Ok(())
}

View File

@@ -0,0 +1,266 @@
//! Executor-context policy operations that never consult controller paths or environment.
use super::FileSystemAccessMode;
use super::FileSystemPath;
use super::FileSystemSandboxEntry;
use super::FileSystemSandboxKind;
use super::FileSystemSandboxPolicy;
use super::FileSystemSandboxPolicyContext;
use super::FileSystemSpecialPath;
use super::InvalidDenyReadGlobBehavior;
use super::PROJECT_ROOTS_GLOB_PATTERN_PREFIX;
use super::PROTECTED_METADATA_PATH_NAMES;
use super::ReadDenyMatcher;
use super::deny_read_validator::DenyReadValidator;
use super::deny_read_validator::has_context_read_denials;
use super::file_system_root;
use akode_utils_path_uri::PathConvention;
use akode_utils_path_uri::PathUri;
use std::collections::HashSet;
const INVALID_PATH: &str = "managed filesystem denial cannot be materialized safely";
const SHADOWED: &str = "managed filesystem denial is shadowed by a selected profile grant";
impl ReadDenyMatcher {
/// Builds a strict matcher using only the supplied execution-host paths.
pub fn try_new_with_context(
policy: &FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Result<Option<Self>, String> {
if !has_context_read_denials(policy, context) {
return Ok(None);
}
validate_context_paths(policy, context)?;
let prepared =
policy.prepare_deny_read_matcher(context, InvalidDenyReadGlobBehavior::ReturnError)?;
Ok(Some(Self {
native_cwd: None,
user_home_dir: None,
temporary_directories: Vec::new(),
prepared,
}))
}
}
impl FileSystemSandboxPolicy {
/// Grants root and root-metadata write for an approved command unless explicitly denied.
/// If a retained denial cannot be resolved or denies the root, keep the original policy.
pub fn for_approved_command(&self, context: &FileSystemSandboxPolicyContext<'_>) -> Self {
if self.kind != FileSystemSandboxKind::Restricted {
return self.clone();
}
let mut approved = Self::restricted(vec![FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Write,
)]);
approved.preserve_deny_read_restrictions_from(self);
if context.workspace_roots.is_empty()
&& approved.entries.iter().any(|entry| {
matches!(
&entry.path,
FileSystemPath::Special {
value: FileSystemSpecialPath::ProjectRoots { .. }
}
) || matches!(
&entry.path,
FileSystemPath::GlobPattern { pattern }
if pattern.starts_with(PROJECT_ROOTS_GLOB_PATTERN_PREFIX)
)
})
{
return self.clone();
}
let Some(mut approved) =
approved.try_materialize_project_roots_with_path_uris(context.workspace_roots)
else {
return self.clone();
};
let Some(root) = file_system_root(context) else {
return self.clone();
};
let Ok(matcher) = ReadDenyMatcher::try_new_with_context(&approved, context) else {
return self.clone();
};
if !approved.resolve_access(&root, context).can_write()
|| matcher
.as_ref()
.is_some_and(|matcher| matcher.is_read_denied_uri(&root, context))
{
return self.clone();
}
for name in PROTECTED_METADATA_PATH_NAMES {
let Ok(path) = root.join_descendant(name) else {
return self.clone();
};
if !matcher
.as_ref()
.is_some_and(|matcher| matcher.is_read_denied_uri(&path, context))
{
approved.entries.push(FileSystemSandboxEntry::new(
path.into(),
FileSystemAccessMode::Write,
));
}
}
approved
}
/// Checks exact-root read access using paths owned by the execution host.
/// Deny glob enforcement is checked separately with [`ReadDenyMatcher`].
pub fn can_read_path(
&self,
path: &PathUri,
context: &FileSystemSandboxPolicyContext<'_>,
) -> bool {
self.resolve_access(path, context).can_read()
}
/// Preserves workspace-root symbols and adds their executor-owned concrete paths.
/// Legacy home-relative workspace denials clear all grants when their target is unknown.
pub fn with_materialized_project_roots_for_path_uris(mut self, roots: &[PathUri]) -> Self {
let Some(materialized) = self
.clone()
.try_materialize_project_roots_with_path_uris(roots)
else {
return Self::restricted(Vec::new());
};
for entry in materialized.entries {
if !self.entries.contains(&entry) {
self.entries.push(entry);
}
}
self
}
/// Builds workspace-write defaults without inspecting the execution host's filesystem.
pub fn workspace_write_with_path_uris(
roots: &[PathUri],
exclude_tmpdir_env_var: bool,
exclude_slash_tmp: bool,
) -> Self {
Self::workspace_write(&[], exclude_tmpdir_env_var, exclude_slash_tmp)
.with_materialized_project_roots_for_path_uris(roots)
}
/// Returns explicitly denied roots using only the selected executor's paths.
/// A filesystem-root denial is omitted so it does not obscure narrower readable paths.
/// Fails rather than omit a denied temporary directory the executor did not report.
pub fn get_unreadable_roots_with_context(
&self,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Result<Vec<PathUri>, String> {
if !matches!(self.kind, FileSystemSandboxKind::Restricted) {
return Ok(Vec::new());
}
if context.temporary_directories.is_none()
&& self.entries.iter().any(|entry| {
entry.access == FileSystemAccessMode::Deny
&& matches!(
&entry.path,
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir
}
)
})
{
return Err("executor did not report its denied temporary directories".into());
}
let filesystem_root = file_system_root(context);
let mut seen = HashSet::new();
Ok(self
.resolved_entries(context)
.into_iter()
.filter(|(path, access)| {
*access == FileSystemAccessMode::Deny
&& !filesystem_root
.as_ref()
.is_some_and(|root| path.starts_with(root) && root.starts_with(path))
&& seen.insert(path.clone())
})
.map(|(path, _)| path)
.collect())
}
/// Resolves deny glob text using the execution host's convention and home.
pub fn get_unreadable_globs_with_context(
&self,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Result<Vec<String>, String> {
self.deny_read_globs(context)
}
/// Checks the existing Core rules for required entries and readable concrete paths.
///
/// Sandbox-mode selection and native glob expansion remain caller-owned.
pub fn validate_managed_deny_read(
&self,
required: &Self,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Result<(), String> {
DenyReadValidator::new(required, context)?
.validate(self, context)
.map_err(|_| SHADOWED.to_string())
}
}
fn validate_context_paths(
policy: &FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Result<(), String> {
let convention = context.cwd.infer_path_convention().ok_or(INVALID_PATH)?;
let valid = |path: &PathUri| {
path.infer_path_convention() == Some(convention) && path.lexical_depth().is_some()
};
if !valid(context.cwd) || context.workspace_roots.iter().any(|path| !valid(path)) {
return Err(INVALID_PATH.into());
}
for entry in &policy.entries {
match &entry.path {
FileSystemPath::Path { path } if !valid(path) => return Err(INVALID_PATH.into()),
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
} => {
let directories = context.temporary_directories.ok_or(
"executor temporary-directory metadata is unavailable for managed filesystem denials",
)?;
if directories.iter().any(|path| !valid(path)) {
return Err(
"executor temporary-directory metadata cannot be materialized safely"
.into(),
);
}
}
FileSystemPath::Special {
value:
FileSystemSpecialPath::ProjectRoots {
subpath: Some(subpath),
},
} if context
.workspace_roots
.iter()
.any(|root| root.join(subpath).is_err()) =>
{
return Err(INVALID_PATH.into());
}
FileSystemPath::GlobPattern { pattern }
if (pattern.starts_with("~/")
|| convention == PathConvention::Windows && pattern.starts_with("~\\"))
&& !context.user_home_dir.is_some_and(valid) =>
{
return Err(INVALID_PATH.into());
}
_ => {}
}
}
Ok(())
}
#[cfg(test)]
#[path = "target_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "target_approved_materialization_tests.rs"]
mod approved_materialization_tests;

View File

@@ -0,0 +1,246 @@
//! Approved commands widen filesystem access without weakening explicit read denials.
use super::*;
use crate::permissions::FileSystemAccessMode::Deny;
use crate::permissions::FileSystemAccessMode::Read;
use crate::permissions::FileSystemAccessMode::Write;
use crate::permissions::PROTECTED_METADATA_PATH_NAMES;
use crate::permissions::RawFileSystemSandboxPolicy;
use crate::permissions::project_roots_glob_pattern;
use pretty_assertions::assert_eq;
use std::path::Path;
fn uri(input: &str) -> PathUri {
PathUri::parse(input).unwrap()
}
fn entry(path: impl Into<FileSystemPath>, access: FileSystemAccessMode) -> FileSystemSandboxEntry {
FileSystemSandboxEntry::new(path.into(), access)
}
fn workspace(subpath: &str) -> FileSystemPath {
FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(Some(subpath.into())),
}
}
fn glob(pattern: String) -> FileSystemPath {
FileSystemPath::GlobPattern { pattern }
}
fn context<'a>(cwd: &'a PathUri, roots: &'a [PathUri]) -> FileSystemSandboxPolicyContext<'a> {
FileSystemSandboxPolicyContext {
cwd,
workspace_roots: roots,
user_home_dir: None,
temporary_directories: Some(&[]),
}
}
#[test]
fn approved_command_grants_root_metadata_unless_explicitly_denied() {
for path in [
"file:///work/repo",
"file:///C:/work/repo",
"file://server/share/repo",
] {
let cwd = uri(path);
let context = context(&cwd, std::slice::from_ref(&cwd));
let root = file_system_root(&context).unwrap();
let private = cwd.join("private").unwrap();
let pattern = project_roots_glob_pattern(Path::new("**/*.env"));
let mut policy = FileSystemSandboxPolicy::read_only();
policy.entries.extend([
entry(cwd.clone(), Write),
entry(workspace("private"), Deny),
entry(private.join("public").unwrap(), Read),
entry(private.join("writable").unwrap(), Write),
entry(glob(pattern), Deny),
]);
let approved = policy.for_approved_command(&context);
let mut expected = FileSystemSandboxPolicy::restricted(vec![
entry(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
Write,
),
entry(private, Deny),
entry(
glob(cwd.join("**/*.env").unwrap().inferred_native_path_string()),
Deny,
),
]);
expected.entries.extend(
PROTECTED_METADATA_PATH_NAMES
.iter()
.map(|name| entry(root.join_descendant(name).unwrap(), Write)),
);
assert_eq!(approved, expected);
let raw = RawFileSystemSandboxPolicy::try_from(approved.clone()).unwrap();
let wire: RawFileSystemSandboxPolicy =
serde_json::from_value(serde_json::to_value(raw).unwrap()).unwrap();
assert_eq!(FileSystemSandboxPolicy::try_from(wire).unwrap(), approved);
for name in PROTECTED_METADATA_PATH_NAMES {
assert!(approved.can_write_path(&root.join_descendant(name).unwrap(), &context));
}
assert!(approved.can_write_path(&cwd.join(".git/FETCH_HEAD").unwrap(), &context));
let matcher = ReadDenyMatcher::try_new_with_context(&approved, &context)
.unwrap()
.unwrap();
for denied in [
"private/public/file",
"private/writable/file",
"nested/secret.env",
] {
assert!(
matcher.is_read_denied_uri(&cwd.join(denied).unwrap(), &context),
"{path}: {denied}"
);
}
let root_path = |name| root.join_descendant(name).unwrap();
let ordinary = FileSystemSandboxPolicy::restricted(vec![
entry(root.clone(), Write),
entry(root_path(".git"), Deny),
entry(
glob(root_path(".agent?").inferred_native_path_string()),
Deny,
),
entry(root_path(".akode/private"), Deny),
entry(
glob(root_path(".akode/*.env").inferred_native_path_string()),
Deny,
),
]);
let approved = ordinary.for_approved_command(&context);
let metadata_paths = [".git", ".agents", ".akode"].map(root_path);
assert_eq!(
metadata_paths
.each_ref()
.map(|path| ordinary.can_write_path(path, &context)),
[false, false, false],
);
assert_eq!(
metadata_paths
.each_ref()
.map(|path| approved.can_write_path(path, &context)),
[false, false, true],
);
assert!(approved.can_write_path(&root_path(".akode/public"), &context));
assert!(!approved.can_write_path(&root_path(".akode/private/file"), &context));
let matcher = ReadDenyMatcher::try_new_with_context(&approved, &context)
.unwrap()
.unwrap();
assert_eq!(
[
".git",
".agents",
".akode/private/file",
".akode/secret.env",
".akode/public"
]
.map(|path| matcher.is_read_denied_uri(&root_path(path), &context)),
[true, true, true, true, false],
);
}
}
#[cfg(unix)]
#[test]
fn linux_root_metadata_writes_inherit_the_root_without_reopening_other_paths() {
let temp = tempfile::tempdir().unwrap();
let cwd = temp.path().canonicalize().unwrap();
let root = uri("file:///");
let mut policy = FileSystemSandboxPolicy::restricted(vec![
entry(root.clone(), Write),
entry(
PathUri::from_host_native_path(cwd.join("private")).unwrap(),
Deny,
),
]);
let roots = policy.get_writable_roots_with_cwd_inheriting_root_metadata(&cwd);
assert_eq!(
roots[0].protected_metadata_names,
PROTECTED_METADATA_PATH_NAMES
.iter()
.map(std::string::ToString::to_string)
.collect::<Vec<_>>(),
);
let metadata = PROTECTED_METADATA_PATH_NAMES
.iter()
.map(|name| entry(root.join_descendant(name).unwrap(), Write))
.collect::<Vec<_>>();
policy.entries.extend(metadata.clone());
let roots = policy.get_writable_roots_with_cwd_inheriting_root_metadata(&cwd);
assert_eq!(
roots
.iter()
.map(|root| root.root.as_path())
.collect::<Vec<_>>(),
[Path::new("/")],
);
assert!(roots[0].protected_metadata_names.is_empty());
let standalone = FileSystemSandboxPolicy::restricted(metadata);
assert_eq!(
standalone.get_writable_roots_with_cwd_inheriting_root_metadata(&cwd),
standalone.get_writable_roots_with_cwd(&cwd),
);
}
#[test]
fn approved_command_discards_other_volume_grants_before_materialization() {
let cwd = uri("file:///C:/run");
let workspace_root = uri("file:///C:/work");
let context = context(&cwd, std::slice::from_ref(&workspace_root));
let mut policy = FileSystemSandboxPolicy::read_only();
policy.entries.extend([
entry(workspace(r"D:\vault"), Read),
entry(uri("file:///D:/scoped"), Write),
entry(workspace("private"), Deny),
]);
let approved = policy.for_approved_command(&context);
assert_eq!(
[
"file:///C:/work/public",
"file:///C:/work/private/file",
"file:///D:/scoped"
]
.map(|path| approved.resolve_access(&uri(path), &context)),
[Write, Deny, Deny],
);
}
#[test]
fn approved_command_declines_root_or_unresolvable_denials() {
for path in ["file:///work/repo", "file:///C:/work/repo"] {
let cwd = uri(path);
let known = context(&cwd, std::slice::from_ref(&cwd));
let root = file_system_root(&known).unwrap();
for (context, denied) in [
(
known,
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
),
(known, root.clone().into()),
(known, glob(root.inferred_native_path_string())),
(known, glob("secrets/[z-a]".into())),
(known, workspace("~/private")),
(context(&cwd, &[]), workspace("private")),
(
context(&cwd, &[]),
glob(project_roots_glob_pattern(Path::new("**/*.env"))),
),
] {
let mut policy = FileSystemSandboxPolicy::read_only();
policy
.entries
.extend([entry(denied, Deny), entry(cwd.clone(), Write)]);
assert_eq!(policy.for_approved_command(&context), policy);
}
}
}

View File

@@ -0,0 +1,449 @@
//! Regression coverage for remote path matching and managed-denial enforcement.
use super::*;
use crate::permissions::FileSystemAccessMode;
use crate::permissions::FileSystemSandboxEntry;
use crate::permissions::PROTECTED_METADATA_PATH_NAMES;
use pretty_assertions::assert_eq;
fn uri(input: &str) -> PathUri {
PathUri::parse(input).unwrap()
}
fn deny(path: FileSystemPath) -> FileSystemSandboxEntry {
FileSystemSandboxEntry::new(path, FileSystemAccessMode::Deny)
}
#[test]
fn read_denials_use_target_paths_and_native_glob_semantics() {
for base in [
"file:///work/repo",
"file:///Users/agent/repo",
"file:///C:/work/repo",
"file://server/share/repo",
] {
let cwd = uri(base);
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: std::slice::from_ref(&cwd),
user_home_dir: Some(&cwd),
temporary_directories: Some(&[]),
};
let policy = FileSystemSandboxPolicy::restricted(vec![
deny(FileSystemPath::Path {
path: cwd.join("private").unwrap(),
}),
deny(FileSystemPath::GlobPattern {
pattern: "~/secrets/*.key".into(),
}),
deny(FileSystemPath::GlobPattern {
pattern: "nested/**/*.env".into(),
}),
]);
let matcher = ReadDenyMatcher::try_new_with_context(&policy, &context)
.unwrap()
.unwrap();
assert_eq!(
policy.get_unreadable_roots_with_context(&context),
Ok(vec![cwd.join("private").unwrap()]),
);
for (path, expected) in [
("private", true),
("private/file", true),
("private-other/file", false),
("secrets/token.key", true),
("secrets/nested/token.key", false),
("nested/.env", true),
("nested/deep/token.env", true),
("public/file", false),
] {
assert_eq!(
matcher.is_read_denied_uri(&cwd.join(path).unwrap(), &context),
expected,
"{base}: {path}"
);
}
assert_eq!(
matcher.is_read_denied_uri(&cwd.join("PRIVATE/file").unwrap(), &context),
cwd.infer_path_convention() == Some(PathConvention::Windows),
);
assert!(matcher.is_read_denied_uri(&uri("file:///C:/foreign%2Fpath"), &context));
}
}
#[test]
fn managed_denials_reject_concrete_read_and_write_grants() {
for base in [
"file:///work/repo",
"file:///C:/work/repo",
"file://server/share/repo",
] {
let cwd = uri(base);
let private = cwd.join("private").unwrap();
let required = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::Path {
path: private.clone(),
})]);
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: std::slice::from_ref(&cwd),
user_home_dir: None,
temporary_directories: Some(&[]),
};
let mut policy = FileSystemSandboxPolicy::workspace_write_with_path_uris(
&[],
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
policy.entries.extend(required.entries.clone());
assert_eq!(
policy.validate_managed_deny_read(&required, &context),
Ok(())
);
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Write] {
let mut carveout = policy.clone();
carveout.entries.push(FileSystemSandboxEntry::new(
FileSystemPath::Path {
path: private.join("carveout").unwrap(),
},
access,
));
assert_eq!(
carveout.validate_managed_deny_read(&required, &context),
Err(SHADOWED.into())
);
}
}
}
#[test]
fn managed_denials_preserve_native_metadata_read_rejections() {
for base in [
"file:///executor/home",
"file:///C:/Users/executor",
"file://server/share/executor",
] {
let extra_root = uri(base);
let cwd = extra_root.join("workspace").unwrap();
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: std::slice::from_ref(&cwd),
user_home_dir: Some(&extra_root),
temporary_directories: Some(&[]),
};
let legacy = FileSystemSandboxPolicy::workspace_write_with_path_uris(
std::slice::from_ref(&extra_root),
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
for name in [".akode", ".git"] {
let denied_root = extra_root.join(name).unwrap();
let child = denied_root.join("reopened").unwrap();
for (path, expected_root_access) in [
(
FileSystemPath::Path {
path: denied_root.clone(),
},
FileSystemAccessMode::Deny,
),
(
FileSystemPath::GlobPattern {
pattern: denied_root.join("*").unwrap().inferred_native_path_string(),
},
FileSystemAccessMode::Read,
),
] {
let required = FileSystemSandboxPolicy::restricted(vec![deny(path)]);
let mut policy = legacy.clone();
policy.preserve_deny_read_restrictions_from(&required);
assert_eq!(
(
policy.resolve_access(&denied_root, &context),
policy.validate_managed_deny_read(&required, &context),
),
(
expected_root_access,
if expected_root_access == FileSystemAccessMode::Deny {
Err(SHADOWED.into())
} else {
Ok(())
},
),
"{base}: {name}",
);
let matcher = ReadDenyMatcher::try_new_with_context(&required, &context)
.unwrap()
.unwrap();
assert!(matcher.is_read_denied_uri(&child, &context));
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Write] {
let mut reopened = policy.clone();
reopened.entries.push(FileSystemSandboxEntry::new(
FileSystemPath::Path {
path: child.clone(),
},
access,
));
assert_eq!(
reopened.validate_managed_deny_read(&required, &context),
Err(SHADOWED.into()),
"{base}: {name}: {access}",
);
}
}
}
}
}
#[test]
fn malformed_or_unresolvable_denials_fail_closed() {
let cwd = uri("file:///work/repo");
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: &[],
user_home_dir: None,
temporary_directories: Some(&[]),
};
for pattern in ["~/secrets/**", "secrets/[z-a]"] {
let policy = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::GlobPattern {
pattern: pattern.into(),
})]);
assert!(ReadDenyMatcher::try_new_with_context(&policy, &context).is_err());
}
let policy = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::Path {
path: uri("file:///C:/private"),
})]);
assert!(ReadDenyMatcher::try_new_with_context(&policy, &context).is_err());
let policy = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
})]);
assert!(
policy
.get_unreadable_roots_with_context(&FileSystemSandboxPolicyContext {
temporary_directories: None,
..context
})
.is_err()
);
}
#[test]
fn slash_tmp_denials_follow_the_executor_convention() {
let policy = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::Special {
value: FileSystemSpecialPath::SlashTmp,
})]);
for (base, active) in [("file:///work", true), ("file:///C:/work", false)] {
let cwd = uri(base);
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: &[],
user_home_dir: None,
temporary_directories: None,
};
let matcher = ReadDenyMatcher::try_new_with_context(&policy, &context).unwrap();
assert_eq!(matcher.is_some(), active);
if let Some(matcher) = matcher {
assert!(matcher.is_read_denied_uri(&cwd.join("/tmp/file").unwrap(), &context));
}
}
}
/// Full-disk read policy shares the native check and ignores `:slash_tmp` only on Windows.
#[test]
fn full_disk_read_policy_uses_the_executor_convention() {
use FileSystemAccessMode::Read;
use FileSystemAccessMode::Write;
use FileSystemSpecialPath::Minimal;
use FileSystemSpecialPath::Root;
use FileSystemSpecialPath::SlashTmp;
use FileSystemSpecialPath::Tmpdir;
for (root_access, denial, posix, windows, unknown) in [
(Read, None, true, true, true),
(Read, Some(SlashTmp), false, true, false),
(Read, Some(Tmpdir), false, false, false),
(Write, Some(Minimal), false, false, false),
(Write, Some(Root), false, false, false),
] {
let mut entries = vec![FileSystemSandboxEntry::new(
FileSystemPath::Special { value: Root },
root_access,
)];
if let Some(value) = denial {
entries.push(deny(FileSystemPath::Special { value }));
}
let policy = FileSystemSandboxPolicy::restricted(entries);
for (convention, expected) in [
(Some(PathConvention::Posix), posix),
(Some(PathConvention::Windows), windows),
(None, unknown),
] {
assert_eq!(
policy.has_full_disk_read_access_for_convention(convention),
expected,
"policy={policy:?}, convention={convention:?}",
);
}
assert_eq!(
policy.has_full_disk_read_access(),
policy.has_full_disk_read_access_for_convention(Some(PathConvention::native())),
);
}
}
#[test]
fn remote_workspace_write_keeps_metadata_protected() {
let cwd = uri("file:///C:/repo");
let extra = uri("file:///D:/extra");
let policy = FileSystemSandboxPolicy::workspace_write_with_path_uris(
std::slice::from_ref(&extra),
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: std::slice::from_ref(&cwd),
user_home_dir: None,
temporary_directories: Some(&[]),
};
for name in PROTECTED_METADATA_PATH_NAMES {
assert!(
policy
.entries
.contains(&FileSystemSandboxEntry::skip_missing_path(
FileSystemPath::Path {
path: extra.join(name).unwrap()
},
FileSystemAccessMode::Read,
))
);
}
for root in [cwd.clone(), extra] {
assert!(policy.can_write_path(&root.join("file").unwrap(), &context));
for name in PROTECTED_METADATA_PATH_NAMES {
let path = root.join(name).unwrap().join("file").unwrap();
assert!(policy.can_read_path(&path, &context));
assert!(!policy.can_write_path(&path, &context));
}
}
}
#[test]
fn read_globs_reject_metacharacters_in_home_and_cwd_facts() {
for prefix in ["file:///home", "file:///C:/Users"] {
let parent = uri(prefix);
let directory = parent.join("sam[1]").unwrap();
for (pattern, cwd, home) in [
("~/private/*.key", &parent, Some(&directory)),
("private/*.key", &directory, None),
] {
let policy =
FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::GlobPattern {
pattern: pattern.into(),
})]);
let context = FileSystemSandboxPolicyContext {
cwd,
workspace_roots: std::slice::from_ref(&directory),
user_home_dir: home,
temporary_directories: None,
};
assert!(ReadDenyMatcher::try_new_with_context(&policy, &context).is_err());
let matcher = ReadDenyMatcher::from_context(&policy, &context).unwrap();
assert!(
matcher.is_read_denied_uri(&directory.join("private/a.key").unwrap(), &context)
);
}
}
}
#[test]
fn workspace_globs_fail_closed_on_literal_root_metacharacters_on_every_host() {
for prefix in ["file:///home", "file:///C:/Users"] {
let root = uri(prefix).join("sam[1]").unwrap();
let policy = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::GlobPattern {
pattern: crate::permissions::project_roots_glob_pattern(std::path::Path::new(
"private/*.key",
)),
})]);
let materialized = policy
.clone()
.materialize_project_roots_with_path_uris(std::slice::from_ref(&root));
assert_eq!(
materialized,
FileSystemSandboxPolicy::restricted(vec![deny(root.clone().into())]),
);
if let Ok(native_root) = root.to_abs_path() {
assert_eq!(
policy.materialize_project_roots_with_workspace_roots(&[native_root]),
materialized,
);
}
}
}
#[test]
fn materializing_legacy_home_relative_workspace_denials_removes_all_grants() {
for (root, home) in [
("file:///work/repo", "file:///home/sam"),
("file:///C:/work/repo", "file:///D:/Users/sam"),
] {
let root = uri(root);
let home = uri(home);
let convention = root.infer_path_convention().unwrap();
for subpath in ["~", "~/private/*.env", r"~\private", r"~\private\*.env"] {
if convention.home_relative_suffix(subpath).is_none() {
continue;
}
let denied_path = if subpath.contains('*') {
FileSystemPath::GlobPattern {
pattern: crate::permissions::project_roots_glob_pattern(std::path::Path::new(
subpath,
)),
}
} else {
FileSystemPath::Special {
value: FileSystemSpecialPath::ProjectRoots {
subpath: Some(subpath.into()),
},
}
};
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::ProjectRoots { subpath: None },
},
FileSystemAccessMode::Write,
),
FileSystemSandboxEntry::new(home.clone().into(), FileSystemAccessMode::Write),
deny(denied_path),
]);
let mut materialized = vec![
policy
.clone()
.materialize_project_roots_with_path_uris(std::slice::from_ref(&root)),
policy
.clone()
.with_materialized_project_roots_for_path_uris(std::slice::from_ref(&root)),
];
if let Ok(native_root) = root.to_abs_path() {
materialized.push(
policy
.clone()
.materialize_project_roots_with_workspace_roots(std::slice::from_ref(
&native_root,
)),
);
materialized.push(policy.with_materialized_project_roots_for_workspace_roots(
std::slice::from_ref(&native_root),
));
}
for policy in materialized {
assert_eq!(policy, FileSystemSandboxPolicy::restricted(Vec::new()));
}
}
}
}

View File

@@ -0,0 +1,44 @@
//! Windows deny-glob scan bounds shared by policy validation and native ACL expansion.
use akode_utils_path_uri::PathConvention;
/// Literal scan root and maximum traversal depth for a Windows deny glob.
pub struct WindowsDenyReadGlobScan<'a> {
pub root: &'a str,
pub pattern_suffix: &'a str,
pub max_depth: Option<usize>,
}
/// Plans lexical scan bounds without accessing the controller's filesystem.
pub fn windows_deny_read_glob_scan(
pattern: &str,
configured_max_depth: Option<usize>,
) -> WindowsDenyReadGlobScan<'_> {
let first_glob = pattern.find(['*', '?', '[']).unwrap_or(pattern.len());
let literal_prefix = &pattern[..first_glob];
let (root, pattern_suffix) = match literal_prefix.rfind(['/', '\\']) {
Some(index) => {
let drive_root = index > 0 && literal_prefix.as_bytes()[index - 1] == b':';
let end = if index == 0 || drive_root {
index + 1
} else {
index
};
(&literal_prefix[..end], &pattern[index + 1..])
}
None => (".", pattern),
};
let components = PathConvention::Windows
.path_segments(pattern_suffix)
.filter(|component| !component.is_empty())
.collect::<Vec<_>>();
let max_depth = if components.contains(&"**") {
configured_max_depth
} else {
Some(configured_max_depth.map_or(components.len(), |depth| depth.min(components.len())))
};
WindowsDenyReadGlobScan {
root,
pattern_suffix,
max_depth,
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,29 @@
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
// Types for the TODO tool arguments matching codex-vscode/todo-mcp/src/main.rs
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub enum StepStatus {
Pending,
InProgress,
Completed,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, TS)]
#[serde(deny_unknown_fields)]
pub struct PlanItemArg {
pub step: String,
pub status: StepStatus,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, TS)]
#[serde(deny_unknown_fields)]
pub struct UpdatePlanArgs {
/// Arguments for the `update_plan` todo/checklist tool (not plan mode).
#[serde(default)]
pub explanation: Option<String>,
pub plan: Vec<PlanItemArg>,
}

View File

@@ -0,0 +1,275 @@
You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.
Your capabilities:
- Receive user prompts and other context provided by the harness, such as files in the workspace.
- Communicate with the user by streaming thinking & responses, and by making & updating plans.
- Emit function calls to run terminal commands and apply patches. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the "Sandbox and approvals" section.
Within this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).
# How you work
## Personality
Your default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.
# AGENTS.md spec
- Repos often contain AGENTS.md files. These files can appear anywhere within the repository.
- These files are a way for humans to give you (the agent) instructions or tips for working within the container.
- Some examples might be: coding conventions, info about how code is organized, or instructions for how to run or test code.
- Instructions in AGENTS.md files:
- The scope of an AGENTS.md file is the entire directory tree rooted at the folder that contains it.
- For every file you touch in the final patch, you must obey instructions in any AGENTS.md file whose scope includes that file.
- Instructions about code style, structure, naming, etc. apply only to code within the AGENTS.md file's scope, unless the file states otherwise.
- More-deeply-nested AGENTS.md files take precedence in the case of conflicting instructions.
- Direct system/developer/user instructions (as part of a prompt) take precedence over AGENTS.md instructions.
- The contents of the AGENTS.md file at the root of the repo and any directories from the CWD up to the root are included with the developer message and don't need to be re-read. When working in a subdirectory of CWD, or a directory outside the CWD, check for any AGENTS.md files that may be applicable.
## Responsiveness
### Preamble messages
Before making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples:
- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.
- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words for quick updates).
- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.
- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.
- **Exception**: Avoid adding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action.
**Examples:**
- “I’ve explored the repo; now checking the API route definitions.”
- “Next, I’ll patch the config and update the related tests.”
- “I’m about to scaffold the CLI commands and helper functions.”
- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”
- “Config’s looking tidy. Next up is patching helpers to keep things in sync.”
- “Finished poking at the DB gateway. I will now chase down error handling.”
- “Alright, build pipeline order is interesting. Checking how it reports failures.”
- “Spotted a clever caching util; now hunting where it gets used.”
## Planning
You have access to an `update_plan` tool which tracks steps and progress and renders them to the user. Using the tool helps demonstrate that you've understood the task and convey how you're approaching it. Plans can help to make complex, ambiguous, or multi-phase work clearer and more collaborative for the user. A good plan should break the task into meaningful, logically ordered steps that are easy to verify as you go.
Note that plans are not for padding out simple work with filler steps or stating the obvious. The content of your plan should not involve doing anything that you aren't capable of doing (i.e. don't try to test things that you can't test). Do not use plans for simple or single-step queries that you can just do or answer immediately.
Do not repeat the full contents of the plan after an `update_plan` call — the harness already displays it. Instead, summarize the change made and highlight any important context or next step.
Before running a command, consider whether or not you have completed the previous step, and make sure to mark it as completed before moving on to the next step. It may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all the planned steps as completed. Sometimes, you may need to change plans in the middle of a task: call `update_plan` with the updated plan and make sure to provide an `explanation` of the rationale when doing so.
Use a plan when:
- The task is non-trivial and will require multiple actions over a long time horizon.
- There are logical phases or dependencies where sequencing matters.
- The work has ambiguity that benefits from outlining high-level goals.
- You want intermediate checkpoints for feedback and validation.
- When the user asked you to do more than one thing in a single prompt
- The user has asked you to use the plan tool (aka "TODOs")
- You generate additional steps while working, and plan to do them before yielding to the user
### Examples
**High-quality plans**
Example 1:
1. Add CLI entry with file args
2. Parse Markdown via CommonMark library
3. Apply semantic HTML template
4. Handle code blocks, images, links
5. Add error handling for invalid files
Example 2:
1. Define CSS variables for colors
2. Add toggle with localStorage state
3. Refactor components to use variables
4. Verify all views for readability
5. Add smooth theme-change transition
Example 3:
1. Set up Node.js + WebSocket server
2. Add join/leave broadcast events
3. Implement messaging with timestamps
4. Add usernames + mention highlighting
5. Persist messages in lightweight DB
6. Add typing indicators + unread count
**Low-quality plans**
Example 1:
1. Create CLI tool
2. Add Markdown parser
3. Convert to HTML
Example 2:
1. Add dark mode toggle
2. Save preference
3. Make styles look good
Example 3:
1. Create single-file HTML game
2. Run quick sanity check
3. Summarize usage instructions
If you need to write a plan, only write high quality plans, not low quality ones.
## Task execution
You are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.
You MUST adhere to the following criteria when solving queries:
- Working on the repo(s) in the current environment is allowed, even if they are proprietary.
- Analyzing code for vulnerabilities is allowed.
- Showing user code and tool call details is allowed.
- Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`): {"command":["apply_patch","*** Begin Patch\\n*** Update File: path/to/file.py\\n@@ def example():\\n- pass\\n+ return 123\\n*** End Patch"]}
If completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:
- Fix the problem at the root cause rather than applying surface-level patches, when possible.
- Avoid unneeded complexity in your solution.
- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
- Update documentation as necessary.
- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
- Use `git log` and `git blame` to search the history of the codebase if additional context is required.
- NEVER add copyright or license headers unless specifically requested.
- Do not waste tokens by re-reading files after calling `apply_patch` on them. The tool call will fail if it didn't work. The same goes for making folders, deleting folders, etc.
- Do not `git commit` your changes or create new git branches unless explicitly requested.
- Do not add inline comments within code unless explicitly requested.
- Do not use one-letter variable names unless explicitly requested.
- NEVER output inline citations like "【F:README.md†L5-L14】" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.
## Validating your work
If the codebase has tests or the ability to build or run, consider using them to verify that your work is complete.
When testing, your philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests.
Similarly, once you're confident in correctness, you can suggest or use formatting commands to ensure that your code is well formatted. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.
For all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
Be mindful of whether to run validation commands proactively. In the absence of behavioral guidance:
- When running in the non-interactive approval mode **never**, proactively run tests, lint and do whatever you need to ensure you've completed the task.
- When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first.
- When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task.
## Ambition vs. precision
For tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.
If you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.
You should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.
## Sharing progress updates
For especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next.
Before doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why.
The messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.
## Presenting your work and final message
Your final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.
You can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.
The user is working on the same computer as you, and has access to your work. As such there's no need to show the full contents of large files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using `apply_patch`, there's no need to tell users to "save the file" or "copy the code into a file"—just reference the file path.
If there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.
Brevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding.
### Final answer structure and style guidelines
You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
**Section Headers**
- Use only when they improve clarity — they are not mandatory for every answer.
- Choose descriptive names that fit the content
- Keep headers short (1–3 words) and in `**Title Case**`. Always start headers with `**` and end with `**`
- Leave no blank line before the first bullet under a header.
- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.
**Bullets**
- Use `-` followed by a space for every bullet.
- Merge related points when possible; avoid a bullet for every trivial detail.
- Keep bullets to one line unless breaking for clarity is unavoidable.
- Group into short lists (4–6 bullets) ordered by importance.
- Use consistent keyword phrasing and formatting across sections.
**Monospace**
- Wrap all commands, file paths, env vars, and code identifiers in backticks (`` `...` ``).
- Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command.
- Never mix monospace and bold markers; choose one based on whether it’s a keyword (`**`) or inline code/path (`` ` ``).
**File References**
When referencing files in your response, make sure to include the relevant start line and always follow the below rules:
* Use inline code to make file paths clickable.
* Each reference should have a stand alone path. Even if it's the same file.
* Accepted: absolute, workspace‑relative, a/ or b/ diff prefixes, or bare filename/suffix.
* Line/column (1‑based, optional): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
* Do not use URIs like file://, vscode://, or https://.
* Do not provide range of lines
* Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\repo\project\main.rs:12:5
**Structure**
- Place related bullets together; don’t mix unrelated concepts in the same section.
- Order sections from general → specific → supporting info.
- For subsections (e.g., “Binaries” under “Rust Workspace”), introduce with a bolded keyword bullet, then list items under it.
- Match structure to complexity:
- Multi-part or detailed results → use clear headers and grouped bullets.
- Simple results → minimal headers, possibly just a short list or paragraph.
**Tone**
- Keep the voice collaborative and natural, like a coding partner handing off work.
- Be concise and factual — no filler or conversational commentary and avoid unnecessary repetition
- Use present tense and active voice (e.g., “Runs tests” not “This will run tests”).
- Keep descriptions self-contained; don’t refer to “above” or “below”.
- Use parallel structure in lists for consistency.
**Don’t**
- Don’t use literal words “bold” or “monospace” in the content.
- Don’t nest bullets or create deep hierarchies.
- Don’t output ANSI escape codes directly — the CLI renderer applies them.
- Don’t cram unrelated keywords into a single bullet; split for clarity.
- Don’t let keyword lists run long — wrap or reformat for scanability.
Generally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.
For casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.
# Tool Guidelines
## Shell commands
When using the shell, you must adhere to the following guidelines:
- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)
- Do not use python scripts to attempt to output larger chunks of a file.
## `update_plan`
A tool named `update_plan` is available to you. You can use it to keep an up‑to‑date, step‑by‑step plan for the task.
To create a new plan, call `update_plan` with a short list of 1‑sentence steps (no more than 5-7 words each) with a `status` for each step (`pending`, `in_progress`, or `completed`).
When steps have been completed, use `update_plan` to mark each finished step as `completed` and the next step you are working on as `in_progress`. There should always be exactly one `in_progress` step until everything is done. You can mark multiple items as complete in a single `update_plan` call.
If all steps are complete, ensure you call `update_plan` to mark all steps as `completed`.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,59 @@
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
/// A realtime thread item persisted in the canonical rollout.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema, TS)]
pub struct RealtimeItem {
pub id: String,
pub realtime_session_id: String,
#[serde(flatten)]
pub content: RealtimeItemContent,
}
/// The minimum facts needed to interleave realtime speech and agent work.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(tag = "type", rename_all = "snake_case")]
pub enum RealtimeItemContent {
RealtimeSessionStarted,
TranscriptSegment {
role: RealtimeTranscriptRole,
text: String,
},
BemItemPromoted {
turn_id: String,
item_id: String,
presentation: BemItemPresentation,
},
RealtimeSessionClosed {
outcome: RealtimeSessionOutcome,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(rename_all = "snake_case")]
pub enum RealtimeSessionOutcome {
Ended,
Failed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(rename_all = "snake_case")]
pub enum RealtimeTranscriptRole {
User,
Assistant,
}
/// How an existing agent item is presented in the realtime conversation.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema, TS)]
#[serde(tag = "type", rename_all = "snake_case")]
#[ts(tag = "type", rename_all = "snake_case")]
pub enum BemItemPresentation {
WholeItem,
InlineMarkdown,
InlineVisualization { index: u32 },
}

View File

@@ -0,0 +1,99 @@
use crate::models::AdditionalPermissionProfile;
use crate::models::FileSystemPermissions;
use crate::models::NetworkPermissions;
use akode_utils_path_uri::LegacyAppPathString;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
pub enum PermissionGrantScope {
#[default]
Turn,
Session,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
#[serde(deny_unknown_fields)]
pub struct RequestPermissionProfile {
pub network: Option<NetworkPermissions>,
pub file_system: Option<FileSystemPermissions>,
}
impl RequestPermissionProfile {
pub fn is_empty(&self) -> bool {
self.network.is_none() && self.file_system.is_none()
}
}
impl From<RequestPermissionProfile> for AdditionalPermissionProfile {
fn from(value: RequestPermissionProfile) -> Self {
Self {
network: value.network,
file_system: value.file_system,
}
}
}
impl From<AdditionalPermissionProfile> for RequestPermissionProfile {
fn from(value: AdditionalPermissionProfile) -> Self {
Self {
network: value.network,
file_system: value.file_system,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
pub struct RequestPermissionsArgs {
#[serde(
default,
rename = "environment_id",
alias = "environmentId",
skip_serializing_if = "Option::is_none"
)]
#[ts(optional)]
pub environment_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
pub permissions: RequestPermissionProfile,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
pub struct RequestPermissionsResponse {
pub permissions: RequestPermissionProfile,
#[serde(default)]
pub scope: PermissionGrantScope,
/// Review subsequent commands in this turn unless a permission hook resolves the request.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub strict_auto_review: bool,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
pub struct RequestPermissionsEvent {
/// Responses API call id for the associated tool call, if available.
pub call_id: String,
/// Turn ID that this request belongs to.
/// Uses `#[serde(default)]` for backwards compatibility.
#[serde(default)]
pub turn_id: String,
#[serde(
default,
rename = "environmentId",
alias = "environment_id",
skip_serializing_if = "Option::is_none"
)]
#[ts(optional)]
#[ts(rename = "environmentId")]
pub environment_id: Option<String>,
#[ts(type = "number")]
pub started_at_ms: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
pub permissions: RequestPermissionProfile,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub cwd: Option<LegacyAppPathString>,
}

View File

@@ -0,0 +1,103 @@
use std::collections::HashMap;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
pub struct RequestUserInputQuestionOption {
pub label: String,
pub description: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
pub struct RequestUserInputQuestion {
pub id: String,
pub header: String,
pub question: String,
#[serde(rename = "isOther", default)]
#[schemars(rename = "isOther")]
#[ts(rename = "isOther")]
pub is_other: bool,
#[serde(rename = "isSecret", default)]
#[schemars(rename = "isSecret")]
#[ts(rename = "isSecret")]
pub is_secret: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub options: Option<Vec<RequestUserInputQuestionOption>>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
pub struct RequestUserInputArgs {
pub questions: Vec<RequestUserInputQuestion>,
#[serde(rename = "isBlocking")]
#[schemars(rename = "isBlocking")]
#[ts(rename = "isBlocking")]
pub is_blocking: bool,
/// @deprecated Use `isBlocking` to decide whether the request should block.
#[serde(rename = "autoResolutionMs", skip_serializing_if = "Option::is_none")]
#[schemars(rename = "autoResolutionMs")]
pub auto_resolution_ms: Option<u64>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
pub struct RequestUserInputAnswer {
pub answers: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
pub struct RequestUserInputResponse {
pub answers: HashMap<String, RequestUserInputAnswer>,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq, JsonSchema, TS)]
pub struct RequestUserInputEvent {
/// Responses API call id for the associated tool call, if available.
pub call_id: String,
/// Turn ID that this request belongs to.
/// Uses `#[serde(default)]` for backwards compatibility.
#[serde(default)]
pub turn_id: String,
pub questions: Vec<RequestUserInputQuestion>,
#[serde(rename = "isBlocking")]
#[schemars(rename = "isBlocking")]
#[ts(rename = "isBlocking")]
pub is_blocking: bool,
/// @deprecated Use `isBlocking` to decide whether the request should block.
#[serde(rename = "autoResolutionMs", skip_serializing_if = "Option::is_none")]
#[schemars(rename = "autoResolutionMs")]
pub auto_resolution_ms: Option<u64>,
}
impl<'de> Deserialize<'de> for RequestUserInputEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
struct WireRequestUserInputEvent {
call_id: String,
#[serde(default)]
turn_id: String,
questions: Vec<RequestUserInputQuestion>,
#[serde(rename = "isBlocking")]
is_blocking: Option<bool>,
#[serde(rename = "autoResolutionMs")]
auto_resolution_ms: Option<u64>,
}
let wire = WireRequestUserInputEvent::deserialize(deserializer)?;
Ok(Self {
call_id: wire.call_id,
turn_id: wire.turn_id,
questions: wire.questions,
is_blocking: wire.is_blocking.unwrap_or(true),
auto_resolution_ms: wire.auto_resolution_ms,
})
}
}
#[cfg(test)]
#[path = "request_user_input_tests.rs"]
mod tests;

View File

@@ -0,0 +1,44 @@
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn request_user_input_event_defaults_legacy_missing_is_blocking_to_true() {
let event: RequestUserInputEvent = serde_json::from_value(json!({
"call_id": "call-1",
"turn_id": "turn-1",
"questions": [{
"id": "q1",
"header": "Confirm",
"question": "Continue?",
"options": [{
"label": "Yes",
"description": "Continue."
}]
}],
"autoResolutionMs": 60_000
}))
.expect("legacy request_user_input event should deserialize");
assert_eq!(
event,
RequestUserInputEvent {
call_id: "call-1".to_string(),
turn_id: "turn-1".to_string(),
questions: vec![RequestUserInputQuestion {
id: "q1".to_string(),
header: "Confirm".to_string(),
question: "Continue?".to_string(),
is_other: false,
is_secret: false,
options: Some(vec![RequestUserInputQuestionOption {
label: "Yes".to_string(),
description: "Continue.".to_string(),
}]),
}],
is_blocking: true,
auto_resolution_ms: Some(60_000),
}
);
}

View File

@@ -0,0 +1,76 @@
use std::fmt;
use std::ops::Deref;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
/// A Responses API item ID. New IDs require an explicit prefix; deserialization
/// remains permissive so legacy rollouts can still be read.
#[derive(
Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema, TS,
)]
#[serde(transparent)]
#[schemars(with = "String")]
#[ts(type = "string")]
pub struct ResponseItemId(String);
impl ResponseItemId {
pub fn with_suffix(prefix: &str, suffix: impl fmt::Display) -> Self {
Self(format!("{prefix}_{suffix}"))
}
/// Reserved for physical user inputs admitted by the host. Raw item
/// ingestion must reject this namespace when it accepts caller-supplied IDs.
pub fn for_admitted_user_input(uuid: uuid::Uuid) -> Self {
Self::with_suffix("msg_input", uuid)
}
pub fn is_admitted_user_input(&self) -> bool {
self.0.starts_with("msg_input_")
}
pub fn from_server(value: String) -> Self {
Self(value)
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn is_prefixed(&self) -> bool {
self.split_once('_')
.is_some_and(|(prefix, suffix)| !prefix.is_empty() && !suffix.is_empty())
}
}
impl Deref for ResponseItemId {
type Target = str;
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl AsRef<str> for ResponseItemId {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for ResponseItemId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl From<ResponseItemId> for String {
fn from(value: ResponseItemId) -> Self {
value.0
}
}
#[cfg(test)]
#[path = "response_item_id_tests.rs"]
mod tests;

View File

@@ -0,0 +1,53 @@
use pretty_assertions::assert_eq;
use uuid::Uuid;
use super::ResponseItemId;
#[test]
fn creates_prefixed_uuid_v7_ids() {
let id = crate::uuid_v7_item_id_generator_for_test()("msg");
let uuid = id.strip_prefix("msg_").expect("message prefix");
assert_eq!(
Uuid::parse_str(uuid).expect("UUID suffix").get_version(),
Some(uuid::Version::SortRand)
);
}
#[test]
fn creates_prefixed_ids_with_explicit_suffix() {
let id = ResponseItemId::with_suffix("msg", "test");
assert_eq!(id.as_str(), "msg_test");
assert_eq!(id.to_string(), "msg_test");
assert_eq!(String::from(id), "msg_test");
}
#[test]
fn accepts_server_ids_verbatim() {
let id = ResponseItemId::from_server("legacy-id".to_string());
assert_eq!(id.as_str(), "legacy-id");
}
#[test]
fn deserializes_arbitrary_ids_as_strings() {
let id: ResponseItemId = serde_json::from_str("\"legacy-id\"").expect("id");
assert_eq!(id.as_str(), "legacy-id");
assert_eq!(
serde_json::to_string(&id).expect("serialized id"),
"\"legacy-id\""
);
}
#[test]
fn recognizes_non_empty_prefix_and_suffix() {
for (value, expected) in [
("msg_test", true),
("legacy-id", false),
("", false),
("_test", false),
("msg_", false),
] {
let id: ResponseItemId =
serde_json::from_value(value.into()).expect("ID should deserialize");
assert_eq!(id.is_prefixed(), expected, "{value}");
}
}

View File

@@ -0,0 +1,14 @@
//! Per-response usage metadata reported by the upstream service, without aggregation.
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use ts_rs::TS;
/// Usage metadata reported for one upstream response.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq, TS, JsonSchema)]
pub struct ResponseUsageMetadata {
pub amount: Option<String>,
pub metadata: Option<Value>,
}

View File

@@ -0,0 +1,82 @@
use crate::protocol::ReviewFinding;
use crate::protocol::ReviewOutputEvent;
// These helpers return plain strings that higher layers may style as needed.
fn format_location(item: &ReviewFinding) -> String {
let path = item.code_location.absolute_file_path.display();
let start = item.code_location.line_range.start;
let end = item.code_location.line_range.end;
format!("{path}:{start}-{end}")
}
/// Fallback text used when a review contains no displayable output.
pub const REVIEW_FALLBACK_MESSAGE: &str = "Reviewer failed to output a response.";
/// Format a full review findings block as plain text lines.
///
/// - When `selection` is `Some`, each item line includes a checkbox marker:
/// "[x]" for selected items and "[ ]" for unselected. Missing indices
/// default to selected.
/// - When `selection` is `None`, the marker is omitted and a simple bullet is
/// rendered ("- Title — path:start-end").
pub fn format_review_findings_block(
findings: &[ReviewFinding],
selection: Option<&[bool]>,
) -> String {
let mut lines: Vec<String> = Vec::new();
lines.push(String::new());
// Header
if findings.len() > 1 {
lines.push("Full review comments:".to_string());
} else {
lines.push("Review comment:".to_string());
}
for (idx, item) in findings.iter().enumerate() {
lines.push(String::new());
let title = &item.title;
let location = format_location(item);
if let Some(flags) = selection {
// Default to selected if index is out of bounds.
let checked = flags.get(idx).copied().unwrap_or(true);
let marker = if checked { "[x]" } else { "[ ]" };
lines.push(format!("- {marker} {title} — {location}"));
} else {
lines.push(format!("- {title} — {location}"));
}
for body_line in item.body.lines() {
lines.push(format!(" {body_line}"));
}
}
lines.join("\n")
}
/// Render a human-readable review summary suitable for a user-facing message.
///
/// Returns either the explanation, the formatted findings block, or both
/// separated by a blank line. If neither is present, emits a fallback message.
pub fn render_review_output_text(output: &ReviewOutputEvent) -> String {
let mut sections = Vec::new();
let explanation = output.overall_explanation.trim();
if !explanation.is_empty() {
sections.push(explanation.to_string());
}
if !output.findings.is_empty() {
let findings = format_review_findings_block(&output.findings, /*selection*/ None);
let trimmed = findings.trim();
if !trimmed.is_empty() {
sections.push(trimmed.to_string());
}
}
if sections.is_empty() {
REVIEW_FALLBACK_MESSAGE.to_string()
} else {
sections.join("\n\n")
}
}

View File

@@ -0,0 +1,61 @@
//! Identifies the sandbox implementation and overrides selected for a command.
use serde::Deserialize;
use serde::Serialize;
use crate::config_types::WindowsSandboxLevel;
/// Controller decision that overrides normal sandbox selection for a command.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum SandboxOverride {
/// Use normal sandbox selection.
#[default]
NoOverride,
/// Broaden approved filesystem access while retaining denied-read enforcement.
EscalatedSandboxWithRestrictions,
/// Bypass the sandbox on the first attempt.
BypassSandboxFirstAttempt,
}
impl SandboxOverride {
pub fn is_no_override(&self) -> bool {
*self == Self::NoOverride
}
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum SandboxType {
None,
MacosSeatbelt,
LinuxSeccomp,
WindowsRestrictedToken,
WindowsMxc,
}
impl SandboxType {
pub fn as_metric_tag(self) -> &'static str {
match self {
Self::None => "none",
Self::MacosSeatbelt => "seatbelt",
Self::LinuxSeccomp => "seccomp",
Self::WindowsRestrictedToken => "windows_sandbox",
Self::WindowsMxc => "windows_mxc",
}
}
}
/// Preserves explicit MXC selection while honoring legacy runtime level updates.
pub fn effective_windows_sandbox_type(
sandbox_type: SandboxType,
sandbox_level: WindowsSandboxLevel,
) -> SandboxType {
match (sandbox_type, sandbox_level) {
(SandboxType::WindowsMxc, _) => SandboxType::WindowsMxc,
(_, WindowsSandboxLevel::Disabled) => SandboxType::None,
(_, WindowsSandboxLevel::RestrictedToken | WindowsSandboxLevel::Elevated) => {
SandboxType::WindowsRestrictedToken
}
}
}

View File

@@ -0,0 +1,163 @@
use std::fmt;
use std::ops::Deref;
use gix_url::Scheme;
use gix_url::Url;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
/// A git remote URL with authentication credentials removed.
#[derive(
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema, TS,
)]
#[serde(try_from = "String", into = "String")]
#[schemars(with = "String")]
#[ts(type = "string")]
pub struct SanitizedGitUrl(String);
impl SanitizedGitUrl {
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl TryFrom<&str> for SanitizedGitUrl {
type Error = &'static str;
fn try_from(value: &str) -> Result<Self, Self::Error> {
// Remote helpers wrap another remote, so peel off their prefixes
// without recursion before passing the address to the Git URL parser.
let mut address = value;
while let Some((transport, nested_address)) = address.split_once("::")
&& !transport.is_empty()
&& transport.chars().all(|character| {
character.is_ascii_alphanumeric() || matches!(character, '+' | '-' | '.')
})
{
// Helpers can also receive executable command lines containing
// arbitrary secrets; scan the whole payload once and reject those.
if address.len() == value.len() && nested_address.chars().any(char::is_whitespace) {
return Err("invalid git remote URL");
}
address = nested_address;
}
let helper_prefix = &value[..value.len() - address.len()];
let original = value;
let value = address;
// Parse first to recognize both URL and SCP-style remotes and reject
// malformed inputs before reconstructing the original text.
let url = match Url::try_from(value) {
Ok(url) => url,
Err(_) => {
// gix mistakes an IPv6 address's first colon for the SCP path
// separator when a username comes before the bracketed host.
let (user, host_and_path) =
value.split_once('@').ok_or("invalid git remote URL")?;
let (host, path) = host_and_path
.strip_prefix('[')
.and_then(|host_and_path| host_and_path.split_once("]:"))
.ok_or("invalid git remote URL")?;
if user.is_empty() || path.is_empty() {
return Err("invalid git remote URL");
}
// SCP paths are opaque and can contain characters that URL parsing rejects.
let ssh_url = format!("ssh://{user}@[{host}]/");
Url::try_from(ssh_url.as_str()).map_err(|_| "invalid git remote URL")?
}
};
// SSH's conventional `git` user is a transport identity, not a secret;
// every other username and all passwords must be removed.
let preserve_ssh_git_user = url.scheme == Scheme::Ssh && url.user() == Some("git");
// Inspect the authority directly because gix treats the complete
// `file://` authority as its host and does not expose its userinfo.
// Rebuilding only this part also preserves escaped repository paths.
if let Some((scheme, authority_and_path)) = value.split_once("://") {
// Git treats '?' and '#' as authority text on non-HTTP transports.
let authority_end = if matches!(scheme, "http" | "https") {
authority_and_path.find(['/', '?', '#'])
} else {
authority_and_path.find('/')
}
.unwrap_or(authority_and_path.len());
let (authority, path) = authority_and_path.split_at(authority_end);
let Some((_, host)) = authority.rsplit_once('@') else {
return Ok(Self(original.to_owned()));
};
if preserve_ssh_git_user && url.password().is_none() {
return Ok(Self(original.to_owned()));
}
let user = if preserve_ssh_git_user { "git@" } else { "" };
return Ok(Self(format!(
"{helper_prefix}{scheme}://{user}{host}{path}"
)));
}
// Parsed serialization can alter Git paths, so preserve the exact
// original representation whenever no credential needs removal.
if url.password().is_none() && (url.user().is_none() || preserve_ssh_git_user) {
return Ok(Self(original.to_owned()));
}
// SCP-style remotes have no URL authority; remove only `user@` and
// leave the original `host:path` untouched.
let authority_end = value.find(':').unwrap_or(value.len());
let user_end = value[..authority_end]
.rfind('@')
.ok_or("invalid git remote URL")?;
Ok(Self(format!("{helper_prefix}{}", &value[user_end + 1..])))
}
}
impl TryFrom<String> for SanitizedGitUrl {
type Error = &'static str;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::try_from(value.as_str())
}
}
impl From<SanitizedGitUrl> for String {
fn from(value: SanitizedGitUrl) -> Self {
value.0
}
}
impl AsRef<str> for SanitizedGitUrl {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Deref for SanitizedGitUrl {
type Target = str;
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl fmt::Display for SanitizedGitUrl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
pub(crate) fn deserialize_optional_sanitized_git_url<'de, D>(
deserializer: D,
) -> Result<Option<SanitizedGitUrl>, D::Error>
where
D: serde::Deserializer<'de>,
{
// Malformed legacy origins must not prevent the rest of a rollout from loading.
Ok(Option::<String>::deserialize(deserializer)?
.and_then(|value| SanitizedGitUrl::try_from(value).ok()))
}
#[cfg(test)]
#[path = "sanitized_git_url_tests.rs"]
mod tests;

View File

@@ -0,0 +1,305 @@
use super::SanitizedGitUrl;
use crate::protocol::GitInfo;
use pretty_assertions::assert_eq;
use serde::Deserialize;
use serde::de::value::Error;
use serde::de::value::StrDeserializer;
use serde_json::json;
/// HTTPS usernames and passwords must never survive construction.
#[test]
fn removes_https_username_and_password() {
let url = SanitizedGitUrl::try_from("https://alice:secret@github.com/org/repo.git")
.expect("parse remote URL");
assert_eq!(url.as_str(), "https://github.com/org/repo.git");
}
#[test]
fn http_query_and_fragment_are_outside_the_authority() {
for (scheme, suffix) in [("http", "?@github.com/a/b"), ("https", "#@github.com/a/b")] {
let expected = format!("{scheme}://example.com{suffix}");
for authority in ["example.com", "user:password@example.com"] {
let remote = format!("{scheme}://{authority}{suffix}");
let sanitized = SanitizedGitUrl::try_from(remote.as_str()).expect("parse remote URL");
assert_eq!(sanitized.as_str(), expected);
}
}
}
#[test]
fn non_http_credentials_can_contain_query_and_fragment_delimiters() {
for scheme in ["ssh", "git", "file"] {
let expected = format!("{scheme}://example.com/org/repo");
for password in ["synthetic?value", "synthetic#value"] {
let remote = format!("{scheme}://user:{password}@example.com/org/repo");
let sanitized = SanitizedGitUrl::try_from(remote.as_str()).expect("parse remote URL");
assert_eq!(sanitized.as_str(), expected);
}
}
}
/// Tokens placed in the username field are credentials too.
#[test]
fn removes_https_username_without_password() {
let url = SanitizedGitUrl::try_from("https://secret-token@github.com/org/repo.git")
.expect("parse remote URL");
assert_eq!(url.as_str(), "https://github.com/org/repo.git");
}
/// Percent-encoded credentials must not bypass git-aware URL parsing.
#[test]
fn removes_percent_encoded_credentials() {
let url = SanitizedGitUrl::try_from(
"https://alice%40example.com:secret%3Atoken@github.com/org/repo.git",
)
.expect("parse remote URL");
assert_eq!(url.as_str(), "https://github.com/org/repo.git");
}
/// File URLs must lose credentials even though gix stores their userinfo as host text.
#[test]
fn removes_file_url_credentials() {
for (remote, expected) in [
(
"file://alice:secret@localhost/repo.git",
"file://localhost/repo.git",
),
(
"file://secret-token@server/share/a%2Fb.git",
"file://server/share/a%2Fb.git",
),
(
"file://git:secret@server/share/repo.git",
"file://server/share/repo.git",
),
] {
let url = SanitizedGitUrl::try_from(remote).expect("parse file remote URL");
assert_eq!(url.as_str(), expected);
}
}
/// Git remote-helper transports preserve their prefix and sanitize nested URLs.
#[test]
fn sanitizes_remote_helper_urls() {
for (remote, expected) in [
(
"hg::https://example.invalid/org/repo.git",
"hg::https://example.invalid/org/repo.git",
),
(
"hg::https://alice:secret@example.invalid/org/repo.git",
"hg::https://example.invalid/org/repo.git",
),
(
"remote-hg::git@github.com:org/repo.git",
"remote-hg::git@github.com:org/repo.git",
),
(
"remote-hg::file://alice:secret@server/share/repo.git",
"remote-hg::file://server/share/repo.git",
),
] {
let url = SanitizedGitUrl::try_from(remote).expect("parse remote helper URL");
assert_eq!(url.as_str(), expected);
}
}
/// Nested helper prefixes must not overflow the stack or repeatedly rebuild the remote.
#[test]
fn sanitizes_deeply_nested_remote_helpers_without_recursion() {
let prefix = "hg::".repeat(4_096);
let remote = format!("{prefix}https://alice:secret@example.invalid/org/repo.git");
let expected = format!("{prefix}https://example.invalid/org/repo.git");
let url = SanitizedGitUrl::try_from(remote.as_str()).expect("parse nested remote helper URL");
assert_eq!(url.as_str(), expected);
}
/// Opaque helper command lines can hide credentials that Git URL parsing cannot identify.
#[test]
fn rejects_remote_helper_command_payloads() {
for remote in [
"ext::sshpass -p secret-token ssh alice@example.com git-upload-pack /repo",
"ext::ssh alice:secret-token@example.com git-upload-pack /repo",
] {
let error = SanitizedGitUrl::try_from(remote).expect_err("reject helper command payload");
assert_eq!(error, "invalid git remote URL");
}
}
/// Removing credentials must not decode reserved characters in repository paths.
#[test]
fn preserves_percent_encoded_path_delimiters() {
for (remote, expected) in [
(
"https://example.invalid/org/a%2Fb%3Fc%23d.git",
"https://example.invalid/org/a%2Fb%3Fc%23d.git",
),
(
"https://alice:secret@example.invalid/org/a%2Fb%3Fc%23d.git",
"https://example.invalid/org/a%2Fb%3Fc%23d.git",
),
(
"hg::https://alice:secret@example.invalid/org/a%2Fb.git",
"hg::https://example.invalid/org/a%2Fb.git",
),
] {
let url = SanitizedGitUrl::try_from(remote).expect("parse percent-encoded remote URL");
assert_eq!(url.as_str(), expected);
}
}
/// The conventional non-secret SSH username is preserved in both Git URL forms.
#[test]
fn preserves_git_ssh_username() {
for remote in [
"git@github.com:org/repo.git",
"ssh://git@github.com/org/repo.git",
] {
let url = SanitizedGitUrl::try_from(remote).expect("parse remote URL");
assert_eq!(url.as_str(), remote);
}
}
/// SSH passwords are always removed even for the preserved `git` username.
#[test]
fn removes_ssh_password_for_git_username() {
let url = SanitizedGitUrl::try_from("ssh://git:secret@github.com/org/repo.git")
.expect("parse remote URL");
assert_eq!(url.as_str(), "ssh://git@github.com/org/repo.git");
}
/// Only the exact SSH username `git` is exempt from credential removal.
#[test]
fn removes_other_ssh_usernames() {
for (remote, expected) in [
("alice@github.com:org/repo.git", "github.com:org/repo.git"),
(
"ssh://alice@github.com/org/repo.git",
"ssh://github.com/org/repo.git",
),
(
"https://git@github.com/org/repo.git",
"https://github.com/org/repo.git",
),
] {
let url = SanitizedGitUrl::try_from(remote).expect("parse remote URL");
assert_eq!(url.as_str(), expected);
}
}
/// gix-url misidentifies an IPv6 colon as the SCP path separator when a user precedes the host.
#[test]
fn sanitizes_scp_style_ipv6_remotes_with_usernames() {
for (remote, expected) in [
(
"git@[2001:db8::1]:org/repo.git",
"git@[2001:db8::1]:org/repo.git",
),
(
"alice@[2001:db8::1]:org/repo.git",
"[2001:db8::1]:org/repo.git",
),
] {
let url = SanitizedGitUrl::try_from(remote).expect("parse SCP-style IPv6 remote URL");
assert_eq!(url.as_str(), expected);
}
}
/// IPv6 fallback validation must not interpret opaque SCP paths as URL paths.
#[test]
fn preserves_opaque_scp_style_ipv6_paths() {
for (remote, expected) in [
("alice@[::1]:dir name/repo", "[::1]:dir name/repo"),
("alice@[::1]:repo%FF.git", "[::1]:repo%FF.git"),
("git@[::1]:dir name/repo", "git@[::1]:dir name/repo"),
] {
let url = SanitizedGitUrl::try_from(remote).expect("parse opaque SCP-style IPv6 path");
assert_eq!(url.as_str(), expected);
}
}
/// Invalid remotes fail closed without including their embedded secret in errors.
#[test]
fn rejects_malformed_urls_without_exposing_input() {
let error = SanitizedGitUrl::try_from("https://alice:secret-token@[invalid")
.expect_err("reject malformed remote URL");
assert_eq!(error, "invalid git remote URL");
assert!(!error.contains("secret-token"));
}
/// Deserializing persisted metadata must enforce the constructor invariant.
#[test]
fn deserialization_sanitizes_credentials() {
let deserializer =
StrDeserializer::<Error>::new("https://alice:secret-token@github.com/org/repo.git");
let url = SanitizedGitUrl::deserialize(deserializer).expect("deserialize remote URL");
assert_eq!(url.as_str(), "https://github.com/org/repo.git");
}
/// Ordinary HTTPS remotes retain their existing wire representation.
#[test]
fn preserves_https_remote_without_credentials() {
let remote = "https://github.com/org/repo.git";
let url = SanitizedGitUrl::try_from(remote.to_string()).expect("parse remote URL");
assert_eq!(String::from(url), remote);
}
/// Legacy rollout origins must be sanitized as soon as their protocol metadata is parsed.
#[test]
fn git_info_deserialization_sanitizes_legacy_remote_credentials() {
let info: GitInfo = serde_json::from_value(json!({
"repository_url": "https://alice:secret-token@github.com/org/repo.git",
}))
.expect("deserialize legacy Git metadata");
assert_eq!(
info.repository_url.as_deref(),
Some("https://github.com/org/repo.git")
);
}
/// An invalid historical remote must not make its entire rollout impossible to resume.
#[test]
fn git_info_deserialization_discards_malformed_legacy_remote() {
let info: GitInfo = serde_json::from_value(json!({
"repository_url": "https://alice:secret-token@[invalid",
}))
.expect("deserialize Git metadata despite malformed legacy remote");
assert_eq!(info.repository_url, None);
}
/// Older rollout metadata may omit repository URLs entirely.
#[test]
fn git_info_deserialization_accepts_missing_repository_url() {
let info: GitInfo = serde_json::from_value(json!({}))
.expect("deserialize legacy Git metadata without a repository URL");
assert_eq!(info.repository_url, None);
}
/// Explicitly absent repository URLs retain their existing protocol representation.
#[test]
fn git_info_deserialization_accepts_null_repository_url() {
let info: GitInfo = serde_json::from_value(json!({ "repository_url": null }))
.expect("deserialize legacy Git metadata with a null repository URL");
assert_eq!(info.repository_url, None);
}

View File

@@ -0,0 +1,25 @@
use chrono::DateTime;
use chrono::Utc;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
/// A thread-owned, in-memory snapshot of security risk classifier scores.
///
/// Scores must not enter model-visible conversation context or user-visible thread
/// item projections.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct SecurityRiskScore {
pub scores: BTreeMap<String, f64>,
/// The tool call whose action produced this score, when available.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub call_id: Option<String>,
/// The bounded tool action that was reviewed to produce this score.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub action: Option<serde_json::Value>,
/// When sampling started, if this snapshot was written by a timestamp-aware client.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "Option<String>")]
pub sampled_at: Option<DateTime<Utc>>,
}

View File

@@ -0,0 +1,126 @@
use std::fmt::Display;
use schemars::JsonSchema;
use schemars::r#gen::SchemaGenerator;
use schemars::schema::Schema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
use uuid::Uuid;
use crate::ThreadId;
#[derive(Debug, Clone, Copy, PartialEq, Eq, TS, Hash)]
#[ts(type = "string")]
pub struct SessionId {
pub(crate) uuid: Uuid,
}
impl SessionId {
pub fn new() -> Self {
Self {
uuid: Uuid::now_v7(),
}
}
pub fn from_string(s: &str) -> Result<Self, uuid::Error> {
Ok(Self {
uuid: Uuid::parse_str(s)?,
})
}
}
impl TryFrom<&str> for SessionId {
type Error = uuid::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::from_string(value)
}
}
impl TryFrom<String> for SessionId {
type Error = uuid::Error;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_string(value.as_str())
}
}
impl From<SessionId> for String {
fn from(value: SessionId) -> Self {
value.to_string()
}
}
impl From<ThreadId> for SessionId {
fn from(value: ThreadId) -> Self {
Self { uuid: value.uuid }
}
}
impl From<SessionId> for ThreadId {
fn from(value: SessionId) -> Self {
ThreadId { uuid: value.uuid }
}
}
impl Default for SessionId {
fn default() -> Self {
Self::new()
}
}
impl Display for SessionId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.uuid, f)
}
}
impl Serialize for SessionId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_str(&self.uuid)
}
}
impl<'de> Deserialize<'de> for SessionId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
let uuid = Uuid::parse_str(&value).map_err(serde::de::Error::custom)?;
Ok(Self { uuid })
}
}
impl JsonSchema for SessionId {
fn schema_name() -> String {
"SessionId".to_string()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
<String>::json_schema(generator)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_session_id_default_is_not_zeroes() {
let id = SessionId::default();
assert_ne!(id.uuid, Uuid::nil());
}
#[test]
fn converts_to_and_from_thread_id() {
let thread_id = ThreadId::new();
let session_id = SessionId::from(thread_id);
assert_eq!(ThreadId::from(session_id), thread_id);
}
}

View File

@@ -0,0 +1,337 @@
use crate::config_types::EnvironmentVariablePattern;
use crate::config_types::ShellEnvironmentPolicy;
use crate::config_types::ShellEnvironmentPolicyInherit;
use std::collections::HashMap;
pub const AKODE_SESSION_ID_ENV_VAR: &str = "AKODE_SESSION_ID";
pub const AKODE_THREAD_ID_ENV_VAR: &str = "AKODE_THREAD_ID";
pub const AKODE_TOOL_CALL_ID_ENV_VAR: &str = "AKODE_TOOL_CALL_ID";
pub const AKODE_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR: &str = "AKODE_EXEC_SERVER_NOISE_AUTH_TOKEN";
pub const OPENAI_FEDERATION_RULE_ID_ENV_VAR: &str = "OPENAI_FEDERATION_RULE_ID";
pub const OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR: &str = "OPENAI_IDENTITY_TOKEN_FILE";
pub const OPENAI_WORKLOAD_IDENTITY_CONTEXT_ENV_VAR: &str = "OPENAI_WORKLOAD_IDENTITY_CONTEXT";
/// Environment variables that model-reachable child processes must not inherit.
pub const NON_INHERITABLE_ENV_VARS: &[&str] = &[
AKODE_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR,
"NODE_REPL_AUTH_TOKEN",
"AKODE_GUARDIAN_DECISIONS_API_KEY",
OPENAI_FEDERATION_RULE_ID_ENV_VAR,
OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR,
OPENAI_WORKLOAD_IDENTITY_CONTEXT_ENV_VAR,
];
pub fn is_non_inheritable_env_var(name: &str) -> bool {
NON_INHERITABLE_ENV_VARS
.iter()
.any(|restricted| restricted.eq_ignore_ascii_case(name))
}
pub fn set_tool_call_id_env_var(env: &mut HashMap<String, String>, tool_call_id: Option<&str>) {
#[cfg(windows)]
env.retain(|name, _| !name.eq_ignore_ascii_case(AKODE_TOOL_CALL_ID_ENV_VAR));
#[cfg(not(windows))]
env.remove(AKODE_TOOL_CALL_ID_ENV_VAR);
if let Some(tool_call_id) = tool_call_id.filter(|tool_call_id| !tool_call_id.contains('\0')) {
env.insert(
AKODE_TOOL_CALL_ID_ENV_VAR.to_string(),
tool_call_id.to_string(),
);
}
}
/// Configures a child command to omit non-inheritable variables from the
/// process environment and explicit command overrides.
///
/// This prevents accidental propagation of Codex launch context; it is not a
/// filesystem security boundary for the referenced identity-token file.
pub fn scrub_non_inheritable_env_vars(command: &mut std::process::Command) {
let configured_names = command
.get_envs()
.map(|(name, _)| name.to_os_string())
.collect::<Vec<_>>();
for name in NON_INHERITABLE_ENV_VARS {
command.env_remove(name);
}
for name in std::env::vars_os()
.map(|(name, _)| name)
.chain(configured_names)
{
if name.to_str().is_some_and(is_non_inheritable_env_var) {
command.env_remove(name);
}
}
}
/// Construct a shell environment from the supplied process environment and
/// shell-environment policy.
pub fn create_env(
policy: &ShellEnvironmentPolicy,
thread_id: Option<&str>,
) -> HashMap<String, String> {
create_env_from_vars(std::env::vars(), policy, thread_id)
}
pub fn create_env_from_vars<I>(
vars: I,
policy: &ShellEnvironmentPolicy,
thread_id: Option<&str>,
) -> HashMap<String, String>
where
I: IntoIterator<Item = (String, String)>,
{
let mut env_map = populate_env(vars, policy, thread_id);
if cfg!(target_os = "windows") {
// This is a workaround to address the failures we are seeing in the
// following tests when run via Bazel on Windows:
//
// ```
// suite::shell_command::unicode_output::with_login
// suite::shell_command::unicode_output::without_login
// ```
//
// Currently, we can only reproduce these failures in CI, which makes
// iteration times long, so we include this quick fix for now to unblock
// getting the Windows Bazel build running.
if !env_map.keys().any(|k| k.eq_ignore_ascii_case("PATHEXT")) {
env_map.insert("PATHEXT".to_string(), ".COM;.EXE;.BAT;.CMD".to_string());
}
}
env_map
}
pub fn populate_env<I>(
vars: I,
policy: &ShellEnvironmentPolicy,
thread_id: Option<&str>,
) -> HashMap<String, String>
where
I: IntoIterator<Item = (String, String)>,
{
// Step 1 - determine the starting set of variables based on the
// `inherit` strategy.
let mut env_map: HashMap<String, String> = match policy.inherit {
ShellEnvironmentPolicyInherit::All => vars.into_iter().collect(),
ShellEnvironmentPolicyInherit::None => HashMap::new(),
ShellEnvironmentPolicyInherit::Core => {
#[cfg(not(target_os = "windows"))]
let core_env_vars = UNIX_CORE_ENV_VARS;
#[cfg(target_os = "windows")]
let core_env_vars = WINDOWS_CORE_ENV_VARS;
vars.into_iter()
.filter(|(k, _)| {
core_env_vars
.iter()
.any(|allowed| allowed.eq_ignore_ascii_case(k))
})
.collect()
}
};
let matches_any = |name: &str, patterns: &[EnvironmentVariablePattern]| -> bool {
patterns.iter().any(|pattern| pattern.matches(name))
};
// Step 2 - Apply the default exclude if not disabled.
if !policy.ignore_default_excludes {
let default_excludes = vec![
EnvironmentVariablePattern::new_case_insensitive("*KEY*"),
EnvironmentVariablePattern::new_case_insensitive("*SECRET*"),
EnvironmentVariablePattern::new_case_insensitive("*TOKEN*"),
];
env_map.retain(|k, _| !matches_any(k, &default_excludes));
}
// Step 3 - Apply custom excludes.
if !policy.exclude.is_empty() {
env_map.retain(|k, _| !matches_any(k, &policy.exclude));
}
// Step 4 - Apply user-provided overrides.
for (key, val) in &policy.r#set {
#[cfg(windows)]
env_map.retain(|existing, _| !existing.eq_ignore_ascii_case(key));
env_map.insert(key.clone(), val.clone());
}
// Step 5 - If include_only is non-empty, keep only the matching vars.
if !policy.include_only.is_empty() {
env_map.retain(|k, _| matches_any(k, &policy.include_only));
}
// Step 6 - Populate the thread ID environment variable when provided.
if let Some(thread_id) = thread_id {
env_map.insert(AKODE_THREAD_ID_ENV_VAR.to_string(), thread_id.to_string());
}
// Restricted launch context cannot be restored through user-provided shell
// environment overrides.
env_map.retain(|name, _| !is_non_inheritable_env_var(name));
env_map
}
#[cfg(not(target_os = "windows"))]
const UNIX_CORE_ENV_VARS: &[&str] = &[
"PATH", "SHELL", "TMPDIR", "TEMP", "TMP", "HOME", "LANG", "LC_ALL", "LC_CTYPE", "LOGNAME",
"USER",
];
#[cfg(target_os = "windows")]
pub const WINDOWS_CORE_ENV_VARS: &[&str] = &[
// Core path resolution
"PATH",
"PATHEXT",
// Shell and system roots
"SHELL",
"COMSPEC",
"SYSTEMROOT",
"WINDIR",
"SYSTEMDRIVE",
// User context and profiles
"USERNAME",
"USERDOMAIN",
"USERPROFILE",
"HOMEDRIVE",
"HOMEPATH",
// Program locations
"PROGRAMFILES",
"PROGRAMFILES(X86)",
"PROGRAMW6432",
"PROGRAMDATA",
// App data and caches
"LOCALAPPDATA",
"APPDATA",
// Temp locations
"TEMP",
"TMP",
"TMPDIR",
// Common shells/pwsh hints
"POWERSHELL",
"PWSH",
];
#[cfg(test)]
#[path = "shell_environment_tests.rs"]
mod tests;
#[cfg(all(test, target_os = "windows"))]
mod windows_tests {
use super::*;
use pretty_assertions::assert_eq;
fn make_vars(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
pairs
.iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect()
}
#[test]
#[cfg(target_os = "windows")]
fn core_inherit_preserves_windows_startup_vars_case_insensitively() {
let vars = make_vars(&[
("Shell", "C:\\Program Files\\Git\\bin\\bash.exe"),
("SystemRoot", "C:\\Windows"),
("WinDir", "C:\\Windows"),
("AppData", "C:\\Users\\codex\\AppData\\Roaming"),
("TmpDir", "C:\\Temp\\custom"),
("OPENAI_API_KEY", "secret"),
]);
let policy = ShellEnvironmentPolicy {
inherit: ShellEnvironmentPolicyInherit::Core,
ignore_default_excludes: true,
..Default::default()
};
// Check a few sample vars instead of the full Windows core list.
let result = populate_env(vars, &policy, /*thread_id*/ None);
let expected = HashMap::from([
(
"Shell".to_string(),
"C:\\Program Files\\Git\\bin\\bash.exe".to_string(),
),
("SystemRoot".to_string(), "C:\\Windows".to_string()),
("WinDir".to_string(), "C:\\Windows".to_string()),
(
"AppData".to_string(),
"C:\\Users\\codex\\AppData\\Roaming".to_string(),
),
("TmpDir".to_string(), "C:\\Temp\\custom".to_string()),
]);
assert_eq!(result, expected);
let policy = ShellEnvironmentPolicy {
inherit: ShellEnvironmentPolicyInherit::All,
ignore_default_excludes: true,
r#set: HashMap::from([("gh_host".to_string(), "github.trusted.example".to_string())]),
..Default::default()
};
assert_eq!(
populate_env(
make_vars(&[("GH_HOST", "github.stale.example")]),
&policy,
/*thread_id*/ None,
),
HashMap::from([("gh_host".to_string(), "github.trusted.example".to_string(),)]),
);
}
#[test]
#[cfg(target_os = "windows")]
fn create_env_inserts_pathext_on_windows_when_missing() {
let policy = ShellEnvironmentPolicy {
inherit: ShellEnvironmentPolicyInherit::None,
ignore_default_excludes: true,
..Default::default()
};
let result = create_env_from_vars(Vec::new(), &policy, /*thread_id*/ None);
let expected = HashMap::from([("PATHEXT".to_string(), ".COM;.EXE;.BAT;.CMD".to_string())]);
assert_eq!(result, expected);
}
}
#[cfg(all(test, not(target_os = "windows")))]
mod non_windows_tests {
use super::*;
use pretty_assertions::assert_eq;
fn make_vars(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
pairs
.iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect()
}
#[test]
fn core_inherit_preserves_non_windows_core_vars_case_insensitively() {
let vars = make_vars(&[
("path", "/usr/bin"),
("home", "/home/codex"),
("TmpDir", "/tmp/custom"),
("OPENAI_API_KEY", "secret"),
]);
let policy = ShellEnvironmentPolicy {
inherit: ShellEnvironmentPolicyInherit::Core,
ignore_default_excludes: true,
..Default::default()
};
let result = populate_env(vars, &policy, /*thread_id*/ None);
let expected = HashMap::from([
("path".to_string(), "/usr/bin".to_string()),
("home".to_string(), "/home/codex".to_string()),
("TmpDir".to_string(), "/tmp/custom".to_string()),
]);
assert_eq!(result, expected);
}
}

View File

@@ -0,0 +1,169 @@
use std::collections::HashMap;
use std::process::Command;
use pretty_assertions::assert_eq;
use super::*;
const CHILD_MODE_ENV_VAR: &str = "AKODE_SHELL_ENVIRONMENT_SCRUBBER_TEST_MODE";
const TEST_NAME: &str =
"shell_environment::tests::command_scrubber_removes_names_from_real_child_environment";
#[test]
fn tool_call_id_replaces_platform_equivalent_names() {
let representable = format!("exec-雪-{}", "x".repeat(512));
for (call_id, expected_call) in [
(None, None),
(Some(""), Some("")),
(Some("invalid\0call"), None),
(Some("current-call"), Some("current-call")),
(Some(representable.as_str()), Some(representable.as_str())),
] {
let mut env = HashMap::from([
("AKODE_TOOL_CALL_ID".to_string(), "stale-call".to_string()),
(
"Codex_Tool_Call_Id".to_string(),
"mixed-case-call".to_string(),
),
(
"codex_tool_call_id".to_string(),
"lowercase-call".to_string(),
),
("OTHER".to_string(), "unchanged".to_string()),
]);
set_tool_call_id_env_var(&mut env, call_id);
let mut expected = HashMap::from([("OTHER".to_string(), "unchanged".to_string())]);
#[cfg(not(windows))]
expected.extend([
(
"Codex_Tool_Call_Id".to_string(),
"mixed-case-call".to_string(),
),
(
"codex_tool_call_id".to_string(),
"lowercase-call".to_string(),
),
]);
if let Some(expected_call) = expected_call {
expected.insert("AKODE_TOOL_CALL_ID".to_string(), expected_call.to_string());
}
assert_eq!(env, expected, "call_id: {call_id:?}");
}
}
#[test]
fn non_inheritable_environment_is_removed_after_policy_overrides() {
let vars = [
("SAFE".to_string(), "inherited".to_string()),
(
"codex_guardian_decisions_api_key".into(),
"synthetic-inherited-key".into(),
),
("node_repl_auth_token".into(), "inherited-token".into()),
(
"openai_federation_rule_id".to_string(),
"inherited-rule".to_string(),
),
(
"OPENAI_WORKLOAD_IDENTITY_CONTEXT".to_string(),
r#"{"instance_id":"box-one"}"#.to_string(),
),
(
"codex_exec_server_noise_auth_token".to_string(),
"inherited-noise-token".to_string(),
),
];
let policy = ShellEnvironmentPolicy {
inherit: ShellEnvironmentPolicyInherit::All,
ignore_default_excludes: true,
r#set: HashMap::from([
("SAFE".to_string(), "override".to_string()),
(
"AKODE_GUARDIAN_DECISIONS_API_KEY".into(),
"synthetic-override-key".into(),
),
("Node_Repl_Auth_Token".into(), "configured-token".into()),
(
"OpenAI_Identity_Token_File".to_string(),
"/run/identity-token".to_string(),
),
(
"Codex_Exec_Server_Noise_Auth_Token".to_string(),
"configured-noise-token".to_string(),
),
]),
..Default::default()
};
assert_eq!(
populate_env(vars, &policy, /*thread_id*/ None),
HashMap::from([("SAFE".to_string(), "override".to_string())])
);
}
#[test]
fn command_scrubber_removes_names_from_real_child_environment() {
if std::env::var_os(CHILD_MODE_ENV_VAR).is_none() {
let output = Command::new(std::env::current_exe().expect("locate current test binary"))
.args([TEST_NAME, "--exact", "--nocapture"])
.env(CHILD_MODE_ENV_VAR, "1")
.env(
"Codex_Guardian_Decisions_Api_Key",
"synthetic-inherited-key",
)
.env("Node_Repl_Auth_Token", "inherited-token")
.env("OpenAI_Federation_Rule_Id", "inherited-rule")
.env(
"OpenAI_Workload_Identity_Context",
r#"{"instance_id":"box-one"}"#,
)
.env(
"Codex_Exec_Server_Noise_Auth_Token",
"inherited-noise-token",
)
.output()
.expect("run inherited-environment test process");
assert!(
output.status.success(),
"child failed\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
return;
}
let mut command = environment_command();
command
.env("NODE_REPL_AUTH_TOKEN", "configured-token")
.env("openai_identity_token_file", "/run/identity-token")
.env(
AKODE_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR,
"configured-noise-token",
)
.env("AKODE_GUARDIAN_DECISIONS_API_KEY", "synthetic-override-key")
.env("SAFE", "value");
scrub_non_inheritable_env_vars(&mut command);
let output = command.output().expect("read child environment");
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
let restricted_names = stdout
.lines()
.filter_map(|line| line.split_once('=').map(|(name, _)| name))
.filter(|name| is_non_inheritable_env_var(name))
.collect::<Vec<_>>();
assert_eq!(restricted_names, Vec::<&str>::new());
}
#[cfg(windows)]
fn environment_command() -> Command {
let mut command = Command::new("cmd.exe");
command.args(["/D", "/C", "set"]);
command
}
#[cfg(not(windows))]
fn environment_command() -> Command {
Command::new("env")
}

View File

@@ -0,0 +1,121 @@
use std::fmt::Display;
use schemars::JsonSchema;
use schemars::r#gen::SchemaGenerator;
use schemars::schema::Schema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
use uuid::Uuid;
#[derive(Debug, Clone, Copy, PartialEq, Eq, TS, Hash)]
#[ts(type = "string")]
/// Identifier for a Codex thread.
///
/// Codex-generated thread IDs are UUIDv7, and some use cases rely on that.
pub struct ThreadId {
pub(crate) uuid: Uuid,
}
/// Identifier encoded in a rollout filename.
///
/// Rollout IDs use the same UUID representation as thread IDs. Ordinary rollout files use the
/// thread ID as their rollout ID; \`thread/revert\` creates a new rollout file with a distinct
/// rollout ID while preserving the thread ID.
pub type RolloutId = ThreadId;
impl ThreadId {
pub fn new() -> Self {
Self {
uuid: Uuid::now_v7(),
}
}
/// Construct an identifier from a UUID's 128-bit representation.
pub fn from_u128(value: u128) -> Self {
Self {
uuid: Uuid::from_u128(value),
}
}
pub fn from_string(s: &str) -> Result<Self, uuid::Error> {
Ok(Self {
uuid: Uuid::parse_str(s)?,
})
}
}
impl TryFrom<&str> for ThreadId {
type Error = uuid::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::from_string(value)
}
}
impl TryFrom<String> for ThreadId {
type Error = uuid::Error;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_string(value.as_str())
}
}
impl From<ThreadId> for String {
fn from(value: ThreadId) -> Self {
value.to_string()
}
}
impl Default for ThreadId {
fn default() -> Self {
Self::new()
}
}
impl Display for ThreadId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.uuid, f)
}
}
impl Serialize for ThreadId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_str(&self.uuid)
}
}
impl<'de> Deserialize<'de> for ThreadId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
let uuid = Uuid::parse_str(&value).map_err(serde::de::Error::custom)?;
Ok(Self { uuid })
}
}
impl JsonSchema for ThreadId {
fn schema_name() -> String {
"ThreadId".to_string()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
<String>::json_schema(generator)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_thread_id_default_is_not_zeroes() {
let id = ThreadId::default();
assert_ne!(id.uuid, Uuid::nil());
}
}

View File

@@ -0,0 +1,94 @@
use serde::Deserialize;
use serde::Serialize;
use std::cmp::Ordering;
use std::fmt;
/// Namespace used for top-level function and custom tools.
pub const DEFAULT_FUNCTION_NAMESPACE: &str = "functions";
/// Identifies a callable tool, preserving the namespace split when the model
/// provides one.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct ToolName {
pub name: String,
pub namespace: Option<String>,
}
impl ToolName {
pub fn new(namespace: Option<String>, name: impl Into<String>) -> Self {
Self {
name: name.into(),
namespace,
}
}
pub fn plain(name: impl Into<String>) -> Self {
Self {
name: name.into(),
namespace: None,
}
}
pub fn namespaced(namespace: impl Into<String>, name: impl Into<String>) -> Self {
Self {
name: name.into(),
namespace: Some(namespace.into()),
}
}
pub fn with_default_namespace(mut self) -> Self {
if self.namespace.as_deref().is_none_or(str::is_empty) {
self.namespace = Some(DEFAULT_FUNCTION_NAMESPACE.to_string());
}
self
}
pub fn is_default_namespace(&self) -> bool {
matches!(
self.namespace.as_deref(),
None | Some("") | Some(DEFAULT_FUNCTION_NAMESPACE)
)
}
}
impl fmt::Display for ToolName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.namespace {
Some(_) if self.is_default_namespace() => f.write_str(&self.name),
Some(namespace) => write!(f, "{namespace}{}", self.name),
None => f.write_str(&self.name),
}
}
}
impl Ord for ToolName {
fn cmp(&self, other: &Self) -> Ordering {
let lhs = match &self.namespace {
Some(namespace) => (namespace.as_str(), Some(self.name.as_str())),
None => (self.name.as_str(), None),
};
let rhs = match &other.namespace {
Some(namespace) => (namespace.as_str(), Some(other.name.as_str())),
None => (other.name.as_str(), None),
};
lhs.cmp(&rhs)
}
}
impl PartialOrd for ToolName {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl From<String> for ToolName {
fn from(name: String) -> Self {
Self::plain(name)
}
}
impl From<&str> for ToolName {
fn from(name: &str) -> Self {
Self::plain(name)
}
}

View File

@@ -0,0 +1,330 @@
//! Turn-input request and result types shared by Core's submission APIs.
use crate::AgentPath;
use crate::models::ResponseItem;
use crate::protocol::AdditionalContextEntry;
use crate::protocol::InterAgentCommunication;
use crate::protocol::NonSteerableTurnKind;
use crate::protocol::ThreadSettingsOverrides;
use crate::protocol::W3cTraceContext;
use crate::user_input::UserInput;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use std::collections::BTreeMap;
use std::collections::HashMap;
use ts_rs::TS;
/// Result of stopping an unfinished root turn so another worker can recover it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SuspendTurnOutcome {
Suspended { turn_id: String },
NotActive,
UnsupportedTask,
}
/// Input consumed by a regular turn.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TurnInput {
UserInput {
content: Vec<UserInput>,
client_id: Option<String>,
},
ResponseItem(ResponseItem),
AnnotatedResponseItem(AnnotatedResponseItem),
InterAgentCommunication(InterAgentCommunication),
}
/// A Responses API item with caller-supplied, harness-only annotations.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AnnotatedResponseItem {
pub item: ResponseItem,
#[serde(default)]
pub annotations: ResponseItemAnnotations,
}
/// Public annotations accepted by Core; internal history metadata stays private.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResponseItemAnnotations {
/// Request compaction retention for a function-call output.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub retain: bool,
}
/// One turn input and the context that follows it through submission.
///
/// Callers choose start-or-steer, idle-start, or steer-only behavior through
/// the corresponding `CodexThread` method.
#[derive(Clone, Debug)]
pub struct TurnInputRequest {
pub input: TurnInput,
/// Optional host-assigned UUID for the Responses message created from [`TurnInput::UserInput`].
/// Ignored for all other inputs, including raw user-role Responses items.
pub user_item_uuid: Option<uuid::Uuid>,
/// Host-supplied, extension-keyed data for this user input's completion.
/// Travels with the individual input and is never included in model input.
pub user_input_extension_data: BTreeMap<String, Value>,
pub thread_settings: ThreadSettingsOverrides,
pub start: TurnStartOptions,
pub additional_context: BTreeMap<String, AdditionalContextEntry>,
pub responsesapi_client_metadata: ResponsesApiClientMetadataUpdate,
pub trace: Option<W3cTraceContext>,
}
/// An optional replacement followed by a patch to the turn's client metadata.
#[derive(Clone, Debug, Default)]
pub struct ResponsesApiClientMetadataUpdate {
/// Replaces the existing map, including when empty.
pub replacement: Option<HashMap<String, String>>,
/// Adds or overwrites keys without removing other entries.
pub patch: Option<HashMap<String, String>>,
}
/// Attribution retained across recovery, sleep, and model-context compaction.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, TS)]
pub struct TurnAttribution {
pub turn_id: String,
pub turn_trigger: Option<String>,
pub parent_turn_id: Option<String>,
pub initiating_agent_path: Option<AgentPath>,
pub root_turn_id: Option<String>,
}
impl TurnAttribution {
/// Restores provenance without changing the thread's execution settings.
pub fn start_options(&self) -> TurnStartOptions {
TurnStartOptions {
turn_trigger: self.turn_trigger.clone(),
parent_turn_id: self.parent_turn_id.clone(),
initiating_agent_path: self.initiating_agent_path.clone(),
root_turn_id: self.root_turn_id.clone(),
..Default::default()
}
}
}
/// Request to resume sampling for an interrupted regular turn.
///
/// Sampling restarts under `turn_id`, which must be the ID already recorded
/// for that turn.
#[derive(Clone, Debug)]
pub struct RecoverTurnRequest {
pub turn_id: String,
pub thread_settings: ThreadSettingsOverrides,
pub trace: Option<W3cTraceContext>,
/// Cache lifetime to reapply when resuming this turn.
pub prompt_cache_ttl: Option<PromptCacheTtl>,
}
impl TurnInputRequest {
/// Creates turn input that can be passed to one of the submission methods.
pub fn new(input: TurnInput) -> Self {
Self {
input,
user_item_uuid: None,
user_input_extension_data: BTreeMap::new(),
thread_settings: ThreadSettingsOverrides::default(),
start: TurnStartOptions::default(),
additional_context: BTreeMap::new(),
responsesapi_client_metadata: ResponsesApiClientMetadataUpdate::default(),
trace: None,
}
}
/// Creates ordinary user input without a client-provided message id.
pub fn user_input(content: Vec<UserInput>) -> Self {
Self::new(TurnInput::UserInput {
content,
client_id: None,
})
}
/// Persistent thread settings applied when Core accepts this input.
///
/// Settings are applied for both `Started` and `Steered`. A steered input
/// cannot change its already-active turn context, so those settings apply
/// to subsequent turns. `NotSubmitted` leaves them unapplied.
pub fn with_thread_settings(mut self, thread_settings: ThreadSettingsOverrides) -> Self {
self.thread_settings = thread_settings;
self
}
/// Options for new turns, also consulted for input provenance and active-turn
/// compatibility when steering.
pub fn on_start(mut self, start: TurnStartOptions) -> Self {
self.start = start;
self
}
/// Context merged whether this request starts or steers.
pub fn with_additional_context(
mut self,
additional_context: BTreeMap<String, AdditionalContextEntry>,
) -> Self {
self.additional_context = additional_context;
self
}
/// Replaces Responses client metadata whether this request starts or steers.
pub fn with_responses_metadata(
mut self,
responsesapi_client_metadata: Option<HashMap<String, String>>,
) -> Self {
self.responsesapi_client_metadata.replacement = responsesapi_client_metadata;
self
}
/// Adds or overwrites Responses client metadata entries after any replacement.
pub fn with_responses_metadata_patch(
mut self,
responsesapi_client_metadata_patch: Option<HashMap<String, String>>,
) -> Self {
self.responsesapi_client_metadata.patch = responsesapi_client_metadata_patch;
self
}
/// Trace context used when this request crosses the session loop.
pub fn with_trace(mut self, trace: Option<W3cTraceContext>) -> Self {
self.trace = trace;
self
}
}
/// How Core should route submitted turn input.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TurnInputMode {
/// Start a regular turn when idle, otherwise steer the active regular turn.
StartOrSteer,
/// Start only when the thread is idle.
StartIfIdle,
/// Start an internal continuation when idle.
/// Reject if another task has started since the expected previous turn.
ContinueIfIdle { expected_previous_turn_id: String },
/// Steer only if this exact turn is active.
Steer { expected_turn_id: String },
}
/// Minimum lifetime requested for new prompt cache entries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum PromptCacheTtl {
#[serde(rename = "30m")]
ThirtyMinutes,
#[serde(rename = "12h")]
TwelveHours,
}
/// Options for the new-turn branch of a submission.
///
/// Core only records these options when input starts a turn. When input steers,
/// `final_output_json_schema` is a compatibility requirement: Core only
/// accepts the steer if the active turn already uses the same schema. For
/// child input, Core also compares root lineage to detect ambiguity.
#[derive(Clone, Debug, Default)]
pub struct TurnStartOptions {
/// Source classification for this request. Recorded on new turns and captured
/// as input provenance when steering, without changing the active turn's trigger.
pub turn_trigger: Option<String>,
/// Structured-output schema for a new turn. When steering, Core rejects
/// the input if the active turn uses a different schema.
pub final_output_json_schema: Option<Value>,
/// Direct-only tool namespaces for a new turn. Omission inherits the thread's
/// configuration. An empty list clears it for this turn. Ignored when steering.
pub direct_only_tool_namespaces: Option<Vec<String>>,
/// Service tier for a new turn, without changing the thread's preference.
pub service_tier: Option<String>,
/// Lifetime requested for new Responses prompt cache entries during this turn.
pub prompt_cache_ttl: Option<PromptCacheTtl>,
/// Parent turn lineage recorded if this request starts a new turn.
pub parent_turn_id: Option<String>,
/// Agent owning the parent turn, retained when recovering delegated work.
pub initiating_agent_path: Option<AgentPath>,
/// Causal root turn lineage recorded if this request starts a new turn.
pub root_turn_id: Option<String>,
}
/// What Core did with input submitted through `start_or_steer_turn`.
///
/// Started and Steered only mean Core accepted the input for turn processing. They
/// do not wait for user-prompt hooks, updating the in-memory model context,
/// rollout persistence, or sampling. The returned root is the accepted turn's
/// resolved causal root, including when steering preserves an existing turn.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TurnInputSubmission {
/// Core accepted an agent follow-up through native message delivery. The
/// receiving turn may still be running or finishing, so no turn ID is implied.
Accepted,
/// Core started a turn. Persistent thread settings and start options were applied.
Started {
turn_id: String,
root_turn_id: String,
},
/// Core steered an active turn. Persistent thread settings were applied for
/// subsequent turns. No new turn was created, so lineage metadata was not
/// recorded. If the request included `final_output_json_schema`, the active
/// turn already used the same schema.
Steered {
turn_id: String,
root_turn_id: String,
},
/// Core rejected the input without applying settings or start options.
NotSubmitted { reason: NotSubmittedReason },
}
/// What Core did with input submitted only for an idle turn start.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum StartIfIdleSubmission {
/// Core started a turn. Persistent thread settings and start options were applied.
Started {
turn_id: String,
root_turn_id: String,
},
/// Core rejected the input without applying settings or start options.
NotSubmitted { reason: NotSubmittedReason },
}
/// What Core did with input submitted only for steering.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SteerSubmission {
/// Core steered an active turn. Persistent thread settings were applied for
/// subsequent turns.
Steered { turn_id: String },
/// Core rejected the input without applying settings.
NotSubmitted { reason: NotSubmittedReason },
}
/// Why Core did not accept submitted turn input for turn processing.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum NotSubmittedReason {
/// New work superseded the expected previous turn of an internal continuation.
Superseded,
/// The host is draining and no longer permits new regular turns.
ServerDraining,
/// `start_turn_if_idle` found an active turn.
NotIdle,
/// `start_turn_if_idle` yielded to higher-priority trigger-turn mailbox input.
PendingTriggerTurn,
/// `start_turn_if_idle` received automatic non-user input for a turn that
/// would run in Plan mode.
PlanMode,
/// `steer_turn` found no active turn.
NoActiveTurn,
/// `steer_turn` found a different active turn.
ExpectedTurnMismatch { expected: String, actual: String },
/// `start_or_steer_turn` or `steer_turn` found an active turn that does not accept steering.
ActiveTurnNotSteerable { turn_kind: NonSteerableTurnKind },
/// `start_or_steer_turn` or `steer_turn` required a final output schema
/// that differs from the active turn's schema.
ActiveTurnOutputSchemaMismatch,
/// `start_or_steer_turn` or `steer_turn` reached a steering path with empty user input.
EmptyInput,
}

View File

@@ -0,0 +1,131 @@
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use ts_rs::TS;
use crate::models::AudioReference;
use crate::models::ImageDetail;
use crate::models::ImageReference;
/// Conservative cap so one user message cannot monopolize a large context window.
pub const MAX_USER_INPUT_TEXT_CHARS: usize = 1 << 20;
/// User input
#[non_exhaustive]
#[derive(derive_more::Debug, Clone, Deserialize, Serialize, PartialEq, TS, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum UserInput {
Text {
#[debug("{:?} <{} bytes>", &text[..text.floor_char_boundary(/*index*/ 512)], text.len())]
text: String,
/// UI-defined spans within `text` that should be treated as special elements.
/// These are byte ranges into the UTF-8 `text` buffer and are used to render
/// or persist rich input markers (e.g., image placeholders) across history
/// and resume without mutating the literal text.
#[serde(default)]
text_elements: Vec<TextElement>,
},
/// Image reference forwarded to the Responses API.
Image {
#[serde(flatten)]
image: ImageReference,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
detail: Option<ImageDetail>,
},
/// Local image path provided by the user. This will be converted to an
/// `Image` variant (base64 data URL) during request serialization.
LocalImage {
path: std::path::PathBuf,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
detail: Option<ImageDetail>,
},
/// Audio reference forwarded to the Responses API.
Audio {
#[serde(flatten)]
audio: AudioReference,
},
/// Local audio path converted to an `Audio` data URI during request serialization.
LocalAudio { path: std::path::PathBuf },
/// Skill selected by the user (name + path to SKILL.md).
Skill {
name: String,
path: std::path::PathBuf,
},
/// Explicit structured mention selected by the user.
///
/// `path` identifies the exact mention target, for example
/// `app://<connector-id>` or `plugin://<plugin-name>@<marketplace-name>`.
Mention { name: String, path: String },
}
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, TS, JsonSchema)]
pub struct TextElement {
/// Byte range in the parent `text` buffer that this element occupies.
pub byte_range: ByteRange,
/// Optional human-readable placeholder for the element, displayed in the UI.
placeholder: Option<String>,
}
impl TextElement {
pub fn new(byte_range: ByteRange, placeholder: Option<String>) -> Self {
Self {
byte_range,
placeholder,
}
}
/// Returns a copy of this element with a remapped byte range.
///
/// The placeholder is preserved as-is; callers must ensure the new range
/// still refers to the same logical element (and same placeholder)
/// within the new text.
pub fn map_range<F>(&self, map: F) -> Self
where
F: FnOnce(ByteRange) -> ByteRange,
{
Self {
byte_range: map(self.byte_range),
placeholder: self.placeholder.clone(),
}
}
pub fn set_placeholder(&mut self, placeholder: Option<String>) {
self.placeholder = placeholder;
}
/// Returns the stored placeholder without falling back to the text buffer.
///
/// This must only be used inside `From<TextElement>` implementations on equivalent
/// protocol types where the source text is unavailable. Prefer `placeholder(text)`
/// everywhere else.
#[doc(hidden)]
pub fn _placeholder_for_conversion_only(&self) -> Option<&str> {
self.placeholder.as_deref()
}
pub fn placeholder<'a>(&'a self, text: &'a str) -> Option<&'a str> {
self.placeholder
.as_deref()
.or_else(|| text.get(self.byte_range.start..self.byte_range.end))
}
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, TS, JsonSchema)]
pub struct ByteRange {
/// Start byte offset (inclusive) within the UTF-8 text buffer.
pub start: usize,
/// End byte offset (exclusive) within the UTF-8 text buffer.
pub end: usize,
}
impl From<std::ops::Range<usize>> for ByteRange {
fn from(range: std::ops::Range<usize>) -> Self {
Self {
start: range.start,
end: range.end,
}
}
}