use super::{ChatId, Value, json};
use subspace_core::log::{Level, Logger};
const OPEN: &str = "<subspace-context>";
const CLOSE: &str = "</subspace-context>";
const PREAMBLE: &str =
"Context from Subspace, the app hosting this chat. It is not part of the user's message.";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Delivery {
SystemPrompt,
FirstPrompt,
}
pub(super) fn system_prompt(text: &str) -> Value {
json!({"mode": "append", "content": [{"type": "text", "text": text}]})
}
pub(super) fn prompt_block(text: &str) -> Value {
json!({"type": "text", "text": format!("{OPEN}\n{PREAMBLE}\n\n{text}\n{CLOSE}")})
}
pub(super) fn without_context(text: &str) -> &str {
match text
.strip_prefix(OPEN)
.and_then(|rest| rest.split_once(CLOSE))
{
Some((_, message)) => message.trim_start(),
None => text,
}
}
pub(super) fn log_delivery(chat: ChatId, delivery: Delivery, text: &str) {
let delivery = match delivery {
Delivery::SystemPrompt => "system_prompt",
Delivery::FirstPrompt => "first_prompt",
};
let chat = chat.to_string();
Logger::new("agent").record(
Level::Debug,
"acp session context sent",
&[("chat", &chat), ("delivery", delivery), ("context", text)],
);
}
#[cfg(test)]
mod tests {
use super::{prompt_block, system_prompt, without_context};
#[test]
fn the_system_prompt_appends_one_text_block() {
let prompt = system_prompt("Boards");
assert_eq!(prompt["mode"], "append");
assert_eq!(prompt["content"][0]["type"], "text");
assert_eq!(prompt["content"][0]["text"], "Boards");
assert_eq!(prompt["content"].as_array().unwrap().len(), 1);
}
#[test]
fn a_replay_drops_the_marked_block_and_keeps_the_message() {
let block = prompt_block("Boards");
let block = block["text"].as_str().unwrap();
assert!(block.starts_with("<subspace-context>\nContext from Subspace"));
assert_eq!(without_context(block), "");
assert_eq!(without_context(&format!("{block}\n\nHello")), "Hello");
assert_eq!(without_context("Hello"), "Hello");
assert_eq!(
without_context("<subspace-context> unfinished"),
"<subspace-context> unfinished"
);
}
}