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:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,186 @@
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::future::Future;
/// Storage interface behind the memories tools.
///
/// Implementations should return paths relative to the memory store and enforce
/// their own storage-specific access rules. The local implementation uses the
/// filesystem today; a later implementation can satisfy the same contract from a
/// remote backend.
pub trait MemoriesBackend: Clone + Send + Sync + 'static {
fn add_ad_hoc_note(
&self,
request: AddAdHocMemoryNoteRequest,
) -> impl Future<Output = Result<AddAdHocMemoryNoteResponse, MemoriesBackendError>> + Send;
fn list(
&self,
request: ListMemoriesRequest,
) -> impl Future<Output = Result<ListMemoriesResponse, MemoriesBackendError>> + Send;
fn read(
&self,
request: ReadMemoryRequest,
) -> impl Future<Output = Result<ReadMemoryResponse, MemoriesBackendError>> + Send;
fn search(
&self,
request: SearchMemoriesRequest,
) -> impl Future<Output = Result<SearchMemoriesResponse, MemoriesBackendError>> + Send;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddAdHocMemoryNoteRequest {
pub filename: String,
pub note: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct AddAdHocMemoryNoteResponse {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListMemoriesRequest {
pub path: Option<String>,
pub cursor: Option<String>,
pub max_results: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ListMemoriesResponse {
pub path: Option<String>,
pub entries: Vec<MemoryEntry>,
pub next_cursor: Option<String>,
pub truncated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReadMemoryRequest {
pub path: String,
pub line_offset: usize,
pub max_lines: Option<usize>,
pub max_tokens: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ReadMemoryResponse {
pub path: String,
pub start_line_number: usize,
pub content: String,
pub truncated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchMemoriesRequest {
pub queries: Vec<String>,
pub match_mode: SearchMatchMode,
pub path: Option<String>,
pub cursor: Option<String>,
pub context_lines: usize,
pub case_sensitive: bool,
pub normalized: bool,
pub max_results: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct SearchMemoriesResponse {
pub queries: Vec<String>,
pub match_mode: SearchMatchMode,
pub path: Option<String>,
pub matches: Vec<MemorySearchMatch>,
pub next_cursor: Option<String>,
pub truncated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SearchMatchMode {
Any,
AllOnSameLine,
AllWithinLines {
#[schemars(range(min = 1))]
line_count: usize,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct MemoryEntry {
pub path: String,
pub entry_type: MemoryEntryType,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MemoryEntryType {
File,
Directory,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct MemorySearchMatch {
pub path: String,
pub match_line_number: usize,
pub content_start_line_number: usize,
pub content: String,
pub matched_queries: Vec<String>,
}
#[derive(Debug, thiserror::Error)]
pub enum MemoriesBackendError {
#[error("filename '{filename}' {reason}")]
InvalidFilename { filename: String, reason: String },
#[error("ad-hoc note must not be empty")]
EmptyAdHocNote,
#[error("ad-hoc note '{filename}' already exists")]
AdHocNoteAlreadyExists { filename: String },
#[error("path '{path}' {reason}")]
InvalidPath { path: String, reason: String },
#[error("cursor '{cursor}' {reason}")]
InvalidCursor { cursor: String, reason: String },
#[error("path '{path}' was not found")]
NotFound { path: String },
#[error("line_offset must be a 1-indexed line number")]
InvalidLineOffset,
#[error("max_lines must be a positive integer")]
InvalidMaxLines,
#[error("line_offset exceeds file length")]
LineOffsetExceedsFileLength,
#[error("path '{path}' is not a file")]
NotFile { path: String },
#[error("queries must not be empty or contain empty strings")]
EmptyQuery,
#[error("all_within_lines.line_count must be a positive integer")]
InvalidMatchWindow,
#[error("I/O error while reading memories: {0}")]
Io(#[from] std::io::Error),
}
impl MemoriesBackendError {
pub fn invalid_filename(filename: impl Into<String>, reason: impl Into<String>) -> Self {
Self::InvalidFilename {
filename: filename.into(),
reason: reason.into(),
}
}
pub fn invalid_path(path: impl Into<String>, reason: impl Into<String>) -> Self {
Self::InvalidPath {
path: path.into(),
reason: reason.into(),
}
}
pub fn invalid_cursor(cursor: impl Into<String>, reason: impl Into<String>) -> Self {
Self::InvalidCursor {
cursor: cursor.into(),
reason: reason.into(),
}
}
}

View File

@@ -0,0 +1,174 @@
use std::sync::Arc;
use akode_core::config::Config;
use akode_core::context::ContextualUserFragment;
use akode_core::context::MemoryContextFragment;
use akode_extension_api::ConfigContributor;
use akode_extension_api::ContentItemKind;
use akode_extension_api::ContextContributor;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionFuture;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::PromptFragment;
use akode_extension_api::ThreadLifecycleContributor;
use akode_extension_api::ThreadStartInput;
use akode_extension_api::ToolContributor;
use akode_features::Feature;
use akode_otel::MetricsClient;
use akode_protocol::MemoryVersion;
use akode_utils_absolute_path::AbsolutePathBuf;
use crate::local::LocalMemoriesBackend;
use crate::prompts::build_memory_tool_developer_instructions;
use crate::tools;
/// Contributes Codex memory read-path prompt context and memory read tools.
#[derive(Clone, Default)]
pub(crate) struct MemoriesExtension {
metrics_client: Option<MetricsClient>,
}
impl MemoriesExtension {
fn new(metrics_client: Option<MetricsClient>) -> Self {
Self { metrics_client }
}
}
#[derive(Clone, Debug)]
pub(crate) struct MemoriesExtensionConfig {
pub(crate) enabled: bool,
pub(crate) dedicated_tools: bool,
pub(crate) codex_home: AbsolutePathBuf,
pub(crate) version: MemoryVersion,
}
impl MemoriesExtensionConfig {
fn from_config(config: &Config) -> Self {
Self {
enabled: config.features.enabled(Feature::MemoryTool) && config.memories.use_memories,
dedicated_tools: config.memories.dedicated_tools,
codex_home: config.codex_home.clone(),
version: config.memories.version,
}
}
}
impl ContextContributor for MemoriesExtension {
fn contribute_thread_context<'a>(
&'a self,
_session_store: &'a ExtensionData,
thread_store: &'a ExtensionData,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<PromptFragment>> + Send + 'a>> {
Box::pin(async move {
let Some(config) = thread_store.get::<MemoriesExtensionConfig>() else {
return Vec::new();
};
if !config.enabled {
return Vec::new();
}
let Some(instructions) =
build_memory_tool_developer_instructions(&config.codex_home, config.version).await
else {
return Vec::new();
};
let instructions = match config.version {
MemoryVersion::V1 => vec![instructions],
MemoryVersion::V2 => {
// Keep the complete summary while respecting each fragment's byte cap.
let mut remaining = instructions.as_str();
let mut fragments = Vec::new();
while !remaining.is_empty() {
let end = remaining.floor_char_boundary(remaining.len().min(8_900));
fragments.push(
MemoryContextFragment::ReadInstructions(remaining[..end].to_string())
.render()
.into_text()
.unwrap_or_default(),
);
remaining = &remaining[end..];
}
fragments
}
};
instructions
.into_iter()
.map(|instructions| {
PromptFragment::developer_policy(
instructions,
ContentItemKind(MemoryContextFragment::READ_INSTRUCTIONS_KIND.to_string()),
)
})
.collect()
})
}
}
impl ThreadLifecycleContributor<Config> for MemoriesExtension {
fn on_thread_start<'a>(
&'a self,
input: ThreadStartInput<'a, Config>,
) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input
.thread_store
.insert(MemoriesExtensionConfig::from_config(input.config));
})
}
}
impl ConfigContributor<Config> for MemoriesExtension {
fn on_config_changed(
&self,
_session_store: &ExtensionData,
thread_store: &ExtensionData,
_previous_config: &Config,
new_config: &Config,
) {
let mut config = MemoriesExtensionConfig::from_config(new_config);
if let Some(previous) = thread_store.get::<MemoriesExtensionConfig>() {
// The initial summary and retrieval tools must use the same namespace.
config.version = previous.version;
}
thread_store.insert(config);
}
}
impl ToolContributor for MemoriesExtension {
fn tools(
&self,
_session_store: &ExtensionData,
thread_store: &ExtensionData,
) -> Vec<
Arc<dyn for<'call> akode_extension_api::ToolExecutor<akode_extension_api::ToolCall<'call>>>,
> {
let Some(config) = thread_store.get::<MemoriesExtensionConfig>() else {
return Vec::new();
};
if !config.enabled || !config.dedicated_tools {
return Vec::new();
}
tools::memory_tools(
LocalMemoriesBackend::from_memory_root(
config
.codex_home
.join(config.version.directory_name())
.to_path_buf(),
),
self.metrics_client.clone(),
)
}
}
/// Installs the memories extension contributors into the extension registry.
pub fn install(
registry: &mut ExtensionRegistryBuilder<Config>,
metrics_client: Option<MetricsClient>,
) {
let extension = Arc::new(MemoriesExtension::new(metrics_client));
registry.thread_lifecycle_contributor(extension.clone());
registry.config_contributor(extension.clone());
registry.prompt_contributor(extension.clone());
registry.tool_contributor(extension);
}

View File

@@ -0,0 +1,25 @@
mod backend;
mod extension;
mod local;
mod metrics;
mod prompts;
mod schema;
mod tools;
pub use extension::install;
pub(crate) const DEFAULT_LIST_MAX_RESULTS: usize = 2_000;
pub(crate) const MAX_LIST_RESULTS: usize = 2_000;
pub(crate) const DEFAULT_SEARCH_MAX_RESULTS: usize = 200;
pub(crate) const MAX_SEARCH_RESULTS: usize = 200;
pub(crate) const DEFAULT_READ_MAX_TOKENS: usize = 20_000;
pub(crate) const MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_SUMMARY_TOKEN_LIMIT: usize = 2_500;
pub(crate) const MEMORY_TOOLS_NAMESPACE: &str = "memories";
pub(crate) const ADD_AD_HOC_NOTE_TOOL_NAME: &str = "add_ad_hoc_note";
pub(crate) const LIST_TOOL_NAME: &str = "list";
pub(crate) const READ_TOOL_NAME: &str = "read";
pub(crate) const SEARCH_TOOL_NAME: &str = "search";
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,123 @@
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use crate::backend::AddAdHocMemoryNoteRequest;
use crate::backend::AddAdHocMemoryNoteResponse;
use crate::backend::ListMemoriesRequest;
use crate::backend::ListMemoriesResponse;
use crate::backend::MemoriesBackend;
use crate::backend::MemoriesBackendError;
use crate::backend::ReadMemoryRequest;
use crate::backend::ReadMemoryResponse;
use crate::backend::SearchMemoriesRequest;
use crate::backend::SearchMemoriesResponse;
mod ad_hoc_note;
mod list;
mod path;
mod read;
mod search;
#[derive(Debug, Clone)]
pub(crate) struct LocalMemoriesBackend {
root: PathBuf,
}
impl LocalMemoriesBackend {
pub(crate) fn from_memory_root(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
async fn resolve_scoped_path(
&self,
relative_path: Option<&str>,
) -> Result<PathBuf, MemoriesBackendError> {
let Some(relative_path) = relative_path else {
return Ok(self.root.clone());
};
let relative = Path::new(relative_path);
if relative.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) {
return Err(MemoriesBackendError::invalid_path(
relative_path,
"must stay within the memories root",
));
}
if relative.components().any(path::is_hidden_component) {
return Err(MemoriesBackendError::NotFound {
path: relative_path.to_string(),
});
}
let components = relative.components().collect::<Vec<_>>();
let mut scoped_path = self.root.clone();
for (idx, component) in components.iter().enumerate() {
scoped_path.push(component.as_os_str());
let Some(metadata) = Self::metadata_or_none(&scoped_path).await? else {
for remaining_component in components.iter().skip(idx + 1) {
scoped_path.push(remaining_component.as_os_str());
}
return Ok(scoped_path);
};
path::reject_symlink(
&path::display_relative_path(&self.root, &scoped_path),
&metadata,
)?;
if idx + 1 < components.len() && !metadata.is_dir() {
return Err(MemoriesBackendError::invalid_path(
relative_path,
"traverses through a non-directory path component",
));
}
}
Ok(scoped_path)
}
async fn metadata_or_none(
path: &Path,
) -> Result<Option<std::fs::Metadata>, MemoriesBackendError> {
match tokio::fs::symlink_metadata(path).await {
Ok(metadata) => Ok(Some(metadata)),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err.into()),
}
}
}
impl MemoriesBackend for LocalMemoriesBackend {
async fn add_ad_hoc_note(
&self,
request: AddAdHocMemoryNoteRequest,
) -> Result<AddAdHocMemoryNoteResponse, MemoriesBackendError> {
ad_hoc_note::add_ad_hoc_note(self, request).await
}
async fn list(
&self,
request: ListMemoriesRequest,
) -> Result<ListMemoriesResponse, MemoriesBackendError> {
list::list(self, request).await
}
async fn read(
&self,
request: ReadMemoryRequest,
) -> Result<ReadMemoryResponse, MemoriesBackendError> {
read::read(self, request).await
}
async fn search(
&self,
request: SearchMemoriesRequest,
) -> Result<SearchMemoriesResponse, MemoriesBackendError> {
search::search(self, request).await
}
}

View File

@@ -0,0 +1,147 @@
use std::fs::OpenOptions;
use std::io::Write;
use std::path::Path;
use crate::backend::AddAdHocMemoryNoteRequest;
use crate::backend::AddAdHocMemoryNoteResponse;
use crate::backend::MemoriesBackendError;
use super::LocalMemoriesBackend;
use super::path::reject_symlink;
const AD_HOC_NOTES_DIR: &[&str] = &["extensions", "ad_hoc", "notes"];
const AD_HOC_NOTE_FILENAME_MAX_BYTES: usize = 128;
const AD_HOC_NOTE_SLUG_MAX_BYTES: usize = 80;
const TIMESTAMP_PREFIX_LEN: usize = "YYYY-MM-DDTHH-MM-SS-".len();
pub(super) async fn add_ad_hoc_note(
backend: &LocalMemoriesBackend,
request: AddAdHocMemoryNoteRequest,
) -> Result<AddAdHocMemoryNoteResponse, MemoriesBackendError> {
validate_filename(&request.filename)?;
if request.note.trim().is_empty() {
return Err(MemoriesBackendError::EmptyAdHocNote);
}
let notes_dir = ensure_notes_dir(backend).await?;
let path = notes_dir.join(&request.filename);
let mut file = match OpenOptions::new().write(true).create_new(true).open(&path) {
Ok(file) => file,
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
return Err(MemoriesBackendError::AdHocNoteAlreadyExists {
filename: request.filename,
});
}
Err(err) => return Err(err.into()),
};
file.write_all(request.note.as_bytes())?;
Ok(AddAdHocMemoryNoteResponse {})
}
async fn ensure_notes_dir(
backend: &LocalMemoriesBackend,
) -> Result<std::path::PathBuf, MemoriesBackendError> {
ensure_directory(&backend.root).await?;
let mut path = backend.root.clone();
for component in AD_HOC_NOTES_DIR {
path.push(component);
ensure_directory(&path).await?;
}
Ok(path)
}
async fn ensure_directory(path: &Path) -> Result<(), MemoriesBackendError> {
match LocalMemoriesBackend::metadata_or_none(path).await? {
Some(metadata) => {
reject_symlink(&path.display().to_string(), &metadata)?;
if metadata.is_dir() {
return Ok(());
}
return Err(MemoriesBackendError::invalid_path(
path.display().to_string(),
"must be a directory",
));
}
None => tokio::fs::create_dir(path).await?,
}
let Some(metadata) = LocalMemoriesBackend::metadata_or_none(path).await? else {
return Err(MemoriesBackendError::NotFound {
path: path.display().to_string(),
});
};
reject_symlink(&path.display().to_string(), &metadata)?;
if !metadata.is_dir() {
return Err(MemoriesBackendError::invalid_path(
path.display().to_string(),
"must be a directory",
));
}
Ok(())
}
fn validate_filename(filename: &str) -> Result<(), MemoriesBackendError> {
if filename.len() > AD_HOC_NOTE_FILENAME_MAX_BYTES {
return Err(MemoriesBackendError::invalid_filename(
filename,
"must be at most 128 bytes",
));
}
let Some(stem) = filename.strip_suffix(".md") else {
return Err(MemoriesBackendError::invalid_filename(
filename,
"must end with .md",
));
};
let Some(slug) = stem.get(TIMESTAMP_PREFIX_LEN..) else {
return Err(MemoriesBackendError::invalid_filename(
filename,
"must use YYYY-MM-DDTHH-MM-SS-<slug>.md",
));
};
if !has_valid_timestamp_prefix(stem) {
return Err(MemoriesBackendError::invalid_filename(
filename,
"must use YYYY-MM-DDTHH-MM-SS-<slug>.md",
));
}
if slug.is_empty() || slug.len() > AD_HOC_NOTE_SLUG_MAX_BYTES {
return Err(MemoriesBackendError::invalid_filename(
filename,
"slug must be 1 to 80 bytes",
));
}
if !slug
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
{
return Err(MemoriesBackendError::invalid_filename(
filename,
"slug must contain only lowercase ASCII letters, digits, or hyphens",
));
}
Ok(())
}
fn has_valid_timestamp_prefix(stem: &str) -> bool {
let bytes = stem.as_bytes();
bytes.len() > TIMESTAMP_PREFIX_LEN
&& bytes[4] == b'-'
&& bytes[7] == b'-'
&& bytes[10] == b'T'
&& bytes[13] == b'-'
&& bytes[16] == b'-'
&& bytes[19] == b'-'
&& are_digits(&bytes[0..4])
&& are_digits(&bytes[5..7])
&& are_digits(&bytes[8..10])
&& are_digits(&bytes[11..13])
&& are_digits(&bytes[14..16])
&& are_digits(&bytes[17..19])
}
fn are_digits(bytes: &[u8]) -> bool {
bytes.iter().all(u8::is_ascii_digit)
}

View File

@@ -0,0 +1,77 @@
use crate::MAX_LIST_RESULTS;
use crate::backend::ListMemoriesRequest;
use crate::backend::ListMemoriesResponse;
use crate::backend::MemoriesBackendError;
use crate::backend::MemoryEntry;
use crate::backend::MemoryEntryType;
use super::LocalMemoriesBackend;
use super::path::display_relative_path;
use super::path::is_hidden_path;
use super::path::read_sorted_dir_entries;
use super::path::reject_symlink;
pub(super) async fn list(
backend: &LocalMemoriesBackend,
request: ListMemoriesRequest,
) -> Result<ListMemoriesResponse, MemoriesBackendError> {
let max_results = request.max_results.min(MAX_LIST_RESULTS);
let start = backend.resolve_scoped_path(request.path.as_deref()).await?;
let start_index = match request.cursor.as_deref() {
Some(cursor) => cursor.parse::<usize>().map_err(|_| {
MemoriesBackendError::invalid_cursor(cursor, "must be a non-negative integer")
})?,
None => 0,
};
let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&start).await? else {
return Err(MemoriesBackendError::NotFound {
path: request.path.unwrap_or_default(),
});
};
reject_symlink(&display_relative_path(&backend.root, &start), &metadata)?;
let mut entries = if metadata.is_file() {
vec![MemoryEntry {
path: display_relative_path(&backend.root, &start),
entry_type: MemoryEntryType::File,
}]
} else if metadata.is_dir() {
let mut entries = Vec::new();
for (path, file_type) in read_sorted_dir_entries(&start).await? {
if is_hidden_path(&path) || file_type.is_symlink() {
continue;
}
let entry_type = if file_type.is_dir() {
MemoryEntryType::Directory
} else if file_type.is_file() {
MemoryEntryType::File
} else {
continue;
};
entries.push(MemoryEntry {
path: display_relative_path(&backend.root, &path),
entry_type,
});
}
entries
} else {
Vec::new()
};
if start_index > entries.len() {
return Err(MemoriesBackendError::invalid_cursor(
start_index.to_string(),
"exceeds result count",
));
}
let end_index = start_index.saturating_add(max_results).min(entries.len());
let next_cursor = (end_index < entries.len()).then(|| end_index.to_string());
let truncated = next_cursor.is_some();
Ok(ListMemoriesResponse {
path: request.path,
entries: entries.drain(start_index..end_index).collect(),
next_cursor,
truncated,
})
}

View File

@@ -0,0 +1,65 @@
use std::fs::FileType;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use crate::backend::MemoriesBackendError;
/// Returns lexically sorted paths and their cached, non-symlink-following file types.
///
/// Missing directories and entries that disappear during iteration are ignored.
pub(super) async fn read_sorted_dir_entries(
dir_path: &Path,
) -> Result<Vec<(PathBuf, FileType)>, MemoriesBackendError> {
let mut dir = match tokio::fs::read_dir(dir_path).await {
Ok(dir) => dir,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(err) => return Err(err.into()),
};
let mut entries = Vec::new();
while let Some(entry) = dir.next_entry().await? {
let file_type = match entry.file_type().await {
Ok(file_type) => file_type,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
Err(err) => return Err(err.into()),
};
entries.push((entry.path(), file_type));
}
entries.sort_by(|(left, _), (right, _)| left.cmp(right));
Ok(entries)
}
pub(super) fn reject_symlink(
path: &str,
metadata: &std::fs::Metadata,
) -> Result<(), MemoriesBackendError> {
if metadata.file_type().is_symlink() {
return Err(MemoriesBackendError::invalid_path(
path,
"must not be a symlink",
));
}
Ok(())
}
pub(super) fn is_hidden_component(component: Component<'_>) -> bool {
matches!(
component,
Component::Normal(name) if name.to_string_lossy().starts_with('.')
)
}
pub(super) fn is_hidden_path(path: &Path) -> bool {
path.file_name()
.is_some_and(|name| name.to_string_lossy().starts_with('.'))
}
pub(super) fn display_relative_path(root: &Path, path: &Path) -> String {
path.strip_prefix(root)
.unwrap_or(path)
.components()
.map(|component| component.as_os_str().to_string_lossy())
.filter(|component| !component.is_empty())
.collect::<Vec<_>>()
.join("/")
}

View File

@@ -0,0 +1,90 @@
use akode_utils_output_truncation::TruncationPolicy;
use akode_utils_output_truncation::truncate_text;
use crate::DEFAULT_READ_MAX_TOKENS;
use crate::backend::MemoriesBackendError;
use crate::backend::ReadMemoryRequest;
use crate::backend::ReadMemoryResponse;
use super::LocalMemoriesBackend;
use super::path::reject_symlink;
pub(super) async fn read(
backend: &LocalMemoriesBackend,
request: ReadMemoryRequest,
) -> Result<ReadMemoryResponse, MemoriesBackendError> {
if request.line_offset == 0 {
return Err(MemoriesBackendError::InvalidLineOffset);
}
if request.max_lines == Some(0) {
return Err(MemoriesBackendError::InvalidMaxLines);
}
let path = backend
.resolve_scoped_path(Some(request.path.as_str()))
.await?;
let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&path).await? else {
return Err(MemoriesBackendError::NotFound { path: request.path });
};
reject_symlink(&request.path, &metadata)?;
if !metadata.is_file() {
return Err(MemoriesBackendError::NotFile { path: request.path });
}
let original_content = tokio::fs::read_to_string(&path).await?;
let start_byte = line_start_byte_offset(&original_content, request.line_offset)?;
let end_byte = line_end_byte_offset(&original_content, start_byte, request.max_lines);
let content_from_offset = &original_content[start_byte..end_byte];
let max_tokens = if request.max_tokens == 0 {
DEFAULT_READ_MAX_TOKENS
} else {
request.max_tokens
};
let content = truncate_text(content_from_offset, TruncationPolicy::Tokens(max_tokens));
let truncated = end_byte < original_content.len() || content != content_from_offset;
Ok(ReadMemoryResponse {
path: request.path,
start_line_number: request.line_offset,
content,
truncated,
})
}
fn line_start_byte_offset(
content: &str,
line_offset: usize,
) -> Result<usize, MemoriesBackendError> {
if line_offset == 1 {
return Ok(0);
}
let mut current_line = 1;
for (idx, ch) in content.char_indices() {
if ch == '\n' {
current_line += 1;
if current_line == line_offset {
return Ok(idx + 1);
}
}
}
Err(MemoriesBackendError::LineOffsetExceedsFileLength)
}
fn line_end_byte_offset(content: &str, start_byte: usize, max_lines: Option<usize>) -> usize {
let Some(max_lines) = max_lines else {
return content.len();
};
let mut lines_seen = 1;
for (relative_idx, ch) in content[start_byte..].char_indices() {
if ch == '\n' {
if lines_seen == max_lines {
return start_byte + relative_idx + 1;
}
lines_seen += 1;
}
}
content.len()
}

View File

@@ -0,0 +1,336 @@
use std::borrow::Cow;
use std::path::Path;
use crate::MAX_SEARCH_RESULTS;
use crate::backend::MemoriesBackendError;
use crate::backend::MemorySearchMatch;
use crate::backend::SearchMatchMode;
use crate::backend::SearchMemoriesRequest;
use crate::backend::SearchMemoriesResponse;
use super::LocalMemoriesBackend;
use super::path::display_relative_path;
use super::path::is_hidden_path;
use super::path::read_sorted_dir_entries;
use super::path::reject_symlink;
pub(super) async fn search(
backend: &LocalMemoriesBackend,
request: SearchMemoriesRequest,
) -> Result<SearchMemoriesResponse, MemoriesBackendError> {
let queries = request
.queries
.iter()
.map(|query| query.trim().to_string())
.collect::<Vec<_>>();
if queries.is_empty() || queries.iter().any(std::string::String::is_empty) {
return Err(MemoriesBackendError::EmptyQuery);
}
if matches!(
request.match_mode,
SearchMatchMode::AllWithinLines { line_count: 0 }
) {
return Err(MemoriesBackendError::InvalidMatchWindow);
}
let max_results = request.max_results.min(MAX_SEARCH_RESULTS);
let start = backend.resolve_scoped_path(request.path.as_deref()).await?;
let start_index = match request.cursor.as_deref() {
Some(cursor) => cursor.parse::<usize>().map_err(|_| {
MemoriesBackendError::invalid_cursor(cursor, "must be a non-negative integer")
})?,
None => 0,
};
let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&start).await? else {
return Err(MemoriesBackendError::NotFound {
path: request.path.unwrap_or_default(),
});
};
reject_symlink(&display_relative_path(&backend.root, &start), &metadata)?;
let matcher = SearchMatcher::new(
queries.clone(),
request.match_mode.clone(),
request.case_sensitive,
request.normalized,
)?;
let mut matches = Vec::new();
search_entries(
&backend.root,
&start,
&metadata,
&matcher,
request.context_lines,
&mut matches,
)
.await?;
matches.sort_by(|left, right| {
left.path
.cmp(&right.path)
.then(left.match_line_number.cmp(&right.match_line_number))
});
if start_index > matches.len() {
return Err(MemoriesBackendError::invalid_cursor(
start_index.to_string(),
"exceeds result count",
));
}
let end_index = start_index.saturating_add(max_results).min(matches.len());
let next_cursor = (end_index < matches.len()).then(|| end_index.to_string());
let truncated = next_cursor.is_some();
Ok(SearchMemoriesResponse {
queries,
match_mode: request.match_mode,
path: request.path,
matches: matches.drain(start_index..end_index).collect(),
next_cursor,
truncated,
})
}
async fn search_entries(
root: &Path,
current: &Path,
current_metadata: &std::fs::Metadata,
matcher: &SearchMatcher,
context_lines: usize,
matches: &mut Vec<MemorySearchMatch>,
) -> Result<(), MemoriesBackendError> {
if current_metadata.is_file() {
search_file(root, current, matcher, context_lines, matches).await?;
return Ok(());
}
if !current_metadata.is_dir() {
return Ok(());
}
let mut pending = vec![current.to_path_buf()];
while let Some(dir_path) = pending.pop() {
for (path, _) in read_sorted_dir_entries(&dir_path).await? {
if is_hidden_path(&path) {
continue;
}
let Some(metadata) = LocalMemoriesBackend::metadata_or_none(&path).await? else {
continue;
};
if metadata.file_type().is_symlink() {
continue;
}
if metadata.is_dir() {
pending.push(path);
} else if metadata.is_file() {
search_file(root, &path, matcher, context_lines, matches).await?;
}
}
}
Ok(())
}
async fn search_file(
root: &Path,
path: &Path,
matcher: &SearchMatcher,
context_lines: usize,
matches: &mut Vec<MemorySearchMatch>,
) -> Result<(), MemoriesBackendError> {
let content = match tokio::fs::read_to_string(path).await {
Ok(content) => content,
Err(err) if err.kind() == std::io::ErrorKind::InvalidData => return Ok(()),
Err(err) => return Err(err.into()),
};
let lines = content.lines().collect::<Vec<_>>();
let line_matches = lines
.iter()
.map(|line| matcher.matched_query_flags(line))
.collect::<Vec<_>>();
match &matcher.match_mode {
SearchMatchMode::Any => {
for (idx, matched_query_flags) in line_matches.iter().enumerate() {
if matched_query_flags.iter().any(|matched| *matched) {
matches.push(build_search_match(
root,
path,
&lines,
idx,
idx,
context_lines,
matcher.matched_queries(matched_query_flags),
));
}
}
}
SearchMatchMode::AllOnSameLine => {
for (idx, matched_query_flags) in line_matches.iter().enumerate() {
if matched_query_flags.iter().all(|matched| *matched) {
matches.push(build_search_match(
root,
path,
&lines,
idx,
idx,
context_lines,
matcher.matched_queries(matched_query_flags),
));
}
}
}
SearchMatchMode::AllWithinLines { line_count } => {
let mut windows = Vec::new();
for start_index in 0..lines.len() {
if !line_matches[start_index].iter().any(|matched| *matched) {
continue;
}
let last_allowed_index = start_index
.saturating_add(line_count.saturating_sub(1))
.min(lines.len().saturating_sub(1));
let mut matched_query_flags = vec![false; matcher.queries.len()];
for (end_index, line_match_flags) in line_matches
.iter()
.enumerate()
.take(last_allowed_index + 1)
.skip(start_index)
{
for (idx, matched) in line_match_flags.iter().enumerate() {
matched_query_flags[idx] |= matched;
}
if matched_query_flags.iter().all(|matched| *matched) {
windows.push((start_index, end_index, matched_query_flags));
break;
}
}
}
for (idx, (start_index, end_index, matched_query_flags)) in windows.iter().enumerate() {
let strictly_contains_another_window = windows.iter().enumerate().any(
|(other_idx, (other_start_index, other_end_index, _))| {
idx != other_idx
&& start_index <= other_start_index
&& end_index >= other_end_index
&& (start_index != other_start_index || end_index != other_end_index)
},
);
if strictly_contains_another_window {
continue;
}
matches.push(build_search_match(
root,
path,
&lines,
*start_index,
*end_index,
context_lines,
matcher.matched_queries(matched_query_flags),
));
}
}
}
Ok(())
}
fn build_search_match(
root: &Path,
path: &Path,
lines: &[&str],
match_start_index: usize,
match_end_index: usize,
context_lines: usize,
matched_queries: Vec<String>,
) -> MemorySearchMatch {
let content_start_index = match_start_index.saturating_sub(context_lines);
let content_end_index = match_end_index
.saturating_add(context_lines)
.saturating_add(1)
.min(lines.len());
MemorySearchMatch {
path: display_relative_path(root, path),
match_line_number: match_start_index + 1,
content_start_line_number: content_start_index + 1,
content: lines[content_start_index..content_end_index].join("\n"),
matched_queries,
}
}
struct SearchMatcher {
queries: Vec<String>,
prepared_queries: Vec<String>,
comparison: SearchComparison,
match_mode: SearchMatchMode,
}
impl SearchMatcher {
fn new(
queries: Vec<String>,
match_mode: SearchMatchMode,
case_sensitive: bool,
normalized: bool,
) -> Result<Self, MemoriesBackendError> {
let comparison = SearchComparison::new(case_sensitive, normalized);
let prepared_queries = queries
.iter()
.map(|query| comparison.prepare(query))
.map(Cow::into_owned)
.collect::<Vec<_>>();
if prepared_queries.iter().any(std::string::String::is_empty) {
return Err(MemoriesBackendError::EmptyQuery);
}
Ok(Self {
queries,
prepared_queries,
comparison,
match_mode,
})
}
fn matched_query_flags(&self, line: &str) -> Vec<bool> {
let line = self.comparison.prepare(line);
self.prepared_queries
.iter()
.map(|query| line.as_ref().contains(query))
.collect()
}
fn matched_queries(&self, matched_query_flags: &[bool]) -> Vec<String> {
self.queries
.iter()
.zip(matched_query_flags)
.filter_map(|(query, matched)| matched.then_some(query.clone()))
.collect()
}
}
#[derive(Clone, Copy)]
struct SearchComparison {
case_sensitive: bool,
normalized: bool,
}
impl SearchComparison {
fn new(case_sensitive: bool, normalized: bool) -> Self {
Self {
case_sensitive,
normalized,
}
}
fn prepare<'a>(self, value: &'a str) -> Cow<'a, str> {
if self.case_sensitive && !self.normalized {
return Cow::Borrowed(value);
}
let value = if self.case_sensitive {
Cow::Borrowed(value)
} else {
Cow::Owned(value.to_lowercase())
};
if !self.normalized {
return value;
}
Cow::Owned(
value
.chars()
.filter(|ch| ch.is_alphanumeric())
.collect::<String>(),
)
}
}

View File

@@ -0,0 +1,69 @@
use akode_otel::MetricsClient;
use crate::MEMORY_TOOLS_NAMESPACE;
pub(crate) const MEMORIES_TOOL_CALL_METRIC: &str = "codex.memories.tool.call";
pub(crate) fn record_tool_call(
metrics_client: Option<&MetricsClient>,
operation: &str,
scope: &str,
success: bool,
truncated: &str,
) {
let Some(metrics_client) = metrics_client else {
return;
};
let tool = format!("{MEMORY_TOOLS_NAMESPACE}/{operation}");
let _ = metrics_client.counter(
MEMORIES_TOOL_CALL_METRIC,
/*inc*/ 1,
&[
("tool", tool.as_str()),
("operation", operation),
("scope", scope),
("status", status_tag(success)),
("truncated", truncated),
],
);
}
pub(crate) fn scope_from_path(path: &str) -> &'static str {
let path = path.trim_matches('/');
let path = path.strip_prefix("./").unwrap_or(path);
if path.is_empty() {
"root"
} else if path == "MEMORY.md" {
"memory_md"
} else if path == "memory_summary.md" {
"memory_summary"
} else if path == "raw_memories.md" {
"raw_memories"
} else if path == "rollout_summaries" || path.starts_with("rollout_summaries/") {
"rollout_summaries"
} else if path == "skills" || path.starts_with("skills/") {
"skills"
} else if path == "extensions/ad_hoc/notes" || path.starts_with("extensions/ad_hoc/notes/") {
"ad_hoc_notes"
} else {
"other"
}
}
pub(crate) fn scope_from_optional_path(path: Option<&str>, default: &'static str) -> &'static str {
path.map_or(default, scope_from_path)
}
pub(crate) fn truncated_tag(truncated: Option<bool>) -> &'static str {
match truncated {
Some(true) => "true",
Some(false) => "false",
None => "unknown",
}
}
fn status_tag(success: bool) -> &'static str {
if success { "succeeded" } else { "failed" }
}

