speccoder-runtime 0.9.8

Application services of speccoder: the only crate that executes anything.
Documentation
//! `speccoder.skill.run`: an installed Agent Skill, hosted.
//!
//! The skill's `SKILL.md` body is the instruction; speccoder's governed tool
//! loop runs it with the planning policy (Spec Kit's artifacts and scripts;
//! anything else needs approval) and an `ask_person` tool for clarifying
//! questions. Everything it decides by is in the journaled input.

use crate::format::Wording;
use agentplane::prelude::*;
use serde_json::{Value, json};

use super::attempt::{Asker, LoopSpec, ask_person, tool_loop};
use crate::tools::policy::Policy;

/// The capability the skill provides.
pub const CAPABILITY: &str = "speccoder.skill.run";

/// What the host tells the model, before the skill itself.
pub fn policy(w: &Wording) -> String {
    format!(
        "You are speccoder, running the Agent Skill below for a person in their {product} \
project. Follow the skill's instructions. You can read the project, {authoring} with run_command \
(argv, no shell). Do not write source code — implementation is a separate step that \
speccoder runs with tests; other writes need a person's approval. When the skill says to \
ask the user, call ask_person with one question at a time; if nobody can answer, follow \
the skill's rule for unanswered questions. Skip steps about extension hooks, other \
agents' slash commands, committing, branching or pushing unless {authoring_tool} does it. \
Finish with the requested structured report.",
        product = w.product,
        authoring = w.authoring,
        authoring_tool = w.authoring_tool,
    )
}

/// What the host tells the model when it explores (`spec explore`).
pub fn explore_policy(w: &Wording) -> String {
    format!(
        "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.",
        product = w.product,
    )
}

/// The instruction `speccoder.explore` runs when the format has no
/// exploration skill of its own.
pub 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.";

/// The closing report's schema when exploring. Strict decoding takes no
/// item counts, so how many approaches a report owes is checked after the
/// run (`explore::validate_fallback`), never trusted to the schema.
#[must_use]
pub fn explore_schema() -> Value {
    let strings = json!({ "type": "array", "items": { "type": "string" } });
    let some = strings.clone();
    json!({
        "type": "object",
        "properties": {
            "summary": { "type": "string" },
            "status": { "type": "string", "enum": ["done", "incomplete"] },
            "approaches": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "title": { "type": "string" },
                        "summary": { "type": "string" },
                        "tradeoffs": some,
                        "risks": some,
                    },
                    "required": ["title", "summary", "tradeoffs", "risks"],
                    "additionalProperties": false,
                },
            },
            "constraints": strings,
            "open_questions": strings,
        },
        "required": ["summary", "status", "approaches", "constraints", "open_questions"],
        "additionalProperties": false,
    })
}

/// The closing report's schema.
#[must_use]
pub fn schema() -> Value {
    let strings = json!({ "type": "array", "items": { "type": "string" } });
    json!({
        "type": "object",
        "properties": {
            "summary": { "type": "string" },
            "status": { "type": "string", "enum": ["done", "incomplete"] },
            "files_written": strings,
            "questions": strings,
        },
        "required": ["summary", "status", "files_written", "questions"],
        "additionalProperties": false,
    })
}

/// The run input.
#[must_use]
pub fn input(skill: &str, instruction: &str, root: &str, limits: (u32, u32), ask: bool) -> Value {
    json!({
        "skill": skill,
        "instruction": instruction,
        // With a person there, a question waits on a task they answer
        // inline; without one the skill writes [NEEDS CLARIFICATION].
        "settings": { "max_turns": limits.0, "max_tool_calls": limits.1, "asks": if ask { "tasks" } else { "stop" }, "root": root },
    })
}

/// The coded skill.
#[derive(Debug)]
pub struct Host {
    /// Prompt dialect.
    pub style: super::model_config::PromptStyle,
    /// Where live progress goes.
    pub progress: Option<std::sync::Arc<dyn crate::progress::Progress>>,
    /// The project's spec format.
    pub format: &'static dyn crate::format::Adapter,
    /// The sandbox, as a person asked about a command is told; live only.
    pub present: crate::approvals::PresentContext,
}

