conversation: absorb tick into the actor via Inbound::Tick #69
No files matched your search
+7
-7
@@ -123,11 +123,11 @@ mod tests {
|
||||
|
||||
let registry = new_registry(tmp.path()).await;
|
||||
registry
|
||||
.push_message(&room_id, ChatMessage::user("hello"))
|
||||
.test_push_message(&room_id, ChatMessage::user("hello"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.push_message(&room_id, ChatMessage::assistant("hi"))
|
||||
.test_push_message(&room_id, ChatMessage::assistant("hi"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(snapshot_for(®istry, &room_id).await.message_count, 2);
|
||||
@@ -143,7 +143,7 @@ mod tests {
|
||||
|
||||
let registry = new_registry(tmp.path()).await;
|
||||
registry
|
||||
.push_message(&room_id, ChatMessage::user("hello"))
|
||||
.test_push_message(&room_id, ChatMessage::user("hello"))
|
||||
.await
|
||||
.unwrap();
|
||||
clear(®istry, &room_id).await;
|
||||
@@ -159,7 +159,7 @@ mod tests {
|
||||
|
||||
let registry = new_registry(tmp.path()).await;
|
||||
registry
|
||||
.push_message(&room_id, ChatMessage::user("hello"))
|
||||
.test_push_message(&room_id, ChatMessage::user("hello"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -167,7 +167,7 @@ mod tests {
|
||||
snapshot_for(®istry, &room_id).await.last_prompt_tokens,
|
||||
None
|
||||
);
|
||||
registry.set_last_prompt_tokens(&room_id, 42).await;
|
||||
registry.test_set_last_prompt_tokens(&room_id, 42).await;
|
||||
assert_eq!(
|
||||
snapshot_for(®istry, &room_id).await.last_prompt_tokens,
|
||||
Some(42)
|
||||
@@ -195,7 +195,7 @@ mod tests {
|
||||
|
||||
let registry = new_registry(tmp.path()).await;
|
||||
registry
|
||||
.push_message(&room_id, ChatMessage::user("hello"))
|
||||
.test_push_message(&room_id, ChatMessage::user("hello"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -230,7 +230,7 @@ mod tests {
|
||||
|
||||
let registry = new_registry(tmp.path()).await;
|
||||
registry
|
||||
.push_message(&room_id, ChatMessage::user("hello"))
|
||||
.test_push_message(&room_id, ChatMessage::user("hello"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
|
||||
+57
-48
@@ -7,11 +7,10 @@
|
||||
//! so two messages arriving close together for the same room are processed
|
||||
//! in arrival order through the inbox.
|
||||
//!
|
||||
//! `Inbound` is the vocabulary for callers that want the actor to run a
|
||||
//! full chat turn or administer the conversation. `LegacyPush`,
|
||||
//! `LegacySetPromptTokens`, and `LegacyMaybeCompact` are primitives for
|
||||
//! callers that assemble their own chat-completion call but still need to
|
||||
//! mutate per-room state in order.
|
||||
//! `Inbound` is the only vocabulary for mutating per-room state. Callers
|
||||
//! ask the actor to run a turn or administer the conversation; the actor
|
||||
//! is the sole writer of `history`, `last_prompt_tokens`, and
|
||||
//! `last_compaction`.
|
||||
|
||||
use anyhow::Context as _;
|
||||
use anyhow::Result;
|
||||
@@ -53,6 +52,13 @@ pub enum Inbound {
|
||||
job_id: Option<String>,
|
||||
system_prompt_extra: Option<String>,
|
||||
},
|
||||
/// Time-driven tick. Offers `tick_silent` in the tool set; if the model
|
||||
/// declines silently the returned reply is `None` and no empty assistant
|
||||
/// message is appended to history.
|
||||
Tick {
|
||||
body: String,
|
||||
sent_at: DateTime<Utc>,
|
||||
},
|
||||
/// Archive the active log and reset in-memory state.
|
||||
Reset,
|
||||
/// Force a compaction round regardless of token count.
|
||||
@@ -84,31 +90,23 @@ impl ConversationHandle {
|
||||
rx.await.context("conversation actor dropped reply channel")
|
||||
}
|
||||
|
||||
// --- Primitives for callers that assemble their own chat turn. ---
|
||||
// --- Test-only primitives. ---
|
||||
//
|
||||
// Used by callers that build the chat-completion call themselves but
|
||||
// still need to mutate per-room state in arrival order with everything
|
||||
// else flowing through the inbox.
|
||||
// Direct mutators used by conversation tests to seed history or
|
||||
// metadata without standing up a real chat turn. They route through
|
||||
// the inbox so they observe the same ordering guarantee as `Inbound`.
|
||||
|
||||
pub(crate) async fn legacy_push(&self, msg: ChatMessage) -> Result<Vec<ChatMessage>> {
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn test_push(&self, msg: ChatMessage) -> Result<Vec<ChatMessage>> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.send(Envelope::LegacyPush { msg, reply: tx })?;
|
||||
self.send(Envelope::TestPush { msg, reply: tx })?;
|
||||
rx.await
|
||||
.context("conversation actor dropped reply channel")?
|
||||
}
|
||||
|
||||
pub(crate) async fn legacy_set_prompt_tokens(&self, tokens: usize) {
|
||||
let _ = self.send(Envelope::LegacySetPromptTokens { tokens });
|
||||
}
|
||||
|
||||
pub(crate) async fn legacy_maybe_compact(&self, prompt_tokens: usize) -> Result<bool> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.send(Envelope::LegacyMaybeCompact {
|
||||
prompt_tokens,
|
||||
reply: tx,
|
||||
})?;
|
||||
rx.await
|
||||
.context("conversation actor dropped reply channel")?
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn test_set_prompt_tokens(&self, tokens: usize) {
|
||||
let _ = self.send(Envelope::TestSetPromptTokens { tokens });
|
||||
}
|
||||
|
||||
fn send(&self, env: Envelope) -> Result<()> {
|
||||
@@ -127,18 +125,16 @@ pub(crate) enum Envelope {
|
||||
reply: oneshot::Sender<Snapshot>,
|
||||
},
|
||||
|
||||
// See `ConversationHandle::legacy_*`.
|
||||
LegacyPush {
|
||||
// See `ConversationHandle::test_*`.
|
||||
#[cfg(test)]
|
||||
TestPush {
|
||||
msg: ChatMessage,
|
||||
reply: oneshot::Sender<Result<Vec<ChatMessage>>>,
|
||||
},
|
||||
LegacySetPromptTokens {
|
||||
#[cfg(test)]
|
||||
TestSetPromptTokens {
|
||||
tokens: usize,
|
||||
},
|
||||
LegacyMaybeCompact {
|
||||
prompt_tokens: usize,
|
||||
reply: oneshot::Sender<Result<bool>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// State + behaviour owned by one actor task. Constructed by the registry,
|
||||
@@ -195,18 +191,14 @@ impl Conversation {
|
||||
Envelope::Snapshot { reply } => {
|
||||
let _ = reply.send(self.snapshot());
|
||||
}
|
||||
Envelope::LegacyPush { msg, reply } => {
|
||||
#[cfg(test)]
|
||||
Envelope::TestPush { msg, reply } => {
|
||||
let _ = reply.send(self.append_message(msg).await);
|
||||
}
|
||||
Envelope::LegacySetPromptTokens { tokens } => {
|
||||
#[cfg(test)]
|
||||
Envelope::TestSetPromptTokens { tokens } => {
|
||||
self.last_prompt_tokens = Some(tokens);
|
||||
}
|
||||
Envelope::LegacyMaybeCompact {
|
||||
prompt_tokens,
|
||||
reply,
|
||||
} => {
|
||||
let _ = reply.send(self.maybe_compact(prompt_tokens).await);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,7 +207,7 @@ impl Conversation {
|
||||
Inbound::User { body, sent_at } => {
|
||||
let tag = sent_at.format(TIMESTAMP_FORMAT).to_string();
|
||||
let stamped = format::format_tagged(&tag, &body);
|
||||
Ok(Some(self.run_turn(stamped, None).await?))
|
||||
Ok(Some(self.run_turn(stamped, None, false).await?))
|
||||
}
|
||||
Inbound::Bot {
|
||||
body,
|
||||
@@ -229,10 +221,20 @@ impl Conversation {
|
||||
None => format::format_tagged(&tag, &body),
|
||||
};
|
||||
Ok(Some(
|
||||
self.run_turn(stamped, system_prompt_extra.as_deref())
|
||||
self.run_turn(stamped, system_prompt_extra.as_deref(), false)
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
Inbound::Tick { body, sent_at } => {
|
||||
let tag = sent_at.format(TIMESTAMP_FORMAT).to_string();
|
||||
let stamped = format::format_tagged(&tag, &body);
|
||||
let reply = self.run_turn(stamped, None, true).await?;
|
||||
if reply.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(reply))
|
||||
}
|
||||
}
|
||||
Inbound::Reset => {
|
||||
self.reset().await?;
|
||||
Ok(None)
|
||||
@@ -253,8 +255,9 @@ impl Conversation {
|
||||
}
|
||||
|
||||
/// Append a message to history, persist to disk, return the full
|
||||
/// history. Used by the legacy push shim for callers that need to feed
|
||||
/// the messages back into an LLM call themselves.
|
||||
/// history. Test-only — used by conversation tests to seed history
|
||||
/// without standing up a real chat turn.
|
||||
#[cfg(test)]
|
||||
async fn append_message(&mut self, msg: ChatMessage) -> Result<Vec<ChatMessage>> {
|
||||
self.history.push(msg.clone());
|
||||
self.persistence.append(&msg).await?;
|
||||
@@ -265,11 +268,15 @@ impl Conversation {
|
||||
/// and tagged. Pushes the user message, calls the LLM (with tools),
|
||||
/// persists intermediates and the assistant reply, sets
|
||||
/// `last_prompt_tokens`, and triggers `maybe_compact`. `system_prompt_extra`
|
||||
/// is appended to the personality system prompt for this turn only.
|
||||
/// is appended to the personality system prompt for this turn only. When
|
||||
/// `tick` is true, the `tick_silent` tool becomes available; if the
|
||||
/// model declines silently (empty reply), no assistant message is
|
||||
/// appended to history.
|
||||
async fn run_turn(
|
||||
&mut self,
|
||||
stamped_body: String,
|
||||
system_prompt_extra: Option<&str>,
|
||||
tick: bool,
|
||||
) -> Result<String> {
|
||||
let user_msg = ChatMessage::user(stamped_body);
|
||||
self.history.push(user_msg.clone());
|
||||
@@ -286,7 +293,7 @@ impl Conversation {
|
||||
|
||||
let ctx = ToolContext {
|
||||
room_id: self.tool_room_id.clone(),
|
||||
tick: false,
|
||||
tick,
|
||||
};
|
||||
|
||||
let result = self
|
||||
@@ -302,10 +309,12 @@ impl Conversation {
|
||||
}
|
||||
}
|
||||
|
||||
let assistant_msg = ChatMessage::assistant(&result.reply);
|
||||
self.history.push(assistant_msg.clone());
|
||||
if let Err(err) = self.persistence.append(&assistant_msg).await {
|
||||
warn!(error = %err, "Failed to persist assistant message");
|
||||
if !(tick && result.reply.is_empty()) {
|
||||
let assistant_msg = ChatMessage::assistant(&result.reply);
|
||||
self.history.push(assistant_msg.clone());
|
||||
if let Err(err) = self.persistence.append(&assistant_msg).await {
|
||||
warn!(error = %err, "Failed to persist assistant message");
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(tokens) = result.prompt_tokens {
|
||||
|
||||
@@ -6,12 +6,6 @@
|
||||
//! on the first `handle()` call; cold lookups read history and the
|
||||
//! compaction record from disk.
|
||||
//!
|
||||
//! `push_message`, `set_last_prompt_tokens`, `maybe_compact`, and `clear`
|
||||
//! give callers that build a chat-completion call themselves a way to
|
||||
//! mutate per-room state without exposing the inner actor types. Each
|
||||
//! routes through the actor's inbox so the per-room ordering guarantee
|
||||
//! holds for them too.
|
||||
//!
|
||||
//! `Persistence` is the on-disk layer for a single room. Each actor owns
|
||||
//! its own `Persistence`; the registry holds the parameters needed to
|
||||
//! construct one (the conversations directory and the archive directory).
|
||||
@@ -273,37 +267,29 @@ impl ConversationRegistry {
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
// --- Mutators used by callers that assemble their own chat turn. ---
|
||||
// --- Test-only direct mutators. ---
|
||||
//
|
||||
// Each method routes through the actor inbox so the per-room
|
||||
// ordering guarantee is preserved for these callers too. These shims
|
||||
// exist for callers (today: the tick loop) that haven't migrated to
|
||||
// `Inbound::*` yet — they wrap real Matrix room ids only.
|
||||
// Conversation tests seed history and metadata through these shims
|
||||
// rather than standing up a real chat turn. They route through the
|
||||
// actor inbox so they share the per-room ordering guarantee.
|
||||
|
||||
pub async fn push_message(
|
||||
#[cfg(test)]
|
||||
pub async fn test_push_message(
|
||||
&self,
|
||||
room_id: &RoomId,
|
||||
message: ChatMessage,
|
||||
) -> Result<Vec<ChatMessage>> {
|
||||
self.matrix_handle(room_id)
|
||||
.await?
|
||||
.legacy_push(message)
|
||||
.await
|
||||
self.matrix_handle(room_id).await?.test_push(message).await
|
||||
}
|
||||
|
||||
pub async fn set_last_prompt_tokens(&self, room_id: &RoomId, tokens: usize) {
|
||||
#[cfg(test)]
|
||||
pub async fn test_set_last_prompt_tokens(&self, room_id: &RoomId, tokens: usize) {
|
||||
if let Ok(handle) = self.matrix_handle(room_id).await {
|
||||
handle.legacy_set_prompt_tokens(tokens).await;
|
||||
handle.test_set_prompt_tokens(tokens).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn maybe_compact(&self, room_id: &RoomId, prompt_tokens: usize) -> Result<bool> {
|
||||
self.matrix_handle(room_id)
|
||||
.await?
|
||||
.legacy_maybe_compact(prompt_tokens)
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
async fn matrix_handle(&self, room_id: &RoomId) -> Result<ConversationHandle> {
|
||||
self.handle(&ConversationId::Matrix(room_id.to_owned()))
|
||||
.await
|
||||
|
||||
@@ -18,16 +18,12 @@ use crate::conversation::ConversationRegistry;
|
||||
use crate::conversation::Inbound;
|
||||
use crate::conversation::outbound::OutboundSender;
|
||||
use crate::llm::LlmClient;
|
||||
use crate::personality::Personality;
|
||||
use crate::scheduler::Scheduler;
|
||||
use crate::tools::ToolRegistry;
|
||||
|
||||
pub struct AppState {
|
||||
pub llm: Arc<LlmClient>,
|
||||
pub trusted_users: Vec<OwnedUserId>,
|
||||
pub conversations: Arc<ConversationRegistry>,
|
||||
pub personality: Arc<Personality>,
|
||||
pub tool_registry: Arc<ToolRegistry>,
|
||||
pub memory_path: PathBuf,
|
||||
pub memory_write: bool,
|
||||
pub scheduler: Option<Arc<Scheduler>>,
|
||||
|
||||
@@ -137,8 +137,6 @@ pub async fn run(config: &Config) -> Result<()> {
|
||||
llm,
|
||||
trusted_users: config.matrix.trusted_users.clone(),
|
||||
conversations,
|
||||
personality,
|
||||
tool_registry,
|
||||
memory_path,
|
||||
memory_write: config.memory.write,
|
||||
scheduler,
|
||||
|
||||
+16
-63
@@ -3,6 +3,7 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use chrono::Utc;
|
||||
use matrix_sdk::Client;
|
||||
use matrix_sdk::ruma::OwnedRoomId;
|
||||
use rand::Rng;
|
||||
@@ -12,10 +13,9 @@ use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::config::TickConfig;
|
||||
use crate::format_current_timestamp;
|
||||
use crate::conversation::ConversationId;
|
||||
use crate::conversation::Inbound;
|
||||
use crate::handler::AppState;
|
||||
use crate::llm::ChatMessage;
|
||||
use crate::tools::ToolContext;
|
||||
|
||||
/// Primes near 30 minutes used when interval is not configured.
|
||||
const DEFAULT_PRIMES: &[u64] = &[29, 31];
|
||||
@@ -156,9 +156,7 @@ async fn tick_room(
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let timestamp = format_current_timestamp();
|
||||
let prompt = format!(
|
||||
"{timestamp} System Tick\n\
|
||||
let body = "System Tick\n\
|
||||
\n\
|
||||
The system has been inactive for some time. The user has not messaged you, this is not an interactive request.\n\
|
||||
\n\
|
||||
@@ -180,68 +178,23 @@ async fn tick_room(
|
||||
- If the reason for speaking would be phrased as \"I thought I should…\", rather than something concrete.\n\
|
||||
\n\
|
||||
Remember that your default is `tick_silent` and that silence is a virtue."
|
||||
);
|
||||
.to_owned();
|
||||
|
||||
let system_prompt = state.personality.build_system_prompt().await;
|
||||
|
||||
let history = state
|
||||
let handle = state
|
||||
.conversations
|
||||
.push_message(room_id, ChatMessage::user(&prompt))
|
||||
.handle(&ConversationId::Matrix(room_id.to_owned()))
|
||||
.await?;
|
||||
|
||||
let mut messages = vec![ChatMessage::system(system_prompt)];
|
||||
messages.extend(history);
|
||||
|
||||
let ctx = ToolContext {
|
||||
room_id: Some(room_id.to_owned()),
|
||||
tick: true,
|
||||
};
|
||||
|
||||
let result = state
|
||||
.llm
|
||||
.chat_completion_with_tools(&messages, &state.tool_registry, &ctx)
|
||||
.await?;
|
||||
|
||||
for msg in &result.intermediate_messages {
|
||||
if let Err(err) = state.conversations.push_message(room_id, msg.clone()).await {
|
||||
warn!(error = %err, "Failed to persist intermediate tick message");
|
||||
}
|
||||
}
|
||||
|
||||
let is_silent = result
|
||||
.intermediate_messages
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|m| m.role == "assistant")
|
||||
.and_then(|m| m.tool_calls.as_ref())
|
||||
.map(|tcs| tcs.iter().any(|tc| tc.function.name == "tick_silent"))
|
||||
.unwrap_or(false);
|
||||
|
||||
if let Some(tokens) = result.prompt_tokens {
|
||||
state
|
||||
.conversations
|
||||
.set_last_prompt_tokens(room_id, tokens)
|
||||
.await;
|
||||
if let Err(err) = state.conversations.maybe_compact(room_id, tokens).await {
|
||||
warn!(error = %err, room = %room_id, "Compaction failed after tick");
|
||||
}
|
||||
}
|
||||
|
||||
if is_silent {
|
||||
info!(room = %room_id, "Tick declined (silent)");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Err(err) = state
|
||||
.conversations
|
||||
.push_message(room_id, ChatMessage::assistant(&result.reply))
|
||||
.await
|
||||
match handle
|
||||
.deliver(Inbound::Tick {
|
||||
body,
|
||||
sent_at: Utc::now(),
|
||||
})
|
||||
.await?
|
||||
{
|
||||
warn!(error = %err, "Failed to persist assistant tick message");
|
||||
}
|
||||
|
||||
if !result.reply.is_empty() {
|
||||
state.outbound.reply(room_id, &result.reply);
|
||||
None => info!(room = %room_id, "Tick declined (silent)"),
|
||||
Some(reply) if !reply.is_empty() => state.outbound.reply(room_id, &reply),
|
||||
Some(_) => {}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
Reference in new issue
Block a user