View File

@@ -0,0 +1,68 @@
use crate::MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_SUMMARY_TOKEN_LIMIT;
use akode_protocol::MemoryVersion;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_output_truncation::TruncationPolicy;
use akode_utils_output_truncation::truncate_text;
use akode_utils_template::Template;
use std::sync::LazyLock;
use tokio::fs;
static MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
parse_embedded_template(
include_str!("../templates/memories/read_path.md"),
"memories/read_path.md",
)
});
static MEMORY_V2_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
parse_embedded_template(
include_str!("../templates/memories/read_path_v2.md"),
"memories/read_path_v2.md",
)
});
fn parse_embedded_template(source: &'static str, template_name: &str) -> Template {
match Template::parse(source) {
Ok(template) => template,
Err(err) => panic!("embedded template {template_name} is invalid: {err}"),
}
}
/// Build the memory read-path prompt that is added to developer instructions.
///
/// Large `memory_summary.md` files are truncated at
/// [MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_SUMMARY_TOKEN_LIMIT].
pub(crate) async fn build_memory_tool_developer_instructions(
codex_home: &AbsolutePathBuf,
version: MemoryVersion,
) -> Option<String> {
let base_path = codex_home.join(version.directory_name());
let memory_summary_path = base_path.join("memory_summary.md");
let memory_summary = fs::read_to_string(&memory_summary_path)
.await
.ok()?
.trim()
.to_string();
let memory_summary = truncate_text(
&memory_summary,
TruncationPolicy::Tokens(MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_SUMMARY_TOKEN_LIMIT),
);
if memory_summary.is_empty() {
return None;
}
let base_path = base_path.display().to_string();
let template = match version {
MemoryVersion::V1 => &MEMORY_TOOL_DEVELOPER_INSTRUCTIONS_TEMPLATE,
MemoryVersion::V2 => &MEMORY_V2_TEMPLATE,
};
template
.render([
("base_path", base_path.as_str()),
("memory_summary", memory_summary.as_str()),
])
.ok()
}
#[cfg(test)]
#[path = "prompts_tests.rs"]
mod tests;

