A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
add per-model system prompt additions from a TOML rule map (#3413)
Sebastian Müller1e894a62c20f
diff --git a/AGENTS.md b/AGENTS.mdindex 528d5ee61e..1a1b41c3b8 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -173,7 +173,7 @@ EXPLICIT EXCEPTION: wire-protocol identifiers that must stay byte-compatible wit- Tools exposed to the model: `bash`, `edit`, `ipython` (internal helpers: `rename`, `stdout`).- RLM kernel API in the persistent Python REPL: `rlm.spawn/find_models/collect/list_subagents/delete_subagent/create_session/progress_note`, `rlm.harness` CRUD, `agent_message.send`, `agent_observe`, `compact`, `goal`, `refine`, `attach_image`, skills (markdown + Python) per the skill contract in the base system prompt.-- System prompt structure: layered — cache-stable static layer files (core harness description with the full API surface, mandatory usage rules, opinionated guidelines, per-model map) followed by one dynamic tail (packages, project context, skills inventory, MCP servers, environment, session role); the harness digest stays a separate `[harness-digest]` user message. `prime-agent prompt` dumps the assembled prompt with its layer breakdown.+- System prompt structure: layered — cache-stable static layer files (core harness description with the full API surface, mandatory usage rules, opinionated guidelines, per-model additions from the model-prompts TOML rule map) followed by one dynamic tail (packages, project context, skills inventory, MCP servers, environment, session role); the harness digest stays a separate `[harness-digest]` user message. `prime-agent prompt` dumps the assembled prompt with its layer breakdown.- CLI shape: `prime-agent` with the same commands/flags as the TS product; headless modes (RPC/daemon/session-worker) with identical behavior.## Cratesdiff --git a/Cargo.lock b/Cargo.lockindex 4c27011da1..76be2a7a59 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1317,6 +1317,7 @@ dependencies = ["thiserror","tokio","tokio-util",+ "toml","tracing","unicode-normalization","url",@@ -1980,6 +1981,15 @@ dependencies = ["zmij",]+[[package]]+name = "serde_spanned"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c"+dependencies = [+ "serde_core",+]+[[package]]name = "serde_urlencoded"version = "0.7.1"@@ -2335,6 +2345,45 @@ dependencies = ["tokio",]+[[package]]+name = "toml"+version = "0.9.12+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"+dependencies = [+ "indexmap",+ "serde_core",+ "serde_spanned",+ "toml_datetime",+ "toml_parser",+ "toml_writer",+ "winnow 0.7.15",+]++[[package]]+name = "toml_datetime"+version = "0.7.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_parser"+version = "1.1.4+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bed810ee007d8e7f9cf20b4774e7198142fa27186e0f805871da7f3c39eaf333"+dependencies = [+ "winnow 1.0.4",+]++[[package]]+name = "toml_writer"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"+[[package]]name = "tower"version = "0.5.3"@@ -2821,6 +2870,18 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"+[[package]]+name = "winnow"+version = "0.7.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"++[[package]]+name = "winnow"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"+[[package]]name = "wit-bindgen"version = "0.57.1"diff --git a/Cargo.toml b/Cargo.tomlindex ee0d46b260..38e1485b47 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -41,6 +41,7 @@ pa-ai = { path = "crates/pa-ai" }pa-agent = { path = "crates/pa-agent" }thiserror = "2"futures = "0.3"+toml = "0.9"# Dev-only; the default fork/timeout features are unused.proptest = { version = "1.11", default-features = false, features = ["std"] }diff --git a/crates/pa-cli/src/command_registry.rs b/crates/pa-cli/src/command_registry.rsindex cbf51d42ff..ca076a9385 100644--- a/crates/pa-cli/src/command_registry.rs+++ b/crates/pa-cli/src/command_registry.rs@@ -296,7 +296,7 @@ refused, never overwritten.",and prints the per-layer breakdown (cached static layers, then the dynamic tail) followed by the full prompt text.",).options(&[- "--model <selector> Preview per-model instructions for a provider/id selector",+ "--model <selector> Preview the per-model additions (model-prompts.toml) for a selector","--cwd <dir> Assemble for this working directory (default: current)","--json Print segments and prompt as JSON",]),diff --git a/crates/pa-cli/src/prompt_command.rs b/crates/pa-cli/src/prompt_command.rsindex f926378e25..ffe4d7019c 100644--- a/crates/pa-cli/src/prompt_command.rs+++ b/crates/pa-cli/src/prompt_command.rs@@ -58,7 +58,10 @@ pub fn run_prompt_command(args: &[String]) -> i32 {.or_else(|| std::env::current_dir().ok()).unwrap_or_else(|| std::path::PathBuf::from("."));match assemble_breakdown(&cwd, parsed.model.as_deref()) {- Ok(breakdown) => {+ Ok((breakdown, errors)) => {+ for error in &errors {+ eprintln!("Error: {error}");+ }if parsed.json {print_json(&breakdown);} else {@@ -76,8 +79,9 @@ pub fn run_prompt_command(args: &[String]) -> i32 {fn assemble_breakdown(cwd: &std::path::Path,model: Option<&str>,-) -> anyhow::Result<pa_core::prompts::SystemPromptBreakdown> {+) -> anyhow::Result<(pa_core::prompts::SystemPromptBreakdown, Vec<String>)> {let agent_dir = get_agent_dir();+ let model_prompts = pa_core::prompts::model_prompts::load_model_prompts(model, &agent_dir);let settings = SettingsManager::create(cwd, &agent_dir);// MCP gating: auth-gated built-in integrations drop their skills; enabled persistent generic// servers add the prompt MCP guidance.@@ -100,12 +104,11 @@ fn assemble_breakdown(system_prompt: None,..ResourceLoaderOptions::new(cwd.to_path_buf(), agent_dir)})?;- Ok(pa_core::prompts::system_prompt::system_prompt_breakdown(+ let breakdown = pa_core::prompts::system_prompt::system_prompt_breakdown(&pa_core::prompts::BuildSystemPromptOptions {cwd: cwd.display().to_string(),// A dump has no session file; the tail states the value it uses.messages_path: None,- model,custom_prompt: resources.system_prompt.clone(),context_files: resources.agents_files@@ -119,9 +122,11 @@ fn assemble_breakdown(allow_recursion: Some(true),generic_mcp_servers: generic_servers,rlm_depth: Some(0),+ model_prompt_extras: model_prompts.extras.as_deref(),..Default::default()},- ))+ );+ Ok((breakdown, model_prompts.errors))}fn print_text(breakdown: &pa_core::prompts::SystemPromptBreakdown) {@@ -216,7 +221,8 @@ mod tests {#[test]fn assembles_the_layered_prompt_for_a_directory() {let dir = tempfile::tempdir().unwrap();- let breakdown = assemble_breakdown(dir.path(), Some("mock/mock-1")).unwrap();+ let (breakdown, errors) = assemble_breakdown(dir.path(), Some("mock/mock-1")).unwrap();+ assert!(errors.is_empty());assert!(breakdown.assembled.starts_with("# prime-agent harness"));assert!(breakdown.assembleddiff --git a/crates/pa-core/Cargo.toml b/crates/pa-core/Cargo.tomlindex f6db562680..2efb183614 100644--- a/crates/pa-core/Cargo.toml+++ b/crates/pa-core/Cargo.toml@@ -34,6 +34,7 @@ getrandom = "0.3"url = "2"hmac = "0.12"globset = "0.4"+toml.workspace = truereqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json", "stream"] }tar = "0.4"flate2 = "1"diff --git a/crates/pa-core/src/models/resolver.rs b/crates/pa-core/src/models/resolver.rsindex 6b74b690df..1ecdcba378 100644--- a/crates/pa-core/src/models/resolver.rs+++ b/crates/pa-core/src/models/resolver.rs@@ -189,7 +189,7 @@ pub fn find_preferred_default_model(available_models: &[Model]) -> Option<&Model.find(|model| default_model_per_provider(&model.provider).is_some_and(|id| model.id == id))}-fn is_valid_thinking_level(value: &str) -> bool {+pub(crate) fn is_valid_thinking_level(value: &str) -> bool {matches!(value,"off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"diff --git a/crates/pa-core/src/prompts/layers.rs b/crates/pa-core/src/prompts/layers.rsindex 27c6be8a52..b4266dad15 100644--- a/crates/pa-core/src/prompts/layers.rs+++ b/crates/pa-core/src/prompts/layers.rs@@ -1,15 +1,9 @@-//! Static system-prompt layers: `core.md`, `usage.md`, `opinionated.md`,-//! and `per_model.md` (shipped empty, mechanism live), assembled into the-//! cache-stable prefix. Layers must never contain session-specific values-//! (the cache-safety guard test pins the boundary).+//! Static system-prompt layers assembled into the cache-stable prefix. Layers must never+//! contain session-specific values (the cache-safety guard test pins the boundary).pub const CORE_LAYER: &str = include_str!("layers/core.md");pub const USAGE_LAYER: &str = include_str!("layers/usage.md");pub const OPINIONATED_LAYER: &str = include_str!("layers/opinionated.md");-pub const PER_MODEL_MAP: &str = include_str!("layers/per_model.md");--/// Layer names, in assembly order, for breakdown rendering.-pub const LAYER_NAMES: [&str; 4] = ["core", "usage", "opinionated", "per-model"];/// Source file of one layer (breakdown provenance).#[must_use]@@ -18,186 +12,7 @@ pub fn layer_source(name: &str) -> Option<&'static str> {"core" => Some("prompts/layers/core.md"),"usage" => Some("prompts/layers/usage.md"),"opinionated" => Some("prompts/layers/opinionated.md"),- "per-model" => Some("prompts/layers/per_model.md"),+ "model-prompts" => Some("prompts/layers/model_prompts.toml"),_ => None,}}--/// One per-model instruction block from the map file.-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct PerModelBlock {- /// Comma-separated selector patterns from the block header.- pub patterns: Vec<String>,- /// The instruction text between the markers.- pub text: String,-}--/// Parse the per-model map. Blocks are delimited by-/// `<!-- pa:model: <patterns> -->` ... `<!-- /pa:model -->`; whitespace-only-/// blocks are ignored. Everything outside blocks is not prompt content.-pub fn parse_per_model_blocks(map: &str) -> Vec<PerModelBlock> {- const OPEN: &str = "<!-- pa:model:";- const CLOSE: &str = "<!-- /pa:model -->";- // Documentation comments are not prompt content; drop them before- // scanning for blocks so prose examples cannot smuggle in markers.- let map = strip_documentation_comments(map);- let mut blocks = Vec::new();- let mut rest = map.as_str();- while let Some(start) = rest.find(OPEN) {- let after_open = &rest[start + OPEN.len()..];- let Some(header_end) = after_open.find("-->") else {- break;- };- let patterns = after_open[..header_end]- .split(',')- .map(str::trim)- .filter(|pattern| !pattern.is_empty())- .map(str::to_string)- .collect::<Vec<_>>();- let body = &after_open[header_end + 3..];- let Some(end) = body.find(CLOSE) else { break };- let text = body[..end].trim().to_string();- if !text.is_empty() {- blocks.push(PerModelBlock { patterns, text });- }- rest = &body[end + CLOSE.len()..];- }- blocks-}--/// Remove `<!-- ... -->` spans that are neither `pa:model` markers nor their-/// terminators.-fn strip_documentation_comments(map: &str) -> String {- let mut out = String::with_capacity(map.len());- let mut rest = map;- while let Some(start) = rest.find("<!--") {- out.push_str(&rest[..start]);- let Some(end) = rest[start..].find("-->") else {- // Unterminated comment: drop the remainder.- return out;- };- let inner = &rest[start + 4..start + end];- if inner.trim_start().starts_with("pa:model:") || inner.trim() == "/pa:model" {- out.push_str(&rest[start..start + end + 3]);- }- rest = &rest[start + end + 3..];- }- out.push_str(rest);- out-}--/// Wildcard match: `*` matches any run of characters, the rest matches-/// literally.-#[must_use]-pub fn selector_matches(pattern: &str, selector: &str) -> bool {- let mut parts = pattern.split('*');- let mut rest = selector;- let Some(first) = parts.next() else {- return selector.is_empty();- };- if !rest.starts_with(first) {- return false;- }- rest = &rest[first.len()..];- for part in parts {- if part.is_empty() {- continue;- }- let Some(at) = rest.find(part) else {- return false;- };- rest = &rest[at + part.len()..];- }- // A pattern ending in `*` matches the remainder; otherwise the pattern- // must end exactly at the selector's end.- pattern.ends_with('*') || rest.is_empty()-}--/// The per-model instructions that apply to `model` (a resolved-/// `provider/id` selector), in map order. `None` model selects blocks whose-/// patterns include `*`.-#[must_use]-pub fn per_model_text(model: Option<&str>) -> Vec<String> {- parse_per_model_blocks(PER_MODEL_MAP)- .into_iter()- .filter(|block| {- model.is_some_and(|selector| {- block- .patterns- .iter()- .any(|pattern| selector_matches(pattern, selector))- })- })- .map(|block| block.text)- .collect()-}--/// The cache-stable static prefix for `model`: the three constant layers plus-/// any matching per-model blocks, joined with blank lines. This is exactly-/// what a provider may cache; everything after it is session-specific.-#[must_use]-pub fn static_prefix(model: Option<&str>) -> String {- let mut parts: Vec<String> = vec![- CORE_LAYER.trim().to_string(),- USAGE_LAYER.trim().to_string(),- OPINIONATED_LAYER.trim().to_string(),- ];- parts.extend(per_model_text(model));- parts.join("\n\n")-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn per_model_map_ships_empty() {- // The shipped map is the blockless format reference: nothing parses- // as a block, so no model selects any per-model text.- assert!(parse_per_model_blocks(PER_MODEL_MAP).is_empty());- assert!(per_model_text(None).is_empty());- assert!(per_model_text(Some("mock/mock-1")).is_empty());- }-- #[test]- fn parses_blocks_and_matches_selectors() {- let map = "<!-- pa:model: openai/gpt-5, anthropic/claude-* -->\nUse thinking mode.\n<!-- /pa:model -->\n<!-- pa:model: * -->\nFallback.\n<!-- /pa:model -->\n";- let blocks = parse_per_model_blocks(map);- assert_eq!(blocks.len(), 2);- assert_eq!(- blocks[0].patterns,- vec!["openai/gpt-5", "anthropic/claude-*"]- );- assert_eq!(blocks[0].text, "Use thinking mode.");- assert_eq!(blocks[1].patterns, vec!["*"]);- assert!(selector_matches(- "anthropic/claude-*",- "anthropic/claude-4-sonnet"- ));- assert!(!selector_matches("anthropic/claude-*", "openai/gpt-5"));- assert!(selector_matches("*", "anything"));- }-- #[test]- fn empty_blocks_are_ignored() {- let map = "<!-- pa:model: * -->\n \n<!-- /pa:model -->\n";- assert!(parse_per_model_blocks(map).is_empty());- }-- #[test]- fn static_prefix_is_layer_composition() {- let prefix = static_prefix(None);- assert!(prefix.starts_with("# prime-agent harness"));- assert!(prefix.contains("The following are mandatory rules"));- assert!(prefix.contains("guidelines to agents have been shown"));- assert_eq!(- prefix,- format!(- "{}\n\n{}\n\n{}",- CORE_LAYER.trim(),- USAGE_LAYER.trim(),- OPINIONATED_LAYER.trim()- )- );- }-}diff --git a/crates/pa-core/src/prompts/layers/model_prompts.toml b/crates/pa-core/src/prompts/layers/model_prompts.tomlnew file mode 100644index 0000000000..7b5918cff3--- /dev/null+++ b/crates/pa-core/src/prompts/layers/model_prompts.toml@@ -0,0 +1,9 @@+# Per-model system-prompt additions.+#+# [[rule]]+# match = ["glm-5.3*"]+# files = ["tier-2-models.md", "glm-5.3-identity.md"]+#+# File names resolve inside the agent dir; absolute paths and ".." are rejected.+# The user map is <agent_dir>/model-prompts.toml; matching, order, and+# error rules live in pa_core::prompts::model_prompts.diff --git a/crates/pa-core/src/prompts/layers/per_model.md b/crates/pa-core/src/prompts/layers/per_model.mddeleted file mode 100644index 882f074630..0000000000--- a/crates/pa-core/src/prompts/layers/per_model.md+++ /dev/null@@ -1,6 +0,0 @@-<!-- pa:per-model-instructions-Format: a block opens with "<!-- pa:model:" plus a comma-separated list of-model selector patterns and "-->", ends with "<!-- /pa:model -->", and holds-the instruction text between the two. In a pattern, "*" matches any run of-characters. Multiple blocks may match; they apply in file order.--->diff --git a/crates/pa-core/src/prompts/mod.rs b/crates/pa-core/src/prompts/mod.rsindex be2d257f9a..fdaa9238d5 100644--- a/crates/pa-core/src/prompts/mod.rs+++ b/crates/pa-core/src/prompts/mod.rs@@ -5,6 +5,8 @@pub mod layers;+pub mod model_prompts;+pub mod system_prompt;pub use system_prompt::{diff --git a/crates/pa-core/src/prompts/model_prompts.rs b/crates/pa-core/src/prompts/model_prompts.rsnew file mode 100644index 0000000000..5d14bd2d6b--- /dev/null+++ b/crates/pa-core/src/prompts/model_prompts.rs@@ -0,0 +1,606 @@+//! Per-model system-prompt additions: a TOML rule map from model selectors to markdown files.+//! Shipped rules run before the user's `<agent_dir>/model-prompts.toml` rules; any problem in+//! either layer disables all additions for the session and is reported, never blocking.++use std::collections::BTreeMap;+use std::io;+use std::path::{Component, Path};++use pa_types::session::CustomMessage;+use serde::Deserialize;++pub const MODEL_PROMPTS_TOML: &str = include_str!("layers/model_prompts.toml");++const MODEL_PROMPT_FILES: &[(&str, &str)] = &[];++const USER_MODEL_PROMPTS_TOML: &str = "model-prompts.toml";++/// `display: true` rows of this type are dropped from LLM context by `messages::convert_to_llm`.+pub const MODEL_PROMPT_ERROR_CUSTOM_TYPE: &str = "model_prompt_error";++const SHIPPED_SOURCE: &str = "shipped model_prompts.toml";++/// `extras` is `None` whenever `errors` is non-empty.+#[derive(Debug, Default, PartialEq, Eq)]+pub struct ModelPromptResolution {+ pub extras: Option<String>,+ pub errors: Vec<String>,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct Rule {+ r#match: Vec<String>,+ files: Vec<String>,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct ModelPromptsDoc {+ #[serde(default)]+ rule: Vec<Rule>,+}++struct ParsedRule {+ patterns: Vec<globset::GlobMatcher>,+ files: Vec<String>,+}++fn compile_pattern(pattern: &str) -> Result<globset::GlobMatcher, String> {+ globset::GlobBuilder::new(pattern)+ .literal_separator(true)+ .case_insensitive(true)+ .build()+ .map_err(|error| format!("pattern {pattern:?}: {error}"))+ .map(|glob| glob.compile_matcher())+}++fn parse_layer(toml_text: &str, source: &str) -> (Vec<ParsedRule>, Vec<String>) {+ let doc = match toml::from_str::<ModelPromptsDoc>(toml_text) {+ Ok(doc) => doc,+ Err(error) => return (Vec::new(), vec![format!("{source}: {error}")]),+ };+ let mut rules = Vec::new();+ let mut errors = Vec::new();+ for rule in doc.rule {+ let mut patterns = Vec::new();+ for pattern in rule.r#match {+ match compile_pattern(&pattern) {+ Ok(matcher) => patterns.push(matcher),+ Err(error) => errors.push(format!("{source}: {error}")),+ }+ }+ let mut files = Vec::new();+ for name in rule.files {+ if Path::new(&name).components().all(|c| {+ !matches!(+ c,+ Component::ParentDir | Component::RootDir | Component::Prefix(_)+ )+ }) {+ // Normalize equivalent spellings before resolution and deduplication.+ let normalized = Path::new(&name)+ .components()+ .filter(|component| !matches!(component, Component::CurDir))+ .map(|component| component.as_os_str().to_string_lossy())+ .collect::<Vec<_>>()+ .join("/");+ files.push(normalized);+ } else {+ errors.push(format!(+ "{source}: file {name:?} must be a relative path inside the agent directory"+ ));+ }+ }+ rules.push(ParsedRule { patterns, files });+ }+ (rules, errors)+}++/// Strips a trailing `:<level>` only when it parses as a thinking level, mirroring the model+/// parser.+fn selector_segments(selector: &str) -> Vec<&str> {+ let selector = match selector.rsplit_once(':') {+ Some((prefix, suffix)) if crate::models::resolver::is_valid_thinking_level(suffix) => {+ prefix+ }+ _ => selector,+ };+ selector.split('/').collect()+}++fn rule_applies(rule: &ParsedRule, segments: &[&str]) -> bool {+ rule.patterns.iter().any(|matcher| {+ (1..=segments.len())+ .any(|count| matcher.is_match(segments[segments.len() - count..].join("/")))+ })+}++// Check the file type before opening: opening a FIFO can wait forever for a writer.+fn read_regular_file(path: &Path) -> io::Result<String> {+ if !std::fs::metadata(path)?.is_file() {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "expected a regular file",+ ));+ }+ std::fs::read_to_string(path)+}++fn resolve_layer_files(+ rules: &[ParsedRule],+ source: &str,+ agent_dir: &Path,+ shipped_files: &[(&str, &str)],+ contents: &mut BTreeMap<String, String>,+) -> Vec<String> {+ let mut errors = Vec::new();+ for rule in rules {+ for name in &rule.files {+ if contents.contains_key(name) {+ continue;+ }+ let user_file = agent_dir.join(name);+ let content = user_file.canonicalize().and_then(|resolved| {+ let root = agent_dir.canonicalize()?;+ if !resolved.starts_with(root) {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "file resolves outside the agent directory",+ ));+ }+ read_regular_file(&resolved)+ });+ match content {+ Ok(content) => {+ contents.insert(name.clone(), content);+ }+ Err(error) if error.kind() == io::ErrorKind::NotFound => {+ if let Some((_, content)) = shipped_files+ .iter()+ .find(|(shipped_name, _)| shipped_name == &name.as_str())+ {+ contents.insert(name.clone(), (*content).to_string());+ } else {+ errors.push(format!("{source}: missing file {name:?}"));+ }+ }+ Err(error) => {+ errors.push(format!("{source}: {}: {error}", user_file.display()));+ }+ }+ }+ }+ errors+}++fn resolve_model_prompts(+ selector: Option<&str>,+ shipped_toml: &str,+ shipped_files: &[(&str, &str)],+ agent_dir: &Path,+) -> ModelPromptResolution {+ // Both layers are validated regardless; the selector only gates which+ // rules match, so `prime-agent prompt` with no `--model` still reports+ // a broken map.+ let segments = selector.map(selector_segments);+ let mut errors = Vec::new();++ let (shipped_rules, mut layer_errors) = parse_layer(shipped_toml, SHIPPED_SOURCE);+ errors.append(&mut layer_errors);+ let user_path = agent_dir.join(USER_MODEL_PROMPTS_TOML);+ let user_layer = user_path.display().to_string();+ let user_rules = match read_regular_file(&user_path) {+ Ok(text) => {+ let (rules, mut layer_errors) = parse_layer(&text, &user_layer);+ errors.append(&mut layer_errors);+ rules+ }+ Err(error) if error.kind() == io::ErrorKind::NotFound => Vec::new(),+ Err(error) => {+ errors.push(format!("{}: {error}", user_path.display()));+ Vec::new()+ }+ };++ let mut contents: BTreeMap<String, String> = BTreeMap::new();+ for (rules, source) in [+ (&shipped_rules, SHIPPED_SOURCE),+ (&user_rules, user_layer.as_str()),+ ] {+ errors.extend(resolve_layer_files(+ rules,+ source,+ agent_dir,+ shipped_files,+ &mut contents,+ ));+ }+ if !errors.is_empty() {+ return ModelPromptResolution {+ extras: None,+ errors,+ };+ }++ let mut included: Vec<&str> = Vec::new();+ for rule in shipped_rules.iter().chain(user_rules.iter()) {+ if segments+ .as_deref()+ .is_some_and(|segments| rule_applies(rule, segments))+ {+ for name in &rule.files {+ if !included.contains(&name.as_str()) {+ included.push(name.as_str());+ }+ }+ }+ }+ let parts = included+ .iter()+ .map(|name| contents[*name].trim())+ .filter(|text| !text.is_empty())+ .collect::<Vec<_>>();+ let extras = (!parts.is_empty()).then(|| parts.join("\n\n"));+ ModelPromptResolution { extras, errors }+}++#[must_use]+pub fn load_model_prompts(selector: Option<&str>, agent_dir: &Path) -> ModelPromptResolution {+ resolve_model_prompts(selector, MODEL_PROMPTS_TOML, MODEL_PROMPT_FILES, agent_dir)+}++#[must_use]+pub fn model_prompt_error_message(errors: &[String]) -> CustomMessage {+ let list = errors+ .iter()+ .map(|error| format!("- {error}"))+ .collect::<Vec<_>>()+ .join("\n");+ CustomMessage {+ custom_type: MODEL_PROMPT_ERROR_CUSTOM_TYPE.to_string(),+ content: pa_types::ai::UserContent::Text(format!(+ "[model-prompt-error]\n\nPer-model system prompt additions were not applied:\n{list}"+ )),+ display: true,+ details: None,+ timestamp: crate::session_engine::refine::now_millis(),+ rest: serde_json::Map::default(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn write_file(dir: &std::path::Path, name: &str, content: &str) {+ std::fs::write(dir.join(name), content).unwrap();+ }++ fn user_layer(toml_rules: &str) -> tempfile::TempDir {+ let dir = tempfile::tempdir().unwrap();+ write_file(dir.path(), USER_MODEL_PROMPTS_TOML, toml_rules);+ dir+ }++ #[test]+ fn documented_selector_examples_match() {+ let cases = [+ ("glm-5.3", "z-ai/glm-5.3", true),+ ("glm-5.3", "internal/glm-5.3-fast", false),+ ("glm-5.3*", "internal/glm-5.3-fast", true),+ (+ "internal/glm-5.3*",+ "prime-inference/internal/glm-5.3-fast",+ true,+ ),+ ("internal/glm-5.3*", "z-ai/glm-5.3-fast", false),+ ("internal/*", "prime-inference/internal/glm-5.3", true),+ (+ "prime-inference/anthropic/claude-fable-5.1",+ "prime-inference/anthropic/claude-fable-5.1",+ true,+ ),+ (+ "prime-inference/anthropic/claude-fable-5.1",+ "anthropic/claude-fable-5.1",+ false,+ ),+ (+ "anthropic/claude-sonnet-4",+ "anthropic/claude-sonnet-4",+ true,+ ),+ (+ "anthropic/claude-sonnet-4",+ "prime-inference/anthropic/claude-sonnet-4",+ true,+ ),+ // case-insensitive+ ("GLM-5.3*", "z-ai/glm-5.3-fast", true),+ // a trailing thinking level is stripped from the selector+ ("glm-5.3", "z-ai/glm-5.3:high", true),+ ("glm-5.3*", "z-ai/glm-5.3-fast:xhigh", true),+ // dots are literal (a regex `.` would match the `-`)+ ("claude-sonnet-3.5", "anthropic/claude-sonnet-3-5", false),+ // `?` matches exactly one character+ ("claude-sonnet-?", "anthropic/claude-sonnet-4", true),+ ("claude-sonnet-?", "anthropic/claude-sonnet-4.5", false),+ // a brace pattern applies when any alternative fits the final+ // segments, even though the pattern string spans more slashes+ ("{anthropic/claude-*,z-ai/glm-*}", "z-ai/glm-5.3", true),+ ];+ for (pattern, selector, expected) in cases {+ let (rules, _) =+ parse_layer(&format!("[[rule]]\nmatch = [{pattern:?}]\nfiles = []"), "t");+ assert_eq!(+ rule_applies(&rules[0], &selector_segments(selector)),+ expected,+ "pattern {pattern:?} against {selector:?}"+ );+ }+ }++ #[test]+ fn every_matching_rule_applies_and_shared_files_dedupe_first() {+ let dir = user_layer(+ r#"+[[rule]]+match = ["glm-5.3"]+files = ["a.md", "b.md"]++[[rule]]+match = ["glm-5.3*"]+files = ["./b.md", "c.md", "././a.md"]++[[rule]]+match = ["claude-*"]+files = ["a.md"]+"#,+ );+ write_file(dir.path(), "a.md", "A");+ write_file(dir.path(), "b.md", "B");+ write_file(dir.path(), "c.md", "C");+ let resolution = resolve_model_prompts(Some("z-ai/glm-5.3"), "", &[], dir.path());+ assert!(resolution.errors.is_empty());+ assert_eq!(resolution.extras.as_deref(), Some("A\n\nB\n\nC"));+ }++ #[test]+ fn user_files_override_shipped_and_user_rules_run_last() {+ let dir = user_layer(+ r#"+[[rule]]+match = ["glm-5.3"]+files = ["shared.md", "user-only.md"]+"#,+ );+ write_file(dir.path(), "shared.md", "USER");+ write_file(dir.path(), "user-only.md", "USER-ONLY");+ let shipped_toml = "[[rule]]\nmatch = [\"glm-5.3\"]\nfiles = [\"shared.md\"]\n";+ let shipped_files = [("shared.md", "SHIPPED")];+ let resolution = resolve_model_prompts(+ Some("z-ai/glm-5.3"),+ shipped_toml,+ &shipped_files,+ dir.path(),+ );+ assert!(resolution.errors.is_empty());+ assert_eq!(resolution.extras.as_deref(), Some("USER\n\nUSER-ONLY"));++ let clean = tempfile::tempdir().unwrap();+ let resolution = resolve_model_prompts(+ Some("z-ai/glm-5.3"),+ shipped_toml,+ &shipped_files,+ clean.path(),+ );+ assert_eq!(resolution.extras.as_deref(), Some("SHIPPED"));+ }++ #[test]+ fn layer_problems_disable_extras_and_name_the_source() {+ let empty = tempfile::tempdir().unwrap();+ let resolution = resolve_model_prompts(Some("z-ai/glm-5.3"), "", &[], empty.path());+ assert_eq!(resolution, ModelPromptResolution::default());++ let cases = [+ ("not a rule map [", USER_MODEL_PROMPTS_TOML),+ (+ "[[rule]]\nmatches = [\"glm-5.3\"]\nfiles = [\"a.md\"]\n",+ USER_MODEL_PROMPTS_TOML,+ ),+ (+ "[[rule]]\nmatch = [\"glm-5.3\"]\nfiles = [\"missing.md\"]\n",+ "missing.md",+ ),+ (+ "[[rule]]\nmatch = [\"glm-5.3[\"]\nfiles = [\"a.md\"]\n",+ "glm-5.3[",+ ),+ ];+ for (toml_text, named) in cases {+ let dir = user_layer(toml_text);+ write_file(dir.path(), "a.md", "A");+ let resolution = resolve_model_prompts(Some("z-ai/glm-5.3"), "", &[], dir.path());+ assert!(resolution.extras.is_none(), "extras survived {toml_text:?}");+ assert!(+ resolution+ .errors+ .iter()+ .any(|error| error.contains(named) && error.contains(USER_MODEL_PROMPTS_TOML)),+ "{toml_text:?}: errors {:#?} do not name {named} in {USER_MODEL_PROMPTS_TOML}",+ resolution.errors+ );+ }++ let dir = user_layer("[[rule]]\nmatch = [\"claude-*\"]\nfiles = [\"missing-user.md\"]\n");+ let resolution = resolve_model_prompts(+ Some("z-ai/glm-5.3"),+ "[[rule]]\nmatch = [\"glm-5.3\"]\nfiles = [\"missing-shipped.md\"]\n",+ &[],+ dir.path(),+ );+ assert!(resolution.extras.is_none());+ assert!(resolution+ .errors+ .iter()+ .any(|error| error.contains("missing-user.md")));+ assert!(resolution+ .errors+ .iter()+ .any(|error| error.contains("missing-shipped.md")));++ let dir = user_layer("not a rule map [");+ let resolution = resolve_model_prompts(None, "", &[], dir.path());+ assert!(resolution.extras.is_none());+ assert!(resolution+ .errors+ .iter()+ .any(|error| error.contains(USER_MODEL_PROMPTS_TOML)));+ }++ #[test]+ fn the_shipped_map_is_valid() {+ let empty = tempfile::tempdir().unwrap();+ let resolution = load_model_prompts(Some("z-ai/glm-5.3"), empty.path());+ assert!(resolution.errors.is_empty());+ }++ #[test]+ fn file_entries_outside_the_agent_dir_are_rejected() {+ let root = tempfile::tempdir().unwrap();+ write_file(root.path(), "outside.md", "OUTSIDE");+ let agent_dir = root.path().join("agent");+ std::fs::create_dir(&agent_dir).unwrap();+ write_file(&agent_dir, "inside.md", "INSIDE");++ let outside = root.path().join("outside.md").display().to_string();+ let cases = [+ ("inside.md", Some("INSIDE"), false),+ ("./inside.md", Some("INSIDE"), false),+ ("../outside.md", None, true),+ (outside.as_str(), None, true),+ ];+ let mut failures = Vec::new();+ for (name, extras, rejected) in cases {+ write_file(+ &agent_dir,+ USER_MODEL_PROMPTS_TOML,+ &format!("[[rule]]\nmatch = [\"glm-5.3\"]\nfiles = [{name:?}]\n"),+ );+ let resolution = resolve_model_prompts(Some("z-ai/glm-5.3"), "", &[], &agent_dir);+ let leaked = resolution.extras.as_deref();+ if leaked != extras {+ failures.push(format!(+ "file {name:?}: extras {leaked:?}, expected {extras:?}"+ ));+ }+ let named = resolution+ .errors+ .iter()+ .any(|error| error.contains(&format!("{name:?}")));+ if named != rejected {+ failures.push(format!("file {name:?}: errors {:#?}", resolution.errors));+ }+ }+ assert!(failures.is_empty(), "{failures:#?}");+ }++ #[test]+ fn normalized_names_resolve_shipped_files() {+ let dir = user_layer("[[rule]]\nmatch = [\"*\"]\nfiles = [\"./a.md\", \"a.md\"]\n");+ let resolution = resolve_model_prompts(Some("model"), "", &[("a.md", "A")], dir.path());+ assert_eq!(+ resolution,+ ModelPromptResolution {+ extras: Some("A".to_string()),+ errors: Vec::new(),+ }+ );+ }++ #[cfg(unix)]+ #[test]+ fn symlink_targets_must_stay_inside_agent_directory() {+ use std::os::unix::fs::symlink;++ let root = tempfile::tempdir().unwrap();+ let agent_dir = root.path().join("agent");+ std::fs::create_dir(&agent_dir).unwrap();+ write_file(root.path(), "outside.md", "OUTSIDE");+ write_file(&agent_dir, "inside.md", "INSIDE");+ symlink(root.path().join("outside.md"), agent_dir.join("escape.md")).unwrap();+ symlink(root.path(), agent_dir.join("escape-dir")).unwrap();+ symlink(agent_dir.join("inside.md"), agent_dir.join("safe.md")).unwrap();+ for name in ["escape.md", "escape-dir/outside.md", "safe.md"] {+ write_file(+ &agent_dir,+ USER_MODEL_PROMPTS_TOML,+ &format!("[[rule]]\nmatch = [\"*\"]\nfiles = [{name:?}]\n"),+ );+ let resolution = resolve_model_prompts(Some("model"), "", &[], &agent_dir);+ if name == "safe.md" {+ assert_eq!(+ resolution,+ ModelPromptResolution {+ extras: Some("INSIDE".to_string()),+ errors: Vec::new(),+ }+ );+ } else {+ assert!(resolution.extras.is_none());+ assert!(resolution+ .errors+ .iter()+ .any(|error| error.contains("outside the agent directory")));+ }+ }+ }++ #[cfg(unix)]+ #[test]+ fn fifos_are_rejected_without_opening_them() {+ // Keep a writer available so a regression fails assertions instead of hanging the suite.+ for name in [USER_MODEL_PROMPTS_TOML, "fifo.md"] {+ let dir =+ user_layer("[[rule]]\nmatch = [\"different-model\"]\nfiles = [\"fifo.md\"]\n");+ let path = dir.path().join(name);+ if name == USER_MODEL_PROMPTS_TOML {+ std::fs::remove_file(&path).unwrap();+ }+ nix::unistd::mkfifo(+ &path,+ nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR,+ )+ .unwrap();+ let writer_path = path.clone();+ let writer = std::thread::spawn(move || {+ // Nonblocking open succeeds only if the loader incorrectly opened the FIFO.+ use std::os::unix::fs::OpenOptionsExt;+ loop {+ if let Ok(file) = std::fs::OpenOptions::new()+ .write(true)+ .custom_flags(libc::O_NONBLOCK)+ .open(&writer_path)+ {+ drop(file);+ break;+ }+ if !writer_path.exists() {+ break;+ }+ std::thread::yield_now();+ }+ });+ let resolution = resolve_model_prompts(Some("model"), "", &[], dir.path());+ std::fs::remove_file(&path).unwrap();+ writer.join().unwrap();+ assert!(resolution.extras.is_none());+ assert!(resolution+ .errors+ .iter()+ .any(|error| error.contains("expected a regular file")));+ }+ }+}diff --git a/crates/pa-core/src/prompts/system_prompt.rs b/crates/pa-core/src/prompts/system_prompt.rsindex 652e2a3a1c..a07e4e53ca 100644--- a/crates/pa-core/src/prompts/system_prompt.rs+++ b/crates/pa-core/src/prompts/system_prompt.rs@@ -60,15 +60,15 @@ pub struct SystemPromptBreakdown {pub cached_prefix_len: usize,}-/// Inputs for one session's prompt. Static inputs (`custom_prompt`, `model`)-/// select the cached prefix; everything else feeds the dynamic tail.+/// Inputs for one session's prompt. Static inputs (`custom_prompt`,+/// `model_prompt_extras`) select the cached prefix; everything else feeds+/// the dynamic tail.#[derive(Debug, Default)]pub struct BuildSystemPromptOptions<'a> {/// Replaces the layered static prefix with user text. The dynamic tail/// still applies.pub custom_prompt: Option<String>,- /// Resolved model selector (`provider/id`), selecting per-model blocks.- pub model: Option<&'a str>,+ pub model_prompt_extras: Option<&'a str>,/// Whether the resolved model accepts image input, when known.pub vision_capable: Option<bool>,/// Active tools. Tool schemas carry tool descriptions outside the prompt.@@ -129,12 +129,11 @@ pub fn system_prompt_breakdown(options: &BuildSystemPromptOptions) -> SystemPromlayers::layer_source("opinionated").unwrap_or_default(),layers::OPINIONATED_LAYER.trim().to_string(),));- let per_model = layers::per_model_text(options.model);- if !per_model.is_empty() {+ if let Some(extras) = options.model_prompt_extras {segments.push(PromptSegment::static_segment(- "per-model",- layers::layer_source("per-model").unwrap_or_default(),- per_model.join("\n\n"),+ "model-prompts",+ layers::layer_source("model-prompts").unwrap_or_default(),+ extras.to_string(),));}}@@ -432,7 +431,6 @@ mod tests {BuildSystemPromptOptions {cwd: "/w".to_string(),messages_path: Some("/log.jsonl".to_string()),- model: Some("mock/mock-1"),skills: vec![skill("web-search", Some("websearch")),skill("refine", Some("refine")),@@ -461,7 +459,12 @@ mod tests {);assert_eq!(&prompt[..breakdown.cached_prefix_len],- layers::static_prefix(Some("mock/mock-1"))+ format!(+ "{}\n\n{}\n\n{}",+ layers::CORE_LAYER.trim(),+ layers::USAGE_LAYER.trim(),+ layers::OPINIONATED_LAYER.trim()+ ));let tail = &prompt[breakdown.cached_prefix_len..];assert!(tail.contains("Working directory: /w"));@@ -497,6 +500,7 @@ mod tests {fn custom_prompt_replaces_layers_keeps_tail() {let mut options = base_options();options.custom_prompt = Some("Be terse.".to_string());+ options.model_prompt_extras = Some("Tier-2 guidance.");options.context_files = vec![("AGENTS.md".to_string(), "Rule one.".to_string())];let breakdown = system_prompt_breakdown(&options);let prompt = &breakdown.assembled;@@ -506,6 +510,7 @@ mod tests {assert!(prompt.contains("Working directory: /w"));assert!(prompt.contains("Current date: "));assert!(!prompt.contains("# prime-agent harness"));+ assert!(!prompt.contains("Tier-2 guidance."));}#[test]@@ -531,25 +536,19 @@ mod tests {}#[test]- fn per_model_blocks_extend_the_cached_prefix() {- // The shipped map has no blocks, so a model-mapped block can only be- // verified through the parser; assert the composition contract here:- // any per-model text lands inside the cached prefix.- let breakdown = system_prompt_breakdown(&base_options());- let static_segments = breakdown+ fn model_prompt_extras_form_the_last_static_segment() {+ let mut options = base_options();+ options.model_prompt_extras = Some("Tier-2 guidance.");+ let breakdown = system_prompt_breakdown(&options);+ let names: Vec<&str> = breakdown.segments.iter()- .filter(|segment| segment.kind == SegmentKind::Static);- for segment in static_segments {- assert_eq!(- breakdown- .assembled- .find(&segment.text)- .map(|at| at < breakdown.cached_prefix_len),- Some(true),- "static segment {} sits inside the cached prefix",- segment.name- );- }+ .map(|segment| segment.name)+ .collect();+ assert_eq!(+ names[..5],+ ["core", "usage", "opinionated", "model-prompts", "packages"],+ "extras are the last static segment, directly before the dynamic tail"+ );}}diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rsindex 692b2a3838..a502f37ca4 100644--- a/crates/pa-core/src/session_engine/engine.rs+++ b/crates/pa-core/src/session_engine/engine.rs@@ -463,12 +463,24 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Slet prompt_guidelines = config.prompt_guidelines.clone();- let prompt_model_selector = Some(format!("{}/{}", model_info.provider, model_info.id));+ let prompt_model_selector = format!("{}/{}", model_info.provider, model_info.id);let prompt_vision_capable = Some(model_info.input.contains(&pa_types::ai::ModelInput::Image));+ let model_prompts = crate::prompts::model_prompts::load_model_prompts(+ Some(&prompt_model_selector),+ &config.agent_dir,+ );+ if !model_prompts.errors.is_empty() {+ boot_notice_rows+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .push(crate::prompts::model_prompts::model_prompt_error_message(+ &model_prompts.errors,+ ));+ }let system_prompt = crate::prompts::system_prompt::build_system_prompt(&crate::prompts::system_prompt::BuildSystemPromptOptions {custom_prompt: resources.system_prompt.clone(),- model: prompt_model_selector.as_deref(),+ model_prompt_extras: model_prompts.extras.as_deref(),vision_capable: prompt_vision_capable,cwd: cwd.display().to_string(),messages_path: conversation_log.clone(),diff --git a/crates/pa-core/src/session_engine/messages.rs b/crates/pa-core/src/session_engine/messages.rsindex cf34bbcbb4..8913bb8335 100644--- a/crates/pa-core/src/session_engine/messages.rs+++ b/crates/pa-core/src/session_engine/messages.rs@@ -325,6 +325,7 @@ pub fn convert_to_llm(messages: &[AgentMessage]) -> Vec<AgentMessage> {| COMPACTION_OUTCOME_CUSTOM_TYPE| REFINEMENT_OUTCOME_CUSTOM_TYPE| PROVIDER_RETRY_OUTCOME_CUSTOM_TYPE+ | crate::prompts::model_prompts::MODEL_PROMPT_ERROR_CUSTOM_TYPE) {continue;}@@ -467,6 +468,14 @@ mod tests {);}+ #[test]+ fn model_prompt_error_row_is_never_context() {+ let message = crate::prompts::model_prompts::model_prompt_error_message(&[+ "/x/model-prompts.toml: bad TOML".to_string(),+ ]);+ assert!(convert_to_llm(&[AgentMessage::Custom(message)]).is_empty());+ }+#[test]fn bash_output_fences_and_status() {let rendered = bash_output_to_text(diff --git a/crates/pa-core/tests/prompt_guards.rs b/crates/pa-core/tests/prompt_guards.rsindex b2e4f629dd..6496cc1b90 100644--- a/crates/pa-core/tests/prompt_guards.rs+++ b/crates/pa-core/tests/prompt_guards.rs@@ -15,7 +15,8 @@use std::collections::BTreeSet;use std::path::Path;-use pa_core::prompts::layers::{self, CORE_LAYER, OPINIONATED_LAYER, PER_MODEL_MAP, USAGE_LAYER};+use pa_core::prompts::layers::{CORE_LAYER, OPINIONATED_LAYER, USAGE_LAYER};+use pa_core::prompts::model_prompts::MODEL_PROMPTS_TOML;use pa_core::prompts::system_prompt::{system_prompt_breakdown, BuildSystemPromptOptions, SegmentKind,};@@ -63,7 +64,7 @@ fn static_layers_contain_no_dynamic_content() {("core", CORE_LAYER),("usage", USAGE_LAYER),("opinionated", OPINIONATED_LAYER),- ("per-model", PER_MODEL_MAP),+ ("model-prompts", MODEL_PROMPTS_TOML),] {for marker in DYNAMIC_ONLY_MARKERS {assert!(@@ -80,7 +81,7 @@ fn cached_prefix_is_stable_across_sessions() {let mut options = BuildSystemPromptOptions {cwd: "/first/cwd".to_string(),messages_path: Some("/first/session.jsonl".to_string()),- model: Some("mock/mock-1"),+ model_prompt_extras: Some("model guidance."),skills: sorted_bundled_skills(),selected_tools: Some(vec!["ipython"]),..Default::default()@@ -104,7 +105,12 @@ fn cached_prefix_is_stable_across_sessions() {);assert_eq!(&first.assembled[..first.cached_prefix_len],- layers::static_prefix(Some("mock/mock-1"))+ &format!(+ "{}\n\n{}\n\n{}\n\nmodel guidance.",+ CORE_LAYER.trim(),+ USAGE_LAYER.trim(),+ OPINIONATED_LAYER.trim()+ ));let first_tail = &first.assembled[first.cached_prefix_len..];@@ -540,7 +546,6 @@ fn generic_mcp_skill_renders_in_the_prompt_inventory() {let mut options = BuildSystemPromptOptions {cwd: "/w".to_string(),messages_path: Some("/log.jsonl".to_string()),- model: Some("mock/mock-1"),skills: sorted_bundled_skills(),selected_tools: Some(vec!["ipython"]),..Default::default()diff --git a/crates/pa-tui/src/custom_message/mod.rs b/crates/pa-tui/src/custom_message/mod.rsindex af2c71a898..311bf2c111 100644--- a/crates/pa-tui/src/custom_message/mod.rs+++ b/crates/pa-tui/src/custom_message/mod.rs@@ -62,6 +62,8 @@ pub const REFINEMENT_OUTCOME_CUSTOM_TYPE: &str = "refinement_outcome";/// operator ruling 2026-09-23: one terminal row per episode instead of TS's per-attempt error/// rows). Wire twin of `pa_core::session_engine::messages::PROVIDER_RETRY_OUTCOME_CUSTOM_TYPE`.pub const PROVIDER_RETRY_OUTCOME_CUSTOM_TYPE: &str = "provider_retry_outcome";+/// Wire twin of `pa_core::prompts::model_prompts::MODEL_PROMPT_ERROR_CUSTOM_TYPE`.+pub const MODEL_PROMPT_ERROR_CUSTOM_TYPE: &str = "model_prompt_error";/// Which agent-message side a row renders: the received transcript rows, or the/// sent/queued ipython cell receipts. The direction word folds into the@@ -192,6 +194,10 @@ pub fn custom_message_entries(message: &Value) -> Vec<ChatEntry> {},}]}+ MODEL_PROMPT_ERROR_CUSTOM_TYPE => vec![ChatEntry::Status {+ text: content,+ kind: crate::chat::StatusKind::Warning,+ }],REFINEMENT_OUTCOME_CUSTOM_TYPE => refinement::refinement_outcome_entries(message, details),AGENT_MESSAGE_CUSTOM_TYPE => agent_message_entry(details).map_or_else(|| vec![generic_panel_entry(custom_type, message)],diff --git a/crates/pa-tui/src/snapshot/tests.rs b/crates/pa-tui/src/snapshot/tests.rsindex f07ee36de5..1d2dee9eb5 100644--- a/crates/pa-tui/src/snapshot/tests.rs+++ b/crates/pa-tui/src/snapshot/tests.rs@@ -1207,6 +1207,24 @@ fn retry_outcome_row_collapses_the_superseded_attempts() {);}+#[test]+fn model_prompt_error_row_is_a_warning_status_line() {+ let message = json!({+ "role": "custom",+ "customType": "model_prompt_error",+ "content": "[model-prompt-error]\n\nPer-model system prompt additions were not applied:\n- /x/model-prompts.toml: bad TOML",+ "display": true,+ });+ let entries = transcript_to_entries(&[message]);+ assert!(+ matches!(+ entries.as_slice(),+ [ChatEntry::Status { text, kind: StatusKind::Warning }] if text.contains("[model-prompt-error]")+ ),+ "entries: {entries:?}"+ );+}+#[test]fn a_lone_failed_attempt_without_an_outcome_row_stays() {let user = json!({"role": "user", "content": "hi"});