use std::path::{Path, PathBuf};
use std::process::Command;
use ag_contracts::{AgentDefinitionPromptUpdate, ResponseStyle};
use ag_protocol::{
ProtocolRequestProfile, ProtocolSchemaInstructionMode, TurnPrompt, TurnPromptAttachment,
TurnPromptContentPart, prepend_protocol_instructions as protocol_prepend_instructions,
prepend_protocol_refresh_reminder as protocol_prepend_refresh_reminder,
split_turn_prompt_content,
};
use askama::Template;
use super::backend::{AgentBackendError, BuildCommandRequest};
use super::instruction::InstructionDeliveryMode;
#[derive(Template)]
#[template(path = "resume_with_transcript_prompt.md", escape = "none")]
struct ResumeWithTranscriptPromptTemplate<'a> {
prompt: &'a str,
transcript: &'a str,
}
#[derive(Template)]
#[template(path = "agent_profile_prompt.md", escape = "none")]
struct AgentDefinitionPromptTemplate<'a> {
heading: &'a str,
agent_profile: &'a str,
prompt: &'a str,
}
#[derive(Template)]
#[template(path = "response_style_prompt.md", escape = "none")]
struct ResponseStylePromptTemplate<'a> {
instruction: &'a str,
prompt: &'a str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PromptPreparationRequest<'a> {
pub instruction_delivery_mode: InstructionDeliveryMode,
pub agent_profile_prompt: Option<&'a str>,
pub agent_profile_update: &'a AgentDefinitionPromptUpdate,
pub prompt: &'a str,
pub protocol_profile: ProtocolRequestProfile,
pub replay_transcript: Option<&'a str>,
pub schema_instruction_mode: ProtocolSchemaInstructionMode,
pub workspace_root: &'a Path,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CliPromptAccessRootMode {
AttachmentsOnly,
WorkspaceThenAttachments,
}
pub(crate) fn prepare_prompt_text(
request: PromptPreparationRequest<'_>,
) -> Result<String, AgentBackendError> {
let agent_profile_prompt = if matches!(
request.agent_profile_update,
AgentDefinitionPromptUpdate::Clear
) {
Some(CLEARED_AGENT_INSTRUCTIONS)
} else {
request.agent_profile_prompt
};
match request.instruction_delivery_mode {
InstructionDeliveryMode::BootstrapFull => {
let prompt = prepend_agent_profile_prompt(request.prompt, agent_profile_prompt)?;
Ok(protocol_prepend_instructions(
&prompt,
request.protocol_profile,
request.schema_instruction_mode,
request.workspace_root,
))
}
InstructionDeliveryMode::DeltaOnly => {
let prompt =
prepend_agent_profile_update(request.prompt, request.agent_profile_update)?;
Ok(protocol_prepend_refresh_reminder(
&prompt,
request.protocol_profile,
request.workspace_root,
))
}
InstructionDeliveryMode::BootstrapWithReplay => {
let prompt = build_resume_prompt(request.prompt, request.replay_transcript)?;
let prompt = prepend_agent_profile_prompt(&prompt, agent_profile_prompt)?;
Ok(protocol_prepend_instructions(
&prompt,
request.protocol_profile,
request.schema_instruction_mode,
request.workspace_root,
))
}
}
}
pub(crate) fn build_resume_prompt(
prompt: &str,
replay_transcript: Option<&str>,
) -> Result<String, AgentBackendError> {
let Some(transcript) = replay_transcript
.map(str::trim)
.filter(|value| !value.is_empty())
else {
return Ok(prompt.to_string());
};
let transcript = serde_json::json!(transcript).to_string();
let template = ResumeWithTranscriptPromptTemplate {
prompt,
transcript: &transcript,
};
render_template(&template)
}
pub(crate) fn build_cli_prompt_text(
request: BuildCommandRequest<'_>,
schema_instruction_mode: ProtocolSchemaInstructionMode,
backend_display_name: &str,
) -> Result<String, AgentBackendError> {
let prompt =
render_prompt_with_local_images(request.prompt, request.attachments, backend_display_name)?;
prepare_prompt_text(PromptPreparationRequest {
instruction_delivery_mode: if request.replay_transcript.is_some() {
InstructionDeliveryMode::BootstrapWithReplay
} else {
InstructionDeliveryMode::BootstrapFull
},
agent_profile_prompt: request.agent_profile_prompt,
agent_profile_update: request.agent_profile_update,
prompt: &prompt,
protocol_profile: request.request_kind.protocol_profile(),
replay_transcript: request.replay_transcript,
schema_instruction_mode,
workspace_root: request.folder,
})
}
pub(crate) fn apply_response_style_prompt(
mut prompt: TurnPrompt,
protocol_profile: ProtocolRequestProfile,
response_style: ResponseStyle,
) -> Result<TurnPrompt, AgentBackendError> {
if protocol_profile == ProtocolRequestProfile::SessionTurn {
let prompt_text = prompt.agent_text();
let template = ResponseStylePromptTemplate {
instruction: response_style.prompt_instruction(),
prompt: &prompt_text,
};
prompt.text = render_template(&template)?;
}
Ok(prompt)
}
fn prepend_agent_profile_prompt(
prompt: &str,
agent_profile_prompt: Option<&str>,
) -> Result<String, AgentBackendError> {
let Some(agent_profile) = agent_profile_prompt
.map(str::trim)
.filter(|agent_profile| !agent_profile.is_empty())
else {
return Ok(prompt.to_string());
};
let template = AgentDefinitionPromptTemplate {
heading: "# Agent",
agent_profile,
prompt,
};
render_template(&template)
}
const CLEARED_AGENT_INSTRUCTIONS: &str =
"The session personality and agent instructions have been cleared. Disregard previous \
personality and agent-profile instructions. Continue following the user's messages, \
application policy, permissions, and response contract.";
fn prepend_agent_profile_update(
prompt: &str,
agent_profile_update: &AgentDefinitionPromptUpdate,
) -> Result<String, AgentBackendError> {
let agent_profile = match agent_profile_update {
AgentDefinitionPromptUpdate::Clear => CLEARED_AGENT_INSTRUCTIONS,
AgentDefinitionPromptUpdate::Set(agent_profile) => agent_profile.trim(),
AgentDefinitionPromptUpdate::Unchanged => return Ok(prompt.to_string()),
};
let template = AgentDefinitionPromptTemplate {
heading: "# Agent Update",
agent_profile,
prompt,
};
render_template(&template)
}
pub(crate) fn append_cli_prompt_access_directories(
command: &mut Command,
workspace_folder: &Path,
attachments: &[TurnPromptAttachment],
root_mode: CliPromptAccessRootMode,
) {
for directory in cli_prompt_access_directories(workspace_folder, attachments, root_mode) {
command.arg("--add-dir").arg(directory);
}
}
pub(crate) fn render_prompt_with_local_images(
prompt: &str,
attachments: &[TurnPromptAttachment],
backend_display_name: &str,
) -> Result<String, AgentBackendError> {
if attachments.is_empty() {
return Ok(prompt.to_string());
}
let mut rendered_prompt = String::new();
for content_part in split_turn_prompt_content(prompt, attachments) {
match content_part {
TurnPromptContentPart::Text(text) => rendered_prompt.push_str(text),
TurnPromptContentPart::Attachment(attachment) => {
let attachment_path = attachment_path_for_prompt(backend_display_name, attachment)?;
rendered_prompt.push_str(&attachment_path);
}
TurnPromptContentPart::OrphanAttachment(attachment) => {
if !rendered_prompt.is_empty()
&& rendered_prompt
.chars()
.last()
.is_some_and(|character| !character.is_whitespace())
{
rendered_prompt.push('\n');
}
rendered_prompt.push_str(&attachment_path_for_prompt(
backend_display_name,
attachment,
)?);
rendered_prompt.push('\n');
}
}
}
Ok(rendered_prompt)
}
pub(crate) fn cli_prompt_access_directories(
workspace_folder: &Path,
attachments: &[TurnPromptAttachment],
root_mode: CliPromptAccessRootMode,
) -> Vec<PathBuf> {
let mut attachment_directories = attachments
.iter()
.filter_map(|attachment| attachment.local_image_path.parent())
.map(ToOwned::to_owned)
.collect::<Vec<_>>();
attachment_directories.sort();
attachment_directories.dedup();
if matches!(root_mode, CliPromptAccessRootMode::AttachmentsOnly) {
return attachment_directories;
}
attachment_directories
.retain(|attachment_directory| attachment_directory.as_path() != workspace_folder);
let mut workspace_directories = Vec::with_capacity(attachment_directories.len() + 1);
workspace_directories.push(workspace_folder.to_path_buf());
workspace_directories.extend(attachment_directories);
workspace_directories
}
fn attachment_path_for_prompt(
backend_display_name: &str,
attachment: &TurnPromptAttachment,
) -> Result<String, AgentBackendError> {
attachment
.local_image_path
.to_str()
.map(ToOwned::to_owned)
.ok_or_else(|| {
AgentBackendError::command_build(format_args!(
"{backend_display_name} prompt image path is not valid UTF-8"
))
})
}
fn render_template(template: &impl Template) -> Result<String, AgentBackendError> {
let rendered = template
.render()
.map_err(AgentBackendError::command_build)?;
Ok(rendered.trim_end().to_string())
}
#[cfg(test)]
#[path = "prompt_test.rs"]
mod tests;