Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-message-board",
crate_name = "codex_agent_message_board_extension",
)

View File

@@ -0,0 +1,32 @@
[package]
edition.workspace = true
license.workspace = true
name = "codex-agent-message-board-extension"
version.workspace = true
[lib]
name = "codex_agent_message_board_extension"
path = "src/lib.rs"
test = false
doctest = false
[lints]
workspace = true
[dependencies]
codex-agent-message-board-client = { workspace = true }
codex-config = { workspace = true }
codex-extension-api = { workspace = true }
codex-features = { workspace = true }
codex-http-client = { workspace = true }
codex-message-board = { workspace = true }
codex-message-board-mcp = { workspace = true }
codex-protocol = { workspace = true }
codex-state = { workspace = true }
codex-tools = { workspace = true }
futures = { workspace = true }
tokio = { workspace = true, features = ["sync"] }
[dev-dependencies]
serde_json = { workspace = true }
tokio = { workspace = true, features = ["fs", "macros", "rt-multi-thread"] }

View File

@@ -0,0 +1,54 @@
# Load a local board template
Create an empty chat, then load its initial channels before starting the agents:
```sh
just agent-board-config ~/.codex <root-session-id> /absolute/path/setup.json
```
Use the same SQLite home as Codex (`sqlite_home`, normally `$CODEX_HOME` or
`~/.codex`). Example `setup.json`:
```json
{
"template": {
"version": 1,
"channels": { "policy": { "description": "Shared policies" } }
}
}
```
The template and channels are saved atomically. Repeating the same setup is safe;
a different template or an already-used board is rejected. The pinned setup
survives reopen. An optional top-level `timestamp` sets the initial creation time;
otherwise it uses UTC now.
This loads channels and descriptions only. ACLs and roles are not accepted by
this version; existing agent access stays unchanged.
## Connect Codex runtimes
The host can give independently created Codex runtimes different access to the
same local board through the existing startup extension settings:
```rust
let board = LocalBoard::new(sqlite_config, board_id);
guardian_options.thread_extension_init.insert(board.read_only());
writer_options.thread_extension_init.insert(board.read_write());
```
Both connections carry the same SQLite configuration and board ID. Read-only
connections can read and manage their own subscriptions; posting, replying,
creating channels and changing another agent's subscriptions return permission
errors. Explicit connections expose effective permissions in channel discovery.
Runtimes without a connection keep the existing behavior and response shapes.
Install `codex_app_server::install_agent_message_board` in the runtime's extension
registry. For isolated Guardians, use their `IsolatedSessionExtensions` registry
and explicitly allow the board tools in their `ToolPolicy`. This does not enable
board access for existing Guardians automatically. Connected runtimes use unique
`/root/<compact-thread-uuid>` paths, independently of their agent trees.
The host supplies the connection again when creating another runtime, including
cold resume and forks. Connections are not database ACLs or inherited through
`spawn_agent`. Local filesystem writers remain trusted.

View File

@@ -0,0 +1,29 @@
//! Operator-only setup for local experiments; no administrative agent tools.
use codex_agent_message_board_extension::local_board_options;
use codex_message_board::LocalBoardSetup;
use codex_message_board::configure_local_board;
use codex_protocol::SessionId;
use codex_state::SqliteConfig;
use std::path::PathBuf;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args_os().collect();
let [_, sqlite_home, board, input] = args.as_slice() else {
return Err("Usage: configure_board <sqlite-home> <board-session-id> <setup.json>".into());
};
let sqlite = SqliteConfig::from_sqlite_home_with_nfs_enforcement(
std::path::absolute(PathBuf::from(sqlite_home))?.try_into()?,
/*enforce_delete_on_nfs*/ false,
);
let board = SessionId::from_string(board.to_str().ok_or("invalid board ID")?)?;
let input = tokio::fs::read(input).await?;
if input.len() > 64 * 1024 {
return Err("setup file exceeds 64 KiB".into());
}
let setup: LocalBoardSetup = serde_json::from_slice(&input)?;
configure_local_board(&sqlite, &local_board_options(), board, setup).await?;
println!("Configured local board {board}");
Ok(())
}

View File

