use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt::Debug;
use std::marker::PhantomData;
use askama::Template;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
#[derive(Template)]
#[template(path = "tagged_block.txt", escape = "none")]
pub(crate) struct TaggedBlockTemplate<'a> {
pub(crate) tag: &'a str,
pub(crate) content: &'a str,
}
impl TaggedBlockTemplate<'_> {
pub(crate) fn into_text(self) -> String {
self.render().expect("tagged block template must render")
}
}
mod sealed {
pub trait Sealed {}
}
pub trait BlockKind: sealed::Sealed + Debug + Clone + PartialEq + Eq + Ord {
type Content: Debug + Clone + PartialEq + Serialize + DeserializeOwned;
const REGION: &'static str;
fn content_len(content: &Self::Content) -> usize;
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Instruction;
impl sealed::Sealed for Instruction {}
impl BlockKind for Instruction {
type Content = String;
const REGION: &'static str = "instruction";
fn content_len(content: &Self::Content) -> usize {
content.len()
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct External;
impl sealed::Sealed for External {}
impl BlockKind for External {
type Content = ExternalContent;
const REGION: &'static str = "external";
fn content_len(content: &Self::Content) -> usize {
content.content.len()
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Slot<K> {
name: Cow<'static, str>,
#[serde(skip)]
kind: PhantomData<fn() -> K>,
}
pub type InstructionSlot = Slot<Instruction>;
pub type ExternalSlot = Slot<External>;
impl<K> Slot<K> {
#[must_use]
pub const fn new(name: &'static str) -> Self {
Self {
name: Cow::Borrowed(name),
kind: PhantomData,
}
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
}
impl InstructionSlot {
pub const BASE_SYSTEM: Self = Self::new("base_system");
pub const PERSONA: Self = Self::new("persona");
pub const PREPARED_TOOLS: Self = Self::new("prepared_tools");
pub const SHELL_RUNTIME: Self = Self::new("shell_runtime");
pub const WORKSPACE_FACTS: Self = Self::new("workspace_facts");
pub const KNOWLEDGE_AND_TIME: Self = Self::new("knowledge_and_time");
pub const PERMISSIONS: Self = Self::new("permissions");
#[cfg(feature = "languages")]
pub const LANGUAGES: Self = Self::new("languages");
#[cfg(not(feature = "languages"))]
pub const BUILTIN: [Self; 7] = [
Self::BASE_SYSTEM,
Self::PERSONA,
Self::PREPARED_TOOLS,
Self::SHELL_RUNTIME,
Self::WORKSPACE_FACTS,
Self::KNOWLEDGE_AND_TIME,
Self::PERMISSIONS,
];
#[cfg(feature = "languages")]
pub const BUILTIN: [Self; 8] = [
Self::BASE_SYSTEM,
Self::PERSONA,
Self::PREPARED_TOOLS,
Self::SHELL_RUNTIME,
Self::WORKSPACE_FACTS,
Self::KNOWLEDGE_AND_TIME,
Self::PERMISSIONS,
Self::LANGUAGES,
];
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SystemLayout {
instructions: Vec<InstructionSlot>,
external: Vec<ExternalSlot>,
}
impl SystemLayout {
#[must_use]
pub fn new(
instructions: impl IntoIterator<Item = InstructionSlot>,
external: impl IntoIterator<Item = ExternalSlot>,
) -> Self {
Self {
instructions: unique_slots(instructions),
external: unique_slots(external),
}
}
#[must_use]
pub fn instructions(&self) -> &[InstructionSlot] {
&self.instructions
}
#[must_use]
pub fn external(&self) -> &[ExternalSlot] {
&self.external
}
pub(crate) fn into_regions(self) -> (Vec<InstructionSlot>, Vec<ExternalSlot>) {
(self.instructions, self.external)
}
}
impl Default for SystemLayout {
fn default() -> Self {
Self::new(InstructionSlot::BUILTIN, [])
}
}
fn unique_slots<K: BlockKind>(slots: impl IntoIterator<Item = Slot<K>>) -> Vec<Slot<K>> {
let slots: Vec<Slot<K>> = slots.into_iter().collect();
for (index, slot) in slots.iter().enumerate() {
assert!(
!slots[..index].contains(slot),
"{} slot `{}` is laid out twice",
K::REGION,
slot.name()
);
}
slots
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(bound(
serialize = "K::Content: Serialize",
deserialize = "K::Content: DeserializeOwned"
))]
pub struct SystemRegion<K: BlockKind> {
order: Vec<Slot<K>>,
blocks: BTreeMap<Slot<K>, K::Content>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
staged: BTreeMap<Slot<K>, K::Content>,
}
impl<K: BlockKind> SystemRegion<K> {
pub(crate) const fn with_order(order: Vec<Slot<K>>) -> Self {
Self {
order,
blocks: BTreeMap::new(),
staged: BTreeMap::new(),
}
}
pub(crate) fn set_order(&mut self, order: Vec<Slot<K>>) {
self.order = order;
for slot in self.blocks.keys().chain(self.staged.keys()) {
self.assert_placed(slot);
}
}
fn assert_placed(&self, slot: &Slot<K>) {
assert!(
self.order.contains(slot),
"{} block `{}` has no slot in the system layout",
K::REGION,
slot.name()
);
}
#[must_use]
pub fn order(&self) -> &[Slot<K>] {
&self.order
}
pub fn insert(&mut self, slot: &Slot<K>, content: impl Into<K::Content>) {
self.assert_placed(slot);
self.blocks.insert(slot.clone(), content.into());
}
pub fn remove(&mut self, slot: &Slot<K>) -> Option<K::Content> {
self.staged.remove(slot);
self.blocks.remove(slot)
}
#[must_use]
pub fn get(&self, slot: &Slot<K>) -> Option<&K::Content> {
self.blocks.get(slot)
}
#[must_use]
pub fn contains(&self, slot: &Slot<K>) -> bool {
self.blocks.contains_key(slot)
}
#[must_use]
pub fn len(&self) -> usize {
self.blocks.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.blocks.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = (&Slot<K>, &K::Content)> {
self.order
.iter()
.filter_map(|slot| self.blocks.get(slot).map(|content| (slot, content)))
}
pub fn stage(&mut self, slot: &Slot<K>, content: impl Into<K::Content>) -> bool {
self.assert_placed(slot);
let content = content.into();
match self.blocks.get(slot) {
Some(existing) if *existing == content => {
self.staged.remove(slot);
false
}
Some(_) => {
self.staged.insert(slot.clone(), content);
true
}
None => {
self.blocks.insert(slot.clone(), content);
false
}
}
}
#[must_use]
pub fn staged(&self, slot: &Slot<K>) -> Option<&K::Content> {
self.staged.get(slot)
}
#[must_use]
pub fn has_staged(&self) -> bool {
!self.staged.is_empty()
}
pub(crate) fn apply_staged(&mut self) -> (usize, usize) {
let mut applied = 0;
let mut freed = 0;
for (slot, content) in std::mem::take(&mut self.staged) {
if let Some(existing) = self.blocks.get(&slot) {
freed += K::content_len(existing).saturating_sub(K::content_len(&content));
}
self.blocks.insert(slot, content);
applied += 1;
}
(applied, freed)
}
pub(crate) fn clear(&mut self) {
self.blocks.clear();
self.staged.clear();
}
}
impl SystemRegion<Instruction> {
pub fn insert_tagged(&mut self, slot: &InstructionSlot, content: &str) {
let wrapped = TaggedBlockTemplate {
tag: slot.name(),
content,
}
.into_text();
self.insert(slot, wrapped);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum ExternalKind {
Data,
RepositoryInstructions,
}
impl ExternalKind {
const fn label(self) -> &'static str {
match self {
Self::Data => "data",
Self::RepositoryInstructions => "repository-instructions",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExternalContent {
kind: ExternalKind,
source: String,
content: String,
}
impl ExternalContent {
#[must_use]
pub fn data(source: impl Into<String>, content: impl Into<String>) -> Self {
Self {
kind: ExternalKind::Data,
source: source.into(),
content: content.into(),
}
}
#[must_use]
pub fn repository_instructions(source: impl Into<String>, content: impl Into<String>) -> Self {
Self {
kind: ExternalKind::RepositoryInstructions,
source: source.into(),
content: content.into(),
}
}
#[must_use]
pub fn source(&self) -> &str {
&self.source
}
#[must_use]
pub fn content(&self) -> &str {
&self.content
}
#[must_use]
pub const fn is_repository_instructions(&self) -> bool {
matches!(self.kind, ExternalKind::RepositoryInstructions)
}
fn boundary(&self) -> String {
let mut attempt: u64 = 0;
loop {
let digest = Sha256::new()
.chain_update(self.kind.label())
.chain_update([0])
.chain_update(&self.source)
.chain_update([0])
.chain_update(&self.content)
.chain_update(attempt.to_le_bytes())
.finalize();
let candidate = crate::agent::hex_encode(&digest[..8]);
if !self.source.contains(&candidate) && !self.content.contains(&candidate) {
return candidate;
}
attempt += 1;
}
}
}
struct ExternalBlockView<'a> {
boundary: String,
kind: &'static str,
source: &'a str,
content: &'a str,
}
#[derive(Template)]
#[template(path = "system_prefix.txt", escape = "none")]
struct SystemPrefixTemplate<'a> {
instructions: Vec<&'a str>,
external: Vec<ExternalBlockView<'a>>,
}
pub(crate) fn render_prefix(
instructions: &SystemRegion<Instruction>,
external: &SystemRegion<External>,
) -> Option<String> {
if instructions.is_empty() && external.is_empty() {
return None;
}
let template = SystemPrefixTemplate {
instructions: instructions.iter().map(|(_, text)| text.as_str()).collect(),
external: external
.iter()
.map(|(_, block)| ExternalBlockView {
boundary: block.boundary(),
kind: block.kind.label(),
source: &block.source,
content: &block.content,
})
.collect(),
};
Some(
template
.render()
.expect("system prefix template must render"),
)
}