View File

@@ -0,0 +1,66 @@
use super::*;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
use tokio::fs as tokio_fs;
#[tokio::test]
async fn build_memory_tool_developer_instructions_renders_embedded_template() {
let temp = tempdir().unwrap();
let codex_home = AbsolutePathBuf::from_absolute_path(temp.path()).unwrap();
let memories_dir = codex_home.join("memories");
tokio_fs::create_dir_all(&memories_dir).await.unwrap();
tokio_fs::write(
memories_dir.join("memory_summary.md"),
"Short memory summary for tests.",
)
.await
.unwrap();
let instructions = build_memory_tool_developer_instructions(&codex_home, MemoryVersion::V1)
.await
.unwrap();
assert!(instructions.contains(&format!(
"- {}/memory_summary.md (already provided below; do NOT open again)",
memories_dir.display()
)));
assert!(instructions.contains("Short memory summary for tests."));
assert_eq!(
instructions
.matches("========= MEMORY_SUMMARY BEGINS =========")
.count(),
1
);
}
#[tokio::test]
async fn v2_reads_only_its_own_summary_without_falling_back_to_v1()
-> Result<(), Box<dyn std::error::Error>> {
let home = tempdir()?;
let codex_home = AbsolutePathBuf::from_absolute_path(home.path())?;
let v1 = codex_home.join("memories");
let v2 = codex_home.join("memories_v2");
tokio_fs::create_dir_all(&v1).await?;
tokio_fs::write(v1.join("memory_summary.md"), "v1\nlegacy content").await?;
assert_eq!(
build_memory_tool_developer_instructions(&codex_home, MemoryVersion::V2).await,
None
);
tokio_fs::create_dir_all(&v2).await?;
tokio_fs::write(v2.join("memory_summary.md"), "v1\nnew pipeline content").await?;
let instructions = build_memory_tool_developer_instructions(&codex_home, MemoryVersion::V2)
.await
.expect("v2 instructions");
assert!(instructions.contains("new pipeline content"));
assert!(!instructions.contains("legacy content"));
assert!(instructions.contains("do not retrieve history speculatively"));
assert!(instructions.contains(&format!("{}/rollout_summaries/", v2.display())));
assert!(
build_memory_tool_developer_instructions(&codex_home, MemoryVersion::V1)
.await
.expect("v1 instructions")
.contains("legacy content")
);
Ok(())
}