@@ -0,0 +1,106 @@
//! Opens the host-selected board backend using the existing lifecycle factory.
//! Hosts supply membership, clocks and notification delivery through `MessageBoardHost`.
//! Installation opens no storage; each runtime binds its own host at thread startup.
use crate::extension;
use crate::local_board_options;
use crate::mcp;
use codex_agent_message_board_client::AccessToken;
use codex_agent_message_board_client::RemoteAgentMessageBoard;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::ThreadStartInput;
use codex_features::RemoteMessageBoardConfigToml;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_message_board::AgentMessageBoard;
use codex_message_board::InMemoryMessageBoards;
use codex_message_board::LocalAgentMessageBoard;
use codex_message_board::LocalBoardConnection;
use codex_message_board::MessageBoardHost;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_state::SqliteConfig;
use std::sync::Arc;
/// A backend selected from the host's effective configuration at thread startup.
pub enum BoardBackend {
Mcp,
Connected(Arc<LocalBoardConnection>),
Remote {
config: RemoteMessageBoardConfigToml,
http: HttpClientFactory,
},
InMemory,
Local(SqliteConfig),
}
/// Installs board backends and tools without depending on the host's runtime types.
/// The host selects a backend and supplies its capabilities, or returns `None`
/// when disabled. Remote hosts are retained in the thread store for the existing
/// turn-bound notification receiver; this does not change delivery semantics.
pub fn install<C: Sync + 'static, H: MessageBoardHost + Clone + 'static>(
registry: &mut ExtensionRegistryBuilder<C>,
namespace_description: &'static str,
tool_namespace: impl Fn(&C) -> Option<String> + Send + Sync + 'static,
host: impl Fn(&ThreadStartInput<'_, C>, SessionId, ThreadId) -> Option<(BoardBackend, H)>
+ Send
+ Sync
+ 'static,
) {
let in_memory_boards = Arc::new(InMemoryMessageBoards::default());
let mcp_boards = mcp::install_mcp(registry);
extension::install(
registry,
namespace_description,
tool_namespace,
move |input, tree, caller| {
let Some((backend, host)) = host(input, tree, caller) else {
return Box::pin(async { Ok(None) });
};
let in_memory_boards = Arc::clone(&in_memory_boards);
let mcp_boards = Arc::clone(&mcp_boards);
let host = Arc::new(host);
Box::pin(async move {
let board: Arc<dyn AgentMessageBoard> = match backend {
BoardBackend::Mcp => {
mcp_boards
.open(input.thread_store, tree, caller, host)
.await?;
return Ok(None);
}
BoardBackend::Connected(connection) => Arc::new(connection.open(host).await?),
BoardBackend::Remote { config, http } => {
let token = match config.bearer_token_env_var {
Some(name) => std::env::var(name).map_err(|_| CodexErr::InvalidRequest(
"message-board credential environment variable is missing or invalid".into(),
))?,
None => config.bearer_token.ok_or_else(|| CodexErr::InvalidRequest(
"remote message board requires a credential".into(),
))?.into_inner(),
};
let token = AccessToken::new(token)
.map_err(|err| CodexErr::InvalidRequest(err.to_string()))?;
let http = http
.build_client(&config.url, ClientRouteClass::Api)
.map_err(|err| CodexErr::Io(std::io::Error::other(err)))?;
input.thread_store.insert(host.as_ref().clone());
let board = RemoteAgentMessageBoard::new(http, &config.url, tree, token)
.map_err(|err| CodexErr::InvalidRequest(err.to_string()))?
.with_clock(move |caller| {
let host = host.clone();
Box::pin(async move { host.current_time(caller).await })
});
input.thread_store.get_or_init(|| board)
}
BoardBackend::InMemory => Arc::new(in_memory_boards.open(tree, host).await),
BoardBackend::Local(sqlite) => Arc::new(
LocalAgentMessageBoard::open(&sqlite, &local_board_options(), tree, host)
.await?,
),
};
Ok(Some(board))
})
},
);
}

View File

@@ -0,0 +1,169 @@
//! Installs caller-bound tools using host identities and optional local connections.
//!
//! Backend selection is a host concern. Startup failures leave tools unavailable
//! and emit a warning; a disabled factory does not open storage.
//! Tool namespaces follow the host's configuration at runtime startup.
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionEventSink;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::ExtensionWarning;
use codex_extension_api::ThreadLifecycleContributor;
use codex_extension_api::ThreadStartInput;
use codex_extension_api::ToolContributor;
use codex_message_board::AgentMessageBoard;
use codex_message_board::LocalBoardConnection;
use codex_message_board::MessageBoardTool;
use codex_message_board::message_board_tools;
use codex_protocol::AgentPath;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result;
use codex_protocol::openai_models::MultiAgentToolMessages;
use codex_tools::ToolCall;
use codex_tools::ToolExecutor;
use futures::future::BoxFuture;
use std::sync::Arc;
type BoardFactory<C> = dyn for<'a> Fn(
&'a ThreadStartInput<'_, C>,
SessionId,
ThreadId,
) -> BoxFuture<'a, Result<Option<Arc<dyn AgentMessageBoard>>>>
+ Send
+ Sync;
type NamespaceResolver<C> = dyn Fn(&C) -> Option<String> + Send + Sync;
struct BoardExtension<C> {
open: Box<BoardFactory<C>>,
tool_namespace: Box<NamespaceResolver<C>>,
namespace_description: &'static str,
events: Arc<dyn ExtensionEventSink>,
}
struct Binding {
board: Arc<dyn AgentMessageBoard>,
caller: ThreadId,
path: AgentPath,
namespace: Option<String>,
}
impl<C: Sync> ThreadLifecycleContributor<C> for BoardExtension<C> {
fn on_thread_start<'a>(&'a self, input: ThreadStartInput<'a, C>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
let result = async {
let tree =
SessionId::from_string(input.session_store.level_id()).map_err(|_| {
CodexErr::InvalidRequest("invalid board session identity".into())
})?;
let caller =
ThreadId::from_string(input.thread_store.level_id()).map_err(|_| {
CodexErr::InvalidRequest("invalid board caller identity".into())
})?;
if let Some(board) = (self.open)(&input, tree, caller).await? {
let connection = input.thread_store.get::<LocalBoardConnection>();
let expected = connection
.as_ref()
.map_or(tree, |connection| connection.identity());
if board.identity() != expected {
return Err(CodexErr::InvalidRequest(
"message-board factory returned another tree".into(),
));
}
input.thread_store.insert(Binding {
board,
caller,
namespace: (self.tool_namespace)(input.config),
path: match connection {
Some(connection) => connection.caller_path(caller)?,
None => input
.session_source
.get_agent_path()
.unwrap_or_else(AgentPath::root),
},
});
}
Ok::<(), CodexErr>(())
}
.await;
if result.is_err() {
self.events.emit_warning(ExtensionWarning {
thread_id: input.thread_store.level_id().into(), turn_id: None,
message: "Agent message-board initialization failed; its tools are unavailable for this runtime.".into(),
});
}
})
}
}
impl<C: Sync> ToolContributor for BoardExtension<C> {
fn tools(
&self,
_session_store: &ExtensionData,
thread_store: &ExtensionData,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
self.tools_with_descriptions(thread_store, /*tool_messages*/ None)
}
fn tools_for_step(
&self,
_session_store: &ExtensionData,
thread_store: &ExtensionData,
step_store: &ExtensionData,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
let tool_messages = step_store.get::<MultiAgentToolMessages>();
self.tools_with_descriptions(thread_store, tool_messages.as_deref())
}
}
impl<C> BoardExtension<C> {
fn tools_with_descriptions(
&self,
thread_store: &ExtensionData,
tool_messages: Option<&MultiAgentToolMessages>,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
thread_store
.get::<Binding>()
.map_or_else(Vec::new, |binding| {
message_board_tools(
&MessageBoardTool::DISCUSSION,
binding.board.clone(),
binding.caller,
binding.path.clone(),
binding.namespace.as_deref(),
self.namespace_description,
tool_messages,
)
})
}
}
/// Installs message-board lifecycle and tool contributions. The factory selects
/// a local or remote backend, or returns None when disabled. Configuration is
/// read at runtime startup, including resume; no board is created by installation.
/// The host supplies its shared namespace description and resolves the namespace
/// name from the runtime's startup configuration. The factory may retain its
/// backend in the existing thread store for other extension contributions.
pub fn install<C: Sync + 'static>(
registry: &mut ExtensionRegistryBuilder<C>,
namespace_description: &'static str,
tool_namespace: impl Fn(&C) -> Option<String> + Send + Sync + 'static,
open: impl for<'a> Fn(
&'a ThreadStartInput<'_, C>,
SessionId,
ThreadId,
) -> BoxFuture<'a, Result<Option<Arc<dyn AgentMessageBoard>>>>
+ Send
+ Sync
+ 'static,
) {
let extension = Arc::new(BoardExtension {
open: Box::new(open),
tool_namespace: Box::new(tool_namespace),
namespace_description,
events: registry.event_sink(),
});
registry.thread_lifecycle_contributor(extension.clone());
registry.tool_contributor(extension);
}

