Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(agent): let an agent send resumed threads its current prompt

Shanu471a55f598e1
diff --git a/AGENTS.md b/AGENTS.md
index 0045848578..c8e5d805af 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -489,7 +489,11 @@ seed history by hand, or pick a transcript by recency.
- **A resumed session's prompt is frozen.** It reuses its persisted system
messages verbatim, which is what keeps the provider's prefix cache warm
across a restart. The accepted consequence is that prompt edits, new skills
- and newly connected integrations do not reach an existing thread.
+ and newly connected integrations do not reach an existing thread, unless
+ the agent's definition sets `refresh_prompt_on_resume`: then a resumed
+ thread is sent the prompt rendered now, and a changed prompt seals the
+ current generation and continues the conversation in the next
+ (`agent/session_host/runtime_session/prompt_refresh.rs`).
- **So is the tool list it was sent.** Every turn records its tool
declarations in the transcript (a `{"kind":"tools"}` record, written only
when they change); resume restores them, the prefix, and the committed-turn
diff --git a/crates/openhuman-core/src/agent/harness/host_definition.rs b/crates/openhuman-core/src/agent/harness/host_definition.rs
index d2f3d325e8..76a7698ecf 100644
--- a/crates/openhuman-core/src/agent/harness/host_definition.rs
+++ b/crates/openhuman-core/src/agent/harness/host_definition.rs
@@ -57,6 +57,23 @@ pub struct AgentExt {
/// `light`; see [`AgentExt::tokenjuice_for`].
#[serde(default)]
pub tokenjuice_compression: AgentTokenjuiceCompression,
+ /// Whether this agent's threads take up the prompt it renders now when
+ /// they resume, rather than replay the one recorded on their transcript.
+ ///
+ /// Off by default: a resumed thread reuses its recorded system messages
+ /// verbatim, which keeps the provider's prefix cache warm across a
+ /// restart, so prompt edits reach only new threads. On, the prompt is
+ /// rendered again on every resumed turn, and a thread whose recorded
+ /// prompt differs continues under the current one with its conversation
+ /// intact: the session seals the transcript generation it was on and
+ /// carries the conversation into the next, and that turn's user message
+ /// opens with a one-time note that the instructions changed, so the model
+ /// does not hold to what it said under the old ones. An unchanged prompt
+ /// writes nothing. A composed prompt also refreshes when the live state it
+ /// renders changes (connected integrations, skills, AGENTS.md), never
+ /// before the session has read its integrations.
+ #[serde(default)]
+ pub refresh_prompt_on_resume: bool,
/// Whether this agent's turns can search and call the tools of every
/// connected MCP server (deferred, through `tool_search`).
#[serde(default)]
@@ -74,6 +91,7 @@ impl Default for AgentExt {
omit_memory_context: true,
omit_safety_preamble: true,
tokenjuice_compression: AgentTokenjuiceCompression::default(),
+ refresh_prompt_on_resume: false,
searches_connected_mcp: false,
prompt_builder: None,
}
diff --git a/crates/openhuman-core/src/agent/harness/host_definition_tests.rs b/crates/openhuman-core/src/agent/harness/host_definition_tests.rs
index 52a0664c08..9cc69a8b13 100644
--- a/crates/openhuman-core/src/agent/harness/host_definition_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/host_definition_tests.rs
@@ -362,6 +362,7 @@ when_to_use = "defaults"
assert!(def.extensions.omit_memory_context);
assert!(def.extensions.omit_safety_preamble);
assert!(!def.extensions.searches_connected_mcp);
+ assert!(!def.extensions.refresh_prompt_on_resume);
assert!(def.extensions.prompt_builder.is_none());
}
@@ -373,12 +374,14 @@ id = "opted_in"
when_to_use = "host flags"
omit_identity = false
searches_connected_mcp = true
+refresh_prompt_on_resume = true
tokenjuice_compression = "light"
"#,
)
.unwrap();
assert!(!def.extensions.omit_identity);
assert!(def.extensions.searches_connected_mcp);
+ assert!(def.extensions.refresh_prompt_on_resume);
assert_eq!(
def.extensions.tokenjuice_compression,
tinyjuice_bus::types::AgentTokenjuiceCompression::Light
diff --git a/crates/openhuman-core/src/agent/session_host/README.md b/crates/openhuman-core/src/agent/session_host/README.md
index f5b70a2fea..1510d04bce 100644
--- a/crates/openhuman-core/src/agent/session_host/README.md
+++ b/crates/openhuman-core/src/agent/session_host/README.md
@@ -49,6 +49,20 @@ deferred executors instead of dropping them when a cache goes cold, and
`prelude_integrations.rs` re-fetches integrations on the first turn of every
session instance rather than only on a brand-new thread.
+An agent whose definition sets `refresh_prompt_on_resume` opts out of the
+prompt half of that freeze. `runtime_session/prompt_refresh.rs` renders its
+prompt again on every resumed turn and offers it as a refreshing prefix; the
+runtime applies it only when it differs from the recorded one, and a
+thread-bound session then seals the current generation and carries the
+conversation into the next. That turn's user message opens with a one-time
+`[instructions update]` note: the conversation before it was written under the
+old prompt, and a model otherwise keeps to what it said there (that a feature
+is "coming soon") over the new instructions. A verbatim prompt therefore costs
+one uncached prompt per thread per edit. A composed one also refreshes when
+the live state it renders changes, but never from integrations the session has
+not read yet. A prompt that fails to render, or a recorded prompt of unknown
+extent, keeps the recorded prompt. The recorded tool list is unaffected.
+
Compaction never erases history. It seals the current generation and opens
the next one, recording the sealed generation as the new one's parent; the
sealed file stays on disk, and `session_api.rs` is what lets a caller list a
diff --git a/crates/openhuman-core/src/agent/session_host/prefix_snapshot.rs b/crates/openhuman-core/src/agent/session_host/prefix_snapshot.rs
index 40301bd22e..4cca0fd9dd 100644
--- a/crates/openhuman-core/src/agent/session_host/prefix_snapshot.rs
+++ b/crates/openhuman-core/src/agent/session_host/prefix_snapshot.rs
@@ -6,7 +6,9 @@
//! prefix, so `runtime_session` never has to know how many messages a prefix
//! is. A resumed thread's prefix is restored by the tinyagents session using
//! the transcript's recorded frozen-prefix count (or the legacy generation
-//! fallback); nothing here re-derives it.
+//! fallback). Only an agent that sets `refresh_prompt_on_resume` has it
+//! rendered again, through this same helper, and offered as a refresh
+//! (`runtime_session/prompt_refresh.rs`).
use tinyagents_runtime::PrefixSnapshot;
use tinyinference_llm::message::Message;
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
index ed3f3b70fe..c47e859742 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -10,6 +10,7 @@ mod attachment_input;
mod memory_ingest;
mod permanent;
mod post_commit;
+mod prompt_refresh;
mod tool_rules;
mod transcript;
#[path = "runtime_session_turn.rs"]
@@ -879,11 +880,9 @@ impl OpenHumanSessionHost {
);
options.run_context.data.memory_turn = memory_turn;
request.input = user_message_from_text(&enriched);
- let mut preparation =
- prelude.prepare(new_session).await.map_err(|error| {
- tinyagents_runtime::RuntimeError::Driver(error.to_string())
- })?;
- prelude.refresh_permanent_prefix(&mut preparation, view.prefix);
+ let mut preparation = prelude
+ .prepare_turn(new_session, &view, &transcript_snapshot, request)
+ .await?;
if turn.overrides.suppress_tools {
// One-off tool-less turn: must not become the
// thread's recorded tool list.
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_refresh.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_refresh.rs
new file mode 100644
index 0000000000..39d4bab613
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_refresh.rs
@@ -0,0 +1,160 @@
+//! The system prompt a resumed thread is sent.
+//!
+//! A resumed thread's prefix is frozen: the runtime restores the system
+//! messages its transcript recorded and sends them verbatim, which keeps the
+//! provider's prefix cache warm across a restart. A turn can still offer a
+//! replacement, which the runtime applies only when it differs from what is
+//! recorded; a thread-bound session then seals the transcript generation it
+//! was on and carries its conversation into the next. Two things offer one:
+//!
+//! - the permanent-tool catalogue (`permanent.rs`), whenever it changes;
+//! - the whole prompt, rendered afresh, when the agent's definition sets
+//! `refresh_prompt_on_resume`, so prompt edits reach existing threads too.
+//!
+//! Whatever is offered, the turn's transcript snapshot boundary moves with
+//! it: the request starts with the offered prefix, not the recorded one.
+//!
+//! When the whole prompt is replaced, the user's message on that turn opens
+//! with a one-time note saying so (`PROMPT_UPDATE_NOTE`). The conversation
+//! before it was written under the old prompt, and a model keeps to what it
+//! already said there (that something is "coming soon", say) over
+//! instructions that changed since.
+
+use std::sync::PoisonError;
+
+use tinyagents_definition::PromptSource;
+use tinyagents_runtime::{
+ PrefixSnapshot, RuntimeError, SessionStateView, SessionTurnRequest, TurnPreparation,
+};
+use tinyinference_llm::message::Message;
+
+use super::OpenHumanTurnPrelude;
+use crate::agent::message_convert::{user_message_from_text, user_text_with_markers};
+use crate::agent::tinyagents::middleware::turn_context::TranscriptSnapshotSink;
+
+/// Prepended to the user's message on the turn a resumed thread's prompt is
+/// replaced; the turn's record keeps it, so later turns see where the change
+/// happened.
+pub(super) const PROMPT_UPDATE_NOTE: &str = "[instructions update] Your system instructions changed since the earlier messages in this conversation. Where they differ from anything said before, including what you said you could or could not do, follow your current instructions. This is an update, not a request: respond to the user's message below.";
+
+impl OpenHumanTurnPrelude {
+ /// This turn's tool snapshot and, when it changes, its prefix: what
+ /// `prepare` builds, plus the refreshes a resumed thread's recorded
+ /// prefix may take (see the module docs). `snapshot`'s request boundary
+ /// is rebased onto the prefix offered, and `request` carries the
+ /// `PROMPT_UPDATE_NOTE` when the prompt is replaced.
+ pub(super) async fn prepare_turn(
+ &self,
+ new_session: bool,
+ view: &SessionStateView<'_>,
+ snapshot: &TranscriptSnapshotSink,
+ request: &mut SessionTurnRequest,
+ ) -> Result<TurnPreparation, RuntimeError> {
+ let mut preparation = self
+ .prepare(new_session)
+ .await
+ .map_err(|error| RuntimeError::Driver(error.to_string()))?;
+ let refresh_prompt = view.resumed && self.refreshes_prompt_on_resume();
+ if refresh_prompt {
+ preparation.prefix = self.current_prompt_prefix(view);
+ }
+ self.refresh_permanent_prefix(&mut preparation, view.prefix);
+ if let Some(prefix) = preparation.prefix.as_ref() {
+ // The runtime sends `prefix` in place of the recorded one, so the
+ // rounds this run produces start that much further on (or back).
+ let mut snapshot = snapshot.lock().unwrap_or_else(PoisonError::into_inner);
+ snapshot.request_base_len = snapshot
+ .request_base_len
+ .saturating_sub(view.prefix.messages().len())
+ + prefix.messages().len();
+ }
+ if refresh_prompt {
+ let changed = preparation
+ .prefix
+ .as_ref()
+ .is_some_and(|prefix| prefix.messages() != view.prefix.messages());
+ if changed {
+ tracing::info!(
+ thread_id = ?self.thread_id,
+ recorded_segments = view.prefix.messages().len(),
+ "[session] refresh_prompt_on_resume: the resumed thread's prompt is out of date; it continues under the current one"
+ );
+ let text = user_text_with_markers(&request.input);
+ request.input = user_message_from_text(&format!("{PROMPT_UPDATE_NOTE}\n\n{text}"));
+ } else {
+ tracing::debug!(
+ thread_id = ?self.thread_id,
+ "[session] refresh_prompt_on_resume: the resumed thread keeps its prompt"
+ );
+ }
+ }
+ Ok(preparation)
+ }
+
+ /// Whether the agent's definition asks for a resumed thread to take up
+ /// the prompt rendered now (`refresh_prompt_on_resume`).
+ fn refreshes_prompt_on_resume(&self) -> bool {
+ self.definition
+ .as_ref()
+ .is_some_and(|definition| definition.extensions.refresh_prompt_on_resume)
+ }
+
+ /// The prompt this agent renders now, offered in place of the prefix the
+ /// resumed thread in `view` restored from its transcript; `None` keeps
+ /// the recorded prompt.
+ ///
+ /// It is kept when:
+ ///
+ /// - that prefix is empty while the history still opens on system rows:
+ /// the extent of the recorded prompt could not be recovered (a
+ /// compacted legacy head), so its old instructions are still part of
+ /// the history, and a new prompt beside them would leave them in place;
+ /// - the prompt renders live state (anything but a verbatim prompt) and
+ /// the connected integrations have not been read this session: a prompt
+ /// rendered without them would replace a complete one;
+ /// - the prompt cannot be rendered: the thread goes on under the one it
+ /// has rather than failing its turn.
+ fn current_prompt_prefix(&self, view: &SessionStateView<'_>) -> Option<PrefixSnapshot> {
+ let unknown_extent = view.prefix.messages().is_empty()
+ && matches!(view.history.first(), Some(Message::System(_)));
+ if unknown_extent {
+ tracing::warn!(
+ thread_id = ?self.thread_id,
+ "[session] refresh_prompt_on_resume: the resumed thread's recorded prompt has no known extent; keeping it"
+ );
+ return None;
+ }
+ let verbatim = self.definition.as_ref().is_some_and(|definition| {
+ matches!(definition.system_prompt, PromptSource::Verbatim(_))
+ });
+ let hydrated = {
+ let mutable = self.mutable.lock().unwrap_or_else(PoisonError::into_inner);
+ mutable.connected_integrations_initialized
+ && mutable.connected_integrations_authoritative
+ };
+ if !verbatim && !hydrated {
+ tracing::debug!(
+ thread_id = ?self.thread_id,
+ "[session] refresh_prompt_on_resume: integrations not read yet; keeping the recorded prompt"
+ );
+ return None;
+ }
+ match self.build_system_prompt_tiered() {
+ Ok(tiered) => {
+ Some(super::super::prefix_snapshot::tiered_prefix_snapshot(&tiered).refreshing())
+ }
+ Err(error) => {
+ tracing::warn!(
+ thread_id = ?self.thread_id,
+ %error,
+ "[session] refresh_prompt_on_resume: the current prompt did not render; keeping the recorded one"
+ );
+ None
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "prompt_refresh_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_refresh_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_refresh_tests.rs
new file mode 100644
index 0000000000..fdb6d67f16
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/prompt_refresh_tests.rs
@@ -0,0 +1,493 @@
+//! A resumed thread whose agent sets `refresh_prompt_on_resume` is sent the
+//! prompt the agent renders now; without it, it keeps the one it recorded.
+
+use super::*;
+use std::sync::Arc;
+
+use crate::agent::harness::host_definition::{AgentDefinition, AgentDefinitionRegistry};
+use crate::agent::prompts::{PromptContext, SystemPromptBuilder};
+use crate::agent::session_store::splice_fixture::memory_locator;
+use tinyagents_harness::testkit::ScriptedModel;
+use tinyagents_session::transcript::TranscriptLocator;
+
+const THREAD: &str = "thread-prompt-refresh";
+
+/// A thread-bound session over `locator` that renders its prompt with
+/// `prompt` and answers from `model`, under the registry's definition as
+/// `define` edits it: the definition the embed factory stamps on its
+/// sessions.
+fn host_with(
+ locator: &Arc<dyn TranscriptLocator>,
+ model: &Arc<ScriptedModel>,
+ root: &std::path::Path,
+ prompt: SystemPromptBuilder,
+ define: impl FnOnce(&mut AgentDefinition),
+) -> crate::agent::OpenHumanSessionHost {
+ let _ = AgentDefinitionRegistry::init_global_builtins();
+ let chat_model: Arc<dyn tinyinference_llm::model::ChatModel<()>> = model.clone();
+ let mut host = crate::agent::SessionHostBuilder::new()
+ .with_session_history_locator(Arc::clone(locator))
+ .chat_model(chat_model)
+ .tools(Vec::new())
+ .prompt_builder(prompt)
+ .workspace_dir(root.join("workspace"))
+ .action_dir(root.to_path_buf())
+ .tool_dispatcher(Box::new(tinytools_agent::dialect::NativeDialect))
+ .build()
+ .expect("session build");
+ let mut definition = (*host.resolved_definition().expect("registry definition")).clone();
+ define(&mut definition);
+ host.definition = Some(Arc::new(definition));
+ host.set_thread_id(Some(THREAD));
+ host
+}
+
+/// As [`host_with`], for an agent whose whole prompt is `prompt`, verbatim
+/// (what embed's `bare_prompt` builds), with `refresh_prompt_on_resume` set
+/// to `refresh`.
+fn host(
+ locator: &Arc<dyn TranscriptLocator>,
+ model: &Arc<ScriptedModel>,
+ root: &std::path::Path,
+ prompt: &str,
+ refresh: bool,
+) -> crate::agent::OpenHumanSessionHost {
+ host_with(
+ locator,
+ model,
+ root,
+ SystemPromptBuilder::verbatim(prompt.to_string()),
+ |definition| {
+ definition.system_prompt = PromptSource::Verbatim(prompt.to_string());
+ definition.extensions.refresh_prompt_on_resume = refresh;
+ },
+ )
+}
+
+/// A model that answers each turn with the next of `replies`. The native
+/// dialect resolves from the model's profile; a profile-less scripted model
+/// would be treated as text-only, like no production model is.
+fn model(replies: Vec<&str>) -> Arc<ScriptedModel> {
+ Arc::new(
+ ScriptedModel::replies(replies).with_profile(tinyinference_llm::model::ModelProfile {
+ tool_calling: true,
+ ..Default::default()
+ }),
+ )
+}
+
+/// The system messages of the model's latest request, in order.
+fn sent_prompt(model: &ScriptedModel) -> Vec<String> {
+ let requests = model.requests();
+ let sent = &requests.last().expect("a turn reached the model").messages;
+ sent.iter()
+ .filter(|message| matches!(message, Message::System(_)))
+ .map(Message::text)
+ .collect()
+}
+
+/// Whether the model's latest request carries a message of `role` whose text
+/// contains `needle`.
+fn sent_contains(model: &ScriptedModel, role: fn(&Message) -> bool, needle: &str) -> bool {
+ let requests = model.requests();
+ let sent = &requests.last().expect("a turn reached the model").messages;
+ sent.iter()
+ .any(|message| role(message) && message.text().contains(needle))
+}
+
+/// The text of the last user message in the model's latest request.
+fn last_user_text(model: &ScriptedModel) -> String {
+ let requests = model.requests();
+ let sent = &requests.last().expect("a turn reached the model").messages;
+ sent.iter()
+ .rev()
+ .find(|message| is_user(message))
+ .map(Message::text)
+ .unwrap_or_default()
+}
+
+fn is_user(message: &Message) -> bool {
+ matches!(message, Message::User(_))
+}
+
+fn is_assistant(message: &Message) -> bool {
+ matches!(message, Message::Assistant(_))
+}
+
+#[test]
+fn a_resumed_thread_takes_up_the_current_prompt_only_when_its_agent_opts_in() {
+ std::thread::Builder::new()
+ .stack_size(crate::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .spawn(|| {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("test runtime")
+ .block_on(resumed_thread_takes_up_the_current_prompt_only_when_opted_in());
+ })
+ .expect("test thread")
+ .join()
+ .expect("test thread panicked");
+}
+
+async fn resumed_thread_takes_up_the_current_prompt_only_when_opted_in() {
+ let root = tempfile::tempdir().expect("tempdir");
+ let locator = memory_locator();
+ let model = model(vec![
+ "first reply",
+ "second reply",
+ "third reply",
+ "fourth reply",
+ ]);
+
+ // A new thread is sent the prompt of its first turn.
+ let mut first = host(&locator, &model, root.path(), "You are release one.", true);
+ assert_eq!(first.turn("first message").await.unwrap(), "first reply");
+ let session = first.session.clone().expect("a thread-bound session");
+ drop(first);
+ assert_eq!(sent_prompt(&model), ["You are release one."]);
+ assert!(!last_user_text(&model).contains(PROMPT_UPDATE_NOTE));
+ assert_eq!(locator.session_chain(&session).len(), 1);
+
+ // After a restart with an edited prompt, the resumed thread is sent the
+ // current prompt alone, with its whole conversation, and the prompt
+ // change opens the transcript's next generation.
+ let mut second = host(&locator, &model, root.path(), "You are release two.", true);
+ assert_eq!(second.turn("second message").await.unwrap(), "second reply");
+ drop(second);
+ assert_eq!(sent_prompt(&model), ["You are release two."]);
+ assert!(sent_contains(&model, is_user, "first message"));
+ assert!(sent_contains(&model, is_assistant, "first reply"));
+ assert!(sent_contains(&model, is_user, "second message"));
+ assert!(
+ last_user_text(&model).starts_with(PROMPT_UPDATE_NOTE),
+ "the turn the prompt changed on says so"
+ );
+ assert_eq!(
+ locator.session_chain(&session).len(),
+ 2,
+ "a changed prompt seals the generation it replaced"
+ );
+
+ // An unchanged prompt is a no-op: same prompt, no new generation.
+ let mut third = host(&locator, &model, root.path(), "You are release two.", true);
+ assert_eq!(third.turn("third message").await.unwrap(), "third reply");
+ drop(third);
+ assert_eq!(sent_prompt(&model), ["You are release two."]);
+ assert!(sent_contains(&model, is_assistant, "second reply"));
+ assert!(!last_user_text(&model).contains(PROMPT_UPDATE_NOTE));
+ assert!(
+ sent_contains(&model, is_user, PROMPT_UPDATE_NOTE),
+ "the note stays where the change happened"
+ );
+ assert_eq!(locator.session_chain(&session).len(), 2);
+
+ // Without the opt-in the thread keeps the prompt it recorded.
+ let mut fourth = host(
+ &locator,
+ &model,
+ root.path(),
+ "You are release three.",
+ false,
+ );
+ assert_eq!(fourth.turn("fourth message").await.unwrap(), "fourth reply");
+ assert_eq!(sent_prompt(&model), ["You are release two."]);
+ assert!(!last_user_text(&model).contains(PROMPT_UPDATE_NOTE));
+ assert_eq!(locator.session_chain(&session).len(), 2);
+}
+
+/// The prelude a turn of `host` is prepared by.
+fn prelude_of(mut host: crate::agent::OpenHumanSessionHost) -> OpenHumanTurnPrelude {
+ host.ensure_runtime_session().expect("runtime session");
+ let state = host
+ .runtime_state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ state.prelude.clone().expect("prelude")
+}
+
+/// The prelude of a session rendering `prompt` verbatim, with `refresh` as
+/// its definition's `refresh_prompt_on_resume`.
+fn prelude(root: &std::path::Path, prompt: &str, refresh: bool) -> OpenHumanTurnPrelude {
+ prelude_of(host(
+ &memory_locator(),
+ &model(Vec::new()),
+ root,
+ prompt,
+ refresh,
+ ))
+}
+
+/// The prelude of a session whose prompt is composed by `prompt` (the
+/// registry definition's own, not verbatim), opted into the refresh.
+fn composed_prelude(root: &std::path::Path, prompt: SystemPromptBuilder) -> OpenHumanTurnPrelude {
+ prelude_of(host_with(
+ &memory_locator(),
+ &model(Vec::new()),
+ root,
+ prompt,
+ |definition| definition.extensions.refresh_prompt_on_resume = true,
+ ))
+}
+
+/// Marks `prelude`'s connected integrations as read this session.
+fn hydrate(prelude: &OpenHumanTurnPrelude) {
+ let mut mutable = prelude
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ mutable.connected_integrations_initialized = true;
+ mutable.connected_integrations_authoritative = true;
+}
+
+/// A resumed thread's view: `prefix` restored, `history` decoded.
+fn resumed<'a>(prefix: &'a PrefixSnapshot, history: &'a [Message]) -> SessionStateView<'a> {
+ SessionStateView {
+ history,
+ raw_history: &[],
+ prefix,
+ transcript_target: None,
+ committed_turns: 1,
+ resumed: true,
+ }
+}
+
+/// A transcript snapshot whose request boundary is `base`, as the hook seeds
+/// it from the history before the turn is prepared.
+fn snapshot(base: usize) -> TranscriptSnapshotSink {
+ let sink = TranscriptSnapshotSink::default();
+ sink.lock().unwrap().request_base_len = base;
+ sink
+}
+
+fn current() -> PrefixSnapshot {
+ PrefixSnapshot::new(vec![Message::system("current")])
+}
+
+/// The user's message this turn, as the hook hands it over.
+fn request() -> SessionTurnRequest {
+ SessionTurnRequest::new(Message::user("hi"))
+}
+
+#[tokio::test]
+async fn a_resumed_thread_is_offered_the_current_prompt_as_a_refresh() {
+ let root = tempfile::tempdir().expect("tempdir");
+ let prelude = prelude(root.path(), "current", true);
+ let recorded = PrefixSnapshot::new(vec![Message::system("recorded")]);
+ let history = [
+ Message::system("recorded"),
+ Message::user("hi"),
+ Message::assistant("hello"),
+ ];
+ let mut request = request();
+ let prepared = prelude
+ .prepare_turn(
+ false,
+ &resumed(&recorded, &history),
+ &snapshot(4),
+ &mut request,
+ )
+ .await
+ .expect("prepared turn");
+ assert_eq!(prepared.prefix, Some(current().refreshing()));
+ assert!(prepared.tools.is_some());
+ assert_eq!(
+ request.input.text(),
+ format!("{PROMPT_UPDATE_NOTE}\n\nhi"),
+ "the turn says the prompt changed"
+ );
+}
+
+#[tokio::test]
+async fn a_current_prompt_is_offered_without_a_note() {
+ // The runtime finds the offer identical to the recorded prompt and keeps
+ // the thread as it is; nothing changed, so nothing is said.
+ let root = tempfile::tempdir().expect("tempdir");
+ let prelude = prelude(root.path(), "current", true);
+ let history = [
+ Message::system("current"),
+ Message::user("earlier"),
+ Message::assistant("hello"),
+ ];
+ let mut request = request();
+ let prepared = prelude
+ .prepare_turn(
+ false,
+ &resumed(&current(), &history),
+ &snapshot(4),
+ &mut request,
+ )
+ .await
+ .expect("prepared turn");
+ assert_eq!(prepared.prefix, Some(current().refreshing()));
+ assert_eq!(request.input.text(), "hi");
+}
+
+#[tokio::test]
+async fn without_the_opt_in_a_resumed_thread_keeps_its_recorded_prompt() {
+ let root = tempfile::tempdir().expect("tempdir");
+ let prelude = prelude(root.path(), "current", false);
+ let recorded = PrefixSnapshot::new(vec![Message::system("recorded")]);
+ let history = [Message::system("recorded"), Message::user("hi")];
+ let sink = snapshot(3);
+ let mut request = request();
+ let prepared = prelude
+ .prepare_turn(false, &resumed(&recorded, &history), &sink, &mut request)
+ .await
+ .expect("prepared turn");
+ assert_eq!(prepared.prefix, None);
+ assert_eq!(sink.lock().unwrap().request_base_len, 3, "nothing moved");
+ assert_eq!(request.input.text(), "hi");
+}
+
+#[tokio::test]
+async fn a_new_session_gets_its_prompt_frozen_whatever_the_opt_in() {
+ let root = tempfile::tempdir().expect("tempdir");
+ let prelude = prelude(root.path(), "current", true);
+ let empty = PrefixSnapshot::default();
+ let view = SessionStateView {
+ resumed: false,
+ committed_turns: 0,
+ ..resumed(&empty, &[])
+ };
+ // The hook seeds the boundary with the user message alone; the request
+ // opens with the prompt in front of it.
+ let sink = snapshot(1);
+ let mut request = request();
+ let prepared = prelude
+ .prepare_turn(true, &view, &sink, &mut request)
+ .await
+ .expect("prepared turn");
+ assert_eq!(prepared.prefix, Some(current()));
+ assert_eq!(sink.lock().unwrap().request_base_len, 2);
+ assert_eq!(
+ request.input.text(),
+ "hi",
+ "a new thread has no earlier prompt"
+ );
+}
+
+#[tokio::test]
+async fn the_snapshot_boundary_moves_with_a_prompt_of_another_length() {
+ // Recorded under a two-message prompt, now rendered as one: the request
+ // is one message shorter, and so is the start of this run's rounds.
+ let root = tempfile::tempdir().expect("tempdir");
+ let prelude = prelude(root.path(), "current", true);
+ let recorded = PrefixSnapshot::new(vec![
+ Message::system("tier one"),
+ Message::system("tier two"),
+ ]);
+ let history = [
+ Message::system("tier one"),
+ Message::system("tier two"),
+ Message::user("hi"),
+ Message::assistant("hello"),
+ ];
+ let sink = snapshot(history.len() + 1);
+ let prepared = prelude
+ .prepare_turn(false, &resumed(&recorded, &history), &sink, &mut request())
+ .await
+ .expect("prepared turn");
+ assert_eq!(prepared.prefix, Some(current().refreshing()));
+ assert_eq!(sink.lock().unwrap().request_base_len, 4);
+}
+
+#[tokio::test]
+async fn a_recorded_prompt_of_unknown_extent_is_kept() {
+ // A compacted legacy head restores no prefix, and its old instructions
+ // are still in the history: a new prompt beside them would leave them.
+ let root = tempfile::tempdir().expect("tempdir");
+ let prelude = prelude(root.path(), "current", true);
+ let unknown = PrefixSnapshot::default();
+ let history = [
+ Message::system("old instructions"),
+ Message::system("summary of earlier turns"),
+ Message::user("hi"),
+ ];
+ let prepared = prelude
+ .prepare_turn(
+ false,
+ &resumed(&unknown, &history),
+ &snapshot(4),
+ &mut request(),
+ )
+ .await
+ .expect("prepared turn");
+ assert_eq!(prepared.prefix, None);
+}
+
+#[tokio::test]
+async fn a_thread_recorded_without_a_prompt_takes_up_the_current_one() {
+ let root = tempfile::tempdir().expect("tempdir");
+ let prelude = prelude(root.path(), "current", true);
+ let none = PrefixSnapshot::default();
+ let history = [Message::user("hi"), Message::assistant("hello")];
+ let prepared = prelude
+ .prepare_turn(
+ false,
+ &resumed(&none, &history),
+ &snapshot(3),
+ &mut request(),
+ )
+ .await
+ .expect("prepared turn");
+ assert_eq!(prepared.prefix, Some(current().refreshing()));
+}
+
+#[tokio::test]
+async fn a_composed_prompt_waits_for_the_integrations_to_be_read() {
+ // A composed prompt renders the connected integrations; rendered before
+ // they are read it would replace a complete prompt with a bare one.
+ let root = tempfile::tempdir().expect("tempdir");
+ let prelude = composed_prelude(root.path(), SystemPromptBuilder::verbatim("current".into()));
+ let recorded = PrefixSnapshot::new(vec![Message::system("recorded")]);
+ let history = [Message::system("recorded"), Message::user("hi")];
+ let prepared = prelude
+ .prepare_turn(
+ false,
+ &resumed(&recorded, &history),
+ &snapshot(3),
+ &mut request(),
+ )
+ .await
+ .expect("prepared turn");
+ assert_eq!(prepared.prefix, None);
+
+ hydrate(&prelude);
+ let prepared = prelude
+ .prepare_turn(
+ false,
+ &resumed(&recorded, &history),
+ &snapshot(3),
+ &mut request(),
+ )
+ .await
+ .expect("prepared turn");
+ assert_eq!(prepared.prefix, Some(current().refreshing()));
+}
+
+fn failing_prompt(_: &PromptContext<'_>) -> anyhow::Result<String> {
+ anyhow::bail!("the prompt source is unavailable")
+}
+
+#[tokio::test]
+async fn a_prompt_that_fails_to_render_keeps_the_recorded_one() {
+ let root = tempfile::tempdir().expect("tempdir");
+ let prelude = composed_prelude(
+ root.path(),
+ SystemPromptBuilder::from_dynamic(failing_prompt),
+ );
+ hydrate(&prelude);
+ let recorded = PrefixSnapshot::new(vec![Message::system("recorded")]);
+ let history = [Message::system("recorded"), Message::user("hi")];
+ let prepared = prelude
+ .prepare_turn(
+ false,
+ &resumed(&recorded, &history),
+ &snapshot(3),
+ &mut request(),
+ )
+ .await
+ .expect("a resumed turn does not fail on its prompt");
+ assert_eq!(prepared.prefix, None);
+}
diff --git a/crates/openhuman-embed/src/agent/definition.rs b/crates/openhuman-embed/src/agent/definition.rs
index 914b122670..c04257e712 100644
--- a/crates/openhuman-embed/src/agent/definition.rs
+++ b/crates/openhuman-embed/src/agent/definition.rs
@@ -81,6 +81,7 @@ pub struct AgentDefinitionSpec {
system_prompt: Option<String>,
/// The prompt is the whole system prompt, with nothing composed around it.
bare_prompt: bool,
+ refresh_prompt_on_resume: Option<bool>,
tools: Option<ToolScopeSpec>,
disallowed_tools: Vec<String>,
tool_rules: Option<tinytools::ToolRules>,
@@ -145,6 +146,9 @@ impl AgentDefinitionSpec {
self.system_prompt = lower.system_prompt;
self.bare_prompt = lower.bare_prompt;
}
+ self.refresh_prompt_on_resume = self
+ .refresh_prompt_on_resume
+ .or(lower.refresh_prompt_on_resume);
self.tools = self.tools.or(lower.tools);
self.disallowed_tools.extend(lower.disallowed_tools);
// Tool rules must retain both layers' restrictions; core also enforces config rules.
@@ -191,6 +195,27 @@ impl AgentDefinitionSpec {
self
}
+ /// Give a resumed thread the prompt this agent renders now, not the one
+ /// recorded when the thread began.
+ ///
+ /// Off by default: a resumed thread replays its recorded system prompt
+ /// verbatim, which keeps the provider's prefix cache warm across a
+ /// restart, so prompt edits reach only new threads. On, the prompt is
+ /// rendered again on every resumed turn, and a thread whose recorded
+ /// prompt differs continues under the current one with its conversation
+ /// intact; the session seals the transcript generation it was on and
+ /// carries the conversation into the next, and that turn's user message
+ /// opens with a one-time note that the instructions changed. Each change
+ /// costs one uncached prompt; an unchanged prompt costs nothing and
+ /// writes nothing.
+ /// With [`bare_prompt`](Self::bare_prompt) the prompt changes only when
+ /// the host's text does; a composed prompt also changes with the live
+ /// state it renders (connected integrations, skills, AGENTS.md).
+ pub fn refresh_prompt_on_resume(mut self, refresh: bool) -> Self {
+ self.refresh_prompt_on_resume = Some(refresh);
+ self
+ }
+
/// Whether this is a [`ToolScopeSpec::HostOnly`] definition.
pub(crate) fn is_host_only(&self) -> bool {
matches!(self.tools, Some(ToolScopeSpec::HostOnly))
@@ -290,6 +315,9 @@ impl AgentDefinitionSpec {
}
None => {}
}
+ if let Some(refresh) = self.refresh_prompt_on_resume {
+ def.extensions.refresh_prompt_on_resume = refresh;
+ }
if custom_base {
if let Some(requested) = &self.tools {
let narrows = match (requested, &def.tools) {
@@ -353,13 +381,14 @@ impl AgentDefinitionSpec {
def.temperature = t;
}
log::debug!(
- "[embed][agent] definition id={id} prompt={} tools={:?} sandbox={:?} max_iterations={}",
+ "[embed][agent] definition id={id} prompt={} refresh_prompt_on_resume={} tools={:?} sandbox={:?} max_iterations={}",
match &def.system_prompt {
PromptSource::Inline(_) => "inline",
PromptSource::File { .. } => "file",
PromptSource::Dynamic(_) => "dynamic",
PromptSource::Verbatim(_) => "verbatim",
},
+ def.extensions.refresh_prompt_on_resume,
def.tools,
def.sandbox_mode,
def.max_iterations
diff --git a/crates/openhuman-embed/src/agent/definition_tests.rs b/crates/openhuman-embed/src/agent/definition_tests.rs
index 737c969664..598aec170a 100644
--- a/crates/openhuman-embed/src/agent/definition_tests.rs
+++ b/crates/openhuman-embed/src/agent/definition_tests.rs
@@ -49,6 +49,54 @@ fn bare_prompt_is_verbatim_with_nothing_composed_around_it() {
);
}
+#[test]
+fn refresh_prompt_on_resume_reaches_the_core_definition_and_is_off_by_default() {
+ let def = AgentDefinitionSpec::new()
+ .bare_prompt("Analyze.")
+ .refresh_prompt_on_resume(true)
+ .into_core("alpha")
+ .expect("definition");
+ assert!(def.extensions.refresh_prompt_on_resume);
+ let replays = AgentDefinitionSpec::new()
+ .bare_prompt("Analyze.")
+ .into_core("beta")
+ .expect("definition");
+ assert!(
+ !replays.extensions.refresh_prompt_on_resume,
+ "a resumed thread replays its recorded prompt unless the agent opts in"
+ );
+}
+
+#[test]
+fn refresh_prompt_on_resume_comes_from_a_template_or_base_unless_set() {
+ let template = AgentDefinitionSpec::new().refresh_prompt_on_resume(true);
+ let inherited = AgentDefinitionSpec::new()
+ .inherit(template.clone())
+ .unwrap()
+ .into_core("inherits")
+ .unwrap();
+ assert!(inherited.extensions.refresh_prompt_on_resume);
+ let overridden = AgentDefinitionSpec::new()
+ .refresh_prompt_on_resume(false)
+ .inherit(template)
+ .unwrap()
+ .into_core("overrides")
+ .unwrap();
+ assert!(!overridden.extensions.refresh_prompt_on_resume);
+
+ let mut base = AgentDefinitionSpec::new().into_core("custom-base").unwrap();
+ base.extensions.refresh_prompt_on_resume = true;
+ let keeps = AgentDefinitionSpec::from_base(base.clone())
+ .into_core("keeps-base")
+ .unwrap();
+ assert!(keeps.extensions.refresh_prompt_on_resume);
+ let clears = AgentDefinitionSpec::from_base(base)
+ .refresh_prompt_on_resume(false)
+ .into_core("clears-base")
+ .unwrap();
+ assert!(!clears.extensions.refresh_prompt_on_resume);
+}
+
#[test]
fn system_prompt_after_bare_prompt_is_wrapped_again() {
let def = AgentDefinitionSpec::new()
diff --git a/docs/gitbooks/en/developing/embed/concepts/skills.md b/docs/gitbooks/en/developing/embed/concepts/skills.md
index a40cf6e558..990d71047d 100644
--- a/docs/gitbooks/en/developing/embed/concepts/skills.md
+++ b/docs/gitbooks/en/developing/embed/concepts/skills.md
@@ -44,4 +44,4 @@ Enable the named Embed `skills` feature for skill setters and registry access. L
The example writes a bundle, registers an agent, checks the copied contents and verifies that the destination is not a symlink. Use the same directory layout for production bundles; do not depend on the fixture's temporary directory lifetime.
-A resumed session's prompt is frozen, so adding or editing a bundle does not rewrite an existing conversation's recorded prefix. Start a new session when you want updated instructions to become visible. See [turns and sessions](turns-sessions.md) and the generated [builder setters](../builder-setters.md) for runtime policy knobs.
+A resumed session's prompt is frozen, so adding or editing a bundle does not rewrite an existing conversation's recorded prefix. Start a new session when you want updated instructions to become visible, or build the agent with `AgentDefinitionSpec::refresh_prompt_on_resume(true)` so a resumed session is sent its current prompt. See [turns and sessions](turns-sessions.md) and the generated [builder setters](../builder-setters.md) for runtime policy knobs.
diff --git a/docs/gitbooks/en/developing/embed/concepts/turns-sessions.md b/docs/gitbooks/en/developing/embed/concepts/turns-sessions.md
index 1f6d5c7c0d..9b3341ab38 100644
--- a/docs/gitbooks/en/developing/embed/concepts/turns-sessions.md
+++ b/docs/gitbooks/en/developing/embed/concepts/turns-sessions.md
@@ -68,4 +68,4 @@ No local path is read, so attachments are accepted whatever the turn's origin, i
The stream example checks that deltas precede the final result and that collected and streaming replies agree. A cancellation token passed to a turn is preserved by streaming; cancellation unblocks forwarding even when the consumer has stopped draining a full buffer.
-The harness derives transcript paths from the thread and agent IDs without a timestamp. Resumed sessions reuse their recorded system prompt and tool declarations; edits to prompts, skills or integrations apply to new sessions. Compaction seals a generation and opens a child instead of erasing history. See [observability](observability.md) for session IDs versus per-call turn IDs, and [API reference](../api-reference.md) for the session-store port.
+The harness derives transcript paths from the thread and agent IDs without a timestamp. Resumed sessions reuse their recorded system prompt and tool declarations; edits to prompts, skills or integrations apply to new sessions. An agent built with `AgentDefinitionSpec::refresh_prompt_on_resume(true)` sends a resumed thread its current prompt instead: when the prompt changed, the thread's transcript generation is sealed and its conversation carries into the next, at the cost of one uncached prompt per change, and that turn's message opens with a one-time note that the instructions changed, so the model does not hold to what it said under the old ones. Compaction seals a generation and opens a child instead of erasing history. See [observability](observability.md) for session IDs versus per-call turn IDs, and [API reference](../api-reference.md) for the session-store port.
diff --git a/scripts/ci/check-openhuman-rust-layout.mjs b/scripts/ci/check-openhuman-rust-layout.mjs
index 81efd7e981..3a366c48e3 100644
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@ -27,7 +27,7 @@ const LEGACY_LIMIT_ENTRIES = [
// under the general 750 limit, so it needs no exception at all.
// The session-todo integration added transcript metadata construction to
// this already-exempt composition seam. Keep its allowance exact.
- ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1080],
+ ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1079],
// Session-host factory still assembles the product's deliberately coupled
// provider, security, memory, tool and prompt policy. Generic session
// state moved to tinyagents-runtime; this remaining composition is split in