lash-sansio 0.1.0-alpha.41

Sans-IO protocol kernel for the lash agent runtime. Pure types and state machine; no IO or async.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};

use crate::{PromptContribution, PromptTemplate};

/// Process-local cache identity for prompt inputs.
///
/// This intentionally uses Rust's default hasher because it only keys in-memory
/// prompt caches inside one process. Do not persist or compare it across
/// processes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PromptFingerprint(u64);

impl PromptFingerprint {
    fn from_hashable(value: impl Hash) -> Self {
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        value.hash(&mut hasher);
        Self(hasher.finish())
    }

    fn write(self, state: &mut impl Hasher) {
        self.0.hash(state);
    }
}

#[derive(Clone, Debug)]
pub struct PromptContributionSet {
    contributions: Arc<Vec<PromptContribution>>,
    fingerprint: PromptFingerprint,
}

impl PromptContributionSet {
    pub fn new(contributions: Vec<PromptContribution>) -> Self {
        let contributions = Arc::new(merge_prompt_contributions(contributions));
        let fingerprint = fingerprint_contributions(&contributions);
        Self {
            contributions,
            fingerprint,
        }
    }

    pub fn empty() -> Self {
        Self::new(Vec::new())
    }

    pub fn as_arc(&self) -> Arc<Vec<PromptContribution>> {
        Arc::clone(&self.contributions)
    }

    pub fn as_slice(&self) -> &[PromptContribution] {
        &self.contributions
    }

    pub fn fingerprint(&self) -> PromptFingerprint {
        self.fingerprint
    }
}

impl Default for PromptContributionSet {
    fn default() -> Self {
        Self::empty()
    }
}

#[derive(Clone, Debug)]
pub struct PromptBuildInput {
    pub template: PromptTemplate,
    pub template_fingerprint: PromptFingerprint,
    pub execution_prompt: Arc<str>,
    pub execution_prompt_fingerprint: PromptFingerprint,
    pub tool_names: Arc<Vec<String>>,
    pub tool_names_fingerprint: PromptFingerprint,
    pub omitted_tool_count: usize,
    pub contributions: PromptContributionSet,
}

#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct PromptContext {
    #[serde(default)]
    pub execution_prompt: Arc<str>,
    pub tool_names: Arc<Vec<String>>,
    pub omitted_tool_count: usize,
    pub contributions: Arc<Vec<PromptContribution>>,
}

impl PromptContext {
    pub fn has_tool(&self, tool_name: &str) -> bool {
        self.tool_names.iter().any(|name| name == tool_name)
    }
}

#[derive(Clone, Debug)]
pub struct PreparedPrompt {
    pub context: PromptContext,
    pub system_prompt: Arc<str>,
}

/// Single-slot memo for the rendered system prompt, keyed by a hash of
/// the inputs. Most consecutive turns in a session pass identical
/// inputs (template, turn-driver-preamble-derived `execution_prompt` /
/// `tool_names`, plus context contributions), so a one-slot cache hits
/// repeatedly and avoids the section-by-section `Vec<String>::join`
/// work in `PromptTemplate::render`.
#[derive(Default)]
pub struct PromptCache {
    inner: Mutex<Option<(u64, Arc<str>)>>,
}

impl PromptCache {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn clear(&self) {
        if let Ok(mut guard) = self.inner.lock() {
            *guard = None;
        }
    }
}

impl std::fmt::Debug for PromptCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PromptCache").finish_non_exhaustive()
    }
}

pub fn build_prompt(input: PromptBuildInput) -> PreparedPrompt {
    build_prompt_cached(input, None)
}

pub fn build_prompt_cached(input: PromptBuildInput, cache: Option<&PromptCache>) -> PreparedPrompt {
    let context = PromptContext {
        execution_prompt: Arc::clone(&input.execution_prompt),
        tool_names: Arc::clone(&input.tool_names),
        omitted_tool_count: input.omitted_tool_count,
        contributions: input.contributions.as_arc(),
    };
    let key = cache.map(|_| hash_prompt_inputs(&input, &context));
    if let (Some(cache), Some(key)) = (cache, key)
        && let Some(cached) = cache.inner.lock().ok().and_then(|guard| {
            guard
                .as_ref()
                .filter(|(k, _)| *k == key)
                .map(|(_, v)| Arc::clone(v))
        })
    {
        return PreparedPrompt {
            context,
            system_prompt: cached,
        };
    }
    let system_prompt: Arc<str> = Arc::from(input.template.render(&context));
    if let (Some(cache), Some(key)) = (cache, key)
        && let Ok(mut guard) = cache.inner.lock()
    {
        *guard = Some((key, Arc::clone(&system_prompt)));
    }
    PreparedPrompt {
        context,
        system_prompt,
    }
}

