mirror of
https://github.com/openai/codex.git
synced 2026-10-30 19:18:49 +00:00
## What
This change introduces a new `ReadOnlyAccess` model and threads it through
sandbox policy consumers so read access is explicit instead of implicit.
- Added `ReadOnlyAccess` to protocol:
- `Restricted { include_platform_defaults, readable_roots }`
- `FullAccess`
- Changed `SandboxPolicy` shape:
- `ReadOnly` is now `ReadOnly { access: ReadOnlyAccess }`
- `WorkspaceWrite` now carries `read_only_access: ReadOnlyAccess`
- Kept existing behavior for now by defaulting to `ReadOnlyAccess::FullAccess`
in constructors and current config/app-server mappings.
- Added helper methods to compute effective readable roots (including optional
platform defaults + cwd) and to detect full read access.
- Updated seatbelt policy generation to honor restricted read roots by emitting
scoped `(allow file-read* ...)` entries when full read access is not granted.
- Updated Linux backends (`bwrap`, legacy landlock path) to fail closed with an
explicit `UnsupportedOperation` when restricted read access is requested but
not yet implemented there.
- Updated Windows sandbox backends (standard, elevated, and runner paths) to
fail closed in the same way for restricted read access.
- Updated all call sites/tests/pattern matches for the new structured variants
and regenerated app-server protocol schema/types.
## Why
The previous `SandboxPolicy::ReadOnly` implied full-disk read access and left
no way to express a narrower read surface.
This refactor establishes the policy model needed to support user-configurable
read restrictions in a follow-up without changing current runtime behavior.
It also ensures we do not silently ignore future restricted-read policies on
platform backends that do not support them yet. Failing closed keeps sandbox
semantics predictable and avoids accidental over-permission.
## Compatibility and rollout notes
- Existing behavior is preserved by default (`FullAccess`).
- Existing config/app-server flows continue to serialize/deserialize cleanly.
- New schema artifacts are included to keep generated protocol outputs in sync.
## Validation
- `just fmt`
- `just fix -p codex-protocol -p codex-core -p codex-linux-sandbox -p codex-windows-sandbox -p codex-app-server-protocol`
- `cargo check -p codex-windows-sandbox`
- Targeted crate/test runs were executed during development for protocol/core/
sandbox-related crates.
261 lines
8.3 KiB
Rust
261 lines
8.3 KiB
Rust
use std::collections::HashMap;
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use crate::client_common::tools::ToolSpec;
|
|
use crate::function_tool::FunctionCallError;
|
|
use crate::protocol::SandboxPolicy;
|
|
use crate::sandbox_tags::sandbox_tag;
|
|
use crate::tools::context::ToolInvocation;
|
|
use crate::tools::context::ToolOutput;
|
|
use crate::tools::context::ToolPayload;
|
|
use async_trait::async_trait;
|
|
use codex_protocol::models::ResponseInputItem;
|
|
use codex_utils_readiness::Readiness;
|
|
use tracing::warn;
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
pub enum ToolKind {
|
|
Function,
|
|
Mcp,
|
|
}
|
|
|
|
#[async_trait]
|
|
pub trait ToolHandler: Send + Sync {
|
|
fn kind(&self) -> ToolKind;
|
|
|
|
fn matches_kind(&self, payload: &ToolPayload) -> bool {
|
|
matches!(
|
|
(self.kind(), payload),
|
|
(ToolKind::Function, ToolPayload::Function { .. })
|
|
| (ToolKind::Mcp, ToolPayload::Mcp { .. })
|
|
)
|
|
}
|
|
|
|
/// Returns `true` if the [ToolInvocation] *might* mutate the environment of the
|
|
/// user (through file system, OS operations, ...).
|
|
/// This function must remains defensive and return `true` if a doubt exist on the
|
|
/// exact effect of a ToolInvocation.
|
|
async fn is_mutating(&self, _invocation: &ToolInvocation) -> bool {
|
|
false
|
|
}
|
|
|
|
/// Perform the actual [ToolInvocation] and returns a [ToolOutput] containing
|
|
/// the final output to return to the model.
|
|
async fn handle(&self, invocation: ToolInvocation) -> Result<ToolOutput, FunctionCallError>;
|
|
}
|
|
|
|
pub struct ToolRegistry {
|
|
handlers: HashMap<String, Arc<dyn ToolHandler>>,
|
|
}
|
|
|
|
impl ToolRegistry {
|
|
pub fn new(handlers: HashMap<String, Arc<dyn ToolHandler>>) -> Self {
|
|
Self { handlers }
|
|
}
|
|
|
|
pub fn handler(&self, name: &str) -> Option<Arc<dyn ToolHandler>> {
|
|
self.handlers.get(name).map(Arc::clone)
|
|
}
|
|
|
|
// TODO(jif) for dynamic tools.
|
|
// pub fn register(&mut self, name: impl Into<String>, handler: Arc<dyn ToolHandler>) {
|
|
// let name = name.into();
|
|
// if self.handlers.insert(name.clone(), handler).is_some() {
|
|
// warn!("overwriting handler for tool {name}");
|
|
// }
|
|
// }
|
|
|
|
pub async fn dispatch(
|
|
&self,
|
|
invocation: ToolInvocation,
|
|
) -> Result<ResponseInputItem, FunctionCallError> {
|
|
let tool_name = invocation.tool_name.clone();
|
|
let call_id_owned = invocation.call_id.clone();
|
|
let otel = invocation.turn.otel_manager.clone();
|
|
let payload_for_response = invocation.payload.clone();
|
|
let log_payload = payload_for_response.log_payload();
|
|
let metric_tags = [
|
|
(
|
|
"sandbox",
|
|
sandbox_tag(
|
|
&invocation.turn.sandbox_policy,
|
|
invocation.turn.windows_sandbox_level,
|
|
),
|
|
),
|
|
(
|
|
"sandbox_policy",
|
|
sandbox_policy_tag(&invocation.turn.sandbox_policy),
|
|
),
|
|
];
|
|
|
|
let handler = match self.handler(tool_name.as_ref()) {
|
|
Some(handler) => handler,
|
|
None => {
|
|
let message =
|
|
unsupported_tool_call_message(&invocation.payload, tool_name.as_ref());
|
|
otel.tool_result_with_tags(
|
|
tool_name.as_ref(),
|
|
&call_id_owned,
|
|
log_payload.as_ref(),
|
|
Duration::ZERO,
|
|
false,
|
|
&message,
|
|
&metric_tags,
|
|
);
|
|
return Err(FunctionCallError::RespondToModel(message));
|
|
}
|
|
};
|
|
|
|
if !handler.matches_kind(&invocation.payload) {
|
|
let message = format!("tool {tool_name} invoked with incompatible payload");
|
|
otel.tool_result_with_tags(
|
|
tool_name.as_ref(),
|
|
&call_id_owned,
|
|
log_payload.as_ref(),
|
|
Duration::ZERO,
|
|
false,
|
|
&message,
|
|
&metric_tags,
|
|
);
|
|
return Err(FunctionCallError::Fatal(message));
|
|
}
|
|
|
|
let output_cell = tokio::sync::Mutex::new(None);
|
|
|
|
let result = otel
|
|
.log_tool_result_with_tags(
|
|
tool_name.as_ref(),
|
|
&call_id_owned,
|
|
log_payload.as_ref(),
|
|
&metric_tags,
|
|
|| {
|
|
let handler = handler.clone();
|
|
let output_cell = &output_cell;
|
|
let invocation = invocation;
|
|
async move {
|
|
if handler.is_mutating(&invocation).await {
|
|
tracing::trace!("waiting for tool gate");
|
|
invocation.turn.tool_call_gate.wait_ready().await;
|
|
tracing::trace!("tool gate released");
|
|
}
|
|
match handler.handle(invocation).await {
|
|
Ok(output) => {
|
|
let preview = output.log_preview();
|
|
let success = output.success_for_logging();
|
|
let mut guard = output_cell.lock().await;
|
|
*guard = Some(output);
|
|
Ok((preview, success))
|
|
}
|
|
Err(err) => Err(err),
|
|
}
|
|
}
|
|
},
|
|
)
|
|
.await;
|
|
|
|
match result {
|
|
Ok(_) => {
|
|
let mut guard = output_cell.lock().await;
|
|
let output = guard.take().ok_or_else(|| {
|
|
FunctionCallError::Fatal("tool produced no output".to_string())
|
|
})?;
|
|
Ok(output.into_response(&call_id_owned, &payload_for_response))
|
|
}
|
|
Err(err) => Err(err),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct ConfiguredToolSpec {
|
|
pub spec: ToolSpec,
|
|
pub supports_parallel_tool_calls: bool,
|
|
}
|
|
|
|
impl ConfiguredToolSpec {
|
|
pub fn new(spec: ToolSpec, supports_parallel_tool_calls: bool) -> Self {
|
|
Self {
|
|
spec,
|
|
supports_parallel_tool_calls,
|
|
}
|
|
}
|
|
}
|
|
|
|
pub struct ToolRegistryBuilder {
|
|
handlers: HashMap<String, Arc<dyn ToolHandler>>,
|
|
specs: Vec<ConfiguredToolSpec>,
|
|
}
|
|
|
|
impl ToolRegistryBuilder {
|
|
pub fn new() -> Self {
|
|
Self {
|
|
handlers: HashMap::new(),
|
|
specs: Vec::new(),
|
|
}
|
|
}
|
|
|
|
pub fn push_spec(&mut self, spec: ToolSpec) {
|
|
self.push_spec_with_parallel_support(spec, false);
|
|
}
|
|
|
|
pub fn push_spec_with_parallel_support(
|
|
&mut self,
|
|
spec: ToolSpec,
|
|
supports_parallel_tool_calls: bool,
|
|
) {
|
|
self.specs
|
|
.push(ConfiguredToolSpec::new(spec, supports_parallel_tool_calls));
|
|
}
|
|
|
|
pub fn register_handler(&mut self, name: impl Into<String>, handler: Arc<dyn ToolHandler>) {
|
|
let name = name.into();
|
|
if self
|
|
.handlers
|
|
.insert(name.clone(), handler.clone())
|
|
.is_some()
|
|
{
|
|
warn!("overwriting handler for tool {name}");
|
|
}
|
|
}
|
|
|
|
// TODO(jif) for dynamic tools.
|
|
// pub fn register_many<I>(&mut self, names: I, handler: Arc<dyn ToolHandler>)
|
|
// where
|
|
// I: IntoIterator,
|
|
// I::Item: Into<String>,
|
|
// {
|
|
// for name in names {
|
|
// let name = name.into();
|
|
// if self
|
|
// .handlers
|
|
// .insert(name.clone(), handler.clone())
|
|
// .is_some()
|
|
// {
|
|
// warn!("overwriting handler for tool {name}");
|
|
// }
|
|
// }
|
|
// }
|
|
|
|
pub fn build(self) -> (Vec<ConfiguredToolSpec>, ToolRegistry) {
|
|
let registry = ToolRegistry::new(self.handlers);
|
|
(self.specs, registry)
|
|
}
|
|
}
|
|
|
|
fn unsupported_tool_call_message(payload: &ToolPayload, tool_name: &str) -> String {
|
|
match payload {
|
|
ToolPayload::Custom { .. } => format!("unsupported custom tool call: {tool_name}"),
|
|
_ => format!("unsupported call: {tool_name}"),
|
|
}
|
|
}
|
|
|
|
fn sandbox_policy_tag(policy: &SandboxPolicy) -> &'static str {
|
|
match policy {
|
|
SandboxPolicy::ReadOnly { .. } => "read-only",
|
|
SandboxPolicy::WorkspaceWrite { .. } => "workspace-write",
|
|
SandboxPolicy::DangerFullAccess => "danger-full-access",
|
|
SandboxPolicy::ExternalSandbox { .. } => "external-sandbox",
|
|
}
|
|
}
|