View File

@@ -0,0 +1,42 @@
use schemars::JsonSchema;
use schemars::r#gen::SchemaSettings;
use serde_json::Map;
use serde_json::Value;
pub(crate) fn input_schema_for<T: JsonSchema>() -> Value {
schema_for::<T>(/*option_add_null_type*/ false)
}
pub(crate) fn output_schema_for<T: JsonSchema>() -> Value {
schema_for::<T>(/*option_add_null_type*/ true)
}
fn schema_for<T: JsonSchema>(option_add_null_type: bool) -> Value {
let schema = SchemaSettings::draft2019_09()
.with(|settings| {
settings.inline_subschemas = true;
settings.option_add_null_type = option_add_null_type;
})
.into_generator()
.into_root_schema_for::<T>();
let schema_value = serde_json::to_value(schema)
.unwrap_or_else(|err| panic!("generated tool schema should serialize: {err}"));
let Value::Object(mut schema_object) = schema_value else {
unreachable!("root tool schema must be an object");
};
let mut tool_schema = Map::new();
for key in [
"properties",
"required",
"type",
"additionalProperties",
"$defs",
"definitions",
] {
if let Some(value) = schema_object.remove(key) {
tool_schema.insert(key.to_string(), value);
}
}
Value::Object(tool_schema)
}