pub fn prompt_template_fingerprint(template: &PromptTemplate) -> PromptFingerprint {
    PromptFingerprint::from_hashable(template)
}

pub fn prompt_text_fingerprint(text: &str) -> PromptFingerprint {
    PromptFingerprint::from_hashable(text)
}

pub fn prompt_tool_names_fingerprint(tool_names: &[String]) -> PromptFingerprint {
    PromptFingerprint::from_hashable(tool_names)
}

fn hash_prompt_inputs(input: &PromptBuildInput, context: &PromptContext) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    input.template_fingerprint.write(&mut hasher);
    input.execution_prompt_fingerprint.write(&mut hasher);
    input.tool_names_fingerprint.write(&mut hasher);
    context.omitted_tool_count.hash(&mut hasher);
    input.contributions.fingerprint().write(&mut hasher);
    hasher.finish()
}

fn fingerprint_contributions(contributions: &[PromptContribution]) -> PromptFingerprint {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    for contribution in contributions {
        contribution.slot.hash(&mut hasher);
        contribution.priority.hash(&mut hasher);
        contribution.title.hash(&mut hasher);
        contribution.content.hash(&mut hasher);
    }
    PromptFingerprint(hasher.finish())
}

fn merge_prompt_contributions(contributions: Vec<PromptContribution>) -> Vec<PromptContribution> {
    let mut merged = contributions
        .into_iter()
        .filter_map(normalize_contribution)
        .collect::<Vec<_>>();

    merged.sort_by(|left, right| {
        slot_order(left.slot)
            .cmp(&slot_order(right.slot))
            .then(left.priority.cmp(&right.priority))
            .then_with(|| left.title.cmp(&right.title))
            .then_with(|| left.content.cmp(&right.content))
    });

    // Duplicates are adjacent after the sort, so `dedup_by` on &str
    // refs drops them without cloning anything.
    merged.dedup_by(|a, b| {
        slot_order(a.slot) == slot_order(b.slot)
            && a.priority == b.priority
            && a.title.as_deref() == b.title.as_deref()
            && a.content == b.content
    });
    merged
}

fn normalize_contribution(mut contribution: PromptContribution) -> Option<PromptContribution> {
    contribution.content = Arc::from(contribution.content.trim());
    if contribution.content.is_empty() {
        return None;
    }
    contribution.title = contribution
        .title
        .as_deref()
        .map(str::trim)
        .filter(|title| !title.is_empty())
        .map(Arc::from);
    Some(contribution)
}