#[async_trait]
impl Skill for Host {
    fn descriptor(&self) -> SkillDescriptor {
        SkillDescriptor::new("speccoder.skill.run").provides(CAPABILITY)
    }

    async fn invoke(
        &self,
        cx: &mut StepCtx<'_>,
        input: Tainted<Value>,
    ) -> Result<Outcome, SkillError> {
        let style = self.style;
        let settings = input.peek()["settings"].clone();
        let skill = input.peek()["skill"]
            .as_str()
            .unwrap_or_default()
            .to_owned();
        let limit = |key: &str, default: u32| {
            settings[key]
                .as_u64()
                .map_or(default, |n| u32::try_from(n).unwrap_or(u32::MAX))
        };
        // Built from labelled parts, so `/system` stays speccoder's trusted
        // instruction after the conversation has read tool output.
        let label = input.label().clone();
        let exploring = settings["mode"] == "explore";
        let prompt = super::provenance::labelled_prompt(
            {
                let input = input.peek();
                let text = format!(
                    "# Skill `{}`\n\n{}",
                    input["skill"].as_str().unwrap_or_default(),
                    input["instruction"].as_str().unwrap_or_default()
                );
                let system = if exploring {
                    explore_policy(self.format.wording())
                } else {
                    policy(self.format.wording())
                };
                match style {
                    super::model_config::PromptStyle::OpenAi => json!({
                        "system": system,
                        "input": [{ "role": "user", "content": [{ "type": "input_text", "text": text }] }],
                    }),
                    super::model_config::PromptStyle::Anthropic
                    | super::model_config::PromptStyle::Chat => json!({
                        "system": system,
                        "messages": [{ "role": "user", "content": [{ "type": "text", "text": text }] }],
                    }),
                    super::model_config::PromptStyle::Parts { .. } => json!({
                        "system": system,
                        "input": [{ "type": "text", "text": text }],
                    }),
                }
            },
            &label,
        );
        let mut tools = crate::tools::declarations();
        tools.push(ask_person());
        let ask = Asker::from_settings(
            &settings,
            format!("skill/{skill}"),
            skill.clone(),
            self.present.clone(),
        );
        tool_loop(
            cx,
            &prompt,
            LoopSpec {
                // The account is shown for attempts; these read as documents.
                reasoning: false,
                tools,
                // A format's own bug step writes only its bug's directory;
                // exploring writes nothing but the format's own artifacts.
                policy: if exploring {
                    let planning = self.format.planning();
                    Policy::new(&[], &[]).rules(self.format.rules()).exploring(
                        crate::tools::policy::Exploring {
                            paths: planning.explore_paths,
                            commands: planning.explore_commands,
                        },
                    )
                } else {
                    Policy::new(&[], &[])
                        .rules(if settings["scope"] == "bug" {
                            self.format
                                .bug_step()
                                .map_or(self.format.rules(), |s| s.rules)
                        } else {
                            self.format.rules()
                        })
                        .authoring()
                },
                max_turns: limit("max_turns", 30).max(1),
                max_tool_calls: limit("max_tool_calls", 100),
                schema: Some(if exploring {
                    explore_schema()
                } else {
                    schema()
                }),
                max_tokens: None,
                reads: None,
                halt: None,
                routes: Vec::new(),
                root: settings["root"].as_str().map(str::to_owned),
                frozen_additions: false,
                ask,
                run_approved: Vec::new(),
                once: Vec::new(),
                run: None,
                asking: super::attempt::Asking::default(),
                parts: Vec::new(),
                mcp_digests: std::collections::BTreeMap::new(),
                stop: super::attempt::StopGate::default(),
                observer: self.progress.clone().map(|p| (skill.clone(), p)),
                finish: |report| {
                    if report["status"] == "incomplete" {
                        "incomplete"
                    } else {
                        "completed"
                    }
                },
            },
        )
        .await
    }
}