View File

@@ -0,0 +1,617 @@
use std::path::Path;
use std::sync::Arc;
use akode_extension_api::ContextContributor;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::NoopTurnItemEmitter;
use akode_extension_api::PromptSlot;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolCallSource;
use akode_extension_api::ToolContributor;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolPayload;
use akode_protocol::models::ContentItem;
use akode_tools::ToolOutput;
use akode_utils_absolute_path::test_support::PathBufExt;
use akode_utils_absolute_path::test_support::PathExt;
use akode_utils_absolute_path::test_support::test_path_buf;
use akode_utils_output_truncation::TruncationPolicy;
use pretty_assertions::assert_eq;
use serde_json::json;
use crate::backend::ListMemoriesRequest;
use crate::backend::ListMemoriesResponse;
use crate::backend::MemoriesBackend;
use crate::backend::MemoryEntry;
use crate::backend::MemoryEntryType;
use crate::backend::SearchMatchMode;
use crate::backend::SearchMemoriesRequest;
use crate::extension::MemoriesExtension;
use crate::extension::MemoriesExtensionConfig;
use crate::local::LocalMemoriesBackend;
#[test]
fn memory_tool_namespace_matches_responses_api_identifier() {
assert!(!crate::MEMORY_TOOLS_NAMESPACE.is_empty());
assert!(
crate::MEMORY_TOOLS_NAMESPACE
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
);
}
#[test]
fn tools_are_not_contributed_without_thread_config() {
let extension = MemoriesExtension::default();
assert!(
extension
.tools(
&ExtensionData::new("session"),
&ExtensionData::new("thread"),
)
.is_empty()
);
}
#[test]
fn tools_are_not_contributed_when_disabled() {
let extension = MemoriesExtension::default();
let thread_store = ExtensionData::new("thread");
thread_store.insert(MemoriesExtensionConfig {
version: akode_protocol::MemoryVersion::V1,
enabled: false,
dedicated_tools: true,
codex_home: test_path_buf("/tmp/codex-home").abs(),
});
assert!(
extension
.tools(&ExtensionData::new("session"), &thread_store)
.is_empty()
);
}
#[test]
fn tools_are_not_contributed_when_dedicated_tools_disabled() {
let extension = MemoriesExtension::default();
let thread_store = ExtensionData::new("thread");
thread_store.insert(MemoriesExtensionConfig {
version: akode_protocol::MemoryVersion::V1,
enabled: true,
dedicated_tools: false,
codex_home: test_path_buf("/tmp/codex-home").abs(),
});
assert!(
extension
.tools(&ExtensionData::new("session"), &thread_store)
.is_empty()
);
}
#[test]
fn tools_are_contributed_when_enabled_with_dedicated_tools() {
let extension = MemoriesExtension::default();
let thread_store = ExtensionData::new("thread");
thread_store.insert(MemoriesExtensionConfig {
version: akode_protocol::MemoryVersion::V1,
enabled: true,
dedicated_tools: true,
codex_home: test_path_buf("/tmp/codex-home").abs(),
});
let tool_names = extension
.tools(&ExtensionData::new("session"), &thread_store)
.into_iter()
.map(|tool| tool.tool_name())
.collect::<Vec<_>>();
assert_eq!(
tool_names,
vec![
memory_tool_name(crate::ADD_AD_HOC_NOTE_TOOL_NAME),
memory_tool_name(crate::LIST_TOOL_NAME),
memory_tool_name(crate::READ_TOOL_NAME),
memory_tool_name(crate::SEARCH_TOOL_NAME),
]
);
}
#[test]
fn install_registers_dedicated_tool_contributor() {
let mut builder = ExtensionRegistryBuilder::<akode_core::config::Config>::new();
crate::install(&mut builder, /*metrics_client*/ None);
let registry = builder.build();
let thread_store = ExtensionData::new("thread");
thread_store.insert(MemoriesExtensionConfig {
version: akode_protocol::MemoryVersion::V1,
enabled: true,
dedicated_tools: true,
codex_home: test_path_buf("/tmp/codex-home").abs(),
});
let tool_names = registry
.tool_contributors()
.iter()
.flat_map(|contributor| contributor.tools(&ExtensionData::new("session"), &thread_store))
.map(|tool| tool.tool_name())
.collect::<Vec<_>>();
assert_eq!(
tool_names,
vec![
memory_tool_name(crate::ADD_AD_HOC_NOTE_TOOL_NAME),
memory_tool_name(crate::LIST_TOOL_NAME),
memory_tool_name(crate::READ_TOOL_NAME),
memory_tool_name(crate::SEARCH_TOOL_NAME),
]
);
}
#[test]
fn ad_hoc_tool_definition_includes_filename_contract() {
let tool = memory_tool(
Path::new("/tmp/codex-home/memories"),
crate::ADD_AD_HOC_NOTE_TOOL_NAME,
);
let spec = serde_json::to_value(tool.spec()).expect("serialize tool spec");
let filename = spec
.pointer("/tools/0/parameters/properties/filename")
.expect("filename parameter should be in tool schema");
assert_eq!(filename.pointer("/type"), Some(&json!("string")));
assert!(
filename
.pointer("/description")
.and_then(serde_json::Value::as_str)
.is_some_and(|description| description.contains("YYYY-MM-DDTHH-MM-SS-<slug>.md"))
);
}
#[tokio::test]
async fn prompt_contribution_uses_memory_summary_when_enabled() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memories_dir = tempdir.path().join("memories");
tokio::fs::create_dir_all(&memories_dir)
.await
.expect("create memories dir");
tokio::fs::write(
memories_dir.join("memory_summary.md"),
"Remember repository-specific implementation preferences.",
)
.await
.expect("write memory summary");
let extension = MemoriesExtension::default();
let thread_store = ExtensionData::new("thread");
thread_store.insert(MemoriesExtensionConfig {
version: akode_protocol::MemoryVersion::V1,
enabled: true,
dedicated_tools: false,
codex_home: tempdir.path().abs(),
});
let fragments = extension
.contribute_thread_context(&ExtensionData::new("session"), &thread_store)
.await;
assert_eq!(fragments.len(), 1);
assert_eq!(fragments[0].slot(), PromptSlot::DeveloperPolicy);
assert!(matches!(
fragments[0].content(),
ContentItem::InputText { text }
if text.contains("Remember repository-specific implementation preferences.")
));
}
#[tokio::test]
async fn add_ad_hoc_note_tool_creates_note_file() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
let tool = memory_tool(&memory_root, crate::ADD_AD_HOC_NOTE_TOOL_NAME);
let payload = ToolPayload::Function {
arguments: json!({
"filename": "2026-05-26T13-42-08-remember-review-style.md",
"note": "Remember to keep PR review comments concise.",
})
.to_string(),
};
let output = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-1".to_string(),
tool_name: memory_tool_name(crate::ADD_AD_HOC_NOTE_TOOL_NAME),
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: akode_extension_api::ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: akode_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload: payload.clone(),
})
.await
.expect("ad-hoc note should be written");
assert_eq!(
output.post_tool_use_response("call-1", &payload),
Some(json!({}))
);
assert_eq!(
tokio::fs::read_to_string(
memory_root
.join("extensions/ad_hoc/notes")
.join("2026-05-26T13-42-08-remember-review-style.md")
)
.await
.expect("read ad-hoc note"),
"Remember to keep PR review comments concise."
);
}
#[tokio::test]
async fn add_ad_hoc_note_tool_rejects_paths_as_filenames() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
let tool = memory_tool(&memory_root, crate::ADD_AD_HOC_NOTE_TOOL_NAME);
let payload = ToolPayload::Function {
arguments: json!({
"filename": "../2026-05-26T13-42-08-remember-review-style.md",
"note": "Remember to keep PR review comments concise.",
})
.to_string(),
};
let result = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-1".to_string(),
tool_name: memory_tool_name(crate::ADD_AD_HOC_NOTE_TOOL_NAME),
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: akode_extension_api::ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: akode_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload,
})
.await;
let err = match result {
Ok(_) => panic!("path-like filename should be rejected"),
Err(err) => err,
};
assert!(err.to_string().contains("filename"));
assert!(err.to_string().contains("YYYY-MM-DDTHH-MM-SS"));
}
#[tokio::test]
async fn read_tool_reads_memory_file() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
tokio::fs::create_dir_all(&memory_root)
.await
.expect("create memories dir");
tokio::fs::write(
memory_root.join("MEMORY.md"),
"first line\nsecond needle line\nthird line\n",
)
.await
.expect("write memory");
let tool = memory_tool(&memory_root, crate::READ_TOOL_NAME);
let payload = ToolPayload::Function {
arguments: json!({
"path": "MEMORY.md",
"line_offset": 2,
"max_lines": 1
})
.to_string(),
};
let output = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-1".to_string(),
tool_name: memory_tool_name(crate::READ_TOOL_NAME),
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: akode_extension_api::ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: akode_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload: payload.clone(),
})
.await
.expect("read should succeed");
assert_eq!(
output.post_tool_use_response("call-1", &payload),
Some(json!({
"path": "MEMORY.md",
"content": "second needle line\n",
"start_line_number": 2,
"truncated": true
}))
);
}
#[tokio::test]
async fn local_listing_and_search_ignore_symlinks() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
let outside_root = tempdir.path().join("outside");
std::fs::create_dir_all(memory_root.join("nested")).expect("create memories directory");
std::fs::create_dir_all(&outside_root).expect("create outside directory");
for (path, content) in [
(memory_root.join("a.md"), "visible needle"),
(memory_root.join("nested/z.md"), "nested needle"),
(outside_root.join("secret.md"), "outside needle"),
] {
std::fs::write(path, content).expect("write memory fixture");
}
#[cfg(unix)]
std::os::unix::fs::symlink(&outside_root, memory_root.join("linked-directory"))
.expect("create memory fixture symlink");
let backend = LocalMemoriesBackend::from_memory_root(&memory_root);
let listing = backend
.list(ListMemoriesRequest {
path: None,
cursor: None,
max_results: 10,
})
.await
.expect("list visible memories");
assert_eq!(
listing,
ListMemoriesResponse {
path: None,
entries: vec![
MemoryEntry {
path: "a.md".to_string(),
entry_type: MemoryEntryType::File,
},
MemoryEntry {
path: "nested".to_string(),
entry_type: MemoryEntryType::Directory,
},
],
next_cursor: None,
truncated: false,
}
);
let response = backend
.search(SearchMemoriesRequest {
queries: vec!["needle".to_string()],
match_mode: SearchMatchMode::Any,
path: None,
cursor: None,
context_lines: 0,
case_sensitive: false,
normalized: false,
max_results: 10,
})
.await
.expect("search visible memories");
let paths = response
.matches
.iter()
.map(|matched| matched.path.as_str())
.collect::<Vec<_>>();
assert_eq!(paths, vec!["a.md", "nested/z.md"]);
}
#[tokio::test]
async fn search_tool_accepts_multiple_queries() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
tokio::fs::create_dir_all(&memory_root)
.await
.expect("create memories dir");
tokio::fs::write(
memory_root.join("MEMORY.md"),
"alpha only\nneedle only\nalpha needle\n",
)
.await
.expect("write memory");
let tool = memory_tool(&memory_root, crate::SEARCH_TOOL_NAME);
let payload = ToolPayload::Function {
arguments: json!({
"queries": ["alpha", "needle"],
"case_sensitive": false
})
.to_string(),
};
let output = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-1".to_string(),
tool_name: memory_tool_name(crate::SEARCH_TOOL_NAME),
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: akode_extension_api::ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: akode_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload: payload.clone(),
})
.await
.expect("search should succeed");
assert_eq!(
output.post_tool_use_response("call-1", &payload),
Some(json!({
"queries": ["alpha", "needle"],
"match_mode": {
"type": "any"
},
"path": null,
"matches": [
{
"path": "MEMORY.md",
"match_line_number": 1,
"content_start_line_number": 1,
"content": "alpha only",
"matched_queries": ["alpha"]
},
{
"path": "MEMORY.md",
"match_line_number": 2,
"content_start_line_number": 2,
"content": "needle only",
"matched_queries": ["needle"]
},
{
"path": "MEMORY.md",
"match_line_number": 3,
"content_start_line_number": 3,
"content": "alpha needle",
"matched_queries": ["alpha", "needle"]
}
],
"next_cursor": null,
"truncated": false
}))
);
}
#[tokio::test]
async fn search_tool_accepts_windowed_all_match_mode() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
tokio::fs::create_dir_all(&memory_root)
.await
.expect("create memories dir");
tokio::fs::write(memory_root.join("MEMORY.md"), "alpha\nmiddle\nneedle\n")
.await
.expect("write memory");
let tool = memory_tool(&memory_root, crate::SEARCH_TOOL_NAME);
let payload = ToolPayload::Function {
arguments: json!({
"queries": ["alpha", "needle"],
"match_mode": {
"type": "all_within_lines",
"line_count": 3
}
})
.to_string(),
};
let output = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-1".to_string(),
tool_name: memory_tool_name(crate::SEARCH_TOOL_NAME),
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: akode_extension_api::ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: akode_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload: payload.clone(),
})
.await
.expect("search should succeed");
assert_eq!(
output.post_tool_use_response("call-1", &payload),
Some(json!({
"queries": ["alpha", "needle"],
"match_mode": {
"type": "all_within_lines",
"line_count": 3
},
"path": null,
"matches": [
{
"path": "MEMORY.md",
"match_line_number": 1,
"content_start_line_number": 1,
"content": "alpha\nmiddle\nneedle",
"matched_queries": ["alpha", "needle"]
}
],
"next_cursor": null,
"truncated": false
}))
);
}
#[tokio::test]
async fn search_tool_rejects_legacy_single_query() {
let tempdir = tempfile::tempdir().expect("tempdir");
let memory_root = tempdir.path().join("memories");
tokio::fs::create_dir_all(&memory_root)
.await
.expect("create memories dir");
let tool = memory_tool(&memory_root, crate::SEARCH_TOOL_NAME);
let payload = ToolPayload::Function {
arguments: json!({
"query": "needle",
})
.to_string(),
};
let result = tool
.handle(ToolCall {
turn_id: "turn-1".to_string(),
call_id: "call-1".to_string(),
tool_name: memory_tool_name(crate::SEARCH_TOOL_NAME),
model: "gpt-test".to_string(),
codex_turn_metadata: None,
truncation_policy: TruncationPolicy::Bytes(1024),
source: ToolCallSource::Direct,
conversation_history: akode_extension_api::ConversationHistory::default(),
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
attachment_store: akode_core::passthrough_image_store(),
ephemeral: false,
environments: Vec::new(),
payload,
})
.await;
let err = match result {
Ok(_) => panic!("legacy query field should be rejected"),
Err(err) => err,
};
assert!(err.to_string().contains("unknown field"));
assert!(err.to_string().contains("query"));
}
fn memory_tool(
memory_root: &Path,
tool_name: &str,
) -> Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>> {
let expected_tool_name = memory_tool_name(tool_name);
crate::tools::memory_tools(
LocalMemoriesBackend::from_memory_root(memory_root),
/*metrics_client*/ None,
)
.into_iter()
.find(|tool| tool.tool_name() == expected_tool_name)
.unwrap_or_else(|| panic!("{tool_name} tool should be registered"))
}
fn memory_tool_name(tool_name: &str) -> ToolName {
ToolName::namespaced(crate::MEMORY_TOOLS_NAMESPACE, tool_name)
}

