lash-sansio 0.1.0-alpha.40

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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use std::collections::HashMap;

use crate::PromptContext;
use crate::plugin::PromptContribution;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PromptBuiltin {
    MainAgentIntro,
    ExecutionInstructions,
    CoreGuidance,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PromptSlot {
    Intro,
    Execution,
    Guidance,
    ProjectInstructions,
    RuntimeContext,
    Environment,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PromptTemplateEntry {
    Text { content: String },
    Builtin { builtin: PromptBuiltin },
    Slot { slot: PromptSlot },
}

impl PromptTemplateEntry {
    pub fn text(content: impl Into<String>) -> Self {
        Self::Text {
            content: content.into(),
        }
    }

    pub fn builtin(builtin: PromptBuiltin) -> Self {
        Self::Builtin { builtin }
    }

    pub fn slot(slot: PromptSlot) -> Self {
        Self::Slot { slot }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PromptTemplateSection {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub entries: Vec<PromptTemplateEntry>,
}

impl PromptTemplateSection {
    pub fn new(title: Option<String>, entries: Vec<PromptTemplateEntry>) -> Self {
        Self { title, entries }
    }

    pub fn untitled(entries: Vec<PromptTemplateEntry>) -> Self {
        Self {
            title: None,
            entries,
        }
    }

    pub fn titled(title: impl Into<String>, entries: Vec<PromptTemplateEntry>) -> Self {
        Self {
            title: Some(title.into()),
            entries,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PromptTemplate {
    pub sections: Vec<PromptTemplateSection>,
}

impl PromptTemplate {
    pub fn new(sections: Vec<PromptTemplateSection>) -> Self {
        Self { sections }
    }

    pub fn render(&self, prompt: &PromptContext) -> String {
        let contributions = grouped_contributions(prompt);
        self.sections
            .iter()
            .filter_map(|section| render_section(section, prompt, &contributions))
            .collect::<Vec<_>>()
            .join("\n\n")
    }
}

impl Default for PromptTemplate {
    fn default() -> Self {
        default_prompt_template()
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PromptLayer {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub template: Option<PromptTemplate>,
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub slots: HashMap<PromptSlot, PromptSlotLayer>,
}

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

    pub fn is_empty(&self) -> bool {
        self.template.is_none() && self.slots.is_empty()
    }

    pub fn with_template(template: PromptTemplate) -> Self {
        Self {
            template: Some(template),
            slots: HashMap::new(),
        }
    }

    pub fn prompt_template(mut self, template: PromptTemplate) -> Self {
        self.template = Some(template);
        self
    }

    pub fn clear_template(mut self) -> Self {
        self.template = None;
        self
    }

    pub fn add_contribution(&mut self, contribution: PromptContribution) {
        self.slots
            .entry(contribution.slot)
            .or_default()
            .contributions
            .push(contribution);
    }

    pub fn with_contribution(mut self, contribution: PromptContribution) -> Self {
        self.add_contribution(contribution);
        self
    }

    pub fn replace_slot(
        &mut self,
        slot: PromptSlot,
        contributions: impl IntoIterator<Item = PromptContribution>,
    ) {
        self.slots.insert(
            slot,
            PromptSlotLayer {
                reset: true,
                contributions: normalize_slot_contributions(slot, contributions),
            },
        );
    }

    pub fn with_replaced_slot(
        mut self,
        slot: PromptSlot,
        contributions: impl IntoIterator<Item = PromptContribution>,
    ) -> Self {
        self.replace_slot(slot, contributions);
        self
    }

    pub fn clear_slot(&mut self, slot: PromptSlot) {
        self.slots.insert(
            slot,
            PromptSlotLayer {
                reset: true,
                contributions: Vec::new(),
            },
        );
    }

    pub fn with_cleared_slot(mut self, slot: PromptSlot) -> Self {
        self.clear_slot(slot);
        self
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PromptSlotLayer {
    #[serde(default)]
    pub reset: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub contributions: Vec<PromptContribution>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedPromptLayer {
    pub template: PromptTemplate,
    pub contributions: Vec<PromptContribution>,
}

pub fn resolve_prompt_layers<'a>(
    layers: impl IntoIterator<Item = &'a PromptLayer>,
) -> ResolvedPromptLayer {
    let mut template = default_prompt_template();
    let mut contributions = Vec::new();
    for layer in layers {
        if let Some(next_template) = &layer.template {
            template = next_template.clone();
        }
        for (slot, slot_layer) in &layer.slots {
            if slot_layer.reset {
                contributions
                    .retain(|contribution: &PromptContribution| contribution.slot != *slot);
            }
            contributions.extend(normalize_slot_contributions(
                *slot,
                slot_layer.contributions.iter().cloned(),
            ));
        }
    }
    ResolvedPromptLayer {
        template,
        contributions,
    }
}

fn normalize_slot_contributions(
    slot: PromptSlot,
    contributions: impl IntoIterator<Item = PromptContribution>,
) -> Vec<PromptContribution> {
    contributions
        .into_iter()
        .map(|mut contribution| {
            contribution.slot = slot;
            contribution
        })
        .collect()
}

pub fn default_prompt_template() -> PromptTemplate {
    PromptTemplate::new(vec![
        PromptTemplateSection::untitled(vec![
            PromptTemplateEntry::builtin(PromptBuiltin::MainAgentIntro),
            PromptTemplateEntry::slot(PromptSlot::Intro),
        ]),
        PromptTemplateSection::titled(
            "Execution",
            vec![
                PromptTemplateEntry::builtin(PromptBuiltin::ExecutionInstructions),
                PromptTemplateEntry::slot(PromptSlot::Execution),
            ],
        ),
        PromptTemplateSection::titled(
            "Guidance",
            vec![
                PromptTemplateEntry::builtin(PromptBuiltin::CoreGuidance),
                PromptTemplateEntry::slot(PromptSlot::ProjectInstructions),
                PromptTemplateEntry::slot(PromptSlot::Guidance),
            ],
        ),
        PromptTemplateSection::titled(
            "Environment",
            vec![
                PromptTemplateEntry::slot(PromptSlot::RuntimeContext),
                PromptTemplateEntry::slot(PromptSlot::Environment),
            ],
        ),
    ])
}

pub const MAIN_AGENT_INTRO: &str = "You are an AI coding assistant piloting the lash harness.";

/// Core guidance delivered in the `## Guidance` section. Rendered
/// through [`render_core_guidance`] rather than inlined as a `const`
/// so we can drop interactive-only advice when the session has no
/// `ask` tool (autonomous `--print` runs, benchmarks, etc.). Rules that
/// depend on being able to talk to a user only make sense when that
/// channel exists.
const CORE_GUIDANCE_BASE: &[&str] = &[
    "- Be concise. Avoid filler, hedging, and performative tone.",
    "- Do not restate a conclusion you already stated. Once a fix location is identified, act on it in the same turn.",
    "- Prefer the simplest correct solution over cleverness or unnecessary abstraction.",
];

const CORE_GUIDANCE_INTERACTIVE_ONLY: &str =
    "- Take initiative when the user's intent is clear. Ask only when progress is blocked.";

pub fn render_core_guidance(prompt: &PromptContext) -> String {
    let mut bullets: Vec<&str> = CORE_GUIDANCE_BASE.to_vec();
    if prompt.has_tool("ask") {
        // Insert after the "Be concise" lead-in so the interactive-
        // only rule sits alongside the other core directives instead
        // of at the end.
        bullets.insert(1, CORE_GUIDANCE_INTERACTIVE_ONLY);
    }
    bullets.join("\n")
}

fn grouped_contributions<'a>(
    prompt: &'a PromptContext,
) -> HashMap<PromptSlot, Vec<&'a PromptContribution>> {
    let mut grouped: HashMap<PromptSlot, Vec<&'a PromptContribution>> = HashMap::new();
    for contribution in prompt.contributions.iter() {
        grouped
            .entry(contribution.slot)
            .or_default()
            .push(contribution);
    }
    for entries in grouped.values_mut() {
        entries.sort_by_key(|contribution| contribution.priority);
    }
    grouped
}

fn render_section(
    section: &PromptTemplateSection,
    prompt: &PromptContext,
    contributions: &HashMap<PromptSlot, Vec<&PromptContribution>>,
) -> Option<String> {
    let mut parts = Vec::new();
    for entry in &section.entries {
        match entry {
            PromptTemplateEntry::Text { content } => push_text(&mut parts, content),
            PromptTemplateEntry::Builtin { builtin } => {
                push_text(&mut parts, &render_builtin(*builtin, prompt))
            }
            PromptTemplateEntry::Slot { slot } => {
                if let Some(entries) = contributions.get(slot) {
                    for contribution in entries {
                        if let Some(rendered) = render_contribution(contribution) {
                            parts.push(rendered);
                        }
                    }
                }
            }
        }
    }

    if parts.is_empty() {
        return None;
    }

    let mut rendered = Vec::new();
    if let Some(title) = section
        .title
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        rendered.push(format!("## {title}"));
    }
    rendered.extend(parts);
    Some(rendered.join("\n\n"))
}

fn push_text(parts: &mut Vec<String>, text: &str) {
    let trimmed = text.trim();
    if !trimmed.is_empty() {
        parts.push(trimmed.to_string());
    }
}

fn render_builtin(builtin: PromptBuiltin, prompt: &PromptContext) -> String {
    match builtin {
        PromptBuiltin::MainAgentIntro => MAIN_AGENT_INTRO.to_string(),
        PromptBuiltin::ExecutionInstructions => prompt.execution_prompt.to_string(),
        PromptBuiltin::CoreGuidance => render_core_guidance(prompt),
    }
}

fn render_contribution(contribution: &PromptContribution) -> Option<String> {
    let content = contribution.content.trim();
    if content.is_empty() {
        return None;
    }
    match contribution
        .title
        .as_deref()
        .map(str::trim)
        .filter(|title| !title.is_empty())
    {
        Some(title) => Some(format!("### {title}\n\n{content}")),
        None => Some(content.to_string()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn prompt() -> PromptContext {
        PromptContext {
            execution_prompt: std::sync::Arc::from("protocol execution"),
            ..PromptContext::default()
        }
    }

    #[test]
    fn default_template_renders_builtin_sections() {
        let mut ctx = prompt();
        ctx.tool_names = std::sync::Arc::new(vec!["ask".to_string()]);
        let text = default_prompt_template().render(&ctx);
        assert!(text.contains(MAIN_AGENT_INTRO));
        assert!(text.contains("## Execution"));
        assert!(text.contains("protocol execution"));
        assert!(text.contains("## Guidance"));
        // Interactive context: the "ask when blocked" guidance is in play.
        assert!(text.contains("Ask only when progress is blocked"));
    }

    #[test]
    fn core_guidance_drops_ask_line_when_ask_tool_absent() {
        // Autonomous `--print` / benchmark sessions filter out the
        // `ask` tool, so the guidance line telling the model "Ask
        // only when progress is blocked" would contradict the
        // run-time constraint. `render_core_guidance` must drop it.
        let ctx = prompt();
        assert!(!ctx.has_tool("ask"));
        let rendered = render_core_guidance(&ctx);
        assert!(rendered.contains("Be concise"));
        assert!(rendered.contains("Prefer the simplest correct solution"));
        assert!(!rendered.contains("Ask only when progress is blocked"));
    }

    #[test]
    fn core_guidance_keeps_ask_line_when_ask_tool_present() {
        let mut ctx = prompt();
        ctx.tool_names = std::sync::Arc::new(vec!["ask".to_string()]);
        let rendered = render_core_guidance(&ctx);
        assert!(rendered.contains("Ask only when progress is blocked"));
    }

    #[test]
    fn template_renders_slot_contributions_in_order() {
        let mut prompt = prompt();
        prompt.contributions = vec![
            PromptContribution::guidance("Second Guide", "Second details.").with_priority(10),
            PromptContribution::guidance("First Guide", "First details.").with_priority(0),
        ]
        .into();
        let text = default_prompt_template().render(&prompt);
        assert!(text.contains("### First Guide"));
        assert!(text.contains("### Second Guide"));
        assert!(text.find("### First Guide").unwrap() < text.find("### Second Guide").unwrap());
    }

    #[test]
    fn template_can_omit_builtin_guidance_and_keep_plugin_guidance() {
        let template = PromptTemplate::new(vec![PromptTemplateSection::titled(
            "Guidance",
            vec![PromptTemplateEntry::slot(PromptSlot::Guidance)],
        )]);
        let mut prompt = prompt();
        prompt.contributions =
            vec![PromptContribution::guidance("Custom", "More guidance.")].into();
        let text = template.render(&prompt);
        assert!(text.contains("## Guidance"));
        assert!(text.contains("### Custom"));
        // Template with no `CoreGuidance` builtin omits the baked-in
        // guidance lines — only plugin contributions should land.
        assert!(!text.contains("Be concise. Avoid filler"));
    }

    #[test]
    fn template_can_place_project_instructions_separately() {
        let template = PromptTemplate::new(vec![
            PromptTemplateSection::titled(
                "Rules",
                vec![PromptTemplateEntry::slot(PromptSlot::ProjectInstructions)],
            ),
            PromptTemplateSection::titled(
                "Guidance",
                vec![PromptTemplateEntry::slot(PromptSlot::Guidance)],
            ),
        ]);
        let mut prompt = prompt();
        prompt.contributions = vec![
            PromptContribution::project_instructions("Repo rules"),
            PromptContribution::guidance("Shell", "Use exec_command."),
        ]
        .into();
        let text = template.render(&prompt);
        assert!(text.contains("## Rules"));
        assert!(text.contains("Repo rules"));
        assert!(text.contains("## Guidance"));
        assert!(text.contains("### Shell"));
    }

    #[test]
    fn empty_sections_are_skipped() {
        let template = PromptTemplate::new(vec![PromptTemplateSection::titled(
            "Environment",
            vec![PromptTemplateEntry::slot(PromptSlot::Environment)],
        )]);
        let text = template.render(&prompt());
        assert!(text.is_empty());
    }
}