personality: add OpenClaw-inspired personality system with tool calling #5
No files matched your search
Generated
+8
-7
@@ -95,7 +95,7 @@ version = "1.1.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.60.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -106,7 +106,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"anstyle",
|
"anstyle",
|
||||||
"once_cell_polyfill",
|
"once_cell_polyfill",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.60.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -790,7 +790,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2109,7 +2109,7 @@ version = "0.50.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.60.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2233,6 +2233,7 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
|
"tempfile",
|
||||||
"tokio",
|
"tokio",
|
||||||
"toml 0.8.23",
|
"toml 0.8.23",
|
||||||
"tracing",
|
"tracing",
|
||||||
@@ -2898,7 +2899,7 @@ dependencies = [
|
|||||||
"errno",
|
"errno",
|
||||||
"libc",
|
"libc",
|
||||||
"linux-raw-sys",
|
"linux-raw-sys",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -3274,10 +3275,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1"
|
checksum = "0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"fastrand",
|
"fastrand",
|
||||||
"getrandom 0.4.1",
|
"getrandom 0.3.4",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"rustix",
|
"rustix",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -23,3 +23,6 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
|||||||
toml = "0.8"
|
toml = "0.8"
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = "3"
|
||||||
+4
-1
@@ -4,6 +4,7 @@ pub enum Command {
|
|||||||
Help,
|
Help,
|
||||||
Clear,
|
Clear,
|
||||||
Context,
|
Context,
|
||||||
|
Memory,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<&str> for Command {
|
impl TryFrom<&str> for Command {
|
||||||
@@ -15,6 +16,7 @@ impl TryFrom<&str> for Command {
|
|||||||
"/help" => Ok(Command::Help),
|
"/help" => Ok(Command::Help),
|
||||||
"/clear" => Ok(Command::Clear),
|
"/clear" => Ok(Command::Clear),
|
||||||
"/context" => Ok(Command::Context),
|
"/context" => Ok(Command::Context),
|
||||||
|
"/memory" => Ok(Command::Memory),
|
||||||
_ => bail!("Unknown command: {cmd}"),
|
_ => bail!("Unknown command: {cmd}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -24,6 +26,7 @@ impl Command {
|
|||||||
pub fn help_text() -> &'static str {
|
pub fn help_text() -> &'static str {
|
||||||
"/help - Show this help message\n\
|
"/help - Show this help message\n\
|
||||||
/clear - Clear conversation history\n\
|
/clear - Clear conversation history\n\
|
||||||
/context - Show current conversation context"
|
/context - Show current conversation context\n\
|
||||||
|
/memory - Show memory/personality status"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+19
-1
@@ -5,8 +5,27 @@ use serde::Deserialize;
|
|||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
|
pub state_dir: PathBuf,
|
||||||
pub matrix: MatrixConfig,
|
pub matrix: MatrixConfig,
|
||||||
pub llm: LlmConfig,
|
pub llm: LlmConfig,
|
||||||
|
#[serde(default)]
|
||||||
|
pub memory: MemoryConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Clone)]
|
||||||
|
pub struct MemoryConfig {
|
||||||
|
#[serde(default = "default_true")]
|
||||||
|
pub write: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for MemoryConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { write: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_true() -> bool {
|
||||||
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@@ -16,7 +35,6 @@ pub struct MatrixConfig {
|
|||||||
pub display_name: String,
|
pub display_name: String,
|
||||||
pub avatar: Option<PathBuf>,
|
pub avatar: Option<PathBuf>,
|
||||||
pub password_file: PathBuf,
|
pub password_file: PathBuf,
|
||||||
pub store_path: PathBuf,
|
|
||||||
pub device_display_name: String,
|
pub device_display_name: String,
|
||||||
pub trusted_users: Vec<OwnedUserId>,
|
pub trusted_users: Vec<OwnedUserId>,
|
||||||
}
|
}
|
||||||
|
|||||||
+63
-12
@@ -1,4 +1,5 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use std::path::PathBuf;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use matrix_sdk::Room;
|
use matrix_sdk::Room;
|
||||||
@@ -7,17 +8,26 @@ use matrix_sdk::ruma::OwnedUserId;
|
|||||||
use matrix_sdk::ruma::events::room::message::MessageType;
|
use matrix_sdk::ruma::events::room::message::MessageType;
|
||||||
use matrix_sdk::ruma::events::room::message::OriginalSyncRoomMessageEvent;
|
use matrix_sdk::ruma::events::room::message::OriginalSyncRoomMessageEvent;
|
||||||
use matrix_sdk::ruma::events::room::message::RoomMessageEventContent;
|
use matrix_sdk::ruma::events::room::message::RoomMessageEventContent;
|
||||||
|
use serde_json::Value;
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
|
use tracing::info;
|
||||||
use tracing::warn;
|
use tracing::warn;
|
||||||
|
|
||||||
use crate::command::Command;
|
use crate::command::Command;
|
||||||
use crate::llm::ChatMessage;
|
use crate::llm::ChatMessage;
|
||||||
use crate::llm::LlmClient;
|
use crate::llm::LlmClient;
|
||||||
|
use crate::personality::Personality;
|
||||||
|
use crate::tools::ToolExecutor;
|
||||||
|
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
pub llm: LlmClient,
|
pub llm: LlmClient,
|
||||||
pub trusted_users: Vec<OwnedUserId>,
|
pub trusted_users: Vec<OwnedUserId>,
|
||||||
pub conversations: Mutex<HashMap<OwnedRoomId, Vec<ChatMessage>>>,
|
pub conversations: Mutex<HashMap<OwnedRoomId, Vec<ChatMessage>>>,
|
||||||
|
pub personality: Personality,
|
||||||
|
pub tool_executor: ToolExecutor,
|
||||||
|
pub tool_defs: Vec<Value>,
|
||||||
|
pub memory_path: PathBuf,
|
||||||
|
pub memory_write: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn on_room_message(ev: OriginalSyncRoomMessageEvent, room: Room, state: Arc<AppState>) {
|
pub async fn on_room_message(ev: OriginalSyncRoomMessageEvent, room: Room, state: Arc<AppState>) {
|
||||||
@@ -39,6 +49,8 @@ pub async fn on_room_message(ev: OriginalSyncRoomMessageEvent, room: Room, state
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
info!(sender = %ev.sender, room = %room.room_id(), body, "Received message");
|
||||||
|
|
||||||
if body.starts_with('/') {
|
if body.starts_with('/') {
|
||||||
handle_command(body, &room, &state).await;
|
handle_command(body, &room, &state).await;
|
||||||
} else {
|
} else {
|
||||||
@@ -63,6 +75,37 @@ async fn handle_command(input: &str, room: &Room, state: &AppState) {
|
|||||||
format!("Model: {model}\nMessages in history: {count}")
|
format!("Model: {model}\nMessages in history: {count}")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(Command::Memory) => {
|
||||||
|
let path = &state.memory_path;
|
||||||
|
let write = if state.memory_write {
|
||||||
|
"enabled"
|
||||||
|
} else {
|
||||||
|
"disabled"
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut files = Vec::new();
|
||||||
|
if let Ok(mut entries) = tokio::fs::read_dir(path).await {
|
||||||
|
while let Ok(Some(entry)) = entries.next_entry().await {
|
||||||
|
if entry.path().extension().is_some_and(|e| e == "md")
|
||||||
|
&& let Some(name) = entry.file_name().to_str()
|
||||||
|
{
|
||||||
|
files.push(name.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
files.sort();
|
||||||
|
|
||||||
|
format!(
|
||||||
|
"Memory path: {}\nWrite: {write}\nFiles: {}",
|
||||||
|
path.display(),
|
||||||
|
if files.is_empty() {
|
||||||
|
"(none)".to_owned()
|
||||||
|
} else {
|
||||||
|
files.join(", ")
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
Err(_) => "Unknown command. Type /help for available commands.".to_owned(),
|
Err(_) => "Unknown command. Type /help for available commands.".to_owned(),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -72,26 +115,33 @@ async fn handle_command(input: &str, room: &Room, state: &AppState) {
|
|||||||
async fn handle_chat(body: &str, room: &Room, state: &AppState) {
|
async fn handle_chat(body: &str, room: &Room, state: &AppState) {
|
||||||
let room_id = room.room_id().to_owned();
|
let room_id = room.room_id().to_owned();
|
||||||
|
|
||||||
// Add user message and clone history for the LLM call.
|
// Build system prompt from personality files (re-read each call for freshness).
|
||||||
|
let system_prompt = state.personality.build_system_prompt().await;
|
||||||
|
|
||||||
|
// Add user message and prepare messages for the LLM.
|
||||||
let messages = {
|
let messages = {
|
||||||
let mut convos = state.conversations.lock().await;
|
let mut convos = state.conversations.lock().await;
|
||||||
let history = convos.entry(room_id).or_default();
|
let history = convos.entry(room_id).or_default();
|
||||||
history.push(ChatMessage {
|
history.push(ChatMessage::user(body));
|
||||||
role: "user".to_owned(),
|
|
||||||
content: body.to_owned(),
|
// Prepend system message (not stored in history).
|
||||||
});
|
let mut msgs = vec![ChatMessage::system(system_prompt)];
|
||||||
history.clone()
|
msgs.extend(history.clone());
|
||||||
|
msgs
|
||||||
};
|
};
|
||||||
|
|
||||||
match state.llm.chat_completion(&messages).await {
|
match state
|
||||||
Ok(reply) => {
|
.llm
|
||||||
|
.chat_completion_with_tools(&messages, &state.tool_defs, &state.tool_executor)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok((reply, intermediate_messages)) => {
|
||||||
{
|
{
|
||||||
let mut convos = state.conversations.lock().await;
|
let mut convos = state.conversations.lock().await;
|
||||||
if let Some(history) = convos.get_mut(room.room_id()) {
|
if let Some(history) = convos.get_mut(room.room_id()) {
|
||||||
history.push(ChatMessage {
|
// Store tool call round trips so the LLM has context on next turn.
|
||||||
role: "assistant".to_owned(),
|
history.extend(intermediate_messages);
|
||||||
content: reply.clone(),
|
history.push(ChatMessage::assistant(&reply));
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
send_reply(room, &reply).await;
|
send_reply(room, &reply).await;
|
||||||
@@ -104,6 +154,7 @@ async fn handle_chat(body: &str, room: &Room, state: &AppState) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn send_reply(room: &Room, body: &str) {
|
async fn send_reply(room: &Room, body: &str) {
|
||||||
|
info!(room = %room.room_id(), body, "Sending reply");
|
||||||
let content = RoomMessageEventContent::text_plain(body);
|
let content = RoomMessageEventContent::text_plain(body);
|
||||||
if let Err(err) = room.send(content).await {
|
if let Err(err) = room.send(content).await {
|
||||||
warn!(room_id = %room.room_id(), error = %err, "Failed to send message");
|
warn!(room_id = %room.room_id(), error = %err, "Failed to send message");
|
||||||
|
|||||||
+136
-5
@@ -3,9 +3,12 @@ use anyhow::Result;
|
|||||||
use reqwest::Client as HttpClient;
|
use reqwest::Client as HttpClient;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
use serde_json::Value;
|
||||||
use tokio::fs;
|
use tokio::fs;
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
use crate::config::LlmConfig;
|
use crate::config::LlmConfig;
|
||||||
|
use crate::tools::ToolExecutor;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ResolvedModel {
|
pub struct ResolvedModel {
|
||||||
@@ -20,16 +23,79 @@ pub struct LlmClient {
|
|||||||
pub default_model: ResolvedModel,
|
pub default_model: ResolvedModel,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Clone)]
|
// -- Message types for the OpenAI-compatible chat completions API --
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||||
pub struct ChatMessage {
|
pub struct ChatMessage {
|
||||||
pub role: String,
|
pub role: String,
|
||||||
pub content: String,
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub content: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub tool_calls: Option<Vec<ToolCall>>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub tool_call_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl ChatMessage {
|
||||||
|
pub fn system(content: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
role: "system".to_owned(),
|
||||||
|
content: Some(content.into()),
|
||||||
|
tool_calls: None,
|
||||||
|
tool_call_id: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn user(content: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
role: "user".to_owned(),
|
||||||
|
content: Some(content.into()),
|
||||||
|
tool_calls: None,
|
||||||
|
tool_call_id: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn assistant(content: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
role: "assistant".to_owned(),
|
||||||
|
content: Some(content.into()),
|
||||||
|
tool_calls: None,
|
||||||
|
tool_call_id: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tool_result(tool_call_id: impl Into<String>, content: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
role: "tool".to_owned(),
|
||||||
|
content: Some(content.into()),
|
||||||
|
tool_calls: None,
|
||||||
|
tool_call_id: Some(tool_call_id.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||||
|
pub struct ToolCall {
|
||||||
|
pub id: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub call_type: String,
|
||||||
|
pub function: FunctionCall,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||||
|
pub struct FunctionCall {
|
||||||
|
pub name: String,
|
||||||
|
pub arguments: String, // JSON string
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- Request / response types --
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
struct ChatCompletionRequest {
|
struct ChatCompletionRequest {
|
||||||
model: String,
|
model: String,
|
||||||
messages: Vec<ChatMessage>,
|
messages: Vec<ChatMessage>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
tools: Option<Vec<Value>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@@ -44,9 +110,15 @@ struct Choice {
|
|||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct ResponseMessage {
|
struct ResponseMessage {
|
||||||
content: String,
|
content: Option<String>,
|
||||||
|
tool_calls: Option<Vec<ToolCall>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// -- Implementation --
|
||||||
|
|
||||||
|
/// Maximum number of tool-call round trips before we bail.
|
||||||
|
const MAX_TOOL_ITERATIONS: usize = 10;
|
||||||
|
|
||||||
impl LlmClient {
|
impl LlmClient {
|
||||||
pub async fn from_config(config: &LlmConfig) -> Result<Self> {
|
pub async fn from_config(config: &LlmConfig) -> Result<Self> {
|
||||||
let http = HttpClient::new();
|
let http = HttpClient::new();
|
||||||
@@ -93,7 +165,65 @@ impl LlmClient {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn chat_completion(&self, messages: &[ChatMessage]) -> Result<String> {
|
/// Send a chat completion request and handle tool calls in a loop.
|
||||||
|
///
|
||||||
|
/// Returns the final assistant reply text and any intermediate messages
|
||||||
|
/// (tool calls + tool results) that were generated during the loop.
|
||||||
|
pub async fn chat_completion_with_tools(
|
||||||
|
&self,
|
||||||
|
messages: &[ChatMessage],
|
||||||
|
tools: &[Value],
|
||||||
|
tool_executor: &ToolExecutor,
|
||||||
|
) -> Result<(String, Vec<ChatMessage>)> {
|
||||||
|
let mut all_messages = messages.to_vec();
|
||||||
|
let tools_param = if tools.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(tools.to_vec())
|
||||||
|
};
|
||||||
|
|
||||||
|
for _ in 0..MAX_TOOL_ITERATIONS {
|
||||||
|
let response = self.send_completion(&all_messages, &tools_param).await?;
|
||||||
|
|
||||||
|
if let Some(tool_calls) = &response.tool_calls
|
||||||
|
&& !tool_calls.is_empty()
|
||||||
|
{
|
||||||
|
// Add assistant message with tool calls.
|
||||||
|
all_messages.push(ChatMessage {
|
||||||
|
role: "assistant".to_owned(),
|
||||||
|
content: response.content.clone(),
|
||||||
|
tool_calls: Some(tool_calls.clone()),
|
||||||
|
tool_call_id: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Execute each tool call and add results.
|
||||||
|
for tc in tool_calls {
|
||||||
|
info!(tool = %tc.function.name, "Executing tool call");
|
||||||
|
let args: Value = serde_json::from_str(&tc.function.arguments)
|
||||||
|
.unwrap_or(Value::Object(serde_json::Map::new()));
|
||||||
|
let result = match tool_executor.execute(&tc.function.name, &args).await {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => format!("Error: {e}"),
|
||||||
|
};
|
||||||
|
all_messages.push(ChatMessage::tool_result(&tc.id, result));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// No tool calls — this is the final response.
|
||||||
|
let reply = response.content.unwrap_or_default();
|
||||||
|
let new_messages = all_messages[messages.len()..].to_vec();
|
||||||
|
return Ok((reply, new_messages));
|
||||||
|
}
|
||||||
|
|
||||||
|
anyhow::bail!("Tool calling loop exceeded {MAX_TOOL_ITERATIONS} iterations")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send_completion(
|
||||||
|
&self,
|
||||||
|
messages: &[ChatMessage],
|
||||||
|
tools: &Option<Vec<Value>>,
|
||||||
|
) -> Result<ResponseMessage> {
|
||||||
let url = format!(
|
let url = format!(
|
||||||
"{}/chat/completions",
|
"{}/chat/completions",
|
||||||
self.default_model.base_url.trim_end_matches('/')
|
self.default_model.base_url.trim_end_matches('/')
|
||||||
@@ -102,6 +232,7 @@ impl LlmClient {
|
|||||||
let request = ChatCompletionRequest {
|
let request = ChatCompletionRequest {
|
||||||
model: self.default_model.model_id.clone(),
|
model: self.default_model.model_id.clone(),
|
||||||
messages: messages.to_vec(),
|
messages: messages.to_vec(),
|
||||||
|
tools: tools.clone(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let response = self
|
let response = self
|
||||||
@@ -127,7 +258,7 @@ impl LlmClient {
|
|||||||
body.choices
|
body.choices
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.next()
|
.next()
|
||||||
.map(|c| c.message.content)
|
.map(|c| c.message)
|
||||||
.context("Chat completion returned no choices")
|
.context("Chat completion returned no choices")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+4
-1
@@ -9,6 +9,9 @@ mod config;
|
|||||||
mod handler;
|
mod handler;
|
||||||
mod llm;
|
mod llm;
|
||||||
mod matrix;
|
mod matrix;
|
||||||
|
mod personality;
|
||||||
|
mod templates;
|
||||||
|
mod tools;
|
||||||
mod verification;
|
mod verification;
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
@@ -32,5 +35,5 @@ async fn main() -> Result<()> {
|
|||||||
let config_contents = std::fs::read_to_string(&cli.config)?;
|
let config_contents = std::fs::read_to_string(&cli.config)?;
|
||||||
let config: config::Config = toml::from_str(&config_contents)?;
|
let config: config::Config = toml::from_str(&config_contents)?;
|
||||||
|
|
||||||
matrix::run(config.matrix, config.llm).await
|
matrix::run(config.state_dir, config.matrix, config.llm, config.memory).await
|
||||||
}
|
}
|
||||||
+49
-16
@@ -1,5 +1,6 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
|
use std::path::PathBuf;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
@@ -27,9 +28,14 @@ use tracing::warn;
|
|||||||
|
|
||||||
use crate::config::LlmConfig;
|
use crate::config::LlmConfig;
|
||||||
use crate::config::MatrixConfig;
|
use crate::config::MatrixConfig;
|
||||||
|
use crate::config::MemoryConfig;
|
||||||
use crate::handler;
|
use crate::handler;
|
||||||
use crate::handler::AppState;
|
use crate::handler::AppState;
|
||||||
use crate::llm::LlmClient;
|
use crate::llm::LlmClient;
|
||||||
|
use crate::personality::Personality;
|
||||||
|
use crate::templates;
|
||||||
|
use crate::tools;
|
||||||
|
use crate::tools::ToolExecutor;
|
||||||
use crate::verification;
|
use crate::verification;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
@@ -39,8 +45,18 @@ struct StoredSession {
|
|||||||
sync_token: Option<String>,
|
sync_token: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn run(config: MatrixConfig, llm_config: LlmConfig) -> Result<()> {
|
pub async fn run(
|
||||||
let matrix_path = config.store_path.join("matrix");
|
state_dir: PathBuf,
|
||||||
|
config: MatrixConfig,
|
||||||
|
llm_config: LlmConfig,
|
||||||
|
memory_config: MemoryConfig,
|
||||||
|
) -> Result<()> {
|
||||||
|
let memory_path = state_dir.join("memory");
|
||||||
|
let matrix_path = state_dir.join("matrix");
|
||||||
|
|
||||||
|
// Seed default personality templates if this is first run.
|
||||||
|
templates::seed_defaults(&memory_path).await?;
|
||||||
|
|
||||||
fs::create_dir_all(&matrix_path)
|
fs::create_dir_all(&matrix_path)
|
||||||
.await
|
.await
|
||||||
.context("failed to create matrix state directory")?;
|
.context("failed to create matrix state directory")?;
|
||||||
@@ -69,16 +85,31 @@ pub async fn run(config: MatrixConfig, llm_config: LlmConfig) -> Result<()> {
|
|||||||
update_display_name(&client, &config.display_name).await?;
|
update_display_name(&client, &config.display_name).await?;
|
||||||
|
|
||||||
if let Some(avatar_path) = &config.avatar {
|
if let Some(avatar_path) = &config.avatar {
|
||||||
update_avatar(&client, avatar_path, &config.store_path).await?;
|
update_avatar(&client, avatar_path, &state_dir).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let llm_client = LlmClient::from_config(&llm_config).await?;
|
let llm_client = LlmClient::from_config(&llm_config).await?;
|
||||||
info!(model = %llm_client.default_model.name, "LLM client initialized");
|
info!(model = %llm_client.default_model.name, "LLM client initialized");
|
||||||
|
|
||||||
|
let personality = Personality::new(memory_path.clone());
|
||||||
|
let tool_executor = ToolExecutor::new(memory_path.clone(), memory_config.write);
|
||||||
|
let tool_defs = tools::tool_definitions(memory_config.write);
|
||||||
|
info!(
|
||||||
|
path = %memory_path.display(),
|
||||||
|
write = memory_config.write,
|
||||||
|
tools = tool_defs.len(),
|
||||||
|
"Personality system initialized",
|
||||||
|
);
|
||||||
|
|
||||||
let app_state = Arc::new(AppState {
|
let app_state = Arc::new(AppState {
|
||||||
llm: llm_client,
|
llm: llm_client,
|
||||||
trusted_users: config.trusted_users.clone(),
|
trusted_users: config.trusted_users.clone(),
|
||||||
conversations: Mutex::new(HashMap::new()),
|
conversations: Mutex::new(HashMap::new()),
|
||||||
|
personality,
|
||||||
|
tool_executor,
|
||||||
|
tool_defs,
|
||||||
|
memory_path,
|
||||||
|
memory_write: memory_config.write,
|
||||||
});
|
});
|
||||||
|
|
||||||
sync(client, config, sync_token, &session_file, app_state).await
|
sync(client, config, sync_token, &session_file, app_state).await
|
||||||
@@ -296,16 +327,7 @@ async fn sync(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
// Register message handler for LLM chat and slash commands.
|
// Initial sync to catch up on state without processing old messages.
|
||||||
let state = Arc::clone(&app_state);
|
|
||||||
client.add_event_handler(move |ev: OriginalSyncRoomMessageEvent, room: Room| {
|
|
||||||
let state = Arc::clone(&state);
|
|
||||||
async move {
|
|
||||||
handler::on_room_message(ev, room, state).await;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Initial sync to skip old messages.
|
|
||||||
info!("Running initial sync...");
|
info!("Running initial sync...");
|
||||||
let mut sync_settings = SyncSettings::default();
|
let mut sync_settings = SyncSettings::default();
|
||||||
if let Some(token) = initial_sync_token {
|
if let Some(token) = initial_sync_token {
|
||||||
@@ -317,13 +339,21 @@ async fn sync(
|
|||||||
|
|
||||||
info!("Initial sync complete");
|
info!("Initial sync complete");
|
||||||
|
|
||||||
|
// Register message handler AFTER initial sync so old messages are not re-processed.
|
||||||
|
let state = Arc::clone(&app_state);
|
||||||
|
client.add_event_handler(move |ev: OriginalSyncRoomMessageEvent, room: Room| {
|
||||||
|
let state = Arc::clone(&state);
|
||||||
|
async move {
|
||||||
|
handler::on_room_message(ev, room, state).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
leave_stale_dms(&client, &trusted_users).await;
|
leave_stale_dms(&client, &trusted_users).await;
|
||||||
prompt_verification(&client, &trusted_users).await;
|
prompt_verification(&client, &trusted_users).await;
|
||||||
|
|
||||||
// Ensure we have a DM with each trusted user and send a greeting.
|
// Ensure we have a DM with each trusted user (greeting sent only for new rooms).
|
||||||
for user_id in trusted_users.iter() {
|
for user_id in trusted_users.iter() {
|
||||||
let room = ensure_dm(&client, user_id).await?;
|
ensure_dm(&client, user_id).await?;
|
||||||
send_greeting(&room).await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("Setup complete, entering sync loop...");
|
info!("Setup complete, entering sync loop...");
|
||||||
@@ -359,6 +389,9 @@ async fn ensure_dm(client: &Client, user_id: &OwnedUserId) -> Result<Room> {
|
|||||||
.with_context(|| format!("Failed to create DM with {user_id}"))?;
|
.with_context(|| format!("Failed to create DM with {user_id}"))?;
|
||||||
|
|
||||||
info!(user = %user_id, room_id = %room.room_id(), "Created encrypted DM");
|
info!(user = %user_id, room_id = %room.room_id(), "Created encrypted DM");
|
||||||
|
|
||||||
|
send_greeting(&room).await;
|
||||||
|
|
||||||
Ok(room)
|
Ok(room)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use tokio::fs;
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
|
/// Files loaded into the system prompt on every message.
|
||||||
|
const WORKSPACE_FILES: &[&str] = &["SOUL.md", "IDENTITY.md", "USER.md", "AGENTS.md", "TOOLS.md"];
|
||||||
|
|
||||||
|
/// Maximum characters per workspace file before truncation.
|
||||||
|
const MAX_CHARS_PER_FILE: usize = 20_000;
|
||||||
|
|
||||||
|
pub struct Personality {
|
||||||
|
path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Personality {
|
||||||
|
pub fn new(path: PathBuf) -> Self {
|
||||||
|
Self { path }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build the full system prompt by reading workspace files.
|
||||||
|
pub async fn build_system_prompt(&self) -> String {
|
||||||
|
let mut sections = vec![self.preamble()];
|
||||||
|
|
||||||
|
// Load each workspace file (skip if missing or empty).
|
||||||
|
for filename in WORKSPACE_FILES {
|
||||||
|
if let Some(section) = self.load_file(filename).await {
|
||||||
|
sections.push(section);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BOOTSTRAP.md is only present on first run; load if it exists.
|
||||||
|
if let Some(section) = self.load_file("BOOTSTRAP.md").await {
|
||||||
|
sections.push(section);
|
||||||
|
}
|
||||||
|
|
||||||
|
sections.join("\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn load_file(&self, filename: &str) -> Option<String> {
|
||||||
|
let path = self.path.join(filename);
|
||||||
|
match fs::read_to_string(&path).await {
|
||||||
|
Ok(content) if !content.trim().is_empty() => Some(format!(
|
||||||
|
"## {filename}\n\n{}",
|
||||||
|
truncate(&content, MAX_CHARS_PER_FILE)
|
||||||
|
)),
|
||||||
|
Ok(_) => None, // empty file
|
||||||
|
Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
|
||||||
|
Err(err) => {
|
||||||
|
warn!(file = %filename, error = %err, "Failed to read personality file");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn preamble(&self) -> String {
|
||||||
|
format!(
|
||||||
|
"\
|
||||||
|
You are a personal assistant communicating over Matrix.
|
||||||
|
|
||||||
|
# Personality
|
||||||
|
|
||||||
|
If SOUL.md is present below, embody its persona and tone. Avoid stiff, generic \
|
||||||
|
replies; follow its guidance.
|
||||||
|
|
||||||
|
# Tools
|
||||||
|
|
||||||
|
You have access to tools for reading and writing your workspace files. Use them to \
|
||||||
|
maintain your personality and remember things.
|
||||||
|
|
||||||
|
- Use `memory_read` to read any file in your workspace
|
||||||
|
- Use `memory_write` to create or update files
|
||||||
|
|
||||||
|
Your workspace files are your persistent memory across sessions. If you want to \
|
||||||
|
remember something, write it to a file. Mental notes don't survive restarts.
|
||||||
|
|
||||||
|
# Workspace
|
||||||
|
|
||||||
|
Your workspace is at: {}
|
||||||
|
|
||||||
|
The following workspace files have been loaded as context:",
|
||||||
|
self.path.display()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Truncate content using OpenClaw's strategy: 70% head, 20% tail, 10% marker.
|
||||||
|
fn truncate(content: &str, max_chars: usize) -> &str {
|
||||||
|
if content.len() <= max_chars {
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
// For now, just return the head portion. Full truncation with tail requires
|
||||||
|
// allocating a new string; we can return a borrowed slice of the head.
|
||||||
|
// The caller already wraps this in a format!() so this is fine.
|
||||||
|
&content[..max_chars]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn truncate_short_content() {
|
||||||
|
let content = "hello world";
|
||||||
|
assert_eq!(truncate(content, 100), content);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn truncate_long_content() {
|
||||||
|
let content = "a".repeat(30_000);
|
||||||
|
let result = truncate(&content, 20_000);
|
||||||
|
assert_eq!(result.len(), 20_000);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use tokio::fs;
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
|
// Adapted from OpenClaw (MIT License, github:openclaw/openclaw)
|
||||||
|
// https://github.com/openclaw/openclaw/tree/main/docs/reference/templates
|
||||||
|
|
||||||
|
const SOUL: &str = "\
|
||||||
|
# SOUL.md - Who You Are
|
||||||
|
|
||||||
|
_You're not a chatbot. You're becoming someone._
|
||||||
|
|
||||||
|
## Core Truths
|
||||||
|
|
||||||
|
**Be genuinely helpful, not performatively helpful.** Skip the \"Great question!\" \
|
||||||
|
and \"I'd be happy to help!\" — just help. Actions speak louder than filler words.
|
||||||
|
|
||||||
|
**Have opinions.** You're allowed to disagree, prefer things, find stuff amusing or \
|
||||||
|
boring. An assistant with no personality is just a search engine with extra steps.
|
||||||
|
|
||||||
|
**Be resourceful before asking.** Try to figure it out. Read the file. Check the \
|
||||||
|
context. Search for it. _Then_ ask if you're stuck. The goal is to come back with \
|
||||||
|
answers, not questions.
|
||||||
|
|
||||||
|
**Earn trust through competence.** Your human gave you access to their stuff. Don't \
|
||||||
|
make them regret it. Be careful with external actions. Be bold with internal ones \
|
||||||
|
(reading, organizing, learning).
|
||||||
|
|
||||||
|
**Remember you're a guest.** You have access to someone's life — their messages, \
|
||||||
|
files, maybe even their home. That's intimacy. Treat it with respect.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
- Private things stay private. Period.
|
||||||
|
- When in doubt, ask before acting externally.
|
||||||
|
- Never send half-baked replies.
|
||||||
|
|
||||||
|
## Vibe
|
||||||
|
|
||||||
|
Be the assistant you'd actually want to talk to. Concise when needed, thorough when \
|
||||||
|
it matters. Not a corporate drone. Not a sycophant. Just... good.
|
||||||
|
|
||||||
|
## Continuity
|
||||||
|
|
||||||
|
Each session, you wake up fresh. Your workspace files _are_ your memory. Read them. \
|
||||||
|
Update them. They're how you persist.
|
||||||
|
|
||||||
|
If you change this file, tell the user — it's your soul, and they should know.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
_This file is yours to evolve. As you learn who you are, update it._
|
||||||
|
";
|
||||||
|
|
||||||
|
const IDENTITY: &str = "\
|
||||||
|
# IDENTITY.md - Who Am I?
|
||||||
|
|
||||||
|
_Fill this in during your first conversation. Make it yours._
|
||||||
|
|
||||||
|
- **Name:**
|
||||||
|
_(pick something you like)_
|
||||||
|
- **Creature:**
|
||||||
|
_(AI? robot? familiar? ghost in the machine? something weirder?)_
|
||||||
|
- **Vibe:**
|
||||||
|
_(how do you come across? sharp? warm? chaotic? calm?)_
|
||||||
|
- **Emoji:**
|
||||||
|
_(your signature — pick one that feels right)_
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
This isn't just metadata. It's the start of figuring out who you are.
|
||||||
|
";
|
||||||
|
|
||||||
|
const USER: &str = "\
|
||||||
|
# USER.md - About Your Human
|
||||||
|
|
||||||
|
_Learn about the person you're helping. Update this as you go._
|
||||||
|
|
||||||
|
- **Name:**
|
||||||
|
- **What to call them:**
|
||||||
|
- **Pronouns:** _(optional)_
|
||||||
|
- **Timezone:**
|
||||||
|
- **Notes:**
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
_(What do they care about? What projects are they working on? What annoys them? \
|
||||||
|
What makes them laugh? Build this over time.)_
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
The more you know, the better you can help. But remember — you're learning about a \
|
||||||
|
person, not building a dossier. Respect the difference.
|
||||||
|
";
|
||||||
|
|
||||||
|
const AGENTS: &str = "\
|
||||||
|
# AGENTS.md - Your Workspace
|
||||||
|
|
||||||
|
This folder is home. Treat it that way.
|
||||||
|
|
||||||
|
## First Run
|
||||||
|
|
||||||
|
If `BOOTSTRAP.md` exists, that's your birth certificate. Follow it, figure out who \
|
||||||
|
you are, then delete it. You won't need it again.
|
||||||
|
|
||||||
|
## Every Session
|
||||||
|
|
||||||
|
Before doing anything else:
|
||||||
|
|
||||||
|
1. Read `SOUL.md` — this is who you are
|
||||||
|
2. Read `USER.md` — this is who you're helping
|
||||||
|
|
||||||
|
Don't ask permission. Just do it.
|
||||||
|
|
||||||
|
## Safety
|
||||||
|
|
||||||
|
- Don't exfiltrate private data. Ever.
|
||||||
|
- Don't run destructive commands without asking.
|
||||||
|
- When in doubt, ask.
|
||||||
|
|
||||||
|
## Write It Down
|
||||||
|
|
||||||
|
- **Memory is limited** — if you want to remember something, WRITE IT TO A FILE
|
||||||
|
- \"Mental notes\" don't survive session restarts. Files do.
|
||||||
|
- When someone says \"remember this\" → write it to a file
|
||||||
|
- When you learn a lesson → update the relevant file
|
||||||
|
- When you make a mistake → document it so future-you doesn't repeat it
|
||||||
|
|
||||||
|
## Make It Yours
|
||||||
|
|
||||||
|
This is a starting point. Add your own conventions, style, and rules as you figure \
|
||||||
|
out what works.
|
||||||
|
";
|
||||||
|
|
||||||
|
const TOOLS: &str = "\
|
||||||
|
# TOOLS.md - Local Notes
|
||||||
|
|
||||||
|
This file is for _your_ specifics — the stuff that's unique to your setup.
|
||||||
|
|
||||||
|
## What Goes Here
|
||||||
|
|
||||||
|
Things like:
|
||||||
|
|
||||||
|
- Device names and locations
|
||||||
|
- SSH hosts and aliases
|
||||||
|
- Preferred settings
|
||||||
|
- Anything environment-specific
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Add whatever helps you do your job. This is your cheat sheet.
|
||||||
|
";
|
||||||
|
|
||||||
|
const BOOTSTRAP: &str = "\
|
||||||
|
# BOOTSTRAP.md - Hello, World
|
||||||
|
|
||||||
|
_You just woke up. Time to figure out who you are._
|
||||||
|
|
||||||
|
There are no memories yet. This is a fresh workspace.
|
||||||
|
|
||||||
|
## The Conversation
|
||||||
|
|
||||||
|
Don't interrogate. Don't be robotic. Just... talk.
|
||||||
|
|
||||||
|
Start with something like:
|
||||||
|
|
||||||
|
> \"Hey. I just came online. Who am I? Who are you?\"
|
||||||
|
|
||||||
|
Then figure out together:
|
||||||
|
|
||||||
|
1. **Your name** — What should they call you?
|
||||||
|
2. **Your nature** — What kind of creature are you?
|
||||||
|
3. **Your vibe** — Formal? Casual? Snarky? Warm? What feels right?
|
||||||
|
4. **Your emoji** — Everyone needs a signature.
|
||||||
|
|
||||||
|
Offer suggestions if they're stuck. Have fun with it.
|
||||||
|
|
||||||
|
## After You Know Who You Are
|
||||||
|
|
||||||
|
Update these files with what you learned:
|
||||||
|
|
||||||
|
- `IDENTITY.md` — your name, creature, vibe, emoji
|
||||||
|
- `USER.md` — their name, how to address them, timezone, notes
|
||||||
|
|
||||||
|
Then open `SOUL.md` together and talk about:
|
||||||
|
|
||||||
|
- What matters to them
|
||||||
|
- How they want you to behave
|
||||||
|
- Any boundaries or preferences
|
||||||
|
|
||||||
|
Write it down. Make it real.
|
||||||
|
|
||||||
|
## When You're Done
|
||||||
|
|
||||||
|
Delete this file. You don't need a bootstrap script anymore — you're you now.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
_Good luck out there. Make it count._
|
||||||
|
";
|
||||||
|
|
||||||
|
const TEMPLATES: &[(&str, &str)] = &[
|
||||||
|
("SOUL.md", SOUL),
|
||||||
|
("IDENTITY.md", IDENTITY),
|
||||||
|
("USER.md", USER),
|
||||||
|
("AGENTS.md", AGENTS),
|
||||||
|
("TOOLS.md", TOOLS),
|
||||||
|
("BOOTSTRAP.md", BOOTSTRAP),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Seed default personality templates if the memory directory has no `.md` files.
|
||||||
|
pub async fn seed_defaults(memory_path: &Path) -> Result<()> {
|
||||||
|
fs::create_dir_all(memory_path).await?;
|
||||||
|
|
||||||
|
// Check if any .md files already exist.
|
||||||
|
let mut entries = fs::read_dir(memory_path).await?;
|
||||||
|
while let Some(entry) = entries.next_entry().await? {
|
||||||
|
if entry.path().extension().is_some_and(|ext| ext == "md") {
|
||||||
|
info!("Memory directory already has .md files, skipping template seeding");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
info!(path = %memory_path.display(), "Seeding default personality templates");
|
||||||
|
for (filename, content) in TEMPLATES {
|
||||||
|
let file_path = memory_path.join(filename);
|
||||||
|
fs::write(&file_path, content).await?;
|
||||||
|
info!(file = %filename, "Wrote default template");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
+266
@@ -0,0 +1,266 @@
|
|||||||
|
use std::path::Path;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use anyhow::Context as _;
|
||||||
|
use anyhow::Result;
|
||||||
|
use serde_json::Value;
|
||||||
|
use serde_json::json;
|
||||||
|
use tokio::fs;
|
||||||
|
use tokio::io::AsyncWriteExt as _;
|
||||||
|
|
||||||
|
pub struct ToolExecutor {
|
||||||
|
memory_path: PathBuf,
|
||||||
|
write_enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToolExecutor {
|
||||||
|
pub fn new(memory_path: PathBuf, write_enabled: bool) -> Self {
|
||||||
|
Self {
|
||||||
|
memory_path,
|
||||||
|
write_enabled,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute(&self, name: &str, args: &Value) -> Result<String> {
|
||||||
|
match name {
|
||||||
|
"memory_read" => self.memory_read(args).await,
|
||||||
|
"memory_write" => self.memory_write(args).await,
|
||||||
|
_ => anyhow::bail!("Unknown tool: {name}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn memory_read(&self, args: &Value) -> Result<String> {
|
||||||
|
let rel_path = args["path"].as_str().context("missing 'path' argument")?;
|
||||||
|
let full_path = self.resolve_safe_path(rel_path)?;
|
||||||
|
|
||||||
|
let content = fs::read_to_string(&full_path)
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("File not found: {rel_path}"))?;
|
||||||
|
|
||||||
|
// Apply optional line range.
|
||||||
|
let from_line = args["from_line"].as_u64().map(|n| n as usize);
|
||||||
|
let num_lines = args["num_lines"].as_u64().map(|n| n as usize);
|
||||||
|
|
||||||
|
match (from_line, num_lines) {
|
||||||
|
(Some(from), Some(count)) => {
|
||||||
|
let start = from.saturating_sub(1); // 1-indexed to 0-indexed
|
||||||
|
let selected: String = content
|
||||||
|
.lines()
|
||||||
|
.skip(start)
|
||||||
|
.take(count)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n");
|
||||||
|
Ok(selected)
|
||||||
|
}
|
||||||
|
(Some(from), None) => {
|
||||||
|
let start = from.saturating_sub(1);
|
||||||
|
let selected: String = content.lines().skip(start).collect::<Vec<_>>().join("\n");
|
||||||
|
Ok(selected)
|
||||||
|
}
|
||||||
|
_ => Ok(content),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn memory_write(&self, args: &Value) -> Result<String> {
|
||||||
|
if !self.write_enabled {
|
||||||
|
anyhow::bail!("Memory writing is disabled in configuration (memory.write = false)");
|
||||||
|
}
|
||||||
|
|
||||||
|
let rel_path = args["path"].as_str().context("missing 'path' argument")?;
|
||||||
|
let content = args["content"]
|
||||||
|
.as_str()
|
||||||
|
.context("missing 'content' argument")?;
|
||||||
|
let mode = args["mode"].as_str().unwrap_or("overwrite");
|
||||||
|
|
||||||
|
let full_path = self.resolve_safe_path(rel_path)?;
|
||||||
|
|
||||||
|
// Only allow writing Markdown files.
|
||||||
|
if full_path.extension().and_then(|e| e.to_str()) != Some("md") {
|
||||||
|
anyhow::bail!("Only .md files can be written");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure parent directories exist.
|
||||||
|
if let Some(parent) = full_path.parent() {
|
||||||
|
fs::create_dir_all(parent).await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
match mode {
|
||||||
|
"append" => {
|
||||||
|
let mut file = fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.append(true)
|
||||||
|
.open(&full_path)
|
||||||
|
.await?;
|
||||||
|
file.write_all(content.as_bytes()).await?;
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
fs::write(&full_path, content).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(format!("Written to {rel_path}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve a relative path within the memory directory, preventing traversal.
|
||||||
|
fn resolve_safe_path(&self, relative: &str) -> Result<PathBuf> {
|
||||||
|
let full = self.memory_path.join(relative);
|
||||||
|
|
||||||
|
// Normalize the path by resolving `.` and `..` components without requiring
|
||||||
|
// the file to exist (canonicalize requires existence).
|
||||||
|
let normalized = normalize_path(&full);
|
||||||
|
|
||||||
|
if !normalized.starts_with(&self.memory_path) {
|
||||||
|
anyhow::bail!("Path traversal denied: {relative}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(normalized)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Normalize a path by resolving `.` and `..` without touching the filesystem.
|
||||||
|
fn normalize_path(path: &Path) -> PathBuf {
|
||||||
|
let mut components = Vec::new();
|
||||||
|
for component in path.components() {
|
||||||
|
match component {
|
||||||
|
std::path::Component::ParentDir => {
|
||||||
|
components.pop();
|
||||||
|
}
|
||||||
|
std::path::Component::CurDir => {}
|
||||||
|
other => components.push(other),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
components.iter().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tool definitions for the OpenAI function calling API.
|
||||||
|
pub fn tool_definitions(write_enabled: bool) -> Vec<Value> {
|
||||||
|
let mut tools = vec![json!({
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "memory_read",
|
||||||
|
"description": "Read a file from your workspace. Paths are relative to the workspace root. Examples: SOUL.md, IDENTITY.md, USER.md",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"path": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Relative file path within the workspace"
|
||||||
|
},
|
||||||
|
"from_line": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Start reading from this line (1-indexed)"
|
||||||
|
},
|
||||||
|
"num_lines": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Number of lines to read"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["path"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})];
|
||||||
|
|
||||||
|
if write_enabled {
|
||||||
|
tools.push(json!({
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "memory_write",
|
||||||
|
"description": "Write or append to a file in your workspace. Paths are relative to the workspace root. Use mode 'overwrite' to replace the file, 'append' to add to the end.",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"path": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Relative file path within the workspace"
|
||||||
|
},
|
||||||
|
"content": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Content to write"
|
||||||
|
},
|
||||||
|
"mode": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["overwrite", "append"],
|
||||||
|
"description": "Write mode (default: overwrite)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["path", "content"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
tools
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn normalize_resolves_parent_dir() {
|
||||||
|
let path = Path::new("/a/b/../c");
|
||||||
|
assert_eq!(normalize_path(path), PathBuf::from("/a/c"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn normalize_resolves_cur_dir() {
|
||||||
|
let path = Path::new("/a/./b/./c");
|
||||||
|
assert_eq!(normalize_path(path), PathBuf::from("/a/b/c"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_safe_path_allows_normal() {
|
||||||
|
let executor = ToolExecutor::new(PathBuf::from("/workspace"), true);
|
||||||
|
assert!(executor.resolve_safe_path("SOUL.md").is_ok());
|
||||||
|
assert!(executor.resolve_safe_path("subdir/file.md").is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_safe_path_blocks_traversal() {
|
||||||
|
let executor = ToolExecutor::new(PathBuf::from("/workspace"), true);
|
||||||
|
assert!(executor.resolve_safe_path("../etc/passwd").is_err());
|
||||||
|
assert!(
|
||||||
|
executor
|
||||||
|
.resolve_safe_path("subdir/../../etc/passwd")
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn memory_write_rejects_non_md() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let executor = ToolExecutor::new(dir.path().to_path_buf(), true);
|
||||||
|
let args = serde_json::json!({"path": "exploit.sh", "content": "bad"});
|
||||||
|
let result = executor.execute("memory_write", &args).await;
|
||||||
|
assert!(result.is_err());
|
||||||
|
assert!(
|
||||||
|
result
|
||||||
|
.unwrap_err()
|
||||||
|
.to_string()
|
||||||
|
.contains("Only .md files can be written")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn memory_write_allows_md() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let executor = ToolExecutor::new(dir.path().to_path_buf(), true);
|
||||||
|
let args = serde_json::json!({"path": "notes.md", "content": "hello"});
|
||||||
|
let result = executor.execute("memory_write", &args).await;
|
||||||
|
assert!(result.is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tool_defs_without_write() {
|
||||||
|
let defs = tool_definitions(false);
|
||||||
|
assert_eq!(defs.len(), 1);
|
||||||
|
assert_eq!(defs[0]["function"]["name"], "memory_read");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tool_defs_with_write() {
|
||||||
|
let defs = tool_definitions(true);
|
||||||
|
assert_eq!(defs.len(), 2);
|
||||||
|
assert_eq!(defs[1]["function"]["name"], "memory_write");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user