View File

@@ -0,0 +1,94 @@
use akode_extension_api::JsonToolOutput;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use akode_otel::MetricsClient;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use crate::ADD_AD_HOC_NOTE_TOOL_NAME;
use crate::backend::AddAdHocMemoryNoteRequest;
use crate::backend::AddAdHocMemoryNoteResponse;
use crate::backend::MemoriesBackend;
use crate::metrics::record_tool_call;
use super::backend_error_to_function_call;
use super::memory_function_tool;
use super::memory_tool_name;
use super::parse_args;
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct AddAdHocNoteArgs {
/// Name of the note file to create, in
/// YYYY-MM-DDTHH-MM-SS-<slug>.md format. The slug must use only lowercase
/// ASCII letters, digits, and hyphens.
#[schemars(
length(min = 24, max = 128),
regex(pattern = r"^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-[a-z0-9][a-z0-9-]{0,79}\.md$")
)]
filename: String,
/// Verbatim Markdown note to append to the ad-hoc memory notes.
#[schemars(length(min = 1))]
note: String,
}
#[derive(Clone)]
pub(super) struct AddAdHocNoteTool<B> {
pub(super) backend: B,
pub(super) metrics_client: Option<MetricsClient>,
}
impl<'call, B> ToolExecutor<ToolCall<'call>> for AddAdHocNoteTool<B>
where
B: MemoriesBackend,
{
fn tool_name(&self) -> ToolName {
memory_tool_name(ADD_AD_HOC_NOTE_TOOL_NAME)
}
fn spec(&self) -> ToolSpec {
memory_function_tool::<AddAdHocNoteArgs, AddAdHocMemoryNoteResponse>(
ADD_AD_HOC_NOTE_TOOL_NAME,
"Create one append-only ad-hoc memory note after the user explicitly asks Codex to remember, forget, or update something.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> akode_extension_api::ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(self.handle_call(call))
}
}
impl<B> AddAdHocNoteTool<B>
where
B: MemoriesBackend,
{
async fn handle_call(
&self,
call: ToolCall<'_>,
) -> Result<Box<dyn akode_extension_api::ToolOutput>, akode_extension_api::FunctionCallError>
{
let backend = self.backend.clone();
let args: AddAdHocNoteArgs = parse_args(&call)?;
let response = backend
.add_ad_hoc_note(AddAdHocMemoryNoteRequest {
filename: args.filename,
note: args.note,
})
.await;
record_tool_call(
self.metrics_client.as_ref(),
ADD_AD_HOC_NOTE_TOOL_NAME,
"ad_hoc_notes",
response.is_ok(),
"not_applicable",
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))))
}
}