fn slot_order(slot: crate::PromptSlot) -> usize {
    match slot {
        crate::PromptSlot::Intro => 0,
        crate::PromptSlot::Execution => 1,
        crate::PromptSlot::Guidance => 2,
        crate::PromptSlot::ProjectInstructions => 3,
        crate::PromptSlot::RuntimeContext => 4,
        crate::PromptSlot::Environment => 5,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        PromptBuiltin, PromptContribution, PromptLayer, PromptSlot, PromptTemplate,
        PromptTemplateEntry, PromptTemplateSection, default_prompt_template, resolve_prompt_layers,
    };

    fn input(
        template: PromptTemplate,
        execution_prompt: &str,
        tool_names: Vec<String>,
        omitted_tool_count: usize,
        contributions: Vec<PromptContribution>,
    ) -> PromptBuildInput {
        let execution_prompt: Arc<str> = Arc::from(execution_prompt);
        let tool_names = Arc::new(tool_names);
        PromptBuildInput {
            template_fingerprint: prompt_template_fingerprint(&template),
            template,
            execution_prompt_fingerprint: prompt_text_fingerprint(&execution_prompt),
            execution_prompt,
            tool_names_fingerprint: prompt_tool_names_fingerprint(&tool_names),
            tool_names,
            omitted_tool_count,
            contributions: PromptContributionSet::new(contributions),
        }
    }

    #[test]
    fn build_prompt_renders_template_from_merged_context() {
        let prepared = build_prompt(input(
            default_prompt_template(),
            "Use tools.",
            vec!["read_file".to_string()],
            0,
            vec![
                PromptContribution::guidance("Repo", "Follow repo rules."),
                PromptContribution::guidance("Repo", "Follow repo rules."),
                PromptContribution::project_instructions("Be careful."),
            ],
        ));

        assert!(prepared.system_prompt.contains("Use tools."));
        assert!(prepared.system_prompt.contains("Follow repo rules."));
        assert!(prepared.system_prompt.contains("Be careful."));
        assert_eq!(prepared.context.contributions.len(), 2);
    }

    #[test]
    fn build_prompt_cached_reuses_arc_on_identical_inputs() {
        let cache = PromptCache::new();
        let inputs = || {
            input(
                default_prompt_template(),
                "Use tools.",
                vec!["read_file".to_string()],
                0,
                vec![PromptContribution::guidance("Repo", "Follow repo rules.")],
            )
        };
        let first = build_prompt_cached(inputs(), Some(&cache));
        let second = build_prompt_cached(inputs(), Some(&cache));
        assert!(Arc::ptr_eq(&first.system_prompt, &second.system_prompt));
    }

    #[test]
    fn build_prompt_cached_renders_again_when_inputs_change() {
        let cache = PromptCache::new();
        let first = build_prompt_cached(
            input(
                default_prompt_template(),
                "Use tools.",
                vec!["read_file".to_string()],
                0,
                vec![],
            ),
            Some(&cache),
        );
        let second = build_prompt_cached(
            input(
                default_prompt_template(),
                "Use other tools.",
                vec!["read_file".to_string()],
                0,
                vec![],
            ),
            Some(&cache),
        );
        assert!(!Arc::ptr_eq(&first.system_prompt, &second.system_prompt));
        assert_ne!(first.system_prompt, second.system_prompt);
    }

    fn template_with_text(text: &str) -> PromptTemplate {
        PromptTemplate::new(vec![PromptTemplateSection::untitled(vec![
            PromptTemplateEntry::text(text),
            PromptTemplateEntry::builtin(PromptBuiltin::ExecutionInstructions),
        ])])
    }

    fn content(contributions: &[PromptContribution]) -> Vec<&str> {
        contributions
            .iter()
            .map(|contribution| contribution.content.as_ref())
            .collect()
    }

    #[test]
    fn prompt_layers_use_later_template() {
        let core = PromptLayer::with_template(template_with_text("core"));
        let session = PromptLayer::with_template(template_with_text("session"));
        let resolved = resolve_prompt_layers([&core, &session]);

        let rendered = resolved.template.render(&PromptContext {
            execution_prompt: Arc::from("execute"),
            ..PromptContext::default()
        });
        assert!(rendered.contains("session"));
        assert!(!rendered.contains("core"));
    }

    #[test]
    fn prompt_layers_append_inherited_slot_content() {
        let core =
            PromptLayer::new().with_contribution(PromptContribution::guidance("Core", "core"));
        let session = PromptLayer::new()
            .with_contribution(PromptContribution::guidance("Session", "session"));

        let resolved = resolve_prompt_layers([&core, &session]);
        assert_eq!(content(&resolved.contributions), vec!["core", "session"]);
    }

    #[test]
    fn prompt_layers_clear_one_slot_without_touching_others() {
        let core = PromptLayer::new()
            .with_contribution(PromptContribution::guidance("Guide", "guide"))
            .with_contribution(PromptContribution::project_instructions("project"));
        let session = PromptLayer::new().with_cleared_slot(PromptSlot::Guidance);

        let resolved = resolve_prompt_layers([&core, &session]);
        assert_eq!(content(&resolved.contributions), vec!["project"]);
    }

    #[test]
    fn prompt_layers_replace_slot_and_normalize_contribution_slot() {
        let core =
            PromptLayer::new().with_contribution(PromptContribution::guidance("Guide", "old"));
        let session = PromptLayer::new().with_replaced_slot(
            PromptSlot::Guidance,
            [PromptContribution::project_instructions("new")],
        );

        let resolved = resolve_prompt_layers([&core, &session]);
        assert_eq!(content(&resolved.contributions), vec!["new"]);
        assert_eq!(resolved.contributions[0].slot, PromptSlot::Guidance);
    }

    #[test]
    fn prompt_layers_allow_later_append_after_replace() {
        let core =
            PromptLayer::new().with_contribution(PromptContribution::guidance("Guide", "old"));
        let session = PromptLayer::new().with_replaced_slot(
            PromptSlot::Guidance,
            [PromptContribution::guidance("New", "new")],
        );
        let turn =
            PromptLayer::new().with_contribution(PromptContribution::guidance("Turn", "turn"));

        let resolved = resolve_prompt_layers([&core, &session, &turn]);
        assert_eq!(content(&resolved.contributions), vec!["new", "turn"]);
    }
}