Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2
akode-rs/prompts/src/compact.rs
Normal file
2
akode-rs/prompts/src/compact.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub const SUMMARIZATION_PROMPT: &str = include_str!("../templates/compact/prompt.md");
|
||||
pub const SUMMARY_PREFIX: &str = include_str!("../templates/compact/summary_prefix.md");
|
||||
177
akode-rs/prompts/src/guardian_instructions.rs
Normal file
177
akode-rs/prompts/src/guardian_instructions.rs
Normal file
@@ -0,0 +1,177 @@
|
||||
//! Composes Guardian prompts and rejection feedback from selected text and runtime inputs.
|
||||
//! Callers select policy overrides, output contracts, calibration, and truncation limits.
|
||||
|
||||
use akode_context_fragments::ContextualUserFragment;
|
||||
use akode_guardian_context::TRANSCRIPT_JSON_INSTRUCTIONS;
|
||||
use akode_guardian_context::TranscriptFormat;
|
||||
use akode_guardian_context::truncate_text;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::ContentItemKind;
|
||||
use akode_protocol::models::input_text;
|
||||
|
||||
const TENANT_POLICY_CONFIG_PLACEHOLDER: &str = "{{ tenant_policy_config }}";
|
||||
const EXTRA_POLICY_PLACEHOLDER: &str = "{{ extra_policy }}";
|
||||
|
||||
/// Reviewer base instructions composed from the effective policy and caller-owned output contract.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct GuardianPolicyInstructions<'a> {
|
||||
transcript_format: TranscriptFormat,
|
||||
tenant_policy_config: &'a str,
|
||||
extra_policy: &'a str,
|
||||
policy_template: &'a str,
|
||||
output_contract: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> GuardianPolicyInstructions<'a> {
|
||||
pub fn new(
|
||||
transcript_format: TranscriptFormat,
|
||||
tenant_policy_config: &'a str,
|
||||
extra_policy: &'a str,
|
||||
policy_template: &'a str,
|
||||
output_contract: &'a str,
|
||||
) -> Self {
|
||||
Self {
|
||||
transcript_format,
|
||||
tenant_policy_config,
|
||||
extra_policy,
|
||||
policy_template,
|
||||
output_contract,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextualUserFragment for GuardianPolicyInstructions<'_> {
|
||||
fn role(&self) -> &'static str {
|
||||
"developer"
|
||||
}
|
||||
|
||||
fn content_kind(&self) -> ContentItemKind {
|
||||
ContentItemKind("guardian.policy_instructions".to_owned())
|
||||
}
|
||||
|
||||
fn markers(&self) -> (&'static str, &'static str) {
|
||||
Self::type_markers()
|
||||
}
|
||||
|
||||
fn type_markers() -> (&'static str, &'static str) {
|
||||
("", "")
|
||||
}
|
||||
|
||||
fn body(&self) -> ContentItem {
|
||||
let Self {
|
||||
transcript_format,
|
||||
tenant_policy_config,
|
||||
extra_policy,
|
||||
policy_template,
|
||||
output_contract,
|
||||
} = *self;
|
||||
// Substitute only template text, leaving placeholder-like text in either policy literal.
|
||||
let prompt = policy_template
|
||||
.trim_end()
|
||||
.split(TENANT_POLICY_CONFIG_PLACEHOLDER)
|
||||
.map(|part| part.replace(EXTRA_POLICY_PLACEHOLDER, extra_policy.trim()))
|
||||
.collect::<Vec<_>>()
|
||||
.join(tenant_policy_config.trim());
|
||||
let instructions = format!("{prompt}\n\n{output_contract}\n");
|
||||
input_text(match transcript_format {
|
||||
TranscriptFormat::Line => instructions,
|
||||
TranscriptFormat::Json => {
|
||||
format!("{TRANSCRIPT_JSON_INSTRUCTIONS}\n\n{instructions}")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Classifier instructions composed from selected text, policy, and the caller-owned output contract.
|
||||
/// A supplied token limit applies before the fixed transcript provenance instructions.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct GuardianClassifierInstructions<'a> {
|
||||
transcript_format: TranscriptFormat,
|
||||
classifier_instructions: &'a str,
|
||||
policy: &'a str,
|
||||
output_contract: &'a str,
|
||||
max_tokens: Option<usize>,
|
||||
}
|
||||
|
||||
impl<'a> GuardianClassifierInstructions<'a> {
|
||||
pub fn new(
|
||||
transcript_format: TranscriptFormat,
|
||||
classifier_instructions: &'a str,
|
||||
policy: &'a str,
|
||||
output_contract: &'a str,
|
||||
max_tokens: Option<usize>,
|
||||
) -> Self {
|
||||
Self {
|
||||
transcript_format,
|
||||
classifier_instructions,
|
||||
policy,
|
||||
output_contract,
|
||||
max_tokens,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextualUserFragment for GuardianClassifierInstructions<'_> {
|
||||
fn role(&self) -> &'static str {
|
||||
"developer"
|
||||
}
|
||||
|
||||
fn content_kind(&self) -> ContentItemKind {
|
||||
ContentItemKind("guardian.classifier_instructions".to_owned())
|
||||
}
|
||||
|
||||
fn markers(&self) -> (&'static str, &'static str) {
|
||||
Self::type_markers()
|
||||
}
|
||||
|
||||
fn type_markers() -> (&'static str, &'static str) {
|
||||
("", "")
|
||||
}
|
||||
|
||||
fn body(&self) -> ContentItem {
|
||||
let Self {
|
||||
transcript_format,
|
||||
classifier_instructions,
|
||||
policy,
|
||||
output_contract,
|
||||
max_tokens,
|
||||
} = *self;
|
||||
let instructions = if classifier_instructions.contains(TENANT_POLICY_CONFIG_PLACEHOLDER) {
|
||||
classifier_instructions.replace(TENANT_POLICY_CONFIG_PLACEHOLDER, policy)
|
||||
} else {
|
||||
format!("{classifier_instructions}\n\n# Security Policy\n{policy}")
|
||||
};
|
||||
let instructions = if instructions.trim_end().ends_with(output_contract) {
|
||||
instructions
|
||||
} else {
|
||||
format!("{instructions}\n\n{output_contract}")
|
||||
};
|
||||
let instructions = match max_tokens {
|
||||
Some(max_tokens) => truncate_text(&instructions, max_tokens),
|
||||
None => instructions,
|
||||
};
|
||||
// Fixed host provenance must survive even the smallest configured prompt cap.
|
||||
input_text(match transcript_format {
|
||||
TranscriptFormat::Line => instructions,
|
||||
TranscriptFormat::Json => {
|
||||
format!("{TRANSCRIPT_JSON_INSTRUCTIONS}\n\n{instructions}")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders feedback for an action the caller has already decided to reject.
|
||||
pub fn render_guardian_rejection(rationale: &str, rejection_instructions: &str) -> String {
|
||||
let rationale = if rationale.trim().is_empty() {
|
||||
"Auto-reviewer denied the action without a specific rationale."
|
||||
} else {
|
||||
rationale.trim()
|
||||
};
|
||||
format!(
|
||||
"This action was rejected due to unacceptable risk.\nReason: {rationale}\n{rejection_instructions}"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "guardian_instructions_tests.rs"]
|
||||
mod tests;
|
||||
157
akode-rs/prompts/src/guardian_instructions_tests.rs
Normal file
157
akode-rs/prompts/src/guardian_instructions_tests.rs
Normal file
@@ -0,0 +1,157 @@
|
||||
//! Covers policy substitution, terminal output contracts, truncation, and rejection-text overrides.
|
||||
|
||||
use akode_context_fragments::ContextualUserFragment;
|
||||
use akode_guardian_context::TRANSCRIPT_JSON_INSTRUCTIONS;
|
||||
use akode_guardian_context::truncate_text;
|
||||
use akode_protocol::TranscriptFormat;
|
||||
use akode_protocol_test_support::ContentItemTestExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::GuardianClassifierInstructions;
|
||||
use super::GuardianPolicyInstructions;
|
||||
use super::render_guardian_rejection;
|
||||
|
||||
#[test]
|
||||
fn reviewer_policy_substitution_preserves_template_layout_and_appends_contract() {
|
||||
for (template, policy, expected) in [
|
||||
(
|
||||
" Review:\n{{ tenant_policy_config }}\nAgain: {{ tenant_policy_config }}\n \t",
|
||||
" \nTenant policy.\n ",
|
||||
" Review:\nTenant policy.\nAgain: Tenant policy.\n\nReview contract.\n",
|
||||
),
|
||||
(
|
||||
"Policy: {{ tenant_policy_config }}",
|
||||
"",
|
||||
"Policy: \n\nReview contract.\n",
|
||||
),
|
||||
(
|
||||
"Tenant: {{ tenant_policy_config }}\nAdditional: {{ extra_policy }}",
|
||||
"Tenant policy.",
|
||||
"Tenant: Tenant policy.\nAdditional: \n\nReview contract.\n",
|
||||
),
|
||||
("", "Tenant policy.", "\n\nReview contract.\n"),
|
||||
] {
|
||||
assert_eq!(
|
||||
GuardianPolicyInstructions::new(
|
||||
TranscriptFormat::Json,
|
||||
policy,
|
||||
"",
|
||||
template,
|
||||
"Review contract."
|
||||
)
|
||||
.render()
|
||||
.expect_text(),
|
||||
format!("{TRANSCRIPT_JSON_INSTRUCTIONS}\n\n{expected}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reviewer_extra_policy_substitution_preserves_tenant_policy() {
|
||||
for (template, extra_policy, expected) in [
|
||||
(
|
||||
"Tenant: {{ tenant_policy_config }}\nAdditional: {{ extra_policy }}\nAgain: {{ extra_policy }}",
|
||||
" \nAdditional policy.\n ",
|
||||
"Tenant: Tenant policy.\nAdditional: Additional policy.\nAgain: Additional policy.\n\nReview contract.\n",
|
||||
),
|
||||
(
|
||||
"Tenant: {{ tenant_policy_config }}\nAdditional: {{ extra_policy }}",
|
||||
" \n\t",
|
||||
"Tenant: Tenant policy.\nAdditional: \n\nReview contract.\n",
|
||||
),
|
||||
(
|
||||
"Tenant: {{ tenant_policy_config }}",
|
||||
"Additional policy.",
|
||||
"Tenant: Tenant policy.\n\nReview contract.\n",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
GuardianPolicyInstructions::new(
|
||||
TranscriptFormat::Json,
|
||||
"Tenant policy.",
|
||||
extra_policy,
|
||||
template,
|
||||
"Review contract.",
|
||||
)
|
||||
.render()
|
||||
.expect_text(),
|
||||
format!("{TRANSCRIPT_JSON_INSTRUCTIONS}\n\n{expected}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reviewer_policy_substitution_keeps_inserted_policy_text_literal() {
|
||||
assert_eq!(
|
||||
GuardianPolicyInstructions::new(
|
||||
TranscriptFormat::Json,
|
||||
"Tenant says {{ tenant_policy_config }} and {{ extra_policy }}.",
|
||||
"Additional says {{ tenant_policy_config }} and {{ extra_policy }}.",
|
||||
"Tenant: {{ tenant_policy_config }}\nAdditional: {{ extra_policy }}",
|
||||
"Review contract.",
|
||||
)
|
||||
.render()
|
||||
.expect_text(),
|
||||
format!(
|
||||
"{TRANSCRIPT_JSON_INSTRUCTIONS}\n\nTenant: Tenant says {{{{ tenant_policy_config }}}} and {{{{ extra_policy }}}}.\nAdditional: Additional says {{{{ tenant_policy_config }}}} and {{{{ extra_policy }}}}.\n\nReview contract.\n"
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifier_policy_substitution_and_legacy_append_keep_one_terminal_contract_before_truncation() {
|
||||
for (instructions, policy, expected) in [
|
||||
(
|
||||
"Classify: {{ tenant_policy_config }}",
|
||||
" Tenant policy.\n",
|
||||
"Classify: Tenant policy.\n\n\nClassifier contract.",
|
||||
),
|
||||
(
|
||||
"Classify: {{ tenant_policy_config }}\n\nClassifier contract.\n \t",
|
||||
"Tenant policy.",
|
||||
"Classify: Tenant policy.\n\nClassifier contract.\n \t",
|
||||
),
|
||||
(
|
||||
"Legacy classifier.",
|
||||
"Tenant policy.",
|
||||
"Legacy classifier.\n\n# Security Policy\nTenant policy.\n\nClassifier contract.",
|
||||
),
|
||||
] {
|
||||
for max_tokens in [None, Some(20)] {
|
||||
let expected = match max_tokens {
|
||||
Some(max_tokens) => truncate_text(expected, max_tokens),
|
||||
None => expected.to_owned(),
|
||||
};
|
||||
assert_eq!(
|
||||
GuardianClassifierInstructions::new(
|
||||
TranscriptFormat::Json,
|
||||
instructions,
|
||||
policy,
|
||||
"Classifier contract.",
|
||||
max_tokens,
|
||||
)
|
||||
.render()
|
||||
.expect_text(),
|
||||
format!("{TRANSCRIPT_JSON_INSTRUCTIONS}\n\n{expected}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejection_feedback_trims_rationale_and_preserves_instruction_overrides() {
|
||||
for (rationale, instructions, expected) in [
|
||||
(
|
||||
" \nSensitive data would leave the workspace.\t ",
|
||||
" Ask for approval.\n",
|
||||
"This action was rejected due to unacceptable risk.\nReason: Sensitive data would leave the workspace.\n Ask for approval.\n",
|
||||
),
|
||||
(
|
||||
" \n\t",
|
||||
"",
|
||||
"This action was rejected due to unacceptable risk.\nReason: Auto-reviewer denied the action without a specific rationale.\n",
|
||||
),
|
||||
] {
|
||||
assert_eq!(render_guardian_rejection(rationale, instructions), expected);
|
||||
}
|
||||
}
|
||||
40
akode-rs/prompts/src/lib.rs
Normal file
40
akode-rs/prompts/src/lib.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
mod compact;
|
||||
mod guardian_instructions;
|
||||
mod model_instructions;
|
||||
mod model_messages;
|
||||
mod multi_agent_instructions;
|
||||
mod permissions_instructions;
|
||||
mod realtime;
|
||||
mod review_exit;
|
||||
mod review_request;
|
||||
mod update_plan_instructions;
|
||||
|
||||
pub use compact::SUMMARIZATION_PROMPT;
|
||||
pub use compact::SUMMARY_PREFIX;
|
||||
pub use guardian_instructions::GuardianClassifierInstructions;
|
||||
pub use guardian_instructions::GuardianPolicyInstructions;
|
||||
pub use guardian_instructions::render_guardian_rejection;
|
||||
pub use model_instructions::render_model_instructions;
|
||||
pub use model_messages::ResolvedAutoReviewMessages;
|
||||
pub use model_messages::ResolvedCollaborationModeMessages;
|
||||
pub use model_messages::ResolvedGenericPluginMessages;
|
||||
pub use model_messages::ResolvedIncrementalToolMessages;
|
||||
pub use model_messages::ResolvedMessage;
|
||||
pub use model_messages::ResolvedModelMessages;
|
||||
pub use model_messages::ResolvedMultiAgentMessages;
|
||||
pub use model_messages::ResolvedPluginRecommendationMessages;
|
||||
pub use model_messages::ResolvedSelectedPluginMessages;
|
||||
pub use multi_agent_instructions::MultiAgentRoleInstructions;
|
||||
pub use permissions_instructions::ApprovalPromptContext;
|
||||
pub use permissions_instructions::PermissionsInstructions;
|
||||
pub use realtime::BACKEND_PROMPT;
|
||||
pub use realtime::END_INSTRUCTIONS;
|
||||
pub use realtime::START_INSTRUCTIONS;
|
||||
pub use review_exit::render_review_exit_interrupted;
|
||||
pub use review_exit::render_review_exit_success;
|
||||
pub use review_request::REVIEW_PROMPT;
|
||||
pub use review_request::ResolvedReviewRequest;
|
||||
pub use review_request::resolve_review_request;
|
||||
pub use review_request::review_prompt;
|
||||
pub use review_request::user_facing_hint;
|
||||
pub use update_plan_instructions::without_update_plan_instructions;
|
||||
21
akode-rs/prompts/src/model_instructions.rs
Normal file
21
akode-rs/prompts/src/model_instructions.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
//! Returns literal model instructions from the captured model metadata.
|
||||
//! Missing templates produce a warning; supplied empty templates remain valid input.
|
||||
|
||||
use crate::ResolvedModelMessages;
|
||||
use akode_protocol::openai_models::ModelInfo;
|
||||
|
||||
/// Renders base instructions from the caller's captured model, retaining missing-template warnings.
|
||||
pub fn render_model_instructions(model_info: &ModelInfo) -> String {
|
||||
let template = ResolvedModelMessages::from_model(model_info).instructions_template();
|
||||
if template.is_none() {
|
||||
tracing::warn!(
|
||||
model = %model_info.slug,
|
||||
"Model has no instruction template; returning empty instructions."
|
||||
);
|
||||
}
|
||||
template.unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "model_instructions_tests.rs"]
|
||||
mod tests;
|
||||
99
akode-rs/prompts/src/model_instructions_tests.rs
Normal file
99
akode-rs/prompts/src/model_instructions_tests.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
//! Covers literal instruction templates and missing-versus-empty inputs.
|
||||
|
||||
use super::*;
|
||||
use akode_protocol::openai_models::ConfigShellToolType;
|
||||
use akode_protocol::openai_models::ModelMessages;
|
||||
use akode_protocol::openai_models::ModelVisibility;
|
||||
use akode_protocol::openai_models::TruncationPolicyConfig;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn test_model(model_messages: Option<ModelMessages>) -> ModelInfo {
|
||||
ModelInfo {
|
||||
slug: "test-model".to_string(),
|
||||
display_name: "Test Model".to_string(),
|
||||
description: None,
|
||||
default_reasoning_level: None,
|
||||
supported_reasoning_levels: vec![],
|
||||
shell_type: ConfigShellToolType::UnifiedExec,
|
||||
visibility: ModelVisibility::List,
|
||||
supported_in_api: true,
|
||||
priority: 1,
|
||||
additional_speed_tiers: vec![],
|
||||
service_tiers: vec![],
|
||||
default_service_tier: None,
|
||||
availability_nux: None,
|
||||
upgrade: None,
|
||||
model_messages,
|
||||
include_skills_usage_instructions: false,
|
||||
include_plugin_usage_instructions: false,
|
||||
include_apps_usage_instructions: false,
|
||||
supports_reasoning_summary_parameter: true,
|
||||
default_reasoning_summary: Default::default(),
|
||||
support_verbosity: false,
|
||||
default_verbosity: None,
|
||||
apply_patch_tool_type: None,
|
||||
web_search_tool_type: Default::default(),
|
||||
web_search_provider: None,
|
||||
truncation_policy: TruncationPolicyConfig::bytes(/*limit*/ 10_000),
|
||||
supports_image_detail_original: false,
|
||||
context_window: None,
|
||||
max_context_window: None,
|
||||
auto_compact_token_limit: None,
|
||||
comp_hash: None,
|
||||
effective_context_window_percent: 95,
|
||||
experimental_supported_tools: vec![],
|
||||
input_modalities: vec![],
|
||||
supports_search_tool: false,
|
||||
supports_experimental_context: false,
|
||||
use_responses_lite: false,
|
||||
supports_reasoning_effort_updates: false,
|
||||
guardian: None,
|
||||
node_repl_auto_review_required: false,
|
||||
node_repl_disabled: false,
|
||||
auto_review_model_override: None,
|
||||
model_specialty: None,
|
||||
tool_mode: None,
|
||||
multi_agent_version: None,
|
||||
multi_agent_reasoning_effort: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_literal_templates() {
|
||||
let template = "Hello {{ personality }}\n\n# Personality\n\nFixed instructions";
|
||||
let model = test_model(Some(ModelMessages {
|
||||
instructions_template: Some(template.to_string()),
|
||||
..Default::default()
|
||||
}));
|
||||
assert_eq!(
|
||||
(
|
||||
ResolvedModelMessages::from_model(&model).instructions_template(),
|
||||
render_model_instructions(&model)
|
||||
),
|
||||
(Some(template), template.to_string()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_and_empty_templates_render_empty_but_retain_presence() {
|
||||
for (messages, template) in [
|
||||
(None, None),
|
||||
(Some(ModelMessages::default()), None),
|
||||
(
|
||||
Some(ModelMessages {
|
||||
instructions_template: Some(String::new()),
|
||||
..Default::default()
|
||||
}),
|
||||
Some(""),
|
||||
),
|
||||
] {
|
||||
let model = test_model(messages);
|
||||
assert_eq!(
|
||||
(
|
||||
render_model_instructions(&model),
|
||||
ResolvedModelMessages::from_model(&model).instructions_template()
|
||||
),
|
||||
(String::new(), template),
|
||||
);
|
||||
}
|
||||
}
|
||||
289
akode-rs/prompts/src/model_messages.rs
Normal file
289
akode-rs/prompts/src/model_messages.rs
Normal file
@@ -0,0 +1,289 @@
|
||||
//! Resolves model-owned messages from catalog values and bundled defaults.
|
||||
//! Resolution preserves sparse catalog data and source identity, with family-specific validation.
|
||||
//! Prompt composition and runtime settings remain with consumers; each accessor
|
||||
//! selects and resolves only the requested message family.
|
||||
|
||||
use akode_protocol::openai_models::CodeModeToolMessages;
|
||||
use akode_protocol::openai_models::ConfirmationPolicies;
|
||||
use akode_protocol::openai_models::IndirectDescriptionPrefixes;
|
||||
use akode_protocol::openai_models::McpResourceToolMessages;
|
||||
use akode_protocol::openai_models::ModelInfo;
|
||||
use akode_protocol::openai_models::ModelMessages;
|
||||
use akode_protocol::openai_models::ToolMessage;
|
||||
use permissions::ResolvedApprovalMessages;
|
||||
use permissions::ResolvedPermissionMessages;
|
||||
|
||||
mod collaboration;
|
||||
mod guardian;
|
||||
mod incremental_tools;
|
||||
mod multi_agent;
|
||||
pub(crate) mod permissions;
|
||||
mod plugins;
|
||||
|
||||
pub use collaboration::ResolvedCollaborationModeMessages;
|
||||
pub use guardian::ResolvedAutoReviewMessages;
|
||||
pub use incremental_tools::ResolvedIncrementalToolMessages;
|
||||
pub use multi_agent::ResolvedMultiAgentMessages;
|
||||
pub use plugins::ResolvedGenericPluginMessages;
|
||||
pub use plugins::ResolvedPluginRecommendationMessages;
|
||||
pub use plugins::ResolvedSelectedPluginMessages;
|
||||
|
||||
/// Text together with whether it was supplied by the catalog, even when it equals the default.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ResolvedMessage<'a> {
|
||||
Catalog(&'a str),
|
||||
Bundled(&'static str),
|
||||
}
|
||||
|
||||
impl<'a> ResolvedMessage<'a> {
|
||||
pub(crate) fn new(catalog: Option<&'a str>, bundled: &'static str) -> Self {
|
||||
catalog.map_or(Self::Bundled(bundled), Self::Catalog)
|
||||
}
|
||||
|
||||
pub fn text(self) -> &'a str {
|
||||
match self {
|
||||
Self::Catalog(text) | Self::Bundled(text) => text,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn catalog_override(self) -> Option<&'a str> {
|
||||
match self {
|
||||
Self::Catalog(text) => Some(text),
|
||||
Self::Bundled(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const REQUEST_USER_INPUT_ASYNC_DESCRIPTION: &str = "Ask the user one or more questions during ongoing work. Use this tool only to request missing information, preferences, constraints, clarification, or approval. The tool returns immediately without ending the turn or waiting for a reply; any reply arrives asynchronously as a new user message. Keep questions concise, self-contained, and easy to understand, using a level of detail appropriate to the user and task. The UI always allows a free-text answer, including when suggested options are provided. A preselected option is not submitted automatically.";
|
||||
const REMINDER_MESSAGE_TEMPLATE: &str = concat!(
|
||||
"Your context window is nearly exhausted (only {n_remaining} tokens remaining) and will be automatically reset for you soon. ",
|
||||
"Once reset, message items in current context window will be cleared in the new window, but notes and history items will be persistent across windows."
|
||||
);
|
||||
const PERSISTENT_INSTRUCTIONS: &str = include_str!("../templates/persistent_mode.md");
|
||||
const CONTENT_FILTER_GUIDANCE: &str = "Your previous response was blocked by a content filter. Do not treat this as a transient failure or try to reproduce or work around the blocked content through repeated attempts, altered formatting, splitting, encoding, tools, subagents, or later wakes. Briefly explain the limitation and offer a permitted alternative. Continue unrelated authorized work.";
|
||||
const MAX_CONTENT_FILTER_GUIDANCE_BYTES: usize = 512;
|
||||
|
||||
/// Resolves model-owned text from catalog overrides or bundled defaults, one family at a time.
|
||||
///
|
||||
/// The view borrows the consumer's captured model metadata without resolving any families.
|
||||
/// Missing values select bundled text or retain delegation to consumer-owned settings.
|
||||
/// Explicit empty strings remain overrides unless a message family validates them.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ResolvedModelMessages<'a> {
|
||||
catalog_messages: Option<&'a ModelMessages>,
|
||||
}
|
||||
|
||||
impl<'a> ResolvedModelMessages<'a> {
|
||||
/// Borrows messages from the selected model; absent catalog values still use defaults.
|
||||
pub fn from_model(model_info: &'a ModelInfo) -> Self {
|
||||
Self {
|
||||
catalog_messages: model_info.model_messages.as_ref(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves only bundled defaults, independently of any selected model.
|
||||
pub fn bundled() -> Self {
|
||||
Self {
|
||||
catalog_messages: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the literal instruction template, preserving missing values.
|
||||
pub fn instructions_template(&self) -> Option<&'a str> {
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.instructions_template.as_deref())
|
||||
}
|
||||
|
||||
/// Resolves approval messages and their bundled alternatives.
|
||||
pub(crate) fn approvals(self) -> ResolvedApprovalMessages<'a> {
|
||||
ResolvedApprovalMessages::new(
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.approvals.as_ref()),
|
||||
)
|
||||
}
|
||||
|
||||
/// Resolves permission templates without preparing runtime permission facts.
|
||||
pub(crate) fn permissions(self) -> ResolvedPermissionMessages<'a> {
|
||||
ResolvedPermissionMessages::new(
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.permissions.as_ref()),
|
||||
)
|
||||
}
|
||||
|
||||
/// Resolves mode overrides while retaining bundled alternatives and absent values.
|
||||
pub fn collaboration_modes(&self) -> ResolvedCollaborationModeMessages<'a> {
|
||||
ResolvedCollaborationModeMessages::new(
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.collaboration_modes.as_ref()),
|
||||
)
|
||||
}
|
||||
|
||||
/// Resolves multi-agent messages while preserving their catalog or bundled source.
|
||||
pub fn multi_agent(&self) -> ResolvedMultiAgentMessages<'a> {
|
||||
ResolvedMultiAgentMessages::new(
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.multi_agent.as_ref()),
|
||||
)
|
||||
}
|
||||
|
||||
/// Resolves auto-review policy messages and rejection/timeout instructions.
|
||||
pub fn auto_review(&self) -> ResolvedAutoReviewMessages<'a> {
|
||||
ResolvedAutoReviewMessages::new(
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.auto_review.as_ref()),
|
||||
)
|
||||
}
|
||||
|
||||
/// Resolves classifier instructions from catalog text or the bundled default.
|
||||
pub fn guardian_classifier_instructions(&self) -> &'a str {
|
||||
guardian::classifier_instructions(self.catalog_messages)
|
||||
}
|
||||
|
||||
/// Resolves reminder text without selecting or validating runtime budget settings.
|
||||
pub fn token_budget_reminder_template(&self) -> &'a str {
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.token_budget.as_ref())
|
||||
.map_or(REMINDER_MESSAGE_TEMPLATE, |messages| {
|
||||
messages.reminder_message_template.as_str()
|
||||
})
|
||||
}
|
||||
|
||||
/// Selects native history definitions; missing fields delegate to the tool owner.
|
||||
pub fn history(self) -> Option<&'a akode_protocol::openai_models::HistoryToolMessages> {
|
||||
self.catalog_messages?.tools.as_ref()?.history.as_ref()
|
||||
}
|
||||
|
||||
/// Selects native notes definitions; missing fields delegate to the tool owner.
|
||||
pub fn notes(self) -> Option<&'a akode_protocol::openai_models::NotesToolMessages> {
|
||||
self.catalog_messages?.tools.as_ref()?.notes.as_ref()
|
||||
}
|
||||
|
||||
/// Selects context-window control definitions independently of runtime tool names.
|
||||
pub fn context_management(
|
||||
self,
|
||||
) -> Option<&'a akode_protocol::openai_models::ContextManagementToolMessages> {
|
||||
self.catalog_messages?
|
||||
.tools
|
||||
.as_ref()?
|
||||
.context_management
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// Resolves optional confirmation policies, leaving missing values to actor defaults.
|
||||
pub fn confirmation_policies(&self) -> Option<&'a ConfirmationPolicies> {
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.confirmation_policies.as_ref())
|
||||
}
|
||||
|
||||
/// Resolves the asynchronous user-input tool description.
|
||||
pub fn request_user_input_async_description(&self) -> &'a str {
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.tools.as_ref())
|
||||
.and_then(|tools| tools.send_user_message_async.as_ref())
|
||||
.and_then(|tool| tool.description.as_deref())
|
||||
.unwrap_or(REQUEST_USER_INPUT_ASYNC_DESCRIPTION)
|
||||
}
|
||||
|
||||
/// Selects the asynchronous user-input schema; parsing belongs to the tool consumer.
|
||||
pub fn request_user_input_async_parameters_override(&self) -> Option<&'a str> {
|
||||
self.catalog_messages?
|
||||
.tools
|
||||
.as_ref()?
|
||||
.send_user_message_async
|
||||
.as_ref()?
|
||||
.parameters
|
||||
.as_deref()
|
||||
}
|
||||
|
||||
/// Selects a V2 tool's static description by its name, independently of its runtime namespace.
|
||||
/// Missing text retains the tool's bundled description; an empty string replaces it.
|
||||
pub fn multi_agent_tool_description_override(&self, tool_name: &str) -> Option<&'a str> {
|
||||
self.multi_agent_tool(tool_name)?.description.as_deref()
|
||||
}
|
||||
|
||||
/// Selects a V2 tool's complete parameter schema; parsing belongs to the tool consumer.
|
||||
pub fn multi_agent_tool_parameters_override(&self, tool_name: &str) -> Option<&'a str> {
|
||||
self.multi_agent_tool(tool_name)?.parameters.as_deref()
|
||||
}
|
||||
|
||||
fn multi_agent_tool(self, tool_name: &str) -> Option<&'a ToolMessage> {
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.tools.as_ref())
|
||||
.and_then(|tools| tools.multi_agent.as_ref())?
|
||||
.by_name(tool_name)
|
||||
}
|
||||
|
||||
/// Selects resource helper messages; schema parsing belongs to the tool owner.
|
||||
pub fn mcp_resources(&self) -> Option<&'a McpResourceToolMessages> {
|
||||
self.catalog_messages?
|
||||
.tools
|
||||
.as_ref()?
|
||||
.mcp_resources
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// Selects indirect tool guidance; tool rendering owns namespace mapping and normalization.
|
||||
pub fn indirect_description_prefixes(&self) -> Option<&'a IndirectDescriptionPrefixes> {
|
||||
self.catalog_messages?
|
||||
.tools
|
||||
.as_ref()?
|
||||
.indirect_description_prefixes
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// Selects per-function guidance restricted to the default `functions` namespace.
|
||||
pub fn functions_namespace_functions_description_prefixes(
|
||||
&self,
|
||||
) -> Option<&'a std::collections::BTreeMap<String, String>> {
|
||||
self.catalog_messages?
|
||||
.tools
|
||||
.as_ref()?
|
||||
.functions_namespace_functions_description_prefixes
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// Resolves bounded incremental catalog wording for an owned world-state section.
|
||||
pub fn incremental_tools(&self) -> ResolvedIncrementalToolMessages {
|
||||
ResolvedIncrementalToolMessages::new(
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.tools.as_ref())
|
||||
.and_then(|tools| tools.incremental_tools.as_ref()),
|
||||
)
|
||||
}
|
||||
|
||||
/// Selects Code Mode messages; bundled text and runtime composition belong to the tool owner.
|
||||
pub fn code_mode(&self) -> Option<&'a CodeModeToolMessages> {
|
||||
self.catalog_messages?.tools.as_ref()?.code_mode.as_ref()
|
||||
}
|
||||
|
||||
/// Selects wait's complete description.
|
||||
pub fn code_mode_wait_description_override(&self) -> Option<&'a str> {
|
||||
self.code_mode()?.wait.as_ref()?.description.as_deref()
|
||||
}
|
||||
|
||||
/// Selects wait's parameter schema. Exec uses a harness-owned freeform grammar.
|
||||
pub fn code_mode_wait_parameters_override(&self) -> Option<&'a str> {
|
||||
self.code_mode()?.wait.as_ref()?.parameters.as_deref()
|
||||
}
|
||||
|
||||
/// Resolves persistent-mode instructions without deciding whether the mode is active.
|
||||
pub fn persistent_instructions(&self) -> &'a str {
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.persistent_instructions.as_deref())
|
||||
.unwrap_or(PERSISTENT_INSTRUCTIONS)
|
||||
}
|
||||
|
||||
/// Resolves bounded recovery guidance, falling back without truncating instructions.
|
||||
pub fn content_filter_guidance(&self) -> &'a str {
|
||||
self.catalog_messages
|
||||
.and_then(|messages| messages.content_filter_guidance.as_deref())
|
||||
.filter(|text| {
|
||||
!text.trim().is_empty() && text.len() <= MAX_CONTENT_FILTER_GUIDANCE_BYTES
|
||||
})
|
||||
.unwrap_or(CONTENT_FILTER_GUIDANCE)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "model_messages/plugins_tests.rs"]
|
||||
mod plugins_tests;
|
||||
22
akode-rs/prompts/src/model_messages/collaboration.rs
Normal file
22
akode-rs/prompts/src/model_messages/collaboration.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
//! Resolves collaboration catalog text and bundled presets while retaining their source.
|
||||
//! Runtime consumers use catalog overrides first, then the selected mode's settings.
|
||||
|
||||
use super::ResolvedMessage;
|
||||
use akode_collaboration_mode_templates::DEFAULT;
|
||||
use akode_collaboration_mode_templates::PLAN;
|
||||
use akode_protocol::openai_models::CollaborationModeMessages;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ResolvedCollaborationModeMessages<'a> {
|
||||
pub default: ResolvedMessage<'a>,
|
||||
pub plan: ResolvedMessage<'a>,
|
||||
}
|
||||
|
||||
impl<'a> ResolvedCollaborationModeMessages<'a> {
|
||||
pub(crate) fn new(messages: Option<&'a CollaborationModeMessages>) -> Self {
|
||||
Self {
|
||||
default: ResolvedMessage::new(messages.and_then(|m| m.default.as_deref()), DEFAULT),
|
||||
plan: ResolvedMessage::new(messages.and_then(|m| m.plan.as_deref()), PLAN),
|
||||
}
|
||||
}
|
||||
}
|
||||
62
akode-rs/prompts/src/model_messages/guardian.rs
Normal file
62
akode-rs/prompts/src/model_messages/guardian.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
//! Resolves Guardian policy, feedback, and classifier text from catalog values or bundled defaults.
|
||||
//! Configuration overlays and prompt composition remain with consumers.
|
||||
|
||||
use akode_protocol::openai_models::AutoReviewMessages;
|
||||
use akode_protocol::openai_models::ModelMessages;
|
||||
|
||||
const POLICY: &str = include_str!("../../templates/guardian/policy.md");
|
||||
const POLICY_TEMPLATE: &str = include_str!("../../templates/guardian/policy_template.md");
|
||||
const NODE_REPL_POLICY: &str = include_str!("../../templates/guardian/node_repl_policy.md");
|
||||
const REJECTION_INSTRUCTIONS: &str = concat!(
|
||||
"The agent must not attempt to achieve the same outcome via workaround, ",
|
||||
"indirect execution, or policy circumvention. ",
|
||||
"Proceed only with a materially safer alternative, ",
|
||||
"or if the user explicitly approves the action after being informed of the risk. ",
|
||||
"Otherwise, stop and request user input.",
|
||||
);
|
||||
const TIMEOUT_INSTRUCTIONS: &str = concat!(
|
||||
"The automatic permission approval review did not finish before its deadline. ",
|
||||
"Do not assume the action is unsafe based on the timeout alone. ",
|
||||
"You may retry once, or ask the user for guidance or explicit approval.",
|
||||
);
|
||||
const CLASSIFIER_INSTRUCTIONS: &str =
|
||||
include_str!("../../templates/guardian/classifier_instructions.md");
|
||||
|
||||
/// Auto-review policy and feedback text before runtime configuration overlays and rendering.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ResolvedAutoReviewMessages<'a> {
|
||||
pub policy: &'a str,
|
||||
pub policy_template: &'a str,
|
||||
pub node_repl_policy: &'a str,
|
||||
pub rejection_instructions: &'a str,
|
||||
pub timeout_instructions: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> ResolvedAutoReviewMessages<'a> {
|
||||
pub(crate) fn new(messages: Option<&'a AutoReviewMessages>) -> Self {
|
||||
Self {
|
||||
policy: messages
|
||||
.and_then(|messages| messages.policy.as_deref())
|
||||
.unwrap_or(POLICY),
|
||||
policy_template: messages
|
||||
.and_then(|messages| messages.policy_template.as_deref())
|
||||
.unwrap_or(POLICY_TEMPLATE),
|
||||
node_repl_policy: messages
|
||||
.and_then(|messages| messages.node_repl_policy.as_deref())
|
||||
.unwrap_or(NODE_REPL_POLICY),
|
||||
rejection_instructions: messages
|
||||
.and_then(|messages| messages.rejection_instructions.as_deref())
|
||||
.unwrap_or(REJECTION_INSTRUCTIONS),
|
||||
timeout_instructions: messages
|
||||
.and_then(|messages| messages.timeout_instructions.as_deref())
|
||||
.unwrap_or(TIMEOUT_INSTRUCTIONS),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn classifier_instructions(messages: Option<&ModelMessages>) -> &str {
|
||||
messages
|
||||
.and_then(|messages| messages.guardian_v2.as_ref())
|
||||
.and_then(|messages| messages.classifier_instructions.as_deref())
|
||||
.unwrap_or(CLASSIFIER_INSTRUCTIONS)
|
||||
}
|
||||
61
akode-rs/prompts/src/model_messages/incremental_tools.rs
Normal file
61
akode-rs/prompts/src/model_messages/incremental_tools.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
//! Resolves incremental catalog wording without changing catalog identity or update timing.
|
||||
//! Text is owned because world-state sections outlive the borrowed model metadata.
|
||||
|
||||
use akode_protocol::openai_models::IncrementalToolMessages;
|
||||
|
||||
/// Resolved static wording; consumers retain ownership of runtime names and instructions.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResolvedIncrementalToolMessages {
|
||||
pub tool_update_hint: String,
|
||||
pub removed_tools_header: String,
|
||||
pub removed_namespaces_header: String,
|
||||
pub namespace_instructions_prefix: String,
|
||||
pub namespace_instructions_cleared: String,
|
||||
pub exec_tools_update_hint: String,
|
||||
pub exec_tools_removed_definitions_header: String,
|
||||
}
|
||||
|
||||
impl Default for ResolvedIncrementalToolMessages {
|
||||
fn default() -> Self {
|
||||
Self::new(/*messages*/ None)
|
||||
}
|
||||
}
|
||||
|
||||
impl ResolvedIncrementalToolMessages {
|
||||
pub(crate) fn new(messages: Option<&IncrementalToolMessages>) -> Self {
|
||||
let resolve = |text: Option<&String>, bundled: &str| {
|
||||
text.filter(|text| text.len() <= 512)
|
||||
.map_or_else(|| bundled.to_owned(), Clone::clone)
|
||||
};
|
||||
Self {
|
||||
tool_update_hint: resolve(
|
||||
messages.and_then(|m| m.tool_update_hint.as_ref()),
|
||||
"This is an incremental tools update. Previously declared tools remain available for direct calls unless explicitly marked unavailable. If a tool is redefined here, its latest definition replaces the earlier one.",
|
||||
),
|
||||
removed_tools_header: resolve(
|
||||
messages.and_then(|m| m.removed_tools_header.as_ref()),
|
||||
"The following tools are no longer available. Do not call them:",
|
||||
),
|
||||
removed_namespaces_header: resolve(
|
||||
messages.and_then(|m| m.removed_namespaces_header.as_ref()),
|
||||
"The following namespaces are no longer available. Do not call tools in them unless those tools are declared in a later update:",
|
||||
),
|
||||
namespace_instructions_prefix: resolve(
|
||||
messages.and_then(|m| m.namespace_instructions_prefix.as_ref()),
|
||||
"Updated instructions for the {name} namespace:\n",
|
||||
),
|
||||
namespace_instructions_cleared: resolve(
|
||||
messages.and_then(|m| m.namespace_instructions_cleared.as_ref()),
|
||||
"The {name} namespace no longer has additional instructions.",
|
||||
),
|
||||
exec_tools_update_hint: resolve(
|
||||
messages.and_then(|m| m.exec_tools_update_hint.as_ref()),
|
||||
"Use these definitions and namespace instructions with `functions.exec`. Each replaces its earlier version in full. Unlisted tools keep their latest definitions and `tools` methods.",
|
||||
),
|
||||
exec_tools_removed_definitions_header: resolve(
|
||||
messages.and_then(|m| m.exec_tools_removed_definitions_header.as_ref()),
|
||||
"Listed `Tool:` entries are unavailable until redefined or rediscovered. `Namespace instructions:` removes guidance only. Unlisted entries are unchanged.",
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
84
akode-rs/prompts/src/model_messages/multi_agent.rs
Normal file
84
akode-rs/prompts/src/model_messages/multi_agent.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
//! Resolves multi-agent role bases and mode text while preserving catalog provenance.
|
||||
//! Consumers own role assembly, suppression, and effort-dependent mode selection.
|
||||
|
||||
use super::ResolvedMessage;
|
||||
use akode_protocol::openai_models::MultiAgentMessages;
|
||||
|
||||
const DEFAULT_MULTI_AGENT_V2_ROOT_AGENT_USAGE_HINT_TEXT: &str = r#"You are `/root`, the primary agent in a team of agents collaborating to fulfill the user's goals.
|
||||
|
||||
At the start of your turn, you are the active agent.
|
||||
You can spawn sub-agents to handle subtasks, and those sub-agents can spawn their own sub-agents.
|
||||
All agents in the team, including the agents that you can assign tasks to, are equally intelligent and capable, and have access to the same set of tools.
|
||||
|
||||
You can use `spawn_agent` to create a new agent, `followup_task` to give an existing agent a new task and trigger a turn, and `send_message` to pass a message to a running agent without triggering a turn.
|
||||
Child agents can also spawn their own sub-agents.
|
||||
You can decide how much context you want to propagate to your sub-agents with the `fork_turns` parameter.
|
||||
|
||||
You will receive messages in the analysis channel in the form:
|
||||
```
|
||||
Message Type: MESSAGE | FINAL_ANSWER
|
||||
Task name: <recipient>
|
||||
Sender: <author>
|
||||
Payload:
|
||||
<payload text>
|
||||
```
|
||||
They may be addressed as to=/root
|
||||
"#;
|
||||
const DEFAULT_MULTI_AGENT_V2_SUBAGENT_USAGE_HINT_TEXT: &str = r#"You are an agent in a team of agents collaborating to complete a task.
|
||||
|
||||
You can spawn sub-agents to handle subtasks, and those sub-agents can spawn their own sub-agents. All agents in the team, including the agents that you can assign tasks to, are equally intelligent and capable, and have access to the same set of tools.
|
||||
|
||||
You can use `spawn_agent` to create a new agent, `followup_task` to give an existing agent a new task and trigger a turn, and `send_message` to pass a message to a running agent.
|
||||
Child agents can also spawn their own sub-agents.
|
||||
|
||||
When you provide a response in the final channel, that content is immediately delivered back to your parent agent.
|
||||
|
||||
You will receive messages in the analysis channel in the form:
|
||||
```
|
||||
Message Type: NEW_TASK | MESSAGE | FINAL_ANSWER
|
||||
Task name: <recipient>
|
||||
Sender: <author>
|
||||
Payload:
|
||||
<payload text>
|
||||
```
|
||||
You may also see them addressed as to=/root/..., which indicates your identity is /root/...
|
||||
"#;
|
||||
const EXPLICIT_REQUEST_ONLY_MULTI_AGENT_MODE_TEXT: &str = "Any earlier instruction enabling proactive multi-agent delegation no longer applies. Do not spawn sub-agents unless the user or applicable AGENTS.md/skill instructions explicitly ask for sub-agents, delegation, or parallel agent work.";
|
||||
const PROACTIVE_MULTI_AGENT_MODE_TEXT: &str = "Proactive multi-agent delegation is active. Any earlier developer instruction requiring an explicit user request before spawning sub-agents no longer applies. This mode remains active until a later multi-agent mode developer message changes it. User requests override this hint.\n\nIf at any point you can parallelize work by delegating tasks to another agent (no matter if you are root or subagent), you should do so using collaboration tools if it could save time or improve quality.";
|
||||
|
||||
/// Model-only role bases and mode alternatives for runtime selection.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ResolvedMultiAgentMessages<'a> {
|
||||
pub root: ResolvedMessage<'a>,
|
||||
pub subagent: ResolvedMessage<'a>,
|
||||
pub explicit: ResolvedMessage<'a>,
|
||||
pub proactive: ResolvedMessage<'a>,
|
||||
/// A supplied hint overrides both effort-specific modes, including when empty.
|
||||
pub hint: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> ResolvedMultiAgentMessages<'a> {
|
||||
pub(crate) fn new(messages: Option<&'a MultiAgentMessages>) -> Self {
|
||||
let role = messages.and_then(|messages| messages.role.as_ref());
|
||||
let mode = messages.and_then(|messages| messages.mode.as_ref());
|
||||
Self {
|
||||
root: ResolvedMessage::new(
|
||||
role.and_then(|role| role.root.as_deref()),
|
||||
DEFAULT_MULTI_AGENT_V2_ROOT_AGENT_USAGE_HINT_TEXT,
|
||||
),
|
||||
subagent: ResolvedMessage::new(
|
||||
role.and_then(|role| role.subagent.as_deref()),
|
||||
DEFAULT_MULTI_AGENT_V2_SUBAGENT_USAGE_HINT_TEXT,
|
||||
),
|
||||
explicit: ResolvedMessage::new(
|
||||
mode.and_then(|mode| mode.explicit.as_deref()),
|
||||
EXPLICIT_REQUEST_ONLY_MULTI_AGENT_MODE_TEXT,
|
||||
),
|
||||
proactive: ResolvedMessage::new(
|
||||
mode.and_then(|mode| mode.proactive.as_deref()),
|
||||
PROACTIVE_MULTI_AGENT_MODE_TEXT,
|
||||
),
|
||||
hint: mode.and_then(|mode| mode.hint_text.as_deref()),
|
||||
}
|
||||
}
|
||||
}
|
||||
113
akode-rs/prompts/src/model_messages/permissions.rs
Normal file
113
akode-rs/prompts/src/model_messages/permissions.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
//! Resolves permission and approval text from sparse catalog messages and bundled defaults.
|
||||
//! Preserves explicit empty strings and source identity; composition and rendering live in
|
||||
//! `permissions_instructions` and consume caller-resolved runtime facts.
|
||||
|
||||
use super::ResolvedMessage;
|
||||
use akode_protocol::openai_models::ApprovalMessages;
|
||||
use akode_protocol::openai_models::PermissionMessages;
|
||||
|
||||
const APPROVAL_POLICY_NEVER: &str =
|
||||
include_str!("../../templates/permissions/approval_policy/never.md");
|
||||
const APPROVAL_POLICY_UNLESS_TRUSTED: &str =
|
||||
include_str!("../../templates/permissions/approval_policy/unless_trusted.md");
|
||||
const APPROVAL_POLICY_ON_REQUEST: &str =
|
||||
include_str!("../../templates/permissions/approval_policy/on_request.md");
|
||||
|
||||
pub(crate) const DANGER_FULL_ACCESS_TEMPLATE: &str =
|
||||
include_str!("../../templates/permissions/sandbox_mode/danger_full_access.md");
|
||||
pub(crate) const WORKSPACE_WRITE_TEMPLATE: &str =
|
||||
include_str!("../../templates/permissions/sandbox_mode/workspace_write.md");
|
||||
pub(crate) const READ_ONLY_TEMPLATE: &str =
|
||||
include_str!("../../templates/permissions/sandbox_mode/read_only.md");
|
||||
pub(crate) const WRITABLE_ROOT_TEMPLATE: &str = " The writable root is {{ roots }}.";
|
||||
pub(crate) const WRITABLE_ROOTS_TEMPLATE: &str = " The writable roots are {{ roots }}.";
|
||||
pub(crate) const DENIED_READS_TEMPLATE: &str = "## Denied filesystem reads\n{{ denied_reads }}";
|
||||
|
||||
/// Resolved approval-policy text; policy and tool selection remain with the consumer.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct ResolvedApprovalMessages<'a> {
|
||||
pub(crate) catalog: Option<&'a ApprovalMessages>,
|
||||
pub(crate) never: ResolvedMessage<'a>,
|
||||
pub(crate) on_request: ResolvedMessage<'a>,
|
||||
pub(crate) on_request_auto_review: ResolvedMessage<'a>,
|
||||
pub(crate) unless_trusted: ResolvedMessage<'a>,
|
||||
}
|
||||
|
||||
impl<'a> ResolvedApprovalMessages<'a> {
|
||||
pub(crate) fn new(messages: Option<&'a ApprovalMessages>) -> Self {
|
||||
Self {
|
||||
catalog: messages,
|
||||
never: ResolvedMessage::new(
|
||||
messages.and_then(|m| m.never.as_deref()),
|
||||
APPROVAL_POLICY_NEVER,
|
||||
),
|
||||
on_request: ResolvedMessage::new(
|
||||
messages.and_then(|m| m.on_request.as_deref()),
|
||||
APPROVAL_POLICY_ON_REQUEST,
|
||||
),
|
||||
on_request_auto_review: ResolvedMessage::new(
|
||||
messages.and_then(|m| m.on_request_auto_review.as_deref()),
|
||||
APPROVAL_POLICY_ON_REQUEST,
|
||||
),
|
||||
unless_trusted: ResolvedMessage::new(
|
||||
messages.and_then(|m| m.unless_trusted.as_deref()),
|
||||
APPROVAL_POLICY_UNLESS_TRUSTED,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Permission text retains its source so renderers can distinguish catalog text from templates.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct ResolvedPermissionMessages<'a> {
|
||||
pub(crate) approved_command_prefix_saved: Option<&'a str>,
|
||||
pub(crate) approved_prefixes: ResolvedMessage<'a>,
|
||||
pub(crate) danger_full_access: ResolvedMessage<'a>,
|
||||
pub(crate) workspace_write: ResolvedMessage<'a>,
|
||||
pub(crate) read_only: ResolvedMessage<'a>,
|
||||
pub(crate) writable_root: ResolvedMessage<'a>,
|
||||
pub(crate) writable_roots: ResolvedMessage<'a>,
|
||||
pub(crate) omitted_paths: ResolvedMessage<'a>,
|
||||
pub(crate) denied_reads: ResolvedMessage<'a>,
|
||||
}
|
||||
|
||||
impl<'a> ResolvedPermissionMessages<'a> {
|
||||
pub(crate) fn new(messages: Option<&'a PermissionMessages>) -> Self {
|
||||
Self {
|
||||
approved_command_prefix_saved: messages
|
||||
.and_then(|m| m.approved_command_prefix_saved.as_deref()),
|
||||
approved_prefixes: ResolvedMessage::new(
|
||||
messages.and_then(|m| m.approved_prefixes.as_deref()),
|
||||
include_str!("../../templates/permissions/approved_prefixes.md").trim_end(),
|
||||
),
|
||||
danger_full_access: ResolvedMessage::new(
|
||||
messages.and_then(|m| m.danger_full_access.as_deref()),
|
||||
DANGER_FULL_ACCESS_TEMPLATE,
|
||||
),
|
||||
workspace_write: ResolvedMessage::new(
|
||||
messages.and_then(|m| m.workspace_write.as_deref()),
|
||||
WORKSPACE_WRITE_TEMPLATE,
|
||||
),
|
||||
read_only: ResolvedMessage::new(
|
||||
messages.and_then(|m| m.read_only.as_deref()),
|
||||
READ_ONLY_TEMPLATE,
|
||||
),
|
||||
writable_root: ResolvedMessage::new(
|
||||
messages.and_then(|m| m.writable_root.as_deref()),
|
||||
WRITABLE_ROOT_TEMPLATE,
|
||||
),
|
||||
writable_roots: ResolvedMessage::new(
|
||||
messages.and_then(|m| m.writable_roots.as_deref()),
|
||||
WRITABLE_ROOTS_TEMPLATE,
|
||||
),
|
||||
omitted_paths: ResolvedMessage::new(
|
||||
messages.and_then(|m| m.omitted_paths.as_deref()),
|
||||
"",
|
||||
),
|
||||
denied_reads: ResolvedMessage::new(
|
||||
messages.and_then(|m| m.denied_reads.as_deref()),
|
||||
DENIED_READS_TEMPLATE,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
192
akode-rs/prompts/src/model_messages/plugins.rs
Normal file
192
akode-rs/prompts/src/model_messages/plugins.rs
Normal file
@@ -0,0 +1,192 @@
|
||||
//! Resolves bounded plugin wording while leaving capability facts and eligibility to callers.
|
||||
//! Missing, blank, oversized, or invalid fields independently retain their bundled wording.
|
||||
|
||||
use super::ResolvedMessage;
|
||||
use super::ResolvedModelMessages;
|
||||
use akode_protocol::openai_models::PluginMessages;
|
||||
|
||||
const MAX_WORDING_BYTES: usize = 500;
|
||||
const MAX_USAGE_BYTES: usize = 2_000;
|
||||
const GENERIC_INTRO: &str = "A plugin is a local bundle of skills, MCP servers, and apps.";
|
||||
const GENERIC_USAGE: &str = r###"- Skill naming: If a plugin contributes skills, those skill entries are prefixed with `plugin_name:` in the Skills list.
|
||||
- MCP naming: Plugin-provided MCP tools keep standard MCP identifiers such as `mcp__server__tool`; use tool provenance to tell which plugin they come from.
|
||||
- Trigger rules: If the user explicitly names a plugin, prefer capabilities associated with that plugin for that turn.
|
||||
- Relationship to capabilities: Plugins are not invoked directly. Use their underlying skills, MCP tools, and app tools to help solve the task.
|
||||
- Relevance: Determine what a plugin can help with from explicit user mention or from the plugin-associated skills, MCP tools, and apps exposed elsewhere in this turn.
|
||||
- Missing/blocked: If the user requests a plugin that does not have relevant callable capabilities for the task, say so briefly and continue with the best fallback."###;
|
||||
const SELECTED_INTRO: &str = "Capabilities from the `{{ plugin_name }}` plugin:";
|
||||
const SEARCH_TOOLS: &str = concat!(
|
||||
"- For the user request that explicitly selected this plugin, and only for that ",
|
||||
"request, if `tool_search` is available and an app from this plugin may help, ",
|
||||
"search for its tools before falling back to unrelated or built-in tools."
|
||||
);
|
||||
const SKILL_NAMESPACE: &str =
|
||||
"- Skills from this plugin are prefixed with `{{ skill_namespace }}:`.";
|
||||
const APPS: &str = "- Apps from this plugin available in this session: {{ apps }}.";
|
||||
const MCP_SERVERS: &str =
|
||||
"- MCP servers from this plugin available in this session: {{ mcp_servers }}.";
|
||||
const CLOSING: &str = "Use these plugin-associated capabilities to help solve the task.";
|
||||
const OMITTED: &str = "\n- Additional plugin capabilities omitted to fit the context limit.";
|
||||
const RECOMMENDATIONS_INTRO: &str =
|
||||
"Here is a list of plugins that are available but not installed.";
|
||||
|
||||
/// Generic wording and its source, retained by the usage-guidance lifecycle.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ResolvedGenericPluginMessages {
|
||||
pub intro: String,
|
||||
pub usage_instructions: String,
|
||||
pub catalog_override: bool,
|
||||
}
|
||||
|
||||
/// Validated templates retain one required placeholder for each harness-owned fact.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ResolvedSelectedPluginMessages {
|
||||
pub intro: String,
|
||||
pub search_tools: String,
|
||||
pub skill_namespace: String,
|
||||
pub apps: String,
|
||||
pub mcp_servers: String,
|
||||
pub closing: String,
|
||||
pub omitted: String,
|
||||
}
|
||||
|
||||
/// Bounded introduction independent of recommendation eligibility and plugin identities.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ResolvedPluginRecommendationMessages {
|
||||
pub intro: String,
|
||||
}
|
||||
|
||||
impl<'a> ResolvedModelMessages<'a> {
|
||||
fn plugin_messages(self) -> Option<&'a PluginMessages> {
|
||||
self.catalog_messages?.plugins.as_ref()
|
||||
}
|
||||
|
||||
/// Resolves the generic plugin guidance used in the conversation's world state.
|
||||
pub fn generic_plugin(self) -> ResolvedGenericPluginMessages {
|
||||
let generic = self
|
||||
.plugin_messages()
|
||||
.and_then(|messages| messages.generic.as_ref());
|
||||
let intro = literal(
|
||||
generic.and_then(|messages| messages.intro.as_deref()),
|
||||
GENERIC_INTRO,
|
||||
MAX_WORDING_BYTES,
|
||||
);
|
||||
let usage = literal(
|
||||
generic.and_then(|messages| messages.usage_instructions.as_deref()),
|
||||
GENERIC_USAGE,
|
||||
MAX_USAGE_BYTES,
|
||||
);
|
||||
ResolvedGenericPluginMessages {
|
||||
intro: intro.text().to_owned(),
|
||||
usage_instructions: usage.text().to_owned(),
|
||||
catalog_override: intro.catalog_override().is_some()
|
||||
|| usage.catalog_override().is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the wording surrounding an explicitly selected plugin's capabilities.
|
||||
pub fn selected_plugin(self) -> ResolvedSelectedPluginMessages {
|
||||
let selected = self
|
||||
.plugin_messages()
|
||||
.and_then(|messages| messages.selected.as_ref());
|
||||
ResolvedSelectedPluginMessages {
|
||||
intro: template(
|
||||
selected.and_then(|messages| messages.intro.as_deref()),
|
||||
SELECTED_INTRO,
|
||||
"{{ plugin_name }}",
|
||||
),
|
||||
search_tools: literal(
|
||||
selected.and_then(|messages| messages.search_tools.as_deref()),
|
||||
SEARCH_TOOLS,
|
||||
MAX_WORDING_BYTES,
|
||||
)
|
||||
.text()
|
||||
.to_owned(),
|
||||
skill_namespace: template(
|
||||
selected.and_then(|messages| messages.skill_namespace.as_deref()),
|
||||
SKILL_NAMESPACE,
|
||||
"{{ skill_namespace }}",
|
||||
),
|
||||
apps: template(
|
||||
selected.and_then(|messages| messages.apps.as_deref()),
|
||||
APPS,
|
||||
"{{ apps }}",
|
||||
),
|
||||
mcp_servers: template(
|
||||
selected.and_then(|messages| messages.mcp_servers.as_deref()),
|
||||
MCP_SERVERS,
|
||||
"{{ mcp_servers }}",
|
||||
),
|
||||
closing: literal(
|
||||
selected.and_then(|messages| messages.closing.as_deref()),
|
||||
CLOSING,
|
||||
MAX_WORDING_BYTES,
|
||||
)
|
||||
.text()
|
||||
.to_owned(),
|
||||
omitted: literal(
|
||||
selected.and_then(|messages| messages.omitted.as_deref()),
|
||||
OMITTED,
|
||||
MAX_WORDING_BYTES,
|
||||
)
|
||||
.text()
|
||||
.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the introduction to the list of recommended plugins.
|
||||
pub fn plugin_recommendations(self) -> ResolvedPluginRecommendationMessages {
|
||||
let recommendations = self
|
||||
.plugin_messages()
|
||||
.and_then(|messages| messages.recommendations.as_ref());
|
||||
ResolvedPluginRecommendationMessages {
|
||||
intro: literal(
|
||||
recommendations.and_then(|messages| messages.intro.as_deref()),
|
||||
RECOMMENDATIONS_INTRO,
|
||||
MAX_WORDING_BYTES,
|
||||
)
|
||||
.text()
|
||||
.to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn literal<'a>(
|
||||
catalog: Option<&'a str>,
|
||||
bundled: &'static str,
|
||||
max_bytes: usize,
|
||||
) -> ResolvedMessage<'a> {
|
||||
ResolvedMessage::new(
|
||||
catalog.filter(|text| {
|
||||
text.len() <= max_bytes
|
||||
&& !text.trim().is_empty()
|
||||
&& !text
|
||||
.chars()
|
||||
.any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t'))
|
||||
&& ![
|
||||
"<plugins_instructions>",
|
||||
"</plugins_instructions>",
|
||||
"<recommended_plugins>",
|
||||
"</recommended_plugins>",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| text.contains(marker))
|
||||
}),
|
||||
bundled,
|
||||
)
|
||||
}
|
||||
|
||||
fn template(catalog: Option<&str>, bundled: &'static str, placeholder: &str) -> String {
|
||||
literal(catalog, bundled, MAX_WORDING_BYTES)
|
||||
.catalog_override()
|
||||
.filter(|text| {
|
||||
!text
|
||||
.chars()
|
||||
.any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}'))
|
||||
&& text.split_once(placeholder).is_some_and(|(before, after)| {
|
||||
![before, after].iter().any(|part| part.contains(['{', '}']))
|
||||
})
|
||||
})
|
||||
.unwrap_or(bundled)
|
||||
.to_owned()
|
||||
}
|
||||
215
akode-rs/prompts/src/model_messages/plugins_tests.rs
Normal file
215
akode-rs/prompts/src/model_messages/plugins_tests.rs
Normal file
@@ -0,0 +1,215 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! Verifies sparse plugin wording, bounded literal bytes, and required runtime fact contracts.
|
||||
|
||||
use super::ResolvedModelMessages;
|
||||
use akode_protocol::openai_models::GenericPluginMessages;
|
||||
use akode_protocol::openai_models::ModelMessages;
|
||||
use akode_protocol::openai_models::PluginMessages;
|
||||
use akode_protocol::openai_models::PluginRecommendationMessages;
|
||||
use akode_protocol::openai_models::SelectedPluginMessages;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn plugin_fields_fall_back_independently_without_losing_valid_siblings() {
|
||||
let bundled = ResolvedModelMessages::bundled();
|
||||
for invalid in [
|
||||
None,
|
||||
Some(String::new()),
|
||||
Some(" \t\r\n".into()),
|
||||
Some("é".repeat(251)),
|
||||
] {
|
||||
let messages = ModelMessages {
|
||||
plugins: Some(PluginMessages {
|
||||
generic: Some(GenericPluginMessages {
|
||||
intro: invalid.clone(),
|
||||
usage_instructions: Some(" literal {{braces}}\r\n".into()),
|
||||
}),
|
||||
selected: Some(SelectedPluginMessages {
|
||||
search_tools: invalid.clone(),
|
||||
closing: Some("closing".into()),
|
||||
..Default::default()
|
||||
}),
|
||||
recommendations: Some(PluginRecommendationMessages { intro: invalid }),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let resolved = ResolvedModelMessages {
|
||||
catalog_messages: Some(&messages),
|
||||
};
|
||||
let generic = resolved.generic_plugin();
|
||||
assert_eq!(generic.intro, bundled.generic_plugin().intro);
|
||||
assert_eq!(generic.usage_instructions, " literal {{braces}}\r\n");
|
||||
assert!(generic.catalog_override);
|
||||
let selected = resolved.selected_plugin();
|
||||
assert_eq!(
|
||||
selected.search_tools,
|
||||
bundled.selected_plugin().search_tools
|
||||
);
|
||||
assert_eq!(selected.closing, "closing");
|
||||
assert_eq!(
|
||||
resolved.plugin_recommendations(),
|
||||
bundled.plugin_recommendations()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_templates_require_exactly_one_harness_fact_placeholder() {
|
||||
let bundled = ResolvedModelMessages::bundled().selected_plugin();
|
||||
for invalid in [
|
||||
"pre-expanded invented fact",
|
||||
"{{plugin_name}}",
|
||||
"{{ plugin_name }} {{ plugin_name }}",
|
||||
"{{ plugin_name }} {{ other }}",
|
||||
"{{ plugin_name }} {broken}",
|
||||
"{{ plugin_name }}\nsecond line",
|
||||
"{{ plugin_name }}\u{2028}second line",
|
||||
] {
|
||||
let messages = ModelMessages {
|
||||
plugins: Some(PluginMessages {
|
||||
selected: Some(SelectedPluginMessages {
|
||||
intro: Some(invalid.into()),
|
||||
closing: Some("valid sibling".into()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let resolved = ResolvedModelMessages {
|
||||
catalog_messages: Some(&messages),
|
||||
}
|
||||
.selected_plugin();
|
||||
assert_eq!(resolved.intro, bundled.intro);
|
||||
assert_eq!(resolved.closing, "valid sibling");
|
||||
}
|
||||
let selected = SelectedPluginMessages {
|
||||
intro: Some("Selected {{ plugin_name }}.".into()),
|
||||
skill_namespace: Some("Namespace {{ skill_namespace }}.".into()),
|
||||
apps: Some("Apps: {{ apps }}.".into()),
|
||||
mcp_servers: Some("Servers: {{ mcp_servers }}.".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let messages = ModelMessages {
|
||||
plugins: Some(PluginMessages {
|
||||
selected: Some(selected.clone()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let resolved = ResolvedModelMessages {
|
||||
catalog_messages: Some(&messages),
|
||||
}
|
||||
.selected_plugin();
|
||||
assert_eq!(resolved.intro, selected.intro.unwrap());
|
||||
assert_eq!(resolved.skill_namespace, selected.skill_namespace.unwrap());
|
||||
assert_eq!(resolved.apps, selected.apps.unwrap());
|
||||
assert_eq!(resolved.mcp_servers, selected.mcp_servers.unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_wording_limits_count_utf8_bytes_and_keep_boundary_values_literal() {
|
||||
let bundled = ResolvedModelMessages::bundled();
|
||||
for (intro, usage, expected_override) in [
|
||||
("é".repeat(250), "é".repeat(1_000), true),
|
||||
("é".repeat(251), "é".repeat(1_001), false),
|
||||
] {
|
||||
let messages = ModelMessages {
|
||||
plugins: Some(PluginMessages {
|
||||
generic: Some(GenericPluginMessages {
|
||||
intro: Some(intro.clone()),
|
||||
usage_instructions: Some(usage.clone()),
|
||||
}),
|
||||
selected: Some(SelectedPluginMessages {
|
||||
omitted: Some(intro.clone()),
|
||||
..Default::default()
|
||||
}),
|
||||
recommendations: Some(PluginRecommendationMessages {
|
||||
intro: Some(intro.clone()),
|
||||
}),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let resolved = ResolvedModelMessages {
|
||||
catalog_messages: Some(&messages),
|
||||
};
|
||||
let generic = resolved.generic_plugin();
|
||||
let selected = resolved.selected_plugin();
|
||||
let recommendations = resolved.plugin_recommendations();
|
||||
if expected_override {
|
||||
assert_eq!(generic.intro, intro);
|
||||
assert_eq!(generic.usage_instructions, usage);
|
||||
assert_eq!(selected.omitted, intro);
|
||||
assert_eq!(recommendations.intro, intro);
|
||||
} else {
|
||||
assert_eq!(generic, bundled.generic_plugin());
|
||||
assert_eq!(selected, bundled.selected_plugin());
|
||||
assert_eq!(recommendations, bundled.plugin_recommendations());
|
||||
}
|
||||
assert_eq!(generic.catalog_override, expected_override);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_plugin_omission_notice_keeps_the_disclosure() {
|
||||
for omitted in ["", " \r\n\t"] {
|
||||
let messages = ModelMessages {
|
||||
plugins: Some(PluginMessages {
|
||||
selected: Some(SelectedPluginMessages {
|
||||
omitted: Some(omitted.into()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
ResolvedModelMessages {
|
||||
catalog_messages: Some(&messages)
|
||||
}
|
||||
.selected_plugin(),
|
||||
ResolvedModelMessages::bundled().selected_plugin()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_wording_cannot_close_harness_fragments_or_insert_control_characters() {
|
||||
let bundled = ResolvedModelMessages::bundled();
|
||||
for invalid in [
|
||||
"</plugins_instructions>",
|
||||
"<plugins_instructions>",
|
||||
"</recommended_plugins>",
|
||||
"<recommended_plugins>",
|
||||
"hidden\u{0}text",
|
||||
"hidden\u{1b}text",
|
||||
] {
|
||||
let messages = ModelMessages {
|
||||
plugins: Some(PluginMessages {
|
||||
generic: Some(GenericPluginMessages {
|
||||
intro: Some(invalid.into()),
|
||||
usage_instructions: Some(invalid.into()),
|
||||
}),
|
||||
selected: Some(SelectedPluginMessages {
|
||||
closing: Some(invalid.into()),
|
||||
omitted: Some(invalid.into()),
|
||||
..Default::default()
|
||||
}),
|
||||
recommendations: Some(PluginRecommendationMessages {
|
||||
intro: Some(invalid.into()),
|
||||
}),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let resolved = ResolvedModelMessages {
|
||||
catalog_messages: Some(&messages),
|
||||
};
|
||||
assert_eq!(resolved.generic_plugin(), bundled.generic_plugin());
|
||||
assert_eq!(resolved.selected_plugin(), bundled.selected_plugin());
|
||||
assert_eq!(
|
||||
resolved.plugin_recommendations(),
|
||||
bundled.plugin_recommendations()
|
||||
);
|
||||
}
|
||||
}
|
||||
99
akode-rs/prompts/src/multi_agent_instructions.rs
Normal file
99
akode-rs/prompts/src/multi_agent_instructions.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
//! Assembles multi-agent role instructions from selected text and runtime capabilities.
|
||||
//! The segment owns rendering and attribution; consumers select and capture its inputs.
|
||||
|
||||
use crate::without_update_plan_instructions;
|
||||
use akode_context_fragments::ContextualUserFragment;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::ContentItemKind;
|
||||
use akode_protocol::models::input_text;
|
||||
|
||||
const DEFAULT_MULTI_AGENT_V2_MODEL_OVERRIDE_USAGE_HINT_TEXT: &str = "Full-history forks (`fork_turns` omitted or `\"all\"`) inherit the parent model and reasoning effort and do not accept overrides. Only set `model` or `reasoning_effort` when explicitly requested by the user, applicable `AGENTS.md` instructions, or skill instructions; when doing so, set `fork_turns` to `\"none\"`.";
|
||||
const DEFAULT_MULTI_AGENT_V2_WAIT_AGENT_USAGE_HINT_TEXT: &str =
|
||||
"When calling `wait_agent`, prefer longer waits (minutes) to avoid busy polling.";
|
||||
const DEFAULT_MULTI_AGENT_V2_SHARED_USAGE_HINT_TEXT: &str = r#"Note that collaboration tools cannot be called from inside `functions.exec`. Call `spawn_agent`, `send_message`, `followup_task`, `wait_agent`, `interrupt_agent`, and `list_agents` only as direct tool calls using the recipient shown in their tool definitions, such as `to=functions.collaboration.spawn_agent`, since they are intentionally absent from the `functions.exec` `tools.*` namespace. Available tools in `functions.exec` are explicitly described with a `tools` namespace in the developer message.
|
||||
|
||||
All agents share the same directory. In detail:
|
||||
- All agents have access to the same container and filesystem as you.
|
||||
- All agents use the same current working directory.
|
||||
- As a result, edits made by one agent are immediately visible to all other agents.
|
||||
"#;
|
||||
|
||||
/// Multi-agent role text and the captured capabilities used to render its context segment.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MultiAgentRoleInstructions {
|
||||
/// Complete configured instructions, emitted verbatim without catalog markers.
|
||||
Configured(String),
|
||||
/// Selected catalog or bundled text, composed with captured runtime guidance.
|
||||
Composed {
|
||||
base: String,
|
||||
marked: bool,
|
||||
omit_update_plan_instructions: bool,
|
||||
max_concurrency: usize,
|
||||
wait_agent_enabled: bool,
|
||||
expose_model_overrides: bool,
|
||||
},
|
||||
}
|
||||
|
||||
impl MultiAgentRoleInstructions {
|
||||
/// Content classification shared by role producers and inherited-history filtering.
|
||||
pub const KIND: &str = "multi_agent.role_instructions";
|
||||
}
|
||||
|
||||
impl ContextualUserFragment for MultiAgentRoleInstructions {
|
||||
fn content_kind(&self) -> ContentItemKind {
|
||||
ContentItemKind(Self::KIND.to_string())
|
||||
}
|
||||
|
||||
fn role(&self) -> &'static str {
|
||||
"developer"
|
||||
}
|
||||
|
||||
fn markers(&self) -> (&'static str, &'static str) {
|
||||
match self {
|
||||
Self::Composed { marked: true, .. } => Self::type_markers(),
|
||||
Self::Configured(_) | Self::Composed { marked: false, .. } => ("", ""),
|
||||
}
|
||||
}
|
||||
|
||||
fn type_markers() -> (&'static str, &'static str) {
|
||||
("<multi_agent_role>", "</multi_agent_role>")
|
||||
}
|
||||
|
||||
fn body(&self) -> ContentItem {
|
||||
input_text(match self {
|
||||
Self::Configured(text) => text.clone(),
|
||||
Self::Composed {
|
||||
base,
|
||||
omit_update_plan_instructions,
|
||||
max_concurrency,
|
||||
wait_agent_enabled,
|
||||
expose_model_overrides,
|
||||
..
|
||||
} => {
|
||||
let base = if *omit_update_plan_instructions {
|
||||
without_update_plan_instructions(base)
|
||||
} else {
|
||||
base.clone()
|
||||
};
|
||||
let wait_agent_guidance = if *wait_agent_enabled {
|
||||
format!("{DEFAULT_MULTI_AGENT_V2_WAIT_AGENT_USAGE_HINT_TEXT}\n\n")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let shared = DEFAULT_MULTI_AGENT_V2_SHARED_USAGE_HINT_TEXT;
|
||||
let mut text = format!(
|
||||
"{base}\n{shared}\n{wait_agent_guidance}There are {max_concurrency} available concurrency slots, meaning that up to {max_concurrency} agents can be active at once, including you."
|
||||
);
|
||||
if *expose_model_overrides {
|
||||
text.push_str("\n\n");
|
||||
text.push_str(DEFAULT_MULTI_AGENT_V2_MODEL_OVERRIDE_USAGE_HINT_TEXT);
|
||||
}
|
||||
text
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "multi_agent_instructions_tests.rs"]
|
||||
mod tests;
|
||||
44
akode-rs/prompts/src/multi_agent_instructions_tests.rs
Normal file
44
akode-rs/prompts/src/multi_agent_instructions_tests.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
//! Covers role composition and attribution for captured model instructions.
|
||||
|
||||
use super::*;
|
||||
use akode_context_fragments::AnnotatedContent;
|
||||
use akode_context_fragments::RenderedFragment;
|
||||
use akode_protocol::models::ContentItemMetadata;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn role_segment_filters_base_and_appends_bundled_guidance() {
|
||||
let shared = DEFAULT_MULTI_AGENT_V2_SHARED_USAGE_HINT_TEXT;
|
||||
let wait = DEFAULT_MULTI_AGENT_V2_WAIT_AGENT_USAGE_HINT_TEXT;
|
||||
let model_override = DEFAULT_MULTI_AGENT_V2_MODEL_OVERRIDE_USAGE_HINT_TEXT;
|
||||
let expected_body = format!(
|
||||
"Role.\n## Work\nContinue.\n{shared}\n{wait}\n\nThere are 2 available concurrency slots, meaning that up to 2 agents can be active at once, including you.\n\n{model_override}"
|
||||
);
|
||||
for marked in [false, true] {
|
||||
let instructions = MultiAgentRoleInstructions::Composed {
|
||||
base: "Role.\n## Plan tool\nOmit role checklist guidance.\n## Work\nContinue."
|
||||
.to_string(),
|
||||
marked,
|
||||
omit_update_plan_instructions: true,
|
||||
max_concurrency: 2,
|
||||
wait_agent_enabled: true,
|
||||
expose_model_overrides: true,
|
||||
};
|
||||
let expected_text = if marked {
|
||||
format!("<multi_agent_role>{expected_body}</multi_agent_role>")
|
||||
} else {
|
||||
expected_body.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
instructions.render_fragment(),
|
||||
RenderedFragment::new(
|
||||
"developer",
|
||||
AnnotatedContent::text(
|
||||
expected_text,
|
||||
ContentItemKind("multi_agent.role_instructions".to_string()),
|
||||
ContentItemMetadata::harness(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
486
akode-rs/prompts/src/permissions_instructions.rs
Normal file
486
akode-rs/prompts/src/permissions_instructions.rs
Normal file
@@ -0,0 +1,486 @@
|
||||
//! Composes selected permission text and prepared runtime facts into a stored fragment body.
|
||||
//! Remote paths use executor context; the local adapter retains host filesystem resolution.
|
||||
//! Displayed paths share a byte budget and are omitted only at whole-entry boundaries.
|
||||
//! Catalog text uses literal substitution; bundled sandbox templates are parsed and cached here.
|
||||
|
||||
use crate::ResolvedMessage;
|
||||
use crate::ResolvedModelMessages;
|
||||
use crate::model_messages::permissions::DANGER_FULL_ACCESS_TEMPLATE;
|
||||
use crate::model_messages::permissions::READ_ONLY_TEMPLATE;
|
||||
use crate::model_messages::permissions::ResolvedApprovalMessages;
|
||||
use crate::model_messages::permissions::ResolvedPermissionMessages;
|
||||
use crate::model_messages::permissions::WORKSPACE_WRITE_TEMPLATE;
|
||||
use approval_instructions::ApprovalInstructions;
|
||||
use akode_context_fragments::ContextualUserFragment;
|
||||
use akode_execpolicy::Policy;
|
||||
use akode_protocol::config_types::ApprovalsReviewer;
|
||||
use akode_protocol::config_types::SandboxMode;
|
||||
use akode_protocol::models::ContentItem;
|
||||
use akode_protocol::models::ContentItemKind;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use akode_protocol::models::format_allow_prefixes;
|
||||
use akode_protocol::models::input_text;
|
||||
use akode_protocol::permissions::FileSystemSandboxPolicyContext;
|
||||
use akode_protocol::protocol::AskForApproval;
|
||||
use akode_protocol::protocol::GranularApprovalConfig;
|
||||
use akode_protocol::protocol::NetworkAccess;
|
||||
use akode_utils_template::Template;
|
||||
use path_warnings::OMITTED_PERMISSION_PATHS;
|
||||
use path_warnings::denied_reads_text;
|
||||
use path_warnings::omitted_paths_text;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::sync::LazyLock;
|
||||
use writable_roots::writable_roots_text;
|
||||
|
||||
mod approval_instructions;
|
||||
mod path_warnings;
|
||||
mod writable_roots;
|
||||
|
||||
const REQUEST_PERMISSION_RULE: &str =
|
||||
include_str!("../templates/permissions/approval_policy/on_request_rule_request_permission.md");
|
||||
const REQUEST_PERMISSIONS_TOOL: &str = "# request_permissions Tool\n\nThe built-in `request_permissions` tool is available in this session. Invoke it when you need to request additional `network` or `file_system` permissions before later shell-like commands need them. Request only the specific permissions required for the task.";
|
||||
const AUTO_REVIEW_SUFFIX: &str = "`approvals_reviewer` is `auto_review`: Sandbox escalations with require_escalated will be reviewed for compliance with the policy. If a rejection happens, you should proceed only with a materially safer alternative, or inform the user of the risk and send a final message to ask for approval.";
|
||||
const GRANULAR_INTRO: &str = "# Approval Requests\n\nApproval policy is `granular`. Categories set to `false` are automatically rejected instead of prompting the user.";
|
||||
const GRANULAR_PROMPTED_CATEGORIES: &str =
|
||||
"These approval categories may still prompt the user when needed:";
|
||||
const GRANULAR_REJECTED_CATEGORIES: &str =
|
||||
"These approval categories are automatically rejected instead of prompting the user:";
|
||||
const MAX_PERMISSION_PATH_BYTES: usize = 32 * 1024;
|
||||
|
||||
static DANGER_FULL_ACCESS: LazyLock<Template> = LazyLock::new(|| {
|
||||
Template::parse(DANGER_FULL_ACCESS_TEMPLATE.trim_end())
|
||||
.unwrap_or_else(|err| panic!("danger-full-access sandbox template must parse: {err}"))
|
||||
});
|
||||
static WORKSPACE_WRITE: LazyLock<Template> = LazyLock::new(|| {
|
||||
Template::parse(WORKSPACE_WRITE_TEMPLATE.trim_end())
|
||||
.unwrap_or_else(|err| panic!("workspace-write sandbox template must parse: {err}"))
|
||||
});
|
||||
static READ_ONLY: LazyLock<Template> = LazyLock::new(|| {
|
||||
Template::parse(READ_ONLY_TEMPLATE.trim_end())
|
||||
.unwrap_or_else(|err| panic!("read-only sandbox template must parse: {err}"))
|
||||
});
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ApprovalPromptContext<'a> {
|
||||
reviewer: ApprovalsReviewer,
|
||||
messages: ResolvedApprovalMessages<'a>,
|
||||
permission_messages: ResolvedPermissionMessages<'a>,
|
||||
}
|
||||
|
||||
impl<'a> ApprovalPromptContext<'a> {
|
||||
pub fn new(reviewer: ApprovalsReviewer, model_messages: ResolvedModelMessages<'a>) -> Self {
|
||||
Self {
|
||||
reviewer,
|
||||
messages: model_messages.approvals(),
|
||||
permission_messages: model_messages.permissions(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a plain heading for the standalone notification about newly saved prefixes.
|
||||
pub fn approved_command_prefix_saved_heading(&self) -> Option<&'a str> {
|
||||
self.permission_messages
|
||||
.approved_command_prefix_saved
|
||||
.filter(|text| {
|
||||
text.len() <= 500
|
||||
&& !text.trim().is_empty()
|
||||
&& !text.chars().any(char::is_control)
|
||||
&& !text.contains(['<', '>', '{', '}', '\u{2028}', '\u{2029}'])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepared runtime facts borrowed only while composing the fragment.
|
||||
/// Paths retain their resolved display spellings and order.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct PermissionsRenderContext<'a> {
|
||||
sandbox_mode: SandboxMode,
|
||||
network_access: NetworkAccess,
|
||||
approval_policy: AskForApproval,
|
||||
approved_command_prefixes: &'a [Vec<String>],
|
||||
writable_roots: &'a [String],
|
||||
denied_read_paths: &'a [String],
|
||||
denied_read_globs: &'a [String],
|
||||
exec_permission_approvals_enabled: bool,
|
||||
request_permissions_tool_enabled: bool,
|
||||
}
|
||||
|
||||
/// Developer fragment describing the active sandbox and approval policy.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PermissionsInstructions {
|
||||
text: String,
|
||||
}
|
||||
|
||||
impl PermissionsInstructions {
|
||||
/// Composes a permission fragment from resolved messages and caller-supplied facts.
|
||||
/// Paths are used verbatim; this constructor does not inspect the filesystem or environment.
|
||||
fn from_resolved(
|
||||
context: PermissionsRenderContext<'_>,
|
||||
approval_context: ApprovalPromptContext<'_>,
|
||||
) -> Self {
|
||||
let mut remaining_path_bytes =
|
||||
MAX_PERMISSION_PATH_BYTES - OMITTED_PERMISSION_PATHS.len() - 1;
|
||||
let mut paths_omitted = false;
|
||||
let mut bounded_paths = |paths: &[String]| {
|
||||
paths
|
||||
.iter()
|
||||
.filter(|path| {
|
||||
// Reserve up to ten bytes for each entry's label, quoting, and separator.
|
||||
if let Some(remaining) = remaining_path_bytes.checked_sub(path.len() + 10) {
|
||||
remaining_path_bytes = remaining;
|
||||
true
|
||||
} else {
|
||||
paths_omitted = true;
|
||||
false
|
||||
}
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let writable_roots = bounded_paths(context.writable_roots);
|
||||
let denied_read_paths = bounded_paths(context.denied_read_paths);
|
||||
let denied_read_globs = bounded_paths(context.denied_read_globs);
|
||||
let mut text = String::new();
|
||||
let sandbox = sandbox_text(
|
||||
context.sandbox_mode,
|
||||
context.network_access,
|
||||
approval_context.permission_messages,
|
||||
);
|
||||
if !sandbox.is_empty() {
|
||||
append_section(&mut text, &sandbox);
|
||||
}
|
||||
append_section(
|
||||
&mut text,
|
||||
&approval_text(
|
||||
context.approval_policy,
|
||||
approval_context,
|
||||
context.approved_command_prefixes,
|
||||
context.exec_permission_approvals_enabled,
|
||||
context.request_permissions_tool_enabled,
|
||||
),
|
||||
);
|
||||
if let Some(writable_roots) =
|
||||
writable_roots_text(&writable_roots, approval_context.permission_messages)
|
||||
{
|
||||
append_section(&mut text, &writable_roots);
|
||||
}
|
||||
let path_messages = approval_context.permission_messages;
|
||||
if let Some(denied_reads) =
|
||||
denied_reads_text(&denied_read_paths, &denied_read_globs, path_messages)
|
||||
{
|
||||
append_section(&mut text, &denied_reads);
|
||||
}
|
||||
if paths_omitted {
|
||||
append_section(&mut text, &omitted_paths_text(path_messages));
|
||||
}
|
||||
if !text.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
Self { text }
|
||||
}
|
||||
|
||||
/// Uses executor paths when supplied, otherwise retaining local path resolution.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn from_permission_profile(
|
||||
permission_profile: &PermissionProfile,
|
||||
approval_policy: AskForApproval,
|
||||
approval_context: ApprovalPromptContext<'_>,
|
||||
exec_policy: &Policy,
|
||||
cwd: &Path,
|
||||
paths: Option<&FileSystemSandboxPolicyContext<'_>>,
|
||||
exec_permission_approvals_enabled: bool,
|
||||
request_permissions_tool_enabled: bool,
|
||||
) -> Self {
|
||||
let file_system_policy = permission_profile.file_system_sandbox_policy();
|
||||
let full_disk_write = paths.map_or_else(
|
||||
|| file_system_policy.has_full_disk_write_access(),
|
||||
|paths| file_system_policy.has_full_disk_write_access_with_context(paths),
|
||||
);
|
||||
let (writable_roots, denied_read_paths, denied_read_globs) = if let Some(paths) = paths {
|
||||
let mut writable_roots = file_system_policy
|
||||
.resolved_entries(paths)
|
||||
.into_iter()
|
||||
.filter(|(path, access)| {
|
||||
!full_disk_write
|
||||
&& access.can_write()
|
||||
&& file_system_policy.can_write_path(path, paths)
|
||||
})
|
||||
.map(|(path, _)| path)
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.map(|path| path.inferred_native_path_string())
|
||||
.collect::<Vec<_>>();
|
||||
writable_roots.sort();
|
||||
let mut denied_read_paths = Vec::new();
|
||||
let mut denied_read_globs = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut entry_policy = file_system_policy.clone();
|
||||
// Missing executor facts should omit only the unresolved entry from the text.
|
||||
for entry in &file_system_policy.entries {
|
||||
entry_policy.entries = vec![entry.clone()];
|
||||
denied_read_paths.extend(
|
||||
entry_policy
|
||||
.get_unreadable_roots_with_context(paths)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|path| seen.insert(path.clone()))
|
||||
.map(|path| path.inferred_native_path_string()),
|
||||
);
|
||||
denied_read_globs.extend(
|
||||
entry_policy
|
||||
.get_unreadable_globs_with_context(paths)
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
denied_read_globs.sort();
|
||||
denied_read_globs.dedup();
|
||||
(writable_roots, denied_read_paths, denied_read_globs)
|
||||
} else {
|
||||
let mut writable_roots = file_system_policy.get_writable_roots_with_cwd(cwd);
|
||||
writable_roots.sort_by(|left, right| left.root.as_path().cmp(right.root.as_path()));
|
||||
(
|
||||
writable_roots
|
||||
.iter()
|
||||
.map(|root| root.root.to_string_lossy().into_owned())
|
||||
.collect(),
|
||||
file_system_policy
|
||||
.get_unreadable_roots_with_cwd(cwd)
|
||||
.iter()
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
.collect(),
|
||||
file_system_policy.get_unreadable_globs_with_cwd(cwd),
|
||||
)
|
||||
};
|
||||
let sandbox_mode = if full_disk_write {
|
||||
SandboxMode::DangerFullAccess
|
||||
} else if writable_roots.is_empty() {
|
||||
SandboxMode::ReadOnly
|
||||
} else {
|
||||
SandboxMode::WorkspaceWrite
|
||||
};
|
||||
Self::from_resolved(
|
||||
PermissionsRenderContext {
|
||||
sandbox_mode,
|
||||
network_access: if permission_profile.network_sandbox_policy().is_enabled() {
|
||||
NetworkAccess::Enabled
|
||||
} else {
|
||||
NetworkAccess::Restricted
|
||||
},
|
||||
approval_policy,
|
||||
approved_command_prefixes: &exec_policy.get_allowed_prefixes(),
|
||||
writable_roots: &writable_roots,
|
||||
denied_read_paths: &denied_read_paths,
|
||||
denied_read_globs: &denied_read_globs,
|
||||
exec_permission_approvals_enabled,
|
||||
request_permissions_tool_enabled,
|
||||
},
|
||||
approval_context,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextualUserFragment for PermissionsInstructions {
|
||||
fn role(&self) -> &'static str {
|
||||
"developer"
|
||||
}
|
||||
|
||||
fn content_kind(&self) -> ContentItemKind {
|
||||
ContentItemKind("permissions.instructions".to_string())
|
||||
}
|
||||
|
||||
fn markers(&self) -> (&'static str, &'static str) {
|
||||
Self::type_markers()
|
||||
}
|
||||
|
||||
fn type_markers() -> (&'static str, &'static str) {
|
||||
("<permissions instructions>", "</permissions instructions>")
|
||||
}
|
||||
|
||||
fn body(&self) -> ContentItem {
|
||||
input_text(self.text.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn append_section(text: &mut String, section: &str) {
|
||||
if !text.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(section);
|
||||
}
|
||||
|
||||
fn approval_text(
|
||||
approval_policy: AskForApproval,
|
||||
approval_context: ApprovalPromptContext<'_>,
|
||||
approved_command_prefixes: &[Vec<String>],
|
||||
exec_permission_approvals_enabled: bool,
|
||||
request_permissions_tool_enabled: bool,
|
||||
) -> String {
|
||||
let messages = approval_context.messages;
|
||||
let selected = match approval_policy {
|
||||
AskForApproval::OnRequest => match approval_context.reviewer {
|
||||
ApprovalsReviewer::User => messages.on_request,
|
||||
ApprovalsReviewer::AutoReview => messages.on_request_auto_review,
|
||||
},
|
||||
AskForApproval::Never => messages.never,
|
||||
AskForApproval::UnlessTrusted => messages.unless_trusted,
|
||||
AskForApproval::Granular(_) => ResolvedMessage::Bundled(GRANULAR_INTRO),
|
||||
};
|
||||
let prefix_template = approval_context.permission_messages.approved_prefixes;
|
||||
let render_prefixes =
|
||||
|| approved_command_prefixes_text(approved_command_prefixes, prefix_template.text());
|
||||
let base = match selected {
|
||||
ResolvedMessage::Catalog(text) => {
|
||||
// Catalog approval prose replaces the bundled section, but not an explicit
|
||||
// approved-prefixes template supplied alongside it.
|
||||
if approval_policy == AskForApproval::OnRequest
|
||||
&& matches!(prefix_template, ResolvedMessage::Catalog(_))
|
||||
&& let Some(prefixes) = render_prefixes()
|
||||
{
|
||||
return if text.is_empty() {
|
||||
prefixes
|
||||
} else {
|
||||
format!("{text}\n\n{prefixes}")
|
||||
};
|
||||
}
|
||||
return text.to_string();
|
||||
}
|
||||
ResolvedMessage::Bundled(text) => text,
|
||||
};
|
||||
let instructions = ApprovalInstructions::new(approval_context);
|
||||
let text = match approval_policy {
|
||||
AskForApproval::Never => return base.to_string(),
|
||||
AskForApproval::UnlessTrusted => {
|
||||
if request_permissions_tool_enabled {
|
||||
format!("{base}\n\n{}", instructions.tool())
|
||||
} else {
|
||||
base.to_string()
|
||||
}
|
||||
}
|
||||
AskForApproval::OnRequest => {
|
||||
let mut sections = vec![if exec_permission_approvals_enabled {
|
||||
REQUEST_PERMISSION_RULE.to_string()
|
||||
} else {
|
||||
base.to_string()
|
||||
}];
|
||||
if request_permissions_tool_enabled {
|
||||
sections.push(instructions.tool());
|
||||
}
|
||||
sections.extend(render_prefixes());
|
||||
sections.join("\n\n")
|
||||
}
|
||||
AskForApproval::Granular(granular_config) => granular_instructions(
|
||||
granular_config,
|
||||
approval_context,
|
||||
render_prefixes(),
|
||||
exec_permission_approvals_enabled,
|
||||
request_permissions_tool_enabled,
|
||||
),
|
||||
};
|
||||
|
||||
if approval_context.reviewer == ApprovalsReviewer::AutoReview {
|
||||
format!("{text}\n\n{}", instructions.auto_review())
|
||||
} else {
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
fn sandbox_text(
|
||||
mode: SandboxMode,
|
||||
network_access: NetworkAccess,
|
||||
messages: ResolvedPermissionMessages<'_>,
|
||||
) -> String {
|
||||
let (selected, template) = match mode {
|
||||
SandboxMode::DangerFullAccess => (messages.danger_full_access, &DANGER_FULL_ACCESS),
|
||||
SandboxMode::WorkspaceWrite => (messages.workspace_write, &WORKSPACE_WRITE),
|
||||
SandboxMode::ReadOnly => (messages.read_only, &READ_ONLY),
|
||||
};
|
||||
let network_access = network_access.to_string();
|
||||
match selected {
|
||||
ResolvedMessage::Catalog(text) => text.replace("{{ network_access }}", &network_access),
|
||||
ResolvedMessage::Bundled(_) => template
|
||||
.render([("network_access", network_access.as_str())])
|
||||
.unwrap_or_else(|err| panic!("sandbox template must render: {err}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn approved_command_prefixes_text(prefixes: &[Vec<String>], template: &str) -> Option<String> {
|
||||
if template.is_empty() || prefixes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let prefixes = format_allow_prefixes(prefixes.to_vec())?;
|
||||
Some(template.replace("{{ approved_prefixes }}", &prefixes))
|
||||
}
|
||||
|
||||
fn granular_instructions(
|
||||
granular_config: GranularApprovalConfig,
|
||||
approval_context: ApprovalPromptContext<'_>,
|
||||
approved_command_prefixes: Option<String>,
|
||||
exec_permission_approvals_enabled: bool,
|
||||
request_permissions_tool_enabled: bool,
|
||||
) -> String {
|
||||
let instructions = ApprovalInstructions::new(approval_context);
|
||||
let sandbox_approval_prompts_allowed = granular_config.allows_sandbox_approval();
|
||||
let shell_permission_requests_available =
|
||||
exec_permission_approvals_enabled && sandbox_approval_prompts_allowed;
|
||||
let request_permissions_tool_prompts_allowed =
|
||||
request_permissions_tool_enabled && granular_config.allows_request_permissions();
|
||||
let categories = [
|
||||
Some((
|
||||
granular_config.allows_sandbox_approval(),
|
||||
"`sandbox_approval`",
|
||||
)),
|
||||
Some((granular_config.allows_rules_approval(), "`rules`")),
|
||||
Some((granular_config.allows_skill_approval(), "`skill_approval`")),
|
||||
request_permissions_tool_enabled.then_some((
|
||||
granular_config.allows_request_permissions(),
|
||||
"`request_permissions`",
|
||||
)),
|
||||
Some((
|
||||
granular_config.allows_mcp_elicitations(),
|
||||
"`mcp_elicitations`",
|
||||
)),
|
||||
];
|
||||
let prompted_categories = categories
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|&&(is_allowed, _)| is_allowed)
|
||||
.map(|&(_, category)| format!("- {category}"))
|
||||
.collect::<Vec<_>>();
|
||||
let rejected_categories = categories
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|&&(is_allowed, _)| !is_allowed)
|
||||
.map(|&(_, category)| format!("- {category}"))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut sections = vec![GRANULAR_INTRO.to_string()];
|
||||
|
||||
if !prompted_categories.is_empty() {
|
||||
sections.push(format!(
|
||||
"{GRANULAR_PROMPTED_CATEGORIES}\n{}",
|
||||
prompted_categories.join("\n")
|
||||
));
|
||||
}
|
||||
if !rejected_categories.is_empty() {
|
||||
sections.push(format!(
|
||||
"{GRANULAR_REJECTED_CATEGORIES}\n{}",
|
||||
rejected_categories.join("\n")
|
||||
));
|
||||
}
|
||||
|
||||
if shell_permission_requests_available {
|
||||
sections.push(REQUEST_PERMISSION_RULE.to_string());
|
||||
}
|
||||
|
||||
if request_permissions_tool_prompts_allowed {
|
||||
sections.push(instructions.tool());
|
||||
}
|
||||
|
||||
sections.extend(approved_command_prefixes);
|
||||
|
||||
sections.join("\n\n")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "permissions_instructions_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,59 @@
|
||||
//! Selects bounded catalog headings while preserving all permission and review guidance.
|
||||
|
||||
use super::AUTO_REVIEW_SUFFIX;
|
||||
use super::ApprovalPromptContext;
|
||||
use super::PermissionsInstructions;
|
||||
use super::REQUEST_PERMISSIONS_TOOL;
|
||||
use akode_context_fragments::ContextualUserFragment;
|
||||
use akode_protocol::openai_models::ApprovalMessages;
|
||||
|
||||
pub(super) struct ApprovalInstructions<'a>(Option<&'a ApprovalMessages>);
|
||||
|
||||
impl<'a> ApprovalInstructions<'a> {
|
||||
pub(super) fn new(context: ApprovalPromptContext<'a>) -> Self {
|
||||
Self(context.messages.catalog)
|
||||
}
|
||||
|
||||
pub(super) fn tool(&self) -> String {
|
||||
with_heading(
|
||||
self.0.and_then(|m| m.request_permissions.as_deref()),
|
||||
REQUEST_PERMISSIONS_TOOL,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn auto_review(&self) -> String {
|
||||
match self
|
||||
.0
|
||||
.and_then(|m| m.auto_review_suffix.as_deref())
|
||||
.filter(|s| valid_heading(s))
|
||||
{
|
||||
Some(heading) => format!("{heading}\n\n{AUTO_REVIEW_SUFFIX}"),
|
||||
None => AUTO_REVIEW_SUFFIX.to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn with_heading(heading: Option<&str>, bundled: &str) -> String {
|
||||
match (
|
||||
heading.filter(|s| valid_heading(s)),
|
||||
bundled.find(['\r', '\n']),
|
||||
) {
|
||||
(Some(heading), Some(end)) => format!("{heading}{}", &bundled[end..]),
|
||||
_ => bundled.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
// One single-line heading can add at most 500 UTF-8 bytes plus its paragraph separator.
|
||||
fn valid_heading(text: &str) -> bool {
|
||||
let (open, close) = PermissionsInstructions::type_markers();
|
||||
text.len() <= 500
|
||||
&& !text.trim().is_empty()
|
||||
&& !text.chars().any(char::is_control)
|
||||
&& !text.contains(['{', '}', '\u{2028}', '\u{2029}'])
|
||||
&& !text.contains(open)
|
||||
&& !text.contains(close)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "approval_instructions_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,34 @@
|
||||
//! Verifies catalog heading bounds and preservation of bundled instruction line endings.
|
||||
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn replacing_heading_preserves_the_bundled_line_endings() {
|
||||
let bundled = "Heading\r\n\r\nRequired instructions.\r\n";
|
||||
assert_eq!(
|
||||
with_heading(Some("Catalog"), bundled),
|
||||
"Catalog\r\n\r\nRequired instructions.\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_bounded_heading_and_rejects_malformed_presentation() {
|
||||
let boundary = "é".repeat(250);
|
||||
assert!(valid_heading(&boundary));
|
||||
let (open, close) = PermissionsInstructions::type_markers();
|
||||
for invalid in [
|
||||
"",
|
||||
" ",
|
||||
&format!("{boundary}a"),
|
||||
open,
|
||||
close,
|
||||
"{{ policy }}",
|
||||
"title\nbody",
|
||||
"title\u{2028}body",
|
||||
] {
|
||||
assert!(!valid_heading(invalid), "accepted {invalid:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! Bounds catalog presentation while retaining harness-owned denial and omission rules.
|
||||
//! Callers bound paths first; catalog wording never changes the path selection budget.
|
||||
|
||||
use super::MAX_PERMISSION_PATH_BYTES;
|
||||
use super::PermissionsInstructions;
|
||||
use crate::model_messages::permissions::DENIED_READS_TEMPLATE;
|
||||
use crate::model_messages::permissions::ResolvedPermissionMessages;
|
||||
use akode_context_fragments::ContextualUserFragment;
|
||||
|
||||
pub(super) const OMITTED_PERMISSION_PATHS: &str = "Additional permission paths/globs are omitted. All restrictions still apply; do not use escalation or additional permissions to bypass omitted read denials.";
|
||||
const DENIED_READS_POLICY: &str = "The active permission profile denies reading these paths/globs. Do not request escalation or additional permissions to read them; these denials are policy restrictions.";
|
||||
const DENIED_READS_PLACEHOLDER: &str = "{{ denied_reads }}";
|
||||
// Together the two overrides introduce at most 1,000 UTF-8 bytes of presentation.
|
||||
const MAX_PRESENTATION_BYTES: usize = 500;
|
||||
|
||||
pub(super) fn omitted_paths_text(messages: ResolvedPermissionMessages<'_>) -> String {
|
||||
match messages.omitted_paths.catalog_override() {
|
||||
Some(text) if valid_presentation(text) && !text.contains(['{', '}']) => {
|
||||
format!("{text}\n{OMITTED_PERMISSION_PATHS}")
|
||||
}
|
||||
_ => OMITTED_PERMISSION_PATHS.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn denied_reads_text(
|
||||
paths: &[String],
|
||||
globs: &[String],
|
||||
messages: ResolvedPermissionMessages<'_>,
|
||||
) -> Option<String> {
|
||||
if paths.is_empty() && globs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let entries = paths
|
||||
.iter()
|
||||
.map(|path| format!("- path `{path}`"))
|
||||
.chain(globs.iter().map(|glob| format!("- glob `{glob}`")))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let facts = format!("{DENIED_READS_POLICY}\n{entries}");
|
||||
let (before, after) = messages
|
||||
.denied_reads
|
||||
.catalog_override()
|
||||
.filter(|template| valid_presentation(template))
|
||||
.and_then(|template| template.split_once(DENIED_READS_PLACEHOLDER))
|
||||
.filter(|(before, after)| !before.contains(['{', '}']) && !after.contains(['{', '}']))
|
||||
.filter(|(before, after)| {
|
||||
before.len() + facts.len() + after.len()
|
||||
<= MAX_PERMISSION_PATH_BYTES
|
||||
+ DENIED_READS_POLICY.len()
|
||||
+ 1
|
||||
+ MAX_PRESENTATION_BYTES
|
||||
})
|
||||
.or_else(|| DENIED_READS_TEMPLATE.split_once(DENIED_READS_PLACEHOLDER))
|
||||
.unwrap_or_default();
|
||||
Some(format!("{before}{facts}{after}"))
|
||||
}
|
||||
|
||||
fn valid_presentation(text: &str) -> bool {
|
||||
let (open, close) = PermissionsInstructions::type_markers();
|
||||
!text.trim().is_empty()
|
||||
&& text.len() <= MAX_PRESENTATION_BYTES
|
||||
&& !text
|
||||
.chars()
|
||||
.any(|c| (c.is_control() && c != '\n') || matches!(c, '\u{2028}' | '\u{2029}'))
|
||||
&& !text.contains(open)
|
||||
&& !text.contains(close)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Renders bounded catalog wording around an already bounded list of writable roots.
|
||||
//! Validate template text before inserting paths once; unusable overrides retain legacy bytes.
|
||||
|
||||
use super::MAX_PERMISSION_PATH_BYTES;
|
||||
use super::PermissionsInstructions;
|
||||
use crate::model_messages::permissions::ResolvedPermissionMessages;
|
||||
use crate::model_messages::permissions::WRITABLE_ROOT_TEMPLATE;
|
||||
use crate::model_messages::permissions::WRITABLE_ROOTS_TEMPLATE;
|
||||
use akode_context_fragments::ContextualUserFragment;
|
||||
|
||||
const ROOTS_PLACEHOLDER: &str = "{{ roots }}";
|
||||
// Replacing the 11-byte marker leaves at most 989 bytes of catalog wording,
|
||||
// bounding it below 1K tokens even with one byte-fallback token per byte.
|
||||
const MAX_ROOTS_TEMPLATE_BYTES: usize = 1_000;
|
||||
const MAX_ROOTS_SENTENCE_BYTES: usize = MAX_PERMISSION_PATH_BYTES + MAX_ROOTS_TEMPLATE_BYTES;
|
||||
|
||||
// The caller bounds paths at whole-entry boundaries before reaching this renderer.
|
||||
pub(super) fn writable_roots_text(
|
||||
roots: &[String],
|
||||
messages: ResolvedPermissionMessages<'_>,
|
||||
) -> Option<String> {
|
||||
let (selected, fallback) = match roots.len() {
|
||||
0 => return None,
|
||||
1 => (messages.writable_root, WRITABLE_ROOT_TEMPLATE),
|
||||
_ => (messages.writable_roots, WRITABLE_ROOTS_TEMPLATE),
|
||||
};
|
||||
let roots_list = roots
|
||||
.iter()
|
||||
.map(|root| format!("`{root}`"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
Some(
|
||||
selected
|
||||
.catalog_override()
|
||||
.and_then(|template| render_roots_override(template, &roots_list))
|
||||
.unwrap_or_else(|| fallback.replace(ROOTS_PLACEHOLDER, &roots_list)),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_roots_override(template: &str, roots: &str) -> Option<String> {
|
||||
if template.len() > MAX_ROOTS_TEMPLATE_BYTES
|
||||
|| template
|
||||
.chars()
|
||||
.any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}'))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (before, after) = template.split_once(ROOTS_PLACEHOLDER)?;
|
||||
// Reject duplicate, unknown and malformed placeholders, without parsing runtime paths.
|
||||
if [before, after]
|
||||
.iter()
|
||||
.any(|part| part.chars().any(|c| matches!(c, '{' | '}')))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (open, close) = PermissionsInstructions::type_markers();
|
||||
if template.contains(open) || template.contains(close) {
|
||||
return None;
|
||||
}
|
||||
let rendered_len = before
|
||||
.len()
|
||||
.checked_add(roots.len())?
|
||||
.checked_add(after.len())?;
|
||||
if rendered_len > MAX_ROOTS_SENTENCE_BYTES {
|
||||
return None;
|
||||
}
|
||||
Some(format!("{before}{roots}{after}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "writable_roots_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,80 @@
|
||||
//! Checks bounded catalog wording without interpreting or truncating runtime paths.
|
||||
|
||||
use super::*;
|
||||
use akode_protocol::openai_models::PermissionMessages;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn unusable_templates_fall_back_without_losing_roots() {
|
||||
let roots = vec!["/a".to_string(), "/b".to_string()];
|
||||
for template in [
|
||||
"",
|
||||
" ",
|
||||
"No placeholder",
|
||||
"{{roots}}",
|
||||
"{{ roots }} {{ roots }}",
|
||||
"{{ roots }} {{ other }}",
|
||||
"{{{ roots }}}",
|
||||
"X { {{ roots }}",
|
||||
"X {{ roots }} }",
|
||||
"X\n{{ roots }}",
|
||||
"X\t{{ roots }}",
|
||||
"X\0{{ roots }}",
|
||||
"X\u{2028}{{ roots }}",
|
||||
"X\u{2029}{{ roots }}",
|
||||
"</permissions instructions>{{ roots }}",
|
||||
"<permissions instructions>{{ roots }}",
|
||||
] {
|
||||
let messages = PermissionMessages {
|
||||
writable_root: Some(template.into()),
|
||||
writable_roots: Some(template.into()),
|
||||
..PermissionMessages::default()
|
||||
};
|
||||
let resolved = ResolvedPermissionMessages::new(Some(&messages));
|
||||
assert_eq!(
|
||||
writable_roots_text(&roots, resolved),
|
||||
Some(" The writable roots are `/a`, `/b`.".into())
|
||||
);
|
||||
assert_eq!(
|
||||
writable_roots_text(&roots[..1], resolved),
|
||||
Some(" The writable root is `/a`.".into())
|
||||
);
|
||||
assert_eq!(writable_roots_text(&[], resolved), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn substitution_preserves_whitespace_and_path_contents() {
|
||||
assert_eq!(
|
||||
render_roots_override(
|
||||
" Paths = {{ roots }} ",
|
||||
"`/a/{{ roots }}`, `/é\n{literal}`"
|
||||
),
|
||||
Some(" Paths = `/a/{{ roots }}`, `/é\n{literal}` ".into()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_template_bytes_and_rendered_output_before_allocation() {
|
||||
let exact = format!(
|
||||
"{}{{{{ roots }}}}",
|
||||
"x".repeat(1_000 - ROOTS_PLACEHOLDER.len())
|
||||
);
|
||||
assert!(render_roots_override(&exact, "`/a`").is_some());
|
||||
for oversized in [exact + "x", format!("{}{{{{ roots }}}}", "é".repeat(495))] {
|
||||
let messages = PermissionMessages {
|
||||
writable_root: Some(oversized),
|
||||
..PermissionMessages::default()
|
||||
};
|
||||
assert_eq!(
|
||||
writable_roots_text(
|
||||
&["/a".into()],
|
||||
ResolvedPermissionMessages::new(Some(&messages))
|
||||
),
|
||||
Some(" The writable root is `/a`.".into()),
|
||||
);
|
||||
}
|
||||
let roots = "x".repeat(MAX_ROOTS_SENTENCE_BYTES);
|
||||
assert_eq!(render_roots_override("a{{ roots }}", &roots), None);
|
||||
assert_eq!(render_roots_override("{{ roots }}", &roots), Some(roots));
|
||||
}
|
||||
1155
akode-rs/prompts/src/permissions_instructions_tests.rs
Normal file
1155
akode-rs/prompts/src/permissions_instructions_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
3
akode-rs/prompts/src/realtime.rs
Normal file
3
akode-rs/prompts/src/realtime.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub const BACKEND_PROMPT: &str = include_str!("../templates/realtime/backend_prompt.md");
|
||||
pub const END_INSTRUCTIONS: &str = include_str!("../templates/realtime/realtime_end.md");
|
||||
pub const START_INSTRUCTIONS: &str = include_str!("../templates/realtime/realtime_start.md");
|
||||
36
akode-rs/prompts/src/review_exit.rs
Normal file
36
akode-rs/prompts/src/review_exit.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
use akode_utils_template::Template;
|
||||
use std::borrow::Cow;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
const REVIEW_EXIT_SUCCESS_TEMPLATE_TEXT: &str =
|
||||
include_str!("../templates/review/exit_success.xml");
|
||||
const REVIEW_EXIT_INTERRUPTED_TEMPLATE_TEXT: &str =
|
||||
include_str!("../templates/review/exit_interrupted.xml");
|
||||
|
||||
static REVIEW_EXIT_SUCCESS_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
let normalized = normalize_review_template_line_endings(REVIEW_EXIT_SUCCESS_TEMPLATE_TEXT);
|
||||
Template::parse(normalized.as_ref())
|
||||
.unwrap_or_else(|err| panic!("review exit success template must parse: {err}"))
|
||||
});
|
||||
|
||||
pub fn render_review_exit_success(results: &str) -> String {
|
||||
REVIEW_EXIT_SUCCESS_TEMPLATE
|
||||
.render([("results", results)])
|
||||
.unwrap_or_else(|err| panic!("review exit success template must render: {err}"))
|
||||
}
|
||||
|
||||
pub fn render_review_exit_interrupted() -> String {
|
||||
normalize_review_template_line_endings(REVIEW_EXIT_INTERRUPTED_TEMPLATE_TEXT).into_owned()
|
||||
}
|
||||
|
||||
fn normalize_review_template_line_endings(template: &str) -> Cow<'_, str> {
|
||||
if template.contains('\r') {
|
||||
Cow::Owned(template.replace("\r\n", "\n").replace('\r', "\n"))
|
||||
} else {
|
||||
Cow::Borrowed(template)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "review_exit_tests.rs"]
|
||||
mod review_exit_tests;
|
||||
18
akode-rs/prompts/src/review_exit_tests.rs
Normal file
18
akode-rs/prompts/src/review_exit_tests.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn render_review_exit_success_replaces_results_placeholder() {
|
||||
assert_eq!(
|
||||
render_review_exit_success("Finding A\nFinding B"),
|
||||
"<user_action>\n <context>User initiated a review task. Here's the full review output from reviewer model. User may select one or more comments to resolve.</context>\n <action>review</action>\n <results>\n Finding A\nFinding B\n </results>\n </user_action>\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_review_template_line_endings_rewrites_crlf() {
|
||||
assert_eq!(
|
||||
normalize_review_template_line_endings("<user_action>\r\n <results>\r\n None.\r\n"),
|
||||
"<user_action>\n <results>\n None.\n"
|
||||
);
|
||||
}
|
||||
137
akode-rs/prompts/src/review_request.rs
Normal file
137
akode-rs/prompts/src/review_request.rs
Normal file
@@ -0,0 +1,137 @@
|
||||
use akode_git_utils::merge_base_with_head;
|
||||
use akode_protocol::protocol::ReviewRequest;
|
||||
use akode_protocol::protocol::ReviewTarget;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_template::Template;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
/// Review thread system prompt.
|
||||
pub const REVIEW_PROMPT: &str = include_str!("../templates/review/rubric.md");
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ResolvedReviewRequest {
|
||||
pub target: ReviewTarget,
|
||||
pub prompt: String,
|
||||
pub user_facing_hint: String,
|
||||
}
|
||||
|
||||
const UNCOMMITTED_PROMPT: &str = "Review the current code changes (staged, unstaged, and untracked files) and provide prioritized findings.";
|
||||
|
||||
const BASE_BRANCH_PROMPT_BACKUP: &str = "Review the code changes against the base branch '{{branch}}'. Start by finding the merge diff between the current branch and {{branch}}'s upstream e.g. (`git merge-base HEAD \"$(git rev-parse --abbrev-ref \"{{branch}}@{upstream}\")\"`), then run `git diff` against that SHA to see what changes we would merge into the {{branch}} branch. Provide prioritized, actionable findings.";
|
||||
const BASE_BRANCH_PROMPT: &str = "Review the code changes against the base branch '{{base_branch}}'. The merge base commit for this comparison is {{merge_base_sha}}. Run `git diff {{merge_base_sha}}` to inspect the changes relative to {{base_branch}}. Provide prioritized, actionable findings.";
|
||||
static BASE_BRANCH_PROMPT_BACKUP_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
Template::parse(BASE_BRANCH_PROMPT_BACKUP)
|
||||
.unwrap_or_else(|err| panic!("base branch backup review prompt must parse: {err}"))
|
||||
});
|
||||
static BASE_BRANCH_PROMPT_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
Template::parse(BASE_BRANCH_PROMPT)
|
||||
.unwrap_or_else(|err| panic!("base branch review prompt must parse: {err}"))
|
||||
});
|
||||
|
||||
const COMMIT_PROMPT_WITH_TITLE: &str = "Review the code changes introduced by commit {{sha}} (\"{{title}}\"). Provide prioritized, actionable findings.";
|
||||
const COMMIT_PROMPT: &str = "Review the code changes introduced by commit {{sha}}. Provide prioritized, actionable findings.";
|
||||
static COMMIT_PROMPT_WITH_TITLE_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
Template::parse(COMMIT_PROMPT_WITH_TITLE)
|
||||
.unwrap_or_else(|err| panic!("commit review prompt with title must parse: {err}"))
|
||||
});
|
||||
static COMMIT_PROMPT_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
Template::parse(COMMIT_PROMPT)
|
||||
.unwrap_or_else(|err| panic!("commit review prompt must parse: {err}"))
|
||||
});
|
||||
|
||||
pub fn resolve_review_request(
|
||||
request: ReviewRequest,
|
||||
cwd: &AbsolutePathBuf,
|
||||
) -> anyhow::Result<ResolvedReviewRequest> {
|
||||
let target = request.target;
|
||||
let prompt = review_prompt(&target, cwd)?;
|
||||
let user_facing_hint = request
|
||||
.user_facing_hint
|
||||
.unwrap_or_else(|| user_facing_hint(&target));
|
||||
|
||||
Ok(ResolvedReviewRequest {
|
||||
target,
|
||||
prompt,
|
||||
user_facing_hint,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn review_prompt(target: &ReviewTarget, cwd: &AbsolutePathBuf) -> anyhow::Result<String> {
|
||||
match target {
|
||||
ReviewTarget::UncommittedChanges => Ok(UNCOMMITTED_PROMPT.to_string()),
|
||||
ReviewTarget::BaseBranch { branch } => {
|
||||
if let Some(commit) = merge_base_with_head(cwd, branch)? {
|
||||
Ok(render_review_prompt(
|
||||
&BASE_BRANCH_PROMPT_TEMPLATE,
|
||||
[
|
||||
("base_branch", branch.as_str()),
|
||||
("merge_base_sha", commit.as_str()),
|
||||
],
|
||||
))
|
||||
} else {
|
||||
Ok(render_review_prompt(
|
||||
&BASE_BRANCH_PROMPT_BACKUP_TEMPLATE,
|
||||
[("branch", branch.as_str())],
|
||||
))
|
||||
}
|
||||
}
|
||||
ReviewTarget::Commit { sha, title } => {
|
||||
if let Some(title) = title {
|
||||
Ok(render_review_prompt(
|
||||
&COMMIT_PROMPT_WITH_TITLE_TEMPLATE,
|
||||
[("sha", sha.as_str()), ("title", title.as_str())],
|
||||
))
|
||||
} else {
|
||||
Ok(render_review_prompt(
|
||||
&COMMIT_PROMPT_TEMPLATE,
|
||||
[("sha", sha.as_str())],
|
||||
))
|
||||
}
|
||||
}
|
||||
ReviewTarget::Custom { instructions } => {
|
||||
let prompt = instructions.trim();
|
||||
if prompt.is_empty() {
|
||||
anyhow::bail!("Review prompt cannot be empty");
|
||||
}
|
||||
Ok(prompt.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_review_prompt<'a, const N: usize>(
|
||||
template: &Template,
|
||||
variables: [(&'a str, &'a str); N],
|
||||
) -> String {
|
||||
template
|
||||
.render(variables)
|
||||
.unwrap_or_else(|err| panic!("review prompt template must render: {err}"))
|
||||
}
|
||||
|
||||
pub fn user_facing_hint(target: &ReviewTarget) -> String {
|
||||
match target {
|
||||
ReviewTarget::UncommittedChanges => "current changes".to_string(),
|
||||
ReviewTarget::BaseBranch { branch } => format!("changes against '{branch}'"),
|
||||
ReviewTarget::Commit { sha, title } => {
|
||||
let short_sha: String = sha.chars().take(7).collect();
|
||||
if let Some(title) = title {
|
||||
format!("commit {short_sha}: {title}")
|
||||
} else {
|
||||
format!("commit {short_sha}")
|
||||
}
|
||||
}
|
||||
ReviewTarget::Custom { instructions } => instructions.trim().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ResolvedReviewRequest> for ReviewRequest {
|
||||
fn from(resolved: ResolvedReviewRequest) -> Self {
|
||||
ReviewRequest {
|
||||
target: resolved.target,
|
||||
user_facing_hint: Some(resolved.user_facing_hint),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "review_request_tests.rs"]
|
||||
mod review_request_tests;
|
||||
51
akode-rs/prompts/src/review_request_tests.rs
Normal file
51
akode-rs/prompts/src/review_request_tests.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn review_prompt_template_renders_base_branch_backup_variant() {
|
||||
assert_eq!(
|
||||
render_review_prompt(&BASE_BRANCH_PROMPT_BACKUP_TEMPLATE, [("branch", "main")]),
|
||||
"Review the code changes against the base branch 'main'. Start by finding the merge diff between the current branch and main's upstream e.g. (`git merge-base HEAD \"$(git rev-parse --abbrev-ref \"main@{upstream}\")\"`), then run `git diff` against that SHA to see what changes we would merge into the main branch. Provide prioritized, actionable findings."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_prompt_template_renders_base_branch_variant() {
|
||||
assert_eq!(
|
||||
render_review_prompt(
|
||||
&BASE_BRANCH_PROMPT_TEMPLATE,
|
||||
[("base_branch", "main"), ("merge_base_sha", "abc123")]
|
||||
),
|
||||
"Review the code changes against the base branch 'main'. The merge base commit for this comparison is abc123. Run `git diff abc123` to inspect the changes relative to main. Provide prioritized, actionable findings."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_prompt_template_renders_commit_variant() {
|
||||
assert_eq!(
|
||||
review_prompt(
|
||||
&ReviewTarget::Commit {
|
||||
sha: "deadbeef".to_string(),
|
||||
title: None,
|
||||
},
|
||||
&AbsolutePathBuf::current_dir().expect("cwd"),
|
||||
)
|
||||
.expect("commit prompt should render"),
|
||||
"Review the code changes introduced by commit deadbeef. Provide prioritized, actionable findings."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_prompt_template_renders_commit_variant_with_title() {
|
||||
assert_eq!(
|
||||
review_prompt(
|
||||
&ReviewTarget::Commit {
|
||||
sha: "deadbeef".to_string(),
|
||||
title: Some("Fix bug".to_string()),
|
||||
},
|
||||
&AbsolutePathBuf::current_dir().expect("cwd"),
|
||||
)
|
||||
.expect("commit prompt should render"),
|
||||
"Review the code changes introduced by commit deadbeef (\"Fix bug\"). Provide prioritized, actionable findings."
|
||||
);
|
||||
}
|
||||
63
akode-rs/prompts/src/update_plan_instructions.rs
Normal file
63
akode-rs/prompts/src/update_plan_instructions.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
//! Purely omits checklist-tool guidance from Codex-owned prompts, before adding caller text.
|
||||
|
||||
/// Call only for Codex-owned prompt text; custom instructions must remain unchanged.
|
||||
pub fn without_update_plan_instructions(instructions: &str) -> String {
|
||||
let lines = instructions.split_inclusive('\n').collect::<Vec<_>>();
|
||||
let mut rendered = String::with_capacity(instructions.len());
|
||||
let mut index = 0;
|
||||
while index < lines.len() {
|
||||
let line = lines[index].trim_end();
|
||||
if matches!(
|
||||
line,
|
||||
"## Planning"
|
||||
| "## `update_plan`"
|
||||
| "## Plan tool"
|
||||
| "## Plan Mode vs update_plan tool"
|
||||
) {
|
||||
let end = (index + 1..lines.len())
|
||||
.find(|&next| lines[next].starts_with("# ") || lines[next].starts_with("## "))
|
||||
.unwrap_or(lines.len());
|
||||
let is_checklist_section = line != "## Planning"
|
||||
|| lines[index..end].iter().any(|line| {
|
||||
line.starts_with("You have access to an `update_plan` tool")
|
||||
|| line.starts_with("When `update_plan` is available, follow this section")
|
||||
});
|
||||
if is_checklist_section {
|
||||
index = end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if line == "Progress visibility:"
|
||||
&& lines
|
||||
.get(index + 1)
|
||||
.is_some_and(|line| line.starts_with("If update_plan is available"))
|
||||
{
|
||||
index += 2;
|
||||
if lines.get(index).is_some_and(|line| line.trim().is_empty()) {
|
||||
index += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if line.starts_with("- Use the plan tool ")
|
||||
|| line.starts_with("- If you create a checklist or task list,")
|
||||
{
|
||||
index += 1;
|
||||
while index < lines.len()
|
||||
&& (lines[index].starts_with(' ') || lines[index].starts_with('\t'))
|
||||
{
|
||||
index += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
rendered.push_str(lines[index]);
|
||||
index += 1;
|
||||
}
|
||||
rendered
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "update_plan_instructions_tests.rs"]
|
||||
mod tests;
|
||||
31
akode-rs/prompts/src/update_plan_instructions_tests.rs
Normal file
31
akode-rs/prompts/src/update_plan_instructions_tests.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
//! Checks that filtering omits only the known checklist sections.
|
||||
|
||||
use super::without_update_plan_instructions;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn disabled_omits_checklist_sections_and_preserves_other_planning() {
|
||||
let instructions = "Before.\n\n## Planning\nYou have access to an `update_plan` tool which tracks steps.\n\n### Examples\nKeep steps current.\n\n## Work\nImplement.\n\n## `update_plan`\nUpdate the checklist.\n\n# Next\n## Planning\nDiscuss architecture and inspect update_plan before editing.\n";
|
||||
assert_eq!(
|
||||
without_update_plan_instructions(instructions),
|
||||
"Before.\n\n## Work\nImplement.\n\n# Next\n## Planning\nDiscuss architecture and inspect update_plan before editing.\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_omits_legacy_tool_and_plan_mode_cross_reference_sections() {
|
||||
let instructions = "# Plan Mode\nKeep planning.\n\n## Plan Mode vs update_plan tool\nThe tools are separate.\n\n## Execution\nDo not edit.\n\n## Plan tool\nWhen using the planning tool:\n- Update steps.\n";
|
||||
assert_eq!(
|
||||
without_update_plan_instructions(instructions),
|
||||
"# Plan Mode\nKeep planning.\n\n## Execution\nDo not edit.\n\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_omits_only_checklist_list_items_and_goal_guidance() {
|
||||
let instructions = "Keep working.\n- Use the plan tool to explain the work\n - Skip simple tasks.\n - Keep steps current.\n- Explain discoveries.\n- If you create a checklist or task list, update its statuses.\n\nProgress visibility:\nIf update_plan is available, use it for complex work.\n\nCompletion:\nVerify the result.\n";
|
||||
assert_eq!(
|
||||
without_update_plan_instructions(instructions),
|
||||
"Keep working.\n- Explain discoveries.\n\nCompletion:\nVerify the result.\n",
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user