aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
554
akode-rs/message-board/src/tools.rs
Normal file
554
akode-rs/message-board/src/tools.rs
Normal file
@@ -0,0 +1,554 @@
|
||||
//! Model tools over a caller-bound board. Results stay valid, bounded JSON.
|
||||
|
||||
mod arguments;
|
||||
pub(crate) mod selection;
|
||||
mod spec;
|
||||
|
||||
use self::selection::MessageBoardTool;
|
||||
use crate::AgentMessageBoard;
|
||||
use crate::AppendRequest;
|
||||
use crate::BoardReadView;
|
||||
use crate::ChannelQuery;
|
||||
use crate::CreateChannelRequest;
|
||||
use crate::PageRequest;
|
||||
use crate::PermissionDenied;
|
||||
use crate::PostDestination;
|
||||
use crate::PostQuery;
|
||||
use crate::PostRequest;
|
||||
use crate::ReadPostRequest;
|
||||
use crate::ReadThreadRequest;
|
||||
use crate::SortDirection;
|
||||
use crate::SubscriptionChange;
|
||||
use crate::SubscriptionRequest;
|
||||
use crate::SubscriptionTarget;
|
||||
use crate::ThreadQuery;
|
||||
use crate::ThreadSort;
|
||||
use akode_protocol::AgentPath;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::error::CodexErrorDetails;
|
||||
use akode_protocol::openai_models::MultiAgentToolMessages;
|
||||
use akode_tools::FunctionCallError;
|
||||
use akode_tools::JsonToolOutput;
|
||||
use akode_tools::ToolCall;
|
||||
use akode_tools::ToolCallSource;
|
||||
use akode_tools::ToolExecutor;
|
||||
use akode_tools::ToolExecutorFuture;
|
||||
use akode_tools::ToolName;
|
||||
use akode_tools::ToolSpec;
|
||||
use futures::future::BoxFuture;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
use std::num::NonZeroU32;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Maximum size of a message-board tool's raw JSON arguments, in KiB.
|
||||
pub const MAX_TOOL_ARGUMENT_KIB: usize = 128;
|
||||
/// Maximum response size including JSON escaping and metadata, for direct and Code Mode calls.
|
||||
pub const MAX_TOOL_RESPONSE_BYTES: usize = 8_000;
|
||||
|
||||
/// Creates only the selected tools, in the supplied order, without registering them.
|
||||
/// The caller and its path must come from the host's authoritative tree metadata.
|
||||
/// Namespace metadata must match the consumer's other tools. Optional model-catalog
|
||||
/// descriptions override the bundled descriptions without changing tool parameters.
|
||||
pub fn message_board_tools(
|
||||
tools: &[MessageBoardTool],
|
||||
board: Arc<dyn AgentMessageBoard>,
|
||||
caller: ThreadId,
|
||||
caller_path: AgentPath,
|
||||
namespace: Option<&str>,
|
||||
namespace_description: &str,
|
||||
tool_messages: Option<&MultiAgentToolMessages>,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
bind_tools(
|
||||
tools,
|
||||
ToolTarget::Live(board),
|
||||
caller,
|
||||
caller_path,
|
||||
namespace,
|
||||
namespace_description,
|
||||
tool_messages,
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates the channel, thread, search and post read tools for one captured view.
|
||||
pub fn message_board_read_tools(
|
||||
view: Arc<dyn BoardReadView>,
|
||||
caller: ThreadId,
|
||||
caller_path: AgentPath,
|
||||
namespace: Option<&str>,
|
||||
namespace_description: &str,
|
||||
tool_messages: Option<&MultiAgentToolMessages>,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
bind_tools(
|
||||
&MessageBoardTool::READ_ONLY,
|
||||
ToolTarget::Fixed(view),
|
||||
caller,
|
||||
caller_path,
|
||||
namespace,
|
||||
namespace_description,
|
||||
tool_messages,
|
||||
)
|
||||
}
|
||||
|
||||
fn bind_tools(
|
||||
tools: &[MessageBoardTool],
|
||||
target: ToolTarget,
|
||||
caller: ThreadId,
|
||||
caller_path: AgentPath,
|
||||
namespace: Option<&str>,
|
||||
namespace_description: &str,
|
||||
tool_messages: Option<&MultiAgentToolMessages>,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
tools
|
||||
.iter()
|
||||
.map(|&tool| {
|
||||
let name = tool.name();
|
||||
let tool_message = tool_messages.and_then(|tools| tools.by_name(name));
|
||||
if tool_message.is_some_and(|tool| tool.parameters.is_some()) {
|
||||
tracing::warn!(
|
||||
tool = name,
|
||||
"Channel tool parameters cannot be overridden; using bundled parameters"
|
||||
);
|
||||
}
|
||||
Arc::new(BoardTool {
|
||||
caller,
|
||||
caller_path: caller_path.clone(),
|
||||
tool,
|
||||
target: target.clone(),
|
||||
namespace: namespace.map(str::to_owned),
|
||||
namespace_description: namespace_description.to_owned(),
|
||||
description: tool_message.and_then(|tool| tool.description.clone()),
|
||||
}) as Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum ToolTarget {
|
||||
Live(Arc<dyn AgentMessageBoard>),
|
||||
Fixed(Arc<dyn BoardReadView>),
|
||||
}
|
||||
|
||||
struct BoardTool {
|
||||
caller: ThreadId,
|
||||
caller_path: AgentPath,
|
||||
tool: MessageBoardTool,
|
||||
target: ToolTarget,
|
||||
namespace: Option<String>,
|
||||
namespace_description: String,
|
||||
description: Option<String>,
|
||||
}
|
||||
|
||||
impl<'call> ToolExecutor<ToolCall<'call>> for BoardTool {
|
||||
fn tool_name(&self) -> ToolName {
|
||||
ToolName::new(self.namespace.clone(), self.tool.name())
|
||||
}
|
||||
fn spec(&self) -> ToolSpec {
|
||||
spec::tool(
|
||||
self.tool,
|
||||
self.namespace.as_deref(),
|
||||
&self.namespace_description,
|
||||
self.description.as_deref(),
|
||||
)
|
||||
}
|
||||
fn supports_parallel_tool_calls(&self) -> bool {
|
||||
MessageBoardTool::READ_ONLY.contains(&self.tool)
|
||||
}
|
||||
|
||||
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
|
||||
where
|
||||
'call: 'a,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let raw = call.function_arguments()?;
|
||||
if raw.len() > MAX_TOOL_ARGUMENT_KIB * 1024 {
|
||||
return Err(model_error(format!(
|
||||
"message-board arguments exceed {MAX_TOOL_ARGUMENT_KIB} KiB"
|
||||
)));
|
||||
}
|
||||
let budget = call.response_byte_budget(MAX_TOOL_RESPONSE_BYTES);
|
||||
let (result, success) = match self.execute(raw, &call, budget).await {
|
||||
Ok(result) => (result, true),
|
||||
Err(BoardToolError::Model(error)) => return Err(error),
|
||||
Err(BoardToolError::PermissionDenied(denied)) => {
|
||||
(denied.model_response(budget)?, false)
|
||||
}
|
||||
};
|
||||
if result.to_string().len() > budget {
|
||||
return Err(model_error(
|
||||
"Result exceeds the output budget. Reduce limit or max_chars_per_post; use read_post with a smaller limit_chars for long posts.",
|
||||
));
|
||||
}
|
||||
Ok(
|
||||
Box::new(
|
||||
JsonToolOutput::with_success(result, Some(success)).with_external_context(),
|
||||
) as Box<dyn akode_tools::ToolOutput>,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl BoardTool {
|
||||
async fn execute(
|
||||
&self,
|
||||
raw: &str,
|
||||
call: &ToolCall<'_>,
|
||||
budget: usize,
|
||||
) -> Result<Value, BoardToolError> {
|
||||
let caller = self.caller;
|
||||
let page_limit = |limit: Option<NonZeroU32>| limit.map_or(20, NonZeroU32::get).min(50);
|
||||
let preview_limit =
|
||||
|limit: Option<NonZeroU32>| limit.map_or(1000, NonZeroU32::get).min(20_000);
|
||||
let page = |limit, cursor, scale| PageRequest {
|
||||
limit: nonzero(limit / scale),
|
||||
cursor,
|
||||
};
|
||||
let direction = |recent_first: Option<bool>| {
|
||||
if recent_first.unwrap_or(true) {
|
||||
SortDirection::NewestFirst
|
||||
} else {
|
||||
SortDirection::OldestFirst
|
||||
}
|
||||
};
|
||||
match (self.tool, &self.target) {
|
||||
(MessageBoardTool::UpsertChannel, ToolTarget::Live(board)) => {
|
||||
let request = serde_json::from_str(raw).map_err(model_error)?;
|
||||
self.check_mutation_budget(budget, /*target_path_bytes*/ 0)?;
|
||||
encode(board.upsert_channel(caller, request).await)
|
||||
}
|
||||
(MessageBoardTool::CreateChannel, ToolTarget::Live(board)) => {
|
||||
let arguments::CreateChannel {
|
||||
channel_name,
|
||||
description,
|
||||
subscribe,
|
||||
} = serde_json::from_str(raw).map_err(model_error)?;
|
||||
// JSON can escape each description byte into six output bytes.
|
||||
let description_budget = description
|
||||
.as_ref()
|
||||
.map_or(0, |text| text.as_str().len() * 6);
|
||||
self.check_mutation_budget(
|
||||
budget.saturating_sub(description_budget),
|
||||
/*target_path_bytes*/ 0,
|
||||
)?;
|
||||
encode(
|
||||
board
|
||||
.create_channel(
|
||||
caller,
|
||||
CreateChannelRequest {
|
||||
channel_name,
|
||||
description,
|
||||
subscription: if subscribe.unwrap_or(true) {
|
||||
SubscriptionChange::Subscribe
|
||||
} else {
|
||||
SubscriptionChange::Unsubscribe
|
||||
},
|
||||
},
|
||||
)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
(MessageBoardTool::GetChannels, target) => {
|
||||
let arguments::GetChannels {
|
||||
query,
|
||||
recent_first,
|
||||
limit,
|
||||
cursor,
|
||||
} = serde_json::from_str(raw).map_err(model_error)?;
|
||||
let limit = page_limit(limit);
|
||||
bounded_read(budget, limit, |scale| {
|
||||
let request = ChannelQuery {
|
||||
query: query.clone(),
|
||||
direction: direction(recent_first),
|
||||
page: page(limit, cursor.clone(), scale),
|
||||
};
|
||||
match target {
|
||||
ToolTarget::Live(board) => board.list_channels(caller, request),
|
||||
ToolTarget::Fixed(view) => view.list_channels(caller, request),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
(MessageBoardTool::ListThreads, target) => {
|
||||
let arguments::ListThreads {
|
||||
channel_name,
|
||||
sort,
|
||||
recent_first,
|
||||
limit,
|
||||
cursor,
|
||||
max_chars_per_post,
|
||||
} = serde_json::from_str(raw).map_err(model_error)?;
|
||||
let limit = page_limit(limit);
|
||||
let max_chars_per_post = preview_limit(max_chars_per_post);
|
||||
bounded_read(budget, limit.max(max_chars_per_post), |scale| {
|
||||
let request = ThreadQuery {
|
||||
channel_name: channel_name.clone(),
|
||||
sort: sort.unwrap_or(ThreadSort::Created),
|
||||
direction: direction(recent_first),
|
||||
max_chars_per_post: nonzero(max_chars_per_post / scale),
|
||||
page: page(limit, cursor.clone(), scale),
|
||||
};
|
||||
match target {
|
||||
ToolTarget::Live(board) => board.list_threads(caller, request),
|
||||
ToolTarget::Fixed(view) => view.list_threads(caller, request),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
(MessageBoardTool::SearchPosts, target) => {
|
||||
let arguments::SearchPosts {
|
||||
channel_name,
|
||||
query,
|
||||
after_message_id,
|
||||
author,
|
||||
limit,
|
||||
cursor,
|
||||
max_chars_per_post,
|
||||
} = serde_json::from_str(raw).map_err(model_error)?;
|
||||
let author = author
|
||||
.map(|path| self.caller_path.resolve(&path))
|
||||
.transpose()
|
||||
.map_err(model_error)?;
|
||||
let limit = page_limit(limit);
|
||||
let max_chars_per_post = preview_limit(max_chars_per_post);
|
||||
bounded_read(budget, limit.max(max_chars_per_post), |scale| {
|
||||
let request = PostQuery {
|
||||
channel_name: channel_name.clone(),
|
||||
query: query.clone(),
|
||||
after_message_id,
|
||||
author: author.clone(),
|
||||
max_chars_per_post: nonzero(max_chars_per_post / scale),
|
||||
page: page(limit, cursor.clone(), scale),
|
||||
};
|
||||
match target {
|
||||
ToolTarget::Live(board) => board.search_posts(caller, request),
|
||||
ToolTarget::Fixed(view) => view.search_posts(caller, request),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
(MessageBoardTool::ReadThread, target) => {
|
||||
let arguments::ReadThread {
|
||||
thread_id,
|
||||
limit,
|
||||
cursor,
|
||||
max_chars_per_post,
|
||||
} = serde_json::from_str(raw).map_err(model_error)?;
|
||||
let limit = page_limit(limit);
|
||||
let max_chars_per_post = preview_limit(max_chars_per_post);
|
||||
bounded_read(budget, limit.max(max_chars_per_post), |scale| {
|
||||
let request = ReadThreadRequest {
|
||||
thread_id,
|
||||
max_chars_per_post: nonzero(max_chars_per_post / scale),
|
||||
page: page(limit, cursor.clone(), scale),
|
||||
};
|
||||
match target {
|
||||
ToolTarget::Live(board) => board.read_thread(caller, request),
|
||||
ToolTarget::Fixed(view) => view.read_thread(caller, request),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
(MessageBoardTool::ReadPost, target) => {
|
||||
let arguments::ReadPost {
|
||||
message_id,
|
||||
offset_chars,
|
||||
limit_chars,
|
||||
} = serde_json::from_str(raw).map_err(model_error)?;
|
||||
let limit_chars = limit_chars.map_or(20_000, NonZeroU32::get).min(20_000);
|
||||
bounded_read(budget, limit_chars, |scale| {
|
||||
let request = ReadPostRequest {
|
||||
message_id,
|
||||
offset_chars: offset_chars.unwrap_or_default(),
|
||||
limit_chars: nonzero(limit_chars / scale),
|
||||
};
|
||||
match target {
|
||||
ToolTarget::Live(board) => board.read_post(caller, request),
|
||||
ToolTarget::Fixed(view) => view.read_post(caller, request),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
(
|
||||
MessageBoardTool::Subscribe | MessageBoardTool::Unsubscribe,
|
||||
ToolTarget::Live(board),
|
||||
) => {
|
||||
let arguments::Subscription {
|
||||
channel_name,
|
||||
thread_id,
|
||||
target_agent,
|
||||
} = serde_json::from_str(raw).map_err(model_error)?;
|
||||
self.check_mutation_budget(budget, target_agent.as_ref().map_or(0, String::len))?;
|
||||
let target = match (channel_name, thread_id) {
|
||||
(Some(channel), None) => SubscriptionTarget::Channel(channel),
|
||||
(None, Some(thread)) => SubscriptionTarget::Thread(thread),
|
||||
_ => {
|
||||
return Err(
|
||||
model_error("Supply exactly one of channel_name or thread_id").into(),
|
||||
);
|
||||
}
|
||||
};
|
||||
encode(
|
||||
board
|
||||
.set_subscription(
|
||||
caller,
|
||||
SubscriptionRequest {
|
||||
target,
|
||||
target_agent: target_agent
|
||||
.map(|path| self.caller_path.resolve(&path))
|
||||
.transpose()
|
||||
.map_err(model_error)?,
|
||||
change: if self.tool == MessageBoardTool::Subscribe {
|
||||
SubscriptionChange::Subscribe
|
||||
} else {
|
||||
SubscriptionChange::Unsubscribe
|
||||
},
|
||||
},
|
||||
)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
(MessageBoardTool::Post | MessageBoardTool::Append, ToolTarget::Live(board)) => {
|
||||
let arguments::Post {
|
||||
text,
|
||||
channel_name,
|
||||
new_channel_name,
|
||||
thread_id,
|
||||
agents_to_notify,
|
||||
} = if self.tool == MessageBoardTool::Append {
|
||||
let args: arguments::Append = serde_json::from_str(raw).map_err(model_error)?;
|
||||
arguments::Post {
|
||||
text: args.text,
|
||||
channel_name: args.channel_name,
|
||||
new_channel_name: args.new_channel_name,
|
||||
thread_id: args.thread_id,
|
||||
agents_to_notify: None,
|
||||
}
|
||||
} else {
|
||||
serde_json::from_str(raw).map_err(model_error)?
|
||||
};
|
||||
self.check_mutation_budget(budget, /*target_path_bytes*/ 0)?;
|
||||
let destination = match (channel_name, new_channel_name, thread_id) {
|
||||
(Some(channel), None, None) => PostDestination::Channel(channel),
|
||||
(None, Some(channel), None) => PostDestination::NewChannel(channel),
|
||||
(None, None, Some(thread)) => PostDestination::Thread(thread),
|
||||
_ => {
|
||||
return Err(model_error(
|
||||
"Supply exactly one of channel_name, new_channel_name or thread_id",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
};
|
||||
let invocation = match &call.source {
|
||||
ToolCallSource::Direct => call.call_id.clone(),
|
||||
ToolCallSource::CodeMode {
|
||||
cell_id,
|
||||
runtime_tool_call_id,
|
||||
} => format!("{cell_id}:{runtime_tool_call_id}"),
|
||||
};
|
||||
let request_id = format!("{}:{invocation}", call.turn_id);
|
||||
encode(if self.tool == MessageBoardTool::Append {
|
||||
board
|
||||
.append(
|
||||
caller,
|
||||
AppendRequest {
|
||||
request_id,
|
||||
destination,
|
||||
text,
|
||||
},
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
board
|
||||
.post(
|
||||
caller,
|
||||
PostRequest {
|
||||
request_id,
|
||||
destination,
|
||||
text,
|
||||
agents_to_notify: agents_to_notify
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|path| self.caller_path.resolve(&path))
|
||||
.collect::<Result<_, _>>()
|
||||
.map_err(model_error)?,
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
(_, ToolTarget::Fixed(_)) => Err(FunctionCallError::Fatal(
|
||||
"A board mutation was bound to a read-only view".to_string(),
|
||||
)
|
||||
.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_mutation_budget(
|
||||
&self,
|
||||
budget: usize,
|
||||
target_path_bytes: usize,
|
||||
) -> Result<(), FunctionCallError> {
|
||||
// Reserve metadata, escaped channel names and agent paths before any write.
|
||||
if budget < 2048 + self.caller_path.len() + target_path_bytes {
|
||||
return Err(model_error(
|
||||
"Output budget is too small to acknowledge a message-board mutation; no change was made.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Try the requested read first. Halve limits only when its serialized output is too large.
|
||||
/// Reissuing the read lets each backend generate a cursor for exactly the returned page.
|
||||
/// Stop once every limit has reached one; another read would repeat the same request.
|
||||
async fn bounded_read<'a, T: Serialize>(
|
||||
budget: usize,
|
||||
largest_limit: u32,
|
||||
fetch: impl Fn(u32) -> BoxFuture<'a, akode_protocol::error::Result<T>>,
|
||||
) -> Result<Value, BoardToolError> {
|
||||
let mut scale = 1;
|
||||
loop {
|
||||
let result = encode(fetch(scale).await)?;
|
||||
if result.to_string().len() <= budget {
|
||||
return Ok(result);
|
||||
}
|
||||
if largest_limit / scale <= 1 {
|
||||
break;
|
||||
}
|
||||
scale *= 2;
|
||||
}
|
||||
Err(model_error("The output budget is too small for this result's metadata.").into())
|
||||
}
|
||||
|
||||
fn nonzero(value: u32) -> NonZeroU32 {
|
||||
NonZeroU32::new(value).unwrap_or(NonZeroU32::MIN)
|
||||
}
|
||||
fn model_error(error: impl std::fmt::Display) -> FunctionCallError {
|
||||
FunctionCallError::RespondToModel(error.to_string().chars().take(512).collect())
|
||||
}
|
||||
|
||||
enum BoardToolError {
|
||||
Model(FunctionCallError),
|
||||
PermissionDenied(PermissionDenied),
|
||||
}
|
||||
|
||||
impl From<FunctionCallError> for BoardToolError {
|
||||
fn from(error: FunctionCallError) -> Self {
|
||||
Self::Model(error)
|
||||
}
|
||||
}
|
||||
|
||||
fn encode<T: Serialize>(value: akode_protocol::error::Result<T>) -> Result<Value, BoardToolError> {
|
||||
let value = value.map_err(|error| {
|
||||
if let CodexErrorDetails::Io(io) = error.details()
|
||||
&& let Some(denied) = io
|
||||
.get_ref()
|
||||
.and_then(|source| source.downcast_ref::<PermissionDenied>())
|
||||
{
|
||||
BoardToolError::PermissionDenied(denied.clone())
|
||||
} else {
|
||||
BoardToolError::Model(model_error(error))
|
||||
}
|
||||
})?;
|
||||
serde_json::to_value(value).map_err(|error| model_error(error).into())
|
||||
}
|
||||
Reference in New Issue
Block a user