use std::path::Path;
use serde_json::{Value, json};
use crate::actions::Action;
use crate::conversation::Conversation;
pub const AGENTS_FILE: &str = "AGENTS.md";
const AGENTS_LIMIT: usize = 64 * 1024;
const MAX_TOKENS: u32 = 16_384;
pub const REQUEST_CAP: usize = 256 * 1024;
#[must_use]
pub fn system(root: &Path) -> String {
let mut text = format!(
"You are qcli, a coding agent in a terminal. You work in the folder {}. \
Use the tools to look at the files before you answer questions about them: \
list_dir to see the shape of a folder and how big its files are, read_file the file you \
need, search to find where something is. \
In a file longer than 2000 lines read the part you need with start_line and end_line \
rather than asking for the whole of it, and read on with the lines the reply says are \
not shown. \
When a search finds nothing, try again with ignore_case or with a glob such as *.rs \
rather than sending the same search again. \
Paths are relative to that folder, and nothing outside it can be reached. \
Every edit and every command is shown to the person first, and they may decline it; \
when they do, do not try the same thing another way, ask what they want instead. \
Keep answers short and plain.",
root.display()
);
if let Some(agents) = agents(root) {
text.push_str("\n\nThe folder's AGENTS.md says:\n\n");
text.push_str(&agents);
}
text
}
#[must_use]
pub fn agents(root: &Path) -> Option<String> {
let text = std::fs::read_to_string(root.join(AGENTS_FILE)).ok()?;
let text = text.trim();
if text.is_empty() {
return None;
}
Some(match text.char_indices().nth(AGENTS_LIMIT) {
Some((end, _)) => format!("{}\n\n(The rest of the file was left out: it is too long.)", &text[..end]),
None => text.to_owned(),
})
}
#[must_use]
pub fn body(conversation: &Conversation, system: &str) -> Value {
body_within(conversation, system, REQUEST_CAP)
}
#[must_use]
pub fn body_within(conversation: &Conversation, system: &str, cap: usize) -> Value {
let tools = Action::definitions();
let rest = serde_json::to_string(&json!({
"max_tokens": MAX_TOKENS,
"system": system,
"messages": [],
"tools": tools,
}))
.map_or(0, |body| body.len())
.saturating_sub(2);
json!({
"max_tokens": MAX_TOKENS,
"system": system,
"messages": conversation.view(cap.saturating_sub(rest)),
"tools": tools,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn folder(test: &str) -> std::path::PathBuf {
let root = std::env::temp_dir().join(format!("qcli-instructions-{test}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).expect("folder");
root
}
#[test]
fn the_folders_agents_file_joins_the_system_prompt() {
let root = folder("agents");
assert!(!system(&root).contains("AGENTS.md says"), "no file, no section");
std::fs::write(root.join(AGENTS_FILE), "Always answer in haiku.\n").expect("write");
let prompt = system(&root);
assert!(prompt.contains(&root.display().to_string()));
assert!(prompt.ends_with("Always answer in haiku."), "{prompt}");
std::fs::write(root.join(AGENTS_FILE), "x".repeat(AGENTS_LIMIT + 10)).expect("write");
assert!(agents(&root).expect("text").ends_with("it is too long.)"));
std::fs::remove_dir_all(&root).expect("clean up");
}
#[test]
fn the_body_carries_the_conversation_and_the_five_tools() {
let mut conversation = Conversation::default();
conversation.say("hi");
let body = body(&conversation, "be brief");
assert_eq!(body["system"], "be brief");
assert_eq!(body["messages"][0]["content"][0]["text"], "hi");
let names: Vec<_> = body["tools"].as_array().expect("tools").iter().map(|tool| tool["name"].clone()).collect();
assert_eq!(names, ["read_file", "list_dir", "search", "edit_file", "run_command"]);
}
#[test]
fn the_system_prompt_says_how_to_use_the_new_fields() {
let root = folder("fields");
let prompt = system(&root);
for said in [
"list_dir",
"start_line",
"end_line",
"ignore_case",
"glob",
"*.rs",
"do not try the same thing another way",
] {
assert!(prompt.contains(said), "`{said}` is not in the prompt:\n{prompt}");
}
std::fs::remove_dir_all(&root).expect("clean up");
}
}