Base: codex-main originale (prima del fork aKode)
This commit is contained in:
6
codex-rs/exec-server-protocol/BUILD.bazel
Normal file
6
codex-rs/exec-server-protocol/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "exec-server-protocol",
|
||||
crate_name = "codex_exec_server_protocol",
|
||||
)
|
||||
31
codex-rs/exec-server-protocol/Cargo.toml
Normal file
31
codex-rs/exec-server-protocol/Cargo.toml
Normal file
@@ -0,0 +1,31 @@
|
||||
[package]
|
||||
name = "codex-exec-server-protocol"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
name = "codex_exec_server_protocol"
|
||||
path = "src/lib.rs"
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64 = { workspace = true }
|
||||
codex-file-system = { workspace = true }
|
||||
codex-install-context = { workspace = true }
|
||||
codex-network-proxy = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-shell-command = { workspace = true }
|
||||
codex-skills = { workspace = true }
|
||||
codex-utils-path-uri = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true, features = ["arbitrary_precision", "raw_value"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
codex-mxc-sandbox = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
130
codex-rs/exec-server-protocol/src/capabilities.rs
Normal file
130
codex-rs/exec-server-protocol/src/capabilities.rs
Normal file
@@ -0,0 +1,130 @@
|
||||
//! Executor capability inventory; callers apply identity and enablement.
|
||||
|
||||
use codex_file_system::FileSystemSandboxContext;
|
||||
use codex_skills::SkillDependencies;
|
||||
use codex_skills::SkillPolicy;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::DiscoveredPluginFiles;
|
||||
|
||||
pub const CAPABILITIES_DISCOVER_V2_METHOD: &str = "capabilities/discoverV2";
|
||||
|
||||
/// Caller-bound discovery result shared by capability consumers within a model step.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
pub environment_id: String,
|
||||
pub result: Result<Arc<DiscoverV2CapabilitiesResponse>, String>,
|
||||
}
|
||||
|
||||
impl ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
/// Compares discovery identity, not inventory contents; repeated errors compare by message.
|
||||
pub fn same_discovery(&self, other: &Self) -> bool {
|
||||
self.environment_id == other.environment_id
|
||||
&& match (&self.result, &other.result) {
|
||||
(Ok(previous), Ok(current)) => Arc::ptr_eq(previous, current),
|
||||
(Err(previous), Err(current)) => previous == current,
|
||||
(Ok(_), Err(_)) | (Err(_), Ok(_)) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Discover installed capabilities for a thread, without client-supplied installation paths.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DiscoverV2CapabilitiesRequest {
|
||||
pub cwd: PathUri,
|
||||
#[serde(default)]
|
||||
pub sandbox: Option<FileSystemSandboxContext>,
|
||||
}
|
||||
|
||||
/// Discovered metadata before caller policy is applied.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DiscoverV2CapabilitiesResponse {
|
||||
pub plugins: Vec<ExecutorPlugin>,
|
||||
/// Skills outside installed packages.
|
||||
pub skills: Vec<ExecutorSkill>,
|
||||
#[serde(default)]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExecutorPlugin {
|
||||
/// Environment-local ID: `<name>@<marketplace>`.
|
||||
pub id: String,
|
||||
/// Manifest display name, falling back to its name or the installation directory.
|
||||
pub display_name: String,
|
||||
pub remote_plugin_id: Option<String>,
|
||||
pub version: String,
|
||||
pub root: PathUri,
|
||||
pub files: DiscoveredPluginFiles,
|
||||
pub skills: Vec<ExecutorSkill>,
|
||||
}
|
||||
|
||||
/// Executor-owned search root for a standalone skill.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SkillDiscoveryRoot {
|
||||
pub id: String,
|
||||
pub path: PathUri,
|
||||
}
|
||||
|
||||
/// Skill metadata, excluding instructions and resources.
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExecutorSkill {
|
||||
/// Final skill name, qualified by the nearest enclosing plugin namespace when present.
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub short_description: Option<String>,
|
||||
/// Path to SKILL.md, not its containing directory.
|
||||
pub path: PathUri,
|
||||
/// Absent for plugin skills and responses from older executors.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub discovery_root: Option<SkillDiscoveryRoot>,
|
||||
pub dependencies: Option<SkillDependencies>,
|
||||
pub policy: Option<SkillPolicy>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for ExecutorPlugin {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("ExecutorPlugin")
|
||||
.field("id", &self.id)
|
||||
.field("remote_plugin_id", &self.remote_plugin_id)
|
||||
.field("version", &self.version)
|
||||
.field("root", &self.root)
|
||||
.field("manifest_path", &self.files.manifest.path)
|
||||
.field(
|
||||
"mcp_config_path",
|
||||
&self.files.mcp_config.as_ref().map(|file| &file.path),
|
||||
)
|
||||
.field(
|
||||
"apps_config_path",
|
||||
&self.files.apps_config.as_ref().map(|file| &file.path),
|
||||
)
|
||||
.field("skills", &self.skills)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ExecutorSkill {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
// Omit potentially sensitive descriptions and file contents.
|
||||
formatter
|
||||
.debug_struct("ExecutorSkill")
|
||||
.field("name", &self.name)
|
||||
.field("path", &self.path)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "capabilities_tests.rs"]
|
||||
mod tests;
|
||||
92
codex-rs/exec-server-protocol/src/capabilities_tests.rs
Normal file
92
codex-rs/exec-server-protocol/src/capabilities_tests.rs
Normal file
@@ -0,0 +1,92 @@
|
||||
//! V2 discovery wire contracts.
|
||||
|
||||
use super::*;
|
||||
use crate::CapabilityTextFile;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn discovery_contract_round_trips_json() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let request = DiscoverV2CapabilitiesRequest {
|
||||
cwd: PathUri::parse("file:///workspace")?,
|
||||
sandbox: None,
|
||||
};
|
||||
let wire = serde_json::to_value(&request)?;
|
||||
assert_eq!(
|
||||
serde_json::from_value::<DiscoverV2CapabilitiesRequest>(wire)?,
|
||||
request
|
||||
);
|
||||
let text_file = CapabilityTextFile {
|
||||
path: PathUri::parse("file:///plugin/config.json")?,
|
||||
contents: "{}".to_string(),
|
||||
};
|
||||
let skill = ExecutorSkill {
|
||||
name: "nested:example".to_string(),
|
||||
description: "Example skill".to_string(),
|
||||
short_description: None,
|
||||
path: PathUri::parse("file:///plugin/skills/example/SKILL.md")?,
|
||||
discovery_root: None,
|
||||
dependencies: Some(codex_skills::SkillDependencies {
|
||||
tools: vec![codex_skills::SkillToolDependency {
|
||||
r#type: "mcp".into(),
|
||||
value: "deploy".into(),
|
||||
description: None,
|
||||
transport: Some("stdio".into()),
|
||||
command: Some("deploy-mcp".into()),
|
||||
url: None,
|
||||
oauth_callback_port: Some(3118),
|
||||
}],
|
||||
}),
|
||||
policy: Some(codex_skills::SkillPolicy {
|
||||
allow_implicit_invocation: Some(false),
|
||||
products: vec![],
|
||||
}),
|
||||
};
|
||||
let mut standalone = skill.clone();
|
||||
standalone.path = PathUri::parse("file:///home/skills/nested/example/SKILL.md")?;
|
||||
standalone.discovery_root = Some(SkillDiscoveryRoot {
|
||||
id: "codex-home-skills".to_string(),
|
||||
path: PathUri::parse("file:///home/skills")?,
|
||||
});
|
||||
let response = DiscoverV2CapabilitiesResponse {
|
||||
plugins: vec![ExecutorPlugin {
|
||||
id: "example@company".to_string(),
|
||||
display_name: "Example".to_string(),
|
||||
remote_plugin_id: None,
|
||||
version: "local".to_string(),
|
||||
root: PathUri::parse("file:///plugin")?,
|
||||
files: DiscoveredPluginFiles {
|
||||
manifest: text_file.clone(),
|
||||
mcp_config: Some(text_file.clone()),
|
||||
apps_config: Some(text_file),
|
||||
},
|
||||
skills: vec![skill],
|
||||
}],
|
||||
skills: vec![standalone],
|
||||
warnings: Vec::new(),
|
||||
};
|
||||
let mut wire = serde_json::to_value(&response)?;
|
||||
assert_eq!(
|
||||
wire["skills"][0]["discoveryRoot"],
|
||||
serde_json::json!({
|
||||
"id": "codex-home-skills",
|
||||
"path": "file:///home/skills",
|
||||
})
|
||||
);
|
||||
assert_eq!(wire["plugins"][0]["skills"][0].get("discoveryRoot"), None);
|
||||
assert_eq!(
|
||||
serde_json::from_value::<DiscoverV2CapabilitiesResponse>(wire.clone())?,
|
||||
response
|
||||
);
|
||||
// Older executors omit the root metadata.
|
||||
wire["skills"][0]
|
||||
.as_object_mut()
|
||||
.expect("skill object")
|
||||
.remove("discoveryRoot");
|
||||
let mut legacy_response = response;
|
||||
legacy_response.skills[0].discovery_root = None;
|
||||
assert_eq!(
|
||||
serde_json::from_value::<DiscoverV2CapabilitiesResponse>(wire)?,
|
||||
legacy_response
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
50
codex-rs/exec-server-protocol/src/environment_config.rs
Normal file
50
codex-rs/exec-server-protocol/src/environment_config.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
pub const ENVIRONMENT_CONFIG_READ_METHOD: &str = "environmentConfig/read";
|
||||
|
||||
/// Selects executor-local config and requirements fields by literal TOML key path.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EnvironmentConfigReadParams {
|
||||
pub cwd: PathUri,
|
||||
pub config_paths: Vec<Vec<String>>,
|
||||
pub requirements_paths: Vec<Vec<String>>,
|
||||
}
|
||||
|
||||
/// Executor-local config and requirements layers selected for one environment.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EnvironmentConfigReadResponse {
|
||||
/// Executor user home used to expand `~` in path-bearing values.
|
||||
pub user_home_dir: Option<PathUri>,
|
||||
/// Executor Codex home used as the base directory for cloud-provided layers.
|
||||
pub codex_home_dir: PathUri,
|
||||
/// Executor hostname used to select matching remote sandbox requirements.
|
||||
pub hostname: Option<String>,
|
||||
pub config: EnvironmentConfigLayerStack,
|
||||
pub requirements: EnvironmentConfigLayerStack,
|
||||
}
|
||||
|
||||
/// One ordered set of selected TOML layers.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EnvironmentConfigLayerStack {
|
||||
/// Layers ordered from lowest to highest precedence.
|
||||
pub layers: Vec<EnvironmentConfigLayer>,
|
||||
/// Position at which cloud-provided layers should be inserted.
|
||||
pub cloud_insertion_index: usize,
|
||||
}
|
||||
|
||||
/// One selected executor-local TOML layer.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EnvironmentConfigLayer {
|
||||
/// Opaque provenance for diagnostics. Callers must not derive behavior from it.
|
||||
pub source: String,
|
||||
/// Directory used to interpret relative paths in this layer.
|
||||
pub base_dir: PathUri,
|
||||
/// Selected raw TOML. Path-bearing values have not been normalized.
|
||||
pub toml: String,
|
||||
}
|
||||
13
codex-rs/exec-server-protocol/src/lib.rs
Normal file
13
codex-rs/exec-server-protocol/src/lib.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
mod capabilities;
|
||||
mod environment_config;
|
||||
mod network_policy;
|
||||
mod process_id;
|
||||
mod protocol;
|
||||
pub mod rpc;
|
||||
|
||||
pub use capabilities::*;
|
||||
pub use environment_config::*;
|
||||
pub use network_policy::*;
|
||||
pub use process_id::ProcessId;
|
||||
pub use protocol::*;
|
||||
pub use rpc::*;
|
||||
73
codex-rs/exec-server-protocol/src/network_policy.rs
Normal file
73
codex-rs/exec-server-protocol/src/network_policy.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::ProcessId;
|
||||
|
||||
pub const NETWORK_POLICY_REQUEST_METHOD: &str = "network/policyRequest";
|
||||
pub const NETWORK_POLICY_DECISION_METHOD: &str = "network/policyDecision";
|
||||
pub const MAX_NETWORK_POLICY_HOST_BYTES: usize = 253;
|
||||
pub const MAX_NETWORK_POLICY_PROCESS_ID_BYTES: usize = 256;
|
||||
pub const MAX_NETWORK_POLICY_REASON_BYTES: usize = 1024;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NetworkPolicyRequestParams {
|
||||
pub process_id: ProcessId,
|
||||
pub request: ExecServerNetworkPolicyRequest,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExecServerNetworkPolicyRequest {
|
||||
pub protocol: ExecServerNetworkProtocol,
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
/// Reports an executor-local network policy decision to its authenticated controller.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NetworkPolicyDecisionNotification {
|
||||
pub process_id: ProcessId,
|
||||
pub timestamp: String,
|
||||
pub scope: String,
|
||||
pub decision: String,
|
||||
pub source: String,
|
||||
pub reason: String,
|
||||
pub protocol: ExecServerNetworkProtocol,
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub method: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub client: Option<String>,
|
||||
#[serde(default)]
|
||||
pub policy_override: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ExecServerNetworkProtocol {
|
||||
Http,
|
||||
HttpsConnect,
|
||||
Socks5Tcp,
|
||||
Socks5Udp,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NetworkPolicyRequestResponse {
|
||||
pub decision: ExecServerNetworkPolicyDecision,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ExecServerNetworkPolicyDecision {
|
||||
Allow,
|
||||
Deny { reason: String },
|
||||
Ask { reason: String },
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "network_policy_tests.rs"]
|
||||
mod tests;
|
||||
118
codex-rs/exec-server-protocol/src/network_policy_tests.rs
Normal file
118
codex-rs/exec-server-protocol/src/network_policy_tests.rs
Normal file
@@ -0,0 +1,118 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::ExecServerNetworkPolicyDecision;
|
||||
use super::ExecServerNetworkPolicyRequest;
|
||||
use super::ExecServerNetworkProtocol;
|
||||
use super::NetworkPolicyDecisionNotification;
|
||||
use super::NetworkPolicyRequestParams;
|
||||
use super::NetworkPolicyRequestResponse;
|
||||
use crate::ProcessId;
|
||||
|
||||
#[test]
|
||||
fn network_policy_request_uses_stable_json_shapes() {
|
||||
let request = NetworkPolicyRequestParams {
|
||||
process_id: ProcessId::from("process-1"),
|
||||
request: ExecServerNetworkPolicyRequest {
|
||||
protocol: ExecServerNetworkProtocol::HttpsConnect,
|
||||
host: "example.com".to_string(),
|
||||
port: 443,
|
||||
},
|
||||
};
|
||||
let request_json = serde_json::json!({
|
||||
"processId": "process-1",
|
||||
"request": {
|
||||
"protocol": "https_connect",
|
||||
"host": "example.com",
|
||||
"port": 443,
|
||||
},
|
||||
});
|
||||
assert_eq!(
|
||||
serde_json::to_value(&request).expect("serialize policy request"),
|
||||
request_json
|
||||
);
|
||||
let decoded_request: NetworkPolicyRequestParams =
|
||||
serde_json::from_value(request_json.clone()).expect("deserialize policy request");
|
||||
assert_eq!(
|
||||
serde_json::to_value(decoded_request).expect("reserialize policy request"),
|
||||
request_json
|
||||
);
|
||||
|
||||
let decision = NetworkPolicyRequestResponse {
|
||||
decision: ExecServerNetworkPolicyDecision::Allow,
|
||||
};
|
||||
let decision_json = serde_json::json!({
|
||||
"decision": {"type": "allow"},
|
||||
});
|
||||
assert_eq!(
|
||||
serde_json::to_value(&decision).expect("serialize policy decision"),
|
||||
decision_json
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_value::<NetworkPolicyRequestResponse>(decision_json)
|
||||
.expect("deserialize policy decision"),
|
||||
decision
|
||||
);
|
||||
|
||||
for (decision, decision_json) in [
|
||||
(
|
||||
ExecServerNetworkPolicyDecision::Deny {
|
||||
reason: "not_allowed".to_string(),
|
||||
},
|
||||
serde_json::json!({"type": "deny", "reason": "not_allowed"}),
|
||||
),
|
||||
(
|
||||
ExecServerNetworkPolicyDecision::Ask {
|
||||
reason: "not_allowed".to_string(),
|
||||
},
|
||||
serde_json::json!({"type": "ask", "reason": "not_allowed"}),
|
||||
),
|
||||
] {
|
||||
let response = NetworkPolicyRequestResponse { decision };
|
||||
assert_eq!(
|
||||
serde_json::to_value(&response).expect("serialize policy decision"),
|
||||
serde_json::json!({"decision": decision_json})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_policy_decision_notification_uses_stable_json_shape() {
|
||||
let notification = NetworkPolicyDecisionNotification {
|
||||
process_id: ProcessId::from("process-1"),
|
||||
timestamp: "2026-08-11T12:34:56.789Z".to_string(),
|
||||
scope: "domain".to_string(),
|
||||
decision: "deny".to_string(),
|
||||
source: "baseline_policy".to_string(),
|
||||
reason: "not_allowed".to_string(),
|
||||
protocol: ExecServerNetworkProtocol::HttpsConnect,
|
||||
host: "example.com".to_string(),
|
||||
port: 443,
|
||||
method: Some("CONNECT".to_string()),
|
||||
client: Some("127.0.0.1".to_string()),
|
||||
policy_override: false,
|
||||
};
|
||||
let expected = serde_json::json!({
|
||||
"processId": "process-1",
|
||||
"timestamp": "2026-08-11T12:34:56.789Z",
|
||||
"scope": "domain",
|
||||
"decision": "deny",
|
||||
"source": "baseline_policy",
|
||||
"reason": "not_allowed",
|
||||
"protocol": "https_connect",
|
||||
"host": "example.com",
|
||||
"port": 443,
|
||||
"method": "CONNECT",
|
||||
"client": "127.0.0.1",
|
||||
"policyOverride": false,
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
serde_json::to_value(¬ification).expect("serialize policy decision notification"),
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_value::<NetworkPolicyDecisionNotification>(expected)
|
||||
.expect("deserialize policy decision notification"),
|
||||
notification
|
||||
);
|
||||
}
|
||||
74
codex-rs/exec-server-protocol/src/process_id.rs
Normal file
74
codex-rs/exec-server-protocol/src/process_id.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
use std::borrow::Borrow;
|
||||
use std::fmt;
|
||||
use std::ops::Deref;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct ProcessId(String);
|
||||
|
||||
impl ProcessId {
|
||||
pub fn new(value: impl Into<String>) -> Self {
|
||||
Self(value.into())
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn into_inner(self) -> String {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for ProcessId {
|
||||
type Target = str;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl Borrow<str> for ProcessId {
|
||||
fn borrow(&self) -> &str {
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<str> for ProcessId {
|
||||
fn as_ref(&self) -> &str {
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ProcessId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for ProcessId {
|
||||
fn from(value: String) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for ProcessId {
|
||||
fn from(value: &str) -> Self {
|
||||
Self(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&String> for ProcessId {
|
||||
fn from(value: &String) -> Self {
|
||||
Self(value.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ProcessId> for String {
|
||||
fn from(value: ProcessId) -> Self {
|
||||
value.0
|
||||
}
|
||||
}
|
||||
2179
codex-rs/exec-server-protocol/src/protocol.rs
Normal file
2179
codex-rs/exec-server-protocol/src/protocol.rs
Normal file
File diff suppressed because it is too large
Load Diff
278
codex-rs/exec-server-protocol/src/rpc.rs
Normal file
278
codex-rs/exec-server-protocol/src/rpc.rs
Normal file
@@ -0,0 +1,278 @@
|
||||
//! JSON-RPC wire envelopes used by exec-server.
|
||||
//!
|
||||
//! Exec-server uses the Codex JSON-RPC dialect, which omits the
|
||||
//! `"jsonrpc": "2.0"` field on the wire.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use codex_protocol::protocol::W3cTraceContext;
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::Serialize;
|
||||
use serde::de;
|
||||
use serde::de::DeserializeSeed;
|
||||
use serde::de::MapAccess;
|
||||
use serde::de::SeqAccess;
|
||||
use serde::de::Visitor;
|
||||
use serde_json::Map;
|
||||
use serde_json::Number;
|
||||
use serde_json::Value;
|
||||
|
||||
pub const JSONRPC_VERSION: &str = "2.0";
|
||||
|
||||
// A maximum-size fs/walk response has at most 50,000 entries and needs roughly
|
||||
// 150,000 JSON values. Keep ample headroom for legitimate protocol messages
|
||||
// while preventing compact arrays from expanding into millions of heap values.
|
||||
const MAX_JSONRPC_VALUE_NODES: usize = 256 * 1024;
|
||||
|
||||
// With `arbitrary_precision` enabled, serde_json presents decimal, exponent,
|
||||
// and out-of-range integer values to visitors as a synthetic one-entry map.
|
||||
const SERDE_JSON_NUMBER_TOKEN: &str = "$serde_json::private::Number";
|
||||
const SERDE_JSON_RAW_VALUE_TOKEN: &str = "$serde_json::private::RawValue";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Deserialize, Serialize, Hash, Eq)]
|
||||
#[serde(untagged)]
|
||||
pub enum RequestId {
|
||||
String(String),
|
||||
Integer(i64),
|
||||
}
|
||||
|
||||
impl fmt::Display for RequestId {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::String(value) => f.write_str(value),
|
||||
Self::Integer(value) => write!(f, "{value}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type Result = serde_json::Value;
|
||||
|
||||
/// Any valid exec-server JSON-RPC object that can be decoded from or encoded onto the wire.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum JSONRPCMessage {
|
||||
Request(JSONRPCRequest),
|
||||
Notification(JSONRPCNotification),
|
||||
Response(JSONRPCResponse),
|
||||
Error(JSONRPCError),
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for JSONRPCMessage {
|
||||
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let mut remaining = MAX_JSONRPC_VALUE_NODES;
|
||||
let value = BoundedValueSeed {
|
||||
remaining: &mut remaining,
|
||||
}
|
||||
.deserialize(deserializer)?;
|
||||
let object = value
|
||||
.as_object()
|
||||
.ok_or_else(|| de::Error::custom("expected a JSON-RPC object"))?;
|
||||
|
||||
if object.contains_key("method") {
|
||||
if object.contains_key("id") {
|
||||
JSONRPCRequest::deserialize(value)
|
||||
.map(Self::Request)
|
||||
.map_err(de::Error::custom)
|
||||
} else {
|
||||
JSONRPCNotification::deserialize(value)
|
||||
.map(Self::Notification)
|
||||
.map_err(de::Error::custom)
|
||||
}
|
||||
} else if object.contains_key("result") {
|
||||
JSONRPCResponse::deserialize(value)
|
||||
.map(Self::Response)
|
||||
.map_err(de::Error::custom)
|
||||
} else {
|
||||
JSONRPCError::deserialize(value)
|
||||
.map(Self::Error)
|
||||
.map_err(de::Error::custom)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BoundedValueSeed<'a> {
|
||||
remaining: &'a mut usize,
|
||||
}
|
||||
|
||||
impl<'de> DeserializeSeed<'de> for BoundedValueSeed<'_> {
|
||||
type Value = Value;
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> std::result::Result<Self::Value, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let Some(remaining) = self.remaining.checked_sub(1) else {
|
||||
return Err(de::Error::custom(format!(
|
||||
"JSON-RPC message exceeds the limit of {MAX_JSONRPC_VALUE_NODES} JSON values"
|
||||
)));
|
||||
};
|
||||
*self.remaining = remaining;
|
||||
deserializer.deserialize_any(BoundedValueVisitor {
|
||||
remaining: self.remaining,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct BoundedValueVisitor<'a> {
|
||||
remaining: &'a mut usize,
|
||||
}
|
||||
|
||||
impl<'de> Visitor<'de> for BoundedValueVisitor<'_> {
|
||||
type Value = Value;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("a JSON value within the exec-server complexity limit")
|
||||
}
|
||||
|
||||
fn visit_bool<E>(self, value: bool) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Value::Bool(value))
|
||||
}
|
||||
|
||||
fn visit_i64<E>(self, value: i64) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Value::Number(value.into()))
|
||||
}
|
||||
|
||||
fn visit_u64<E>(self, value: u64) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Value::Number(value.into()))
|
||||
}
|
||||
|
||||
fn visit_f64<E>(self, value: f64) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Number::from_f64(value).map_or(Value::Null, Value::Number))
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Value::String(value.to_string()))
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, value: String) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Value::String(value))
|
||||
}
|
||||
|
||||
fn visit_none<E>(self) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn visit_some<D>(self, deserializer: D) -> std::result::Result<Self::Value, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
BoundedValueSeed {
|
||||
remaining: self.remaining,
|
||||
}
|
||||
.deserialize(deserializer)
|
||||
}
|
||||
|
||||
fn visit_unit<E>(self) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn visit_seq<A>(self, mut sequence: A) -> std::result::Result<Self::Value, A::Error>
|
||||
where
|
||||
A: SeqAccess<'de>,
|
||||
{
|
||||
let mut values = Vec::new();
|
||||
while let Some(value) = sequence.next_element_seed(BoundedValueSeed {
|
||||
remaining: &mut *self.remaining,
|
||||
})? {
|
||||
values.push(value);
|
||||
}
|
||||
Ok(Value::Array(values))
|
||||
}
|
||||
|
||||
fn visit_map<A>(self, mut object: A) -> std::result::Result<Self::Value, A::Error>
|
||||
where
|
||||
A: MapAccess<'de>,
|
||||
{
|
||||
let Some(first_key) = object.next_key::<String>()? else {
|
||||
return Ok(Value::Object(Map::new()));
|
||||
};
|
||||
|
||||
if first_key == SERDE_JSON_NUMBER_TOKEN {
|
||||
let encoded = object.next_value::<String>()?;
|
||||
let number = encoded.parse::<Number>().map_err(de::Error::custom)?;
|
||||
return Ok(Value::Number(number));
|
||||
}
|
||||
|
||||
if first_key == SERDE_JSON_RAW_VALUE_TOKEN {
|
||||
let encoded = object.next_value::<String>()?;
|
||||
let mut deserializer = serde_json::Deserializer::from_str(&encoded);
|
||||
// The raw wrapper already consumed one value from the budget. Reuse
|
||||
// that slot for the decoded root while charging all of its children.
|
||||
let value = (&mut deserializer)
|
||||
.deserialize_any(BoundedValueVisitor {
|
||||
remaining: &mut *self.remaining,
|
||||
})
|
||||
.map_err(de::Error::custom)?;
|
||||
deserializer.end().map_err(de::Error::custom)?;
|
||||
return Ok(value);
|
||||
}
|
||||
|
||||
let mut values = Map::new();
|
||||
let first_value = object.next_value_seed(BoundedValueSeed {
|
||||
remaining: &mut *self.remaining,
|
||||
})?;
|
||||
values.insert(first_key, first_value);
|
||||
|
||||
while let Some(key) = object.next_key::<String>()? {
|
||||
if values.contains_key(&key) {
|
||||
return Err(de::Error::custom(format!(
|
||||
"duplicate JSON object key `{key}`"
|
||||
)));
|
||||
}
|
||||
let value = object.next_value_seed(BoundedValueSeed {
|
||||
remaining: &mut *self.remaining,
|
||||
})?;
|
||||
values.insert(key, value);
|
||||
}
|
||||
Ok(Value::Object(values))
|
||||
}
|
||||
}
|
||||
|
||||
/// A request that expects a response.
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
pub struct JSONRPCRequest {
|
||||
pub id: RequestId,
|
||||
pub method: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub params: Option<serde_json::Value>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub trace: Option<W3cTraceContext>,
|
||||
}
|
||||
|
||||
/// A notification that does not expect a response.
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
pub struct JSONRPCNotification {
|
||||
pub method: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub params: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
/// A successful response to a request.
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
pub struct JSONRPCResponse {
|
||||
pub id: RequestId,
|
||||
pub result: Result,
|
||||
}
|
||||
|
||||
/// A response indicating that a request failed.
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
pub struct JSONRPCError {
|
||||
pub error: JSONRPCErrorError,
|
||||
pub id: RequestId,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
pub struct JSONRPCErrorError {
|
||||
pub code: i64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub data: Option<serde_json::Value>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rpc_tests.rs"]
|
||||
mod tests;
|
||||
146
codex-rs/exec-server-protocol/src/rpc_tests.rs
Normal file
146
codex-rs/exec-server-protocol/src/rpc_tests.rs
Normal file
@@ -0,0 +1,146 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
|
||||
use super::JSONRPCError;
|
||||
use super::JSONRPCErrorError;
|
||||
use super::JSONRPCMessage;
|
||||
use super::JSONRPCNotification;
|
||||
use super::JSONRPCRequest;
|
||||
use super::JSONRPCResponse;
|
||||
use super::MAX_JSONRPC_VALUE_NODES;
|
||||
use super::RequestId;
|
||||
use super::SERDE_JSON_RAW_VALUE_TOKEN;
|
||||
|
||||
#[test]
|
||||
fn round_trips_every_jsonrpc_message_variant() -> serde_json::Result<()> {
|
||||
let messages = [
|
||||
JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: RequestId::Integer(1),
|
||||
method: "request".to_string(),
|
||||
params: Some(json!({"items": [1, 2, 3]})),
|
||||
trace: None,
|
||||
}),
|
||||
JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "notification".to_string(),
|
||||
params: Some(json!({"enabled": true})),
|
||||
}),
|
||||
JSONRPCMessage::Response(JSONRPCResponse {
|
||||
id: RequestId::String("response".to_string()),
|
||||
result: json!({"value": "ok"}),
|
||||
}),
|
||||
JSONRPCMessage::Error(JSONRPCError {
|
||||
error: JSONRPCErrorError {
|
||||
code: -32603,
|
||||
data: Some(json!({"retryable": false})),
|
||||
message: "failed".to_string(),
|
||||
},
|
||||
id: RequestId::Integer(2),
|
||||
}),
|
||||
];
|
||||
|
||||
for expected in messages {
|
||||
let encoded = serde_json::to_string(&expected)?;
|
||||
let actual = serde_json::from_str::<JSONRPCMessage>(&encoded)?;
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_arbitrary_precision_numbers() -> serde_json::Result<()> {
|
||||
let encoded = r#"{"method":"numbers","params":{"decimal":1.5,"exponent":1e100,"largeInteger":18446744073709551616}}"#;
|
||||
let expected = serde_json::from_str::<Value>(encoded)?;
|
||||
|
||||
let message = serde_json::from_str::<JSONRPCMessage>(encoded)?;
|
||||
let actual = serde_json::to_value(message)?;
|
||||
|
||||
assert_eq!(actual, expected);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applies_value_limit_to_raw_value_wrapper() -> serde_json::Result<()> {
|
||||
let encoded =
|
||||
format!(r#"{{"method":"raw","params":{{"{SERDE_JSON_RAW_VALUE_TOKEN}":"[0,1]"}}}}"#);
|
||||
let actual = serde_json::from_str::<JSONRPCMessage>(&encoded)?;
|
||||
let expected = JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "raw".to_string(),
|
||||
params: Some(json!([0, 1])),
|
||||
});
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let mut wrapped = String::with_capacity(2 * MAX_JSONRPC_VALUE_NODES + 1);
|
||||
wrapped.push('[');
|
||||
for index in 0..MAX_JSONRPC_VALUE_NODES {
|
||||
if index != 0 {
|
||||
wrapped.push(',');
|
||||
}
|
||||
wrapped.push('0');
|
||||
}
|
||||
wrapped.push(']');
|
||||
let encoded =
|
||||
format!(r#"{{"method":"raw","params":{{"{SERDE_JSON_RAW_VALUE_TOKEN}":"{wrapped}"}}}}"#);
|
||||
|
||||
let error = serde_json::from_str::<JSONRPCMessage>(&encoded)
|
||||
.expect_err("raw value wrapper should not bypass the JSON value limit");
|
||||
let expected_error = format!("exceeds the limit of {MAX_JSONRPC_VALUE_NODES} JSON values");
|
||||
assert!(
|
||||
error.to_string().contains(&expected_error),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_large_scalar_payload() -> serde_json::Result<()> {
|
||||
let expected = JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "large".to_string(),
|
||||
params: Some(json!({"data": "x".repeat(MAX_JSONRPC_VALUE_NODES + 1)})),
|
||||
});
|
||||
|
||||
let encoded = serde_json::to_string(&expected)?;
|
||||
let actual = serde_json::from_str::<JSONRPCMessage>(&encoded)?;
|
||||
|
||||
assert_eq!(actual, expected);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicate_object_keys() {
|
||||
let error = serde_json::from_str::<JSONRPCMessage>(r#"{"method":"safe","method":"dangerous"}"#)
|
||||
.expect_err("duplicate JSON object keys should be rejected");
|
||||
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("duplicate JSON object key `method`"),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_compact_array_heap_amplification() {
|
||||
const REPRO_VALUE_COUNT: usize = 2_097_137;
|
||||
const REPRO_MESSAGE_BYTES: usize = 4_194_303;
|
||||
|
||||
let mut encoded = String::with_capacity(REPRO_MESSAGE_BYTES);
|
||||
encoded.push_str(r#"{"method":"probe","params":["#);
|
||||
for index in 0..REPRO_VALUE_COUNT {
|
||||
if index != 0 {
|
||||
encoded.push(',');
|
||||
}
|
||||
encoded.push('0');
|
||||
}
|
||||
encoded.push_str("]}");
|
||||
assert_eq!(encoded.len(), REPRO_MESSAGE_BYTES);
|
||||
|
||||
let error = serde_json::from_str::<JSONRPCMessage>(&encoded)
|
||||
.expect_err("amplification payload should exceed the JSON value limit");
|
||||
let expected_error = format!("exceeds the limit of {MAX_JSONRPC_VALUE_NODES} JSON values");
|
||||
assert!(
|
||||
error.to_string().contains(&expected_error),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user