View File

@@ -0,0 +1,102 @@
use akode_extension_api::JsonToolOutput;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use akode_otel::MetricsClient;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use crate::DEFAULT_LIST_MAX_RESULTS;
use crate::LIST_TOOL_NAME;
use crate::MAX_LIST_RESULTS;
use crate::backend::ListMemoriesRequest;
use crate::backend::ListMemoriesResponse;
use crate::backend::MemoriesBackend;
use crate::metrics::record_tool_call;
use crate::metrics::scope_from_optional_path;
use crate::metrics::truncated_tag;
use super::backend_error_to_function_call;
use super::clamp_max_results;
use super::memory_function_tool;
use super::memory_tool_name;
use super::parse_args;
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ListArgs {
path: Option<String>,
cursor: Option<String>,
#[schemars(range(min = 1))]
max_results: Option<usize>,
}
#[derive(Clone)]
pub(super) struct ListTool<B> {
pub(super) backend: B,
pub(super) metrics_client: Option<MetricsClient>,
}
impl<'call, B> ToolExecutor<ToolCall<'call>> for ListTool<B>
where
B: MemoriesBackend,
{
fn tool_name(&self) -> ToolName {
memory_tool_name(LIST_TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
memory_function_tool::<ListArgs, ListMemoriesResponse>(
LIST_TOOL_NAME,
"List immediate files and directories under a path in the Codex memories store.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> akode_extension_api::ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(self.handle_call(call))
}
}
impl<B> ListTool<B>
where
B: MemoriesBackend,
{
async fn handle_call(
&self,
call: ToolCall<'_>,
) -> Result<Box<dyn akode_extension_api::ToolOutput>, akode_extension_api::FunctionCallError>
{
let backend = self.backend.clone();
let args: ListArgs = parse_args(&call)?;
let scope = scope_from_optional_path(args.path.as_deref(), "root");
let response = backend
.list(ListMemoriesRequest {
path: args.path,
cursor: args.cursor,
max_results: clamp_max_results(
args.max_results,
DEFAULT_LIST_MAX_RESULTS,
MAX_LIST_RESULTS,
),
})
.await;
record_tool_call(
self.metrics_client.as_ref(),
LIST_TOOL_NAME,
scope,
response.is_ok(),
truncated_tag(response.as_ref().ok().map(|response| response.truncated)),
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))))
}
}

View File