View File

@@ -0,0 +1,16 @@
//! Constructs configured boards and installs tools over the shared board interface.
//! Storage, backend behavior and tool implementations live in `codex-message-board`.
mod backend;
mod extension;
mod mcp;
pub use backend::BoardBackend;
pub use backend::install;
/// Storage selected by the agent consumer for opening, setup and permanent deletion.
pub fn local_board_options() -> codex_message_board::LocalBoardOptions {
codex_message_board::LocalBoardOptions {
storage_namespace: "agent_message_board".into(),
}
}

View File

@@ -0,0 +1,156 @@
//! Publishes the existing in-memory launcher through ordinary MCP discovery.
use codex_config::AppToolApproval;
use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use codex_config::McpServerConfig;
use codex_config::McpServerTransportConfig;
use codex_extension_api::CatalogRefreshInput;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::McpServerContribution;
use codex_extension_api::McpServerContributionContext;
use codex_extension_api::McpServerContributor;
use codex_extension_api::ThreadLifecycleContributor;
use codex_extension_api::ThreadStopInput;
use codex_extension_api::TurnLifecycleContributor;
use codex_message_board::MessageBoardHost;
use codex_message_board_mcp::LocalServer;
use codex_message_board_mcp::launch_in_memory;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::Weak;
use tokio::sync::OnceCell;
/// Shared launchers opened by the existing board factory when the MCP flag is enabled.
#[derive(Default)]
pub struct McpBoards {
servers: Mutex<HashMap<SessionId, Weak<OnceCell<LocalServer>>>>,
}
struct Binding(Arc<OnceCell<LocalServer>>);
struct PendingMcpRefresh;
impl McpBoards {
pub async fn open(
&self,
store: &ExtensionData,
tree: SessionId,
caller: ThreadId,
host: Arc<dyn MessageBoardHost>,
) -> Result<()> {
let slot = {
let mut servers = self
.servers
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
servers.retain(|_, server| server.strong_count() > 0);
let entry = servers.entry(tree).or_default();
entry.upgrade().unwrap_or_else(|| {
let slot = Arc::new(OnceCell::new());
*entry = Arc::downgrade(&slot);
slot
})
};
let server = slot
.get_or_try_init(launch_in_memory)
.await
.map_err(|error| CodexErr::Io(std::io::Error::other(error)))?;
server
.bind_agent(tree, caller, host)
.await
.map_err(|error| CodexErr::Io(std::io::Error::other(error)))?;
store.insert(Binding(slot));
store.insert(PendingMcpRefresh);
Ok(())
}
}
impl<C: Sync> ThreadLifecycleContributor<C> for McpBoards {
fn on_thread_stop<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.thread_store.remove::<Binding>();
})
}
}
impl TurnLifecycleContributor for McpBoards {
fn refresh_catalog_for_step<'a>(
&'a self,
input: CatalogRefreshInput<'a>,
) -> ExtensionFuture<'a, bool> {
// Initial MCP projection precedes the board factory's startup hook.
Box::pin(async move { input.thread_store.remove::<PendingMcpRefresh>().is_some() })
}
}
impl<C: Sync> McpServerContributor<C> for McpBoards {
fn id(&self) -> &'static str {
"agent_message_board_mcp"
}
fn contribute<'a>(
&'a self,
context: McpServerContributionContext<'a, C>,
) -> ExtensionFuture<'a, Vec<McpServerContribution>> {
Box::pin(async move {
let Some(binding) = context
.thread_store()
.and_then(ExtensionData::get::<Binding>)
else {
return Vec::new();
};
let Some(server) = binding.0.get() else {
return Vec::new();
};
let Ok(authorization) = server.authorization().to_str() else {
return Vec::new();
};
vec![McpServerContribution::Set {
name: "codex_message_board".into(),
config: Box::new(McpServerConfig {
transport: McpServerTransportConfig::StreamableHttp {
url: server.url().into(),
bearer_token_env_var: None,
http_headers: Some([("Authorization".into(), authorization.into())].into()),
env_http_headers: None,
http_headers_helper: None,
},
auth: Default::default(),
environment_id: DEFAULT_MCP_SERVER_ENVIRONMENT_ID.into(),
enabled: true,
required: true,
startup_readiness: Default::default(),
supports_parallel_tool_calls: false,
tool_input_schema_max_bytes: None,
omit_tools_from: None,
disabled_reason: None,
startup_timeout_sec: None,
tool_timeout_sec: None,
default_tools_approval_mode: Some(AppToolApproval::Approve),
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth: None,
oauth_resource: None,
tools: HashMap::new(),
}),
}]
})
}
}
/// Registers discovery for launchers created by the board factory.
pub fn install_mcp<C: Sync + 'static>(
registry: &mut ExtensionRegistryBuilder<C>,
) -> Arc<McpBoards> {
let boards = Arc::new(McpBoards::default());
registry.thread_lifecycle_contributor(boards.clone());
registry.turn_lifecycle_contributor(boards.clone());
registry.mcp_server_contributor(boards.clone());
boards
}