Skip to main content

speccoder_runtime/substrate/
host.rs

1//! `speccoder.skill.run`: an installed Agent Skill, hosted.
2//!
3//! The skill's `SKILL.md` body is the instruction; speccoder's governed tool
4//! loop runs it with the planning policy (Spec Kit's artifacts and scripts;
5//! anything else needs approval) and an `ask_person` tool for clarifying
6//! questions. Everything it decides by is in the journaled input.
7
8use crate::format::Wording;
9use agentplane::prelude::*;
10use serde_json::{Value, json};
11
12use super::attempt::{Asker, LoopSpec, ask_person, tool_loop};
13use crate::tools::policy::Policy;
14
15/// The capability the skill provides.
16pub const CAPABILITY: &str = "speccoder.skill.run";
17
18/// What the host tells the model, before the skill itself.
19pub fn policy(w: &Wording) -> String {
20    format!(
21        "You are speccoder, running the Agent Skill below for a person in their {product} \
22project. Follow the skill's instructions. You can read the project, {authoring} with run_command \
23(argv, no shell). Do not write source code — implementation is a separate step that \
24speccoder runs with tests; other writes need a person's approval. When the skill says to \
25ask the user, call ask_person with one question at a time; if nobody can answer, follow \
26the skill's rule for unanswered questions. Skip steps about extension hooks, other \
27agents' slash commands, committing, branching or pushing unless {authoring_tool} does it. \
28Finish with the requested structured report.",
29        product = w.product,
30        authoring = w.authoring,
31        authoring_tool = w.authoring_tool,
32    )
33}
34
35/// What the host tells the model when it explores (`spec explore`).
36pub fn explore_policy(w: &Wording) -> String {
37    format!(
38        "You are speccoder, exploring an idea with a person in their {product} project before any spec exists. You can read the project; you cannot write anything — the person chooses an approach afterwards, speccoder writes the brief, and *Start spec* writes the spec. When you need the person's view, call ask_person with one question at a time; if nobody can answer, list the question under open questions and go on. Look at how the project works today, then end with the structured report: approaches that really differ, each with what it gives up and what could go wrong, the constraints any of them must respect, and the questions still open. Your report is a proposal; you do not choose.",
39        product = w.product,
40    )
41}
42
43/// The instruction `speccoder.explore` runs when the format has no
44/// exploration skill of its own.
45pub const EXPLORE_FALLBACK: &str = "Explore the idea below with the person. Read what the project already has that it touches (code, specs, docs). Ask the person at most a few questions, one at a time, only where the answer changes which approach fits. Then propose at least three approaches that differ in kind, not degree — e.g. the smallest change, the cleanest design, a different way altogether — each with its trade-offs and its risks. Name the constraints any approach must respect and the questions still open. Do not choose: the person does.";
46
47/// The closing report's schema when exploring. Strict decoding takes no
48/// item counts, so how many approaches a report owes is checked after the
49/// run (`explore::validate_fallback`), never trusted to the schema.
50#[must_use]
51pub fn explore_schema() -> Value {
52    super::answers::schema::<super::answers::Explored>()
53}
54
55/// The closing report's schema.
56#[must_use]
57pub fn schema() -> Value {
58    super::answers::schema::<super::answers::Hosted>()
59}
60
61/// The run input.
62#[must_use]
63pub fn input(skill: &str, instruction: &str, root: &str, limits: (u32, u32), ask: bool) -> Value {
64    json!({
65        "skill": skill,
66        "instruction": instruction,
67        // With a person there, a question waits on a task they answer
68        // inline; without one the skill writes [NEEDS CLARIFICATION].
69        "settings": { "max_turns": limits.0, "max_tool_calls": limits.1, "asks": if ask { "tasks" } else { "stop" }, "root": root },
70    })
71}
72
73/// The coded skill.
74#[derive(Debug)]
75pub struct Host {
76    /// Prompt dialect.
77    pub style: super::model_config::PromptStyle,
78    /// Where live progress goes.
79    pub progress: Option<std::sync::Arc<dyn crate::progress::Progress>>,
80    /// The project's spec format.
81    pub format: &'static dyn crate::format::Adapter,
82    /// The sandbox, as a person asked about a command is told; live only.
83    pub present: crate::approvals::PresentContext,
84}
85
86#[async_trait]
87impl Skill for Host {
88    fn descriptor(&self) -> SkillDescriptor {
89        SkillDescriptor::new("speccoder.skill.run").provides(CAPABILITY)
90    }
91
92    async fn invoke(
93        &self,
94        cx: &mut StepCtx<'_>,
95        input: Tainted<Value>,
96    ) -> Result<Outcome, SkillError> {
97        let style = self.style;
98        let settings = input.peek()["settings"].clone();
99        let skill = input.peek()["skill"]
100            .as_str()
101            .unwrap_or_default()
102            .to_owned();
103        let limit = |key: &str, default: u32| {
104            settings[key]
105                .as_u64()
106                .map_or(default, |n| u32::try_from(n).unwrap_or(u32::MAX))
107        };
108        // Built from labelled parts, so `/system` stays speccoder's trusted
109        // instruction after the conversation has read tool output.
110        let label = input.label().clone();
111        let exploring = settings["mode"] == "explore";
112        let prompt = super::provenance::labelled_prompt(
113            {
114                let input = input.peek();
115                let text = format!(
116                    "# Skill `{}`\n\n{}",
117                    input["skill"].as_str().unwrap_or_default(),
118                    input["instruction"].as_str().unwrap_or_default()
119                );
120                let system = if exploring {
121                    explore_policy(self.format.wording())
122                } else {
123                    policy(self.format.wording())
124                };
125                match style {
126                    super::model_config::PromptStyle::OpenAi => json!({
127                        "system": system,
128                        "input": [{ "role": "user", "content": [{ "type": "input_text", "text": text }] }],
129                    }),
130                    super::model_config::PromptStyle::Anthropic
131                    | super::model_config::PromptStyle::Chat => json!({
132                        "system": system,
133                        "messages": [{ "role": "user", "content": [{ "type": "text", "text": text }] }],
134                    }),
135                    super::model_config::PromptStyle::Parts { .. } => json!({
136                        "system": system,
137                        "input": [{ "type": "text", "text": text }],
138                    }),
139                }
140            },
141            &label,
142        );
143        let mut tools = crate::tools::declarations();
144        tools.push(ask_person());
145        let ask = Asker::from_settings(
146            &settings,
147            format!("skill/{skill}"),
148            skill.clone(),
149            self.present.clone(),
150        );
151        tool_loop(
152            cx,
153            &prompt,
154            LoopSpec {
155                // The account is shown for attempts; these read as documents.
156                reasoning: false,
157                tools,
158                // A format's own bug step writes only its bug's directory;
159                // exploring writes nothing but the format's own artifacts.
160                policy: if exploring {
161                    let planning = self.format.planning();
162                    Policy::new(&[], &[]).rules(self.format.rules()).exploring(
163                        crate::tools::policy::Exploring {
164                            paths: planning.explore_paths,
165                            commands: planning.explore_commands,
166                        },
167                    )
168                } else {
169                    Policy::new(&[], &[])
170                        .rules(if settings["scope"] == "bug" {
171                            self.format
172                                .bug_step()
173                                .map_or(self.format.rules(), |s| s.rules)
174                        } else {
175                            self.format.rules()
176                        })
177                        .authoring()
178                },
179                max_turns: limit("max_turns", 30).max(1),
180                max_tool_calls: limit("max_tool_calls", 100),
181                schema: Some(if exploring {
182                    explore_schema()
183                } else {
184                    schema()
185                }),
186                max_tokens: None,
187                left: None,
188                reads: None,
189                halt: None,
190                routes: Vec::new(),
191                root: settings["root"].as_str().map(str::to_owned),
192                frozen_additions: false,
193                ask,
194                run_approved: Vec::new(),
195                once: Vec::new(),
196                run: None,
197                asking: super::attempt::Asking::default(),
198                parts: Vec::new(),
199                mcp_digests: std::collections::BTreeMap::new(),
200                stop: super::attempt::StopGate::default(),
201                observer: self.progress.clone().map(|p| (skill.clone(), p)),
202                finish: |report| {
203                    if report["status"] == "incomplete" {
204                        "incomplete"
205                    } else {
206                        "completed"
207                    }
208                },
209            },
210        )
211        .await
212    }
213}