1use std::borrow::Cow;
20use std::collections::BTreeMap;
21use std::fmt::Debug;
22use std::marker::PhantomData;
23
24use askama::Template;
25use serde::de::DeserializeOwned;
26use serde::{Deserialize, Serialize};
27use sha2::{Digest, Sha256};
28
29#[derive(Template)]
31#[template(path = "tagged_block.txt", escape = "none")]
32pub(crate) struct TaggedBlockTemplate<'a> {
33 pub(crate) tag: &'a str,
34 pub(crate) content: &'a str,
35}
36
37impl TaggedBlockTemplate<'_> {
38 pub(crate) fn into_text(self) -> String {
39 self.render().expect("tagged block template must render")
40 }
41}
42
43mod sealed {
44 pub trait Sealed {}
45}
46
47pub trait BlockKind: sealed::Sealed + Debug + Clone + PartialEq + Eq + Ord {
50 type Content: Debug + Clone + PartialEq + Serialize + DeserializeOwned;
52
53 const REGION: &'static str;
55
56 fn text(content: &Self::Content) -> &str;
58}
59
60#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
62pub struct Instruction;
63
64impl sealed::Sealed for Instruction {}
65
66impl BlockKind for Instruction {
67 type Content = String;
68 const REGION: &'static str = "instruction";
69
70 fn text(content: &Self::Content) -> &str {
71 content
72 }
73}
74
75#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
77pub struct External;
78
79impl sealed::Sealed for External {}
80
81impl BlockKind for External {
82 type Content = ExternalContent;
83 const REGION: &'static str = "external";
84
85 fn text(content: &Self::Content) -> &str {
86 &content.content
87 }
88}
89
90#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
93pub struct Sourced;
94
95impl sealed::Sealed for Sourced {}
96
97impl BlockKind for Sourced {
98 type Content = String;
99 const REGION: &'static str = "live source";
100
101 fn text(content: &Self::Content) -> &str {
102 content
103 }
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
111#[serde(transparent)]
112pub struct Slot<K> {
113 name: Cow<'static, str>,
114 #[serde(skip)]
115 kind: PhantomData<fn() -> K>,
116}
117
118pub type InstructionSlot = Slot<Instruction>;
120
121pub type ExternalSlot = Slot<External>;
123
124pub type SourcedSlot = Slot<Sourced>;
127
128impl<K> Slot<K> {
129 #[must_use]
132 pub const fn new(name: &'static str) -> Self {
133 Self {
134 name: Cow::Borrowed(name),
135 kind: PhantomData,
136 }
137 }
138
139 pub(crate) fn owned(name: String) -> Self {
141 Self {
142 name: Cow::Owned(name),
143 kind: PhantomData,
144 }
145 }
146
147 #[must_use]
149 pub fn name(&self) -> &str {
150 &self.name
151 }
152}
153
154#[cfg(test)]
155impl InstructionSlot {
156 pub(crate) const BASE_SYSTEM: Self = Self::new("base_system");
157 pub(crate) const PERSONA: Self = Self::new("persona");
158 pub(crate) const PERMISSIONS: Self = Self::new("permissions");
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct SystemLayout {
170 instructions: Vec<InstructionSlot>,
171 external: Vec<ExternalSlot>,
172}
173
174impl SystemLayout {
175 #[must_use]
182 pub fn new(
183 instructions: impl IntoIterator<Item = InstructionSlot>,
184 external: impl IntoIterator<Item = ExternalSlot>,
185 ) -> Self {
186 Self {
187 instructions: unique_slots(instructions),
188 external: unique_slots(external),
189 }
190 }
191
192 #[must_use]
194 pub fn instructions(&self) -> &[InstructionSlot] {
195 &self.instructions
196 }
197
198 #[must_use]
200 pub fn external(&self) -> &[ExternalSlot] {
201 &self.external
202 }
203
204 pub(crate) fn into_regions(self) -> (Vec<InstructionSlot>, Vec<ExternalSlot>) {
206 (self.instructions, self.external)
207 }
208}
209
210impl Default for SystemLayout {
211 fn default() -> Self {
214 Self::new([], [])
215 }
216}
217
218fn unique_slots<K: BlockKind>(slots: impl IntoIterator<Item = Slot<K>>) -> Vec<Slot<K>> {
219 let slots: Vec<Slot<K>> = slots.into_iter().collect();
220 for (index, slot) in slots.iter().enumerate() {
221 assert!(
222 !slots[..index].contains(slot),
223 "{} slot `{}` is laid out twice",
224 K::REGION,
225 slot.name()
226 );
227 }
228 slots
229}
230
231#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
234#[serde(bound(
235 serialize = "K::Content: Serialize",
236 deserialize = "K::Content: DeserializeOwned"
237))]
238pub struct SystemRegion<K: BlockKind> {
239 order: Vec<Slot<K>>,
240 blocks: BTreeMap<Slot<K>, K::Content>,
241 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
248 staged: BTreeMap<Slot<K>, Option<K::Content>>,
249}
250
251#[derive(Debug)]
254pub(crate) struct TextChange {
255 pub(crate) before: String,
256 pub(crate) after: String,
257}
258
259impl<K: BlockKind> SystemRegion<K> {
260 pub(crate) const fn with_order(order: Vec<Slot<K>>) -> Self {
261 Self {
262 order,
263 blocks: BTreeMap::new(),
264 staged: BTreeMap::new(),
265 }
266 }
267
268 pub(crate) fn set_order(&mut self, order: Vec<Slot<K>>) {
274 self.order = order;
275 for slot in self.blocks.keys().chain(self.staged.keys()) {
276 self.assert_placed(slot);
277 }
278 }
279
280 pub(crate) fn place(&mut self, slot: Slot<K>) {
282 if !self.order.contains(&slot) {
283 self.order.push(slot);
284 }
285 }
286
287 fn assert_placed(&self, slot: &Slot<K>) {
288 assert!(
289 self.order.contains(slot),
290 "{} block `{}` has no slot in the system layout",
291 K::REGION,
292 slot.name()
293 );
294 }
295
296 #[must_use]
298 pub fn order(&self) -> &[Slot<K>] {
299 &self.order
300 }
301
302 pub fn insert(&mut self, slot: &Slot<K>, content: impl Into<K::Content>) {
308 self.assert_placed(slot);
309 self.blocks.insert(slot.clone(), content.into());
310 }
311
312 pub fn remove(&mut self, slot: &Slot<K>) -> Option<K::Content> {
314 self.staged.remove(slot);
315 self.blocks.remove(slot)
316 }
317
318 #[must_use]
320 pub fn get(&self, slot: &Slot<K>) -> Option<&K::Content> {
321 self.blocks.get(slot)
322 }
323
324 #[must_use]
326 pub fn contains(&self, slot: &Slot<K>) -> bool {
327 self.blocks.contains_key(slot)
328 }
329
330 #[must_use]
332 pub fn len(&self) -> usize {
333 self.blocks.len()
334 }
335
336 #[must_use]
338 pub fn is_empty(&self) -> bool {
339 self.blocks.is_empty()
340 }
341
342 pub fn iter(&self) -> impl Iterator<Item = (&Slot<K>, &K::Content)> {
344 self.order
345 .iter()
346 .filter_map(|slot| self.blocks.get(slot).map(|content| (slot, content)))
347 }
348
349 fn known(&self, slot: &Slot<K>) -> Option<&K::Content> {
352 self.staged
353 .get(slot)
354 .map_or_else(|| self.blocks.get(slot), Option::as_ref)
355 }
356
357 pub(crate) fn change(
369 &mut self,
370 slot: &Slot<K>,
371 desired: Option<K::Content>,
372 warm: bool,
373 ) -> Option<TextChange> {
374 self.assert_placed(slot);
375 let known = self.known(slot);
376 if known == desired.as_ref() {
377 return None;
378 }
379 if warm {
380 let change = TextChange {
381 before: known.map_or("", K::text).to_owned(),
382 after: desired.as_ref().map_or("", K::text).to_owned(),
383 };
384 if self.blocks.get(slot) == desired.as_ref() {
385 self.staged.remove(slot);
386 } else {
387 self.staged.insert(slot.clone(), desired);
388 }
389 return (change.before != change.after).then_some(change);
390 }
391 self.staged.remove(slot);
392 match desired {
393 Some(content) => self.blocks.insert(slot.clone(), content),
394 None => self.blocks.remove(slot),
395 };
396 None
397 }
398
399 #[must_use]
401 pub fn has_staged(&self) -> bool {
402 !self.staged.is_empty()
403 }
404
405 pub(crate) fn apply_staged(&mut self) -> (usize, usize) {
408 let mut applied = 0;
409 let mut freed = 0;
410 for (slot, content) in std::mem::take(&mut self.staged) {
411 let before = self
412 .blocks
413 .get(&slot)
414 .map_or(0, |block| K::text(block).len());
415 let after = content.as_ref().map_or(0, |block| K::text(block).len());
416 freed += before.saturating_sub(after);
417 match content {
418 Some(content) => self.blocks.insert(slot, content),
419 None => self.blocks.remove(&slot),
420 };
421 applied += 1;
422 }
423 (applied, freed)
424 }
425
426 pub(crate) fn clear(&mut self) {
428 self.blocks.clear();
429 self.staged.clear();
430 }
431}
432
433impl SystemRegion<Instruction> {
434 pub fn insert_tagged(&mut self, slot: &InstructionSlot, content: &str) {
441 let wrapped = TaggedBlockTemplate {
442 tag: slot.name(),
443 content,
444 }
445 .into_text();
446 self.insert(slot, wrapped);
447 }
448}
449
450#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
452#[serde(rename_all = "snake_case")]
453enum ExternalKind {
454 Data,
456 RepositoryInstructions,
459}
460
461impl ExternalKind {
462 const fn label(self) -> &'static str {
463 match self {
464 Self::Data => "data",
465 Self::RepositoryInstructions => "repository-instructions",
466 }
467 }
468}
469
470#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
477pub struct ExternalContent {
478 kind: ExternalKind,
479 source: String,
480 content: String,
481}
482
483impl ExternalContent {
484 #[must_use]
486 pub fn data(source: impl Into<String>, content: impl Into<String>) -> Self {
487 Self {
488 kind: ExternalKind::Data,
489 source: source.into(),
490 content: content.into(),
491 }
492 }
493
494 #[must_use]
497 pub fn repository_instructions(source: impl Into<String>, content: impl Into<String>) -> Self {
498 Self {
499 kind: ExternalKind::RepositoryInstructions,
500 source: source.into(),
501 content: content.into(),
502 }
503 }
504
505 #[must_use]
507 pub fn source(&self) -> &str {
508 &self.source
509 }
510
511 #[must_use]
513 pub fn content(&self) -> &str {
514 &self.content
515 }
516
517 #[must_use]
519 pub const fn is_repository_instructions(&self) -> bool {
520 matches!(self.kind, ExternalKind::RepositoryInstructions)
521 }
522
523 fn boundary(&self) -> String {
530 boundary(&[self.kind.label(), &self.source, &self.content])
531 }
532}
533
534pub(crate) fn boundary(parts: &[&str]) -> String {
537 let mut attempt: u64 = 0;
538 loop {
539 let mut hasher = Sha256::new();
540 for (index, part) in parts.iter().enumerate() {
541 if index > 0 {
542 hasher.update([0]);
543 }
544 hasher.update(part);
545 }
546 hasher.update(attempt.to_le_bytes());
547 let candidate = crate::agent::hex_encode(&hasher.finalize()[..8]);
548 if parts.iter().all(|part| !part.contains(&candidate)) {
549 return candidate;
550 }
551 attempt += 1;
552 }
553}
554
555impl ExternalContent {
556 fn view(&self) -> ExternalBlockView<'_> {
558 ExternalBlockView {
559 boundary: self.boundary(),
560 kind: self.kind.label(),
561 source: &self.source,
562 content: &self.content,
563 }
564 }
565
566 #[must_use]
579 pub fn render(&self) -> String {
580 ExternalBlockTemplate { block: self.view() }
581 .render()
582 .expect("external block template must render")
583 }
584
585 pub(crate) fn render_with_notice(&self) -> String {
588 ExternalAlertTemplate { block: self.view() }
589 .render()
590 .expect("external alert template must render")
591 }
592}
593
594struct ExternalBlockView<'a> {
596 boundary: String,
597 kind: &'static str,
598 source: &'a str,
599 content: &'a str,
600}
601
602#[derive(Template)]
604#[template(path = "external_block.txt", escape = "none")]
605struct ExternalBlockTemplate<'a> {
606 block: ExternalBlockView<'a>,
607}
608
609#[derive(Template)]
611#[template(path = "external_alert.txt", escape = "none")]
612struct ExternalAlertTemplate<'a> {
613 block: ExternalBlockView<'a>,
614}
615
616#[derive(Template)]
618#[template(path = "system_prefix.txt", escape = "none")]
619struct SystemPrefixTemplate<'a> {
620 instructions: Vec<&'a str>,
621 external: Vec<ExternalBlockView<'a>>,
622}
623
624pub(crate) fn render_prefix(
627 instructions: &SystemRegion<Instruction>,
628 external: &SystemRegion<External>,
629) -> Option<String> {
630 if instructions.is_empty() && external.is_empty() {
631 return None;
632 }
633 let template = SystemPrefixTemplate {
634 instructions: instructions.iter().map(|(_, text)| text.as_str()).collect(),
635 external: external.iter().map(|(_, block)| block.view()).collect(),
636 };
637 Some(
638 template
639 .render()
640 .expect("system prefix template must render"),
641 )
642}