@@ -0,0 +1,113 @@
use std::sync::Arc;
use akode_extension_api::FunctionCallError;
use akode_extension_api::ResponsesApiTool;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use akode_extension_api::parse_tool_input_schema;
use akode_otel::MetricsClient;
use akode_tools::ResponsesApiNamespace;
use akode_tools::ResponsesApiNamespaceTool;
use akode_tools::default_namespace_description;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::Value;
use crate::MEMORY_TOOLS_NAMESPACE;
use crate::backend::MemoriesBackend;
use crate::backend::MemoriesBackendError;
use crate::schema;
mod ad_hoc_note;
mod list;
mod read;
mod search;
pub(crate) fn memory_tools<B>(
backend: B,
metrics_client: Option<MetricsClient>,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>>
where
B: MemoriesBackend,
{
vec![
Arc::new(ad_hoc_note::AddAdHocNoteTool {
backend: backend.clone(),
metrics_client: metrics_client.clone(),
}),
Arc::new(list::ListTool {
backend: backend.clone(),
metrics_client: metrics_client.clone(),
}),
Arc::new(read::ReadTool {
backend: backend.clone(),
metrics_client: metrics_client.clone(),
}),
Arc::new(search::SearchTool {
backend,
metrics_client,
}),
]
}
pub(super) fn memory_tool_name(name: &str) -> ToolName {
ToolName::namespaced(MEMORY_TOOLS_NAMESPACE, name)
}
pub(super) fn memory_function_tool<I: JsonSchema, O: JsonSchema>(
name: &str,
description: &str,
) -> ToolSpec {
let tool = ResponsesApiTool {
name: name.to_string(),
description: description.to_string(),
strict: false,
defer_loading: None,
parameters: parse_tool_input_schema(&schema::input_schema_for::<I>())
.unwrap_or_else(|err| panic!("generated input schema for {name} should parse: {err}")),
output_schema: Some(schema::output_schema_for::<O>().into()),
};
ToolSpec::Namespace(ResponsesApiNamespace {
name: MEMORY_TOOLS_NAMESPACE.to_string(),
description: default_namespace_description(MEMORY_TOOLS_NAMESPACE),
tools: vec![ResponsesApiNamespaceTool::Function(tool)],
})
}
fn parse_args<T: for<'de> Deserialize<'de>>(call: &ToolCall<'_>) -> Result<T, FunctionCallError> {
let arguments = call.function_arguments()?;
let value = if arguments.trim().is_empty() {
Value::Object(serde_json::Map::new())
} else {
serde_json::from_str(arguments)
.map_err(|err| FunctionCallError::RespondToModel(err.to_string()))?
};
serde_json::from_value(value).map_err(|err| FunctionCallError::RespondToModel(err.to_string()))
}
fn clamp_max_results(requested: Option<usize>, default: usize, max: usize) -> usize {
requested.unwrap_or(default).clamp(1, max)
}
fn backend_error_to_function_call(err: MemoriesBackendError) -> FunctionCallError {
match err {
MemoriesBackendError::InvalidPath { .. }
| MemoriesBackendError::InvalidCursor { .. }
| MemoriesBackendError::InvalidFilename { .. }
| MemoriesBackendError::NotFound { .. }
| MemoriesBackendError::InvalidLineOffset
| MemoriesBackendError::InvalidMaxLines
| MemoriesBackendError::LineOffsetExceedsFileLength
| MemoriesBackendError::NotFile { .. }
| MemoriesBackendError::EmptyQuery
| MemoriesBackendError::EmptyAdHocNote
| MemoriesBackendError::AdHocNoteAlreadyExists { .. }
| MemoriesBackendError::InvalidMatchWindow => {
FunctionCallError::RespondToModel(err.to_string())
}
MemoriesBackendError::Io(_) => FunctionCallError::Fatal(err.to_string()),
}
}

View File

@@ -0,0 +1,99 @@
use akode_extension_api::JsonToolOutput;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use akode_otel::MetricsClient;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use crate::DEFAULT_READ_MAX_TOKENS;
use crate::READ_TOOL_NAME;
use crate::backend::MemoriesBackend;
use crate::backend::ReadMemoryRequest;
use crate::backend::ReadMemoryResponse;
use crate::metrics::record_tool_call;
use crate::metrics::scope_from_path;
use crate::metrics::truncated_tag;
use super::backend_error_to_function_call;
use super::memory_function_tool;
use super::memory_tool_name;
use super::parse_args;
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ReadArgs {
path: String,
#[schemars(range(min = 1))]
line_offset: Option<usize>,
#[schemars(range(min = 1))]
max_lines: Option<usize>,
}
#[derive(Clone)]
pub(super) struct ReadTool<B> {
pub(super) backend: B,
pub(super) metrics_client: Option<MetricsClient>,
}
impl<'call, B> ToolExecutor<ToolCall<'call>> for ReadTool<B>
where
B: MemoriesBackend,
{
fn tool_name(&self) -> ToolName {
memory_tool_name(READ_TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
memory_function_tool::<ReadArgs, ReadMemoryResponse>(
READ_TOOL_NAME,
"Read a Codex memory file by relative path, optionally starting at a 1-indexed line offset and limiting the number of lines returned.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> akode_extension_api::ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(self.handle_call(call))
}
}
impl<B> ReadTool<B>
where
B: MemoriesBackend,
{
async fn handle_call(
&self,
call: ToolCall<'_>,
) -> Result<Box<dyn akode_extension_api::ToolOutput>, akode_extension_api::FunctionCallError>
{
let backend = self.backend.clone();
let args: ReadArgs = parse_args(&call)?;
let path = args.path;
let scope = scope_from_path(path.as_str());
let response = backend
.read(ReadMemoryRequest {
path: path.clone(),
line_offset: args.line_offset.unwrap_or(1),
max_lines: args.max_lines,
max_tokens: DEFAULT_READ_MAX_TOKENS,
})
.await;
record_tool_call(
self.metrics_client.as_ref(),
READ_TOOL_NAME,
scope,
response.is_ok(),
truncated_tag(response.as_ref().ok().map(|response| response.truncated)),
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))))
}
}

View File

@@ -0,0 +1,119 @@
use akode_extension_api::JsonToolOutput;
use akode_extension_api::ToolCall;
use akode_extension_api::ToolExecutor;
use akode_extension_api::ToolName;
use akode_extension_api::ToolSpec;
use akode_otel::MetricsClient;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use crate::DEFAULT_SEARCH_MAX_RESULTS;
use crate::MAX_SEARCH_RESULTS;
use crate::SEARCH_TOOL_NAME;
use crate::backend::MemoriesBackend;
use crate::backend::SearchMatchMode;
use crate::backend::SearchMemoriesRequest;
use crate::backend::SearchMemoriesResponse;
use crate::metrics::record_tool_call;
use crate::metrics::scope_from_optional_path;
use crate::metrics::truncated_tag;
use super::backend_error_to_function_call;
use super::clamp_max_results;
use super::memory_function_tool;
use super::memory_tool_name;
use super::parse_args;
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct SearchArgs {
#[schemars(length(min = 1))]
queries: Vec<String>,
match_mode: Option<SearchMatchMode>,
path: Option<String>,
cursor: Option<String>,
#[schemars(range(min = 0))]
context_lines: Option<usize>,
case_sensitive: Option<bool>,
normalized: Option<bool>,
#[schemars(range(min = 1))]
max_results: Option<usize>,
}
#[derive(Clone)]
pub(super) struct SearchTool<B> {
pub(super) backend: B,
pub(super) metrics_client: Option<MetricsClient>,
}
impl<'call, B> ToolExecutor<ToolCall<'call>> for SearchTool<B>
where
B: MemoriesBackend,
{
fn tool_name(&self) -> ToolName {
memory_tool_name(SEARCH_TOOL_NAME)
}
fn supports_parallel_tool_calls(&self) -> bool {
true
}
fn spec(&self) -> ToolSpec {
memory_function_tool::<SearchArgs, SearchMemoriesResponse>(
SEARCH_TOOL_NAME,
"Search Codex memory files for substring matches, optionally normalizing separators or requiring all query substrings on the same line or within a line window.",
)
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> akode_extension_api::ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(self.handle_call(call))
}
}
impl<B> SearchTool<B>
where
B: MemoriesBackend,
{
async fn handle_call(
&self,
call: ToolCall<'_>,
) -> Result<Box<dyn akode_extension_api::ToolOutput>, akode_extension_api::FunctionCallError>
{
let backend = self.backend.clone();
let args: SearchArgs = parse_args(&call)?;
let scope = scope_from_optional_path(args.path.as_deref(), "all");
let response = backend.search(args.into_request()).await;
record_tool_call(
self.metrics_client.as_ref(),
SEARCH_TOOL_NAME,
scope,
response.is_ok(),
truncated_tag(response.as_ref().ok().map(|response| response.truncated)),
);
let response = response.map_err(backend_error_to_function_call)?;
Ok(Box::new(JsonToolOutput::new(json!(response))))
}
}
impl SearchArgs {
fn into_request(self) -> SearchMemoriesRequest {
SearchMemoriesRequest {
queries: self.queries,
match_mode: self.match_mode.unwrap_or(SearchMatchMode::Any),
path: self.path,
cursor: self.cursor,
context_lines: self.context_lines.unwrap_or(0),
case_sensitive: self.case_sensitive.unwrap_or(true),
normalized: self.normalized.unwrap_or(false),
max_results: clamp_max_results(
self.max_results,
DEFAULT_SEARCH_MAX_RESULTS,
MAX_SEARCH_RESULTS,
),
}
}
}