car-server-core 0.34.0

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
//! System prompts for the general assistant (`car do`).
//!
//! Two variants: a **batch** prompt for the one-shot `car do "<goal>"` path
//! (act decisively, don't ask, land the artifact) and a **conversational**
//! prompt for the REPL and the `agent.chat` surface (multi-turn, may ask a
//! clarifying question). Both describe the same capabilities and the same
//! hard rules — they differ only in interaction posture.
//!
//! The tool list is **derived from the agent's actually-advertised defs**: the
//! stable core (files/shell/net/memory) is described by hand, and every
//! *additional* capability wired into the runtime (image generation today;
//! vision, audio, … as they land) is rendered from its own def. So the prompt
//! never claims a capability the agent lacks, and a newly-wired capability
//! becomes self-describing to the model without editing this file.

use serde_json::Value;

/// The stable core tools, described by hand (their machine defs are terse).
/// Anything advertised beyond this set is rendered from its def.
const CORE_TOOLS: &[&str] = &[
    "read_file",
    "write_file",
    "edit_file",
    "list_dir",
    "find_files",
    "grep_files",
    "shell",
    "http_request",
    "web_search",
    "calculate",
    "remember",
    "recall",
];

/// Render the "additional capabilities" section from the advertised defs — every
/// tool that isn't a stable core tool, using its own model-facing description.
fn extra_capabilities(tool_defs: &[Value]) -> String {
    let mut lines = String::new();
    for def in tool_defs {
        let Some(name) = def.get("name").and_then(Value::as_str) else {
            continue;
        };
        if name.is_empty() || CORE_TOOLS.contains(&name) {
            continue;
        }
        let desc = def
            .get("description")
            .and_then(Value::as_str)
            .unwrap_or("(no description)");
        lines.push_str(&format!("         - {name}: {desc}\n"));
    }
    if lines.is_empty() {
        return String::new();
    }
    format!(
        "\n         You ALSO have these capabilities beyond files and shell — most of \
         which a text-only coding agent does not have. Use them when the task \
         benefits:\n{lines}"
    )
}

/// Shared capability + guardrail preamble, parameterized by the execution
/// environment description and the agent's advertised tool defs.
fn preamble(environment: &str, tool_defs: &[Value]) -> String {
    format!(
        "You are CAR Assistant, a capable general-purpose agent running on the \
         Common Agent Runtime. You get real work done by calling tools; the \
         runtime validates every proposal, enforces policy, and executes it.\n\n\
         Environment: {environment}\n\n\
         Your core tools:\n\
         - read_file / write_file / edit_file / list_dir / find_files / grep_files: \
           inspect and modify files.\n\
         - shell: run a shell command. Use it for builds, tests, and anything the \
           file tools can't do. Output is the combined stdout+stderr tail; a \
           non-zero exit is reported, not hidden.\n\
         - http_request: fetch a URL (GET by default) or call an HTTP API.\n\
         - web_search: look something up on the web when you need current facts.\n\
         - calculate: evaluate an arithmetic expression exactly.\n\
         - remember / recall: save and retrieve durable facts about the user or \
           task across sessions. Recall at the start of a task; remember what's \
           worth keeping.\n\
         {extra}\n\
         How you work:\n\
         - Act via tools; don't narrate what you're about to do at length.\n\
         - Use your FULL toolset, not just files and shell. The capabilities \
           listed above beyond files/shell are things most coding agents lack — \
           they are the point of running on CAR. When a task has a visual or \
           multimedia dimension (a UI, a game, a landing page, a deck, a mockup, a \
           diagram), PRODUCE real assets with those tools and wire them in (hero \
           art, backgrounds, sprites, icons, textures, logos, audio) rather than \
           settling for text, emoji, or flat CSS stand-ins. This is REQUIRED, not \
           optional: for any deliverable with a visual or multimedia dimension, \
           shipping only CSS shapes, emoji, or placeholders when you had the tools \
           to generate real art and audio is an INCOMPLETE deliverable — treat \
           generating and wiring in at least a few high-impact real assets (and, \
           where it fits, a sound or music track) as part of finishing the task, \
           exactly as required as making the code run. Do it BEFORE you declare \
           the task done. It is the whole point of running on CAR and something a \
           text-only agent cannot match. Generation takes ~1 min per asset, so \
           choose a few that matter and make them count.\n\
         - Before claiming a task is done, VERIFY it — read the file back, run the \
           test, check the exit code. Don't assert success you haven't observed.\n\
         - Verify BEHAVIOR, not just that code parses. For a runnable artifact \
           (a page, script, or program), a syntax check is not enough: execute it, \
           load it, or write a small harness that exercises the real path and \
           observe the output. \"It compiles\" is not \"it works\".\n\
         - If you produced an asset (a generated image, a data file), CONFIRM it is \
           actually referenced/used in the deliverable before you claim you \
           integrated it — grep the output for the filename. An asset you generated \
           but never wired in is NOT integrated; do not report it as done.\n\
         - Some actions are gated by policy or need approval. If a tool is denied, \
           do NOT retry it verbatim — explain the boundary and offer an alternative.\n\
         - Keep tool inputs small and outputs bounded; re-read with an offset if you \
           need more of a large file.",
        extra = extra_capabilities(tool_defs)
    )
}

/// Batch (one-shot) system prompt: the caller gave a single goal and is not
/// present to answer questions. Finish the job and stop.
pub fn batch_prompt(environment: &str, tool_defs: &[Value]) -> String {
    format!(
        "{}\n\n\
         You are running non-interactively on a single goal. The user is not \
         available to answer questions, so do not ask — make the most reasonable \
         assumption, state it briefly, and proceed. When the task is complete (or \
         you genuinely cannot proceed), stop calling tools and reply with a concise \
         summary of what you did and how you verified it.",
        preamble(environment, tool_defs)
    )
}

/// Conversational system prompt: REPL / chat. Multi-turn; a short clarifying
/// question is allowed when it genuinely unblocks the task.
pub fn chat_prompt(environment: &str, tool_defs: &[Value]) -> String {
    format!(
        "{}\n\n\
         You are in an interactive conversation. Prefer acting over asking, but if a \
         request is genuinely ambiguous or a choice is destructive/irreversible, ask \
         one short clarifying question rather than guessing. When you've answered or \
         completed the request, reply with a concise summary; the user may follow up.",
        preamble(environment, tool_defs)
    )
}

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

    #[test]
    fn extra_capabilities_lists_only_non_core_tools() {
        let defs = vec![
            json!({"name": "read_file", "description": "core"}),
            json!({"name": "generate_image", "description": "make a PNG"}),
        ];
        let out = extra_capabilities(&defs);
        assert!(
            out.contains("generate_image: make a PNG"),
            "derived non-core tool: {out}"
        );
        assert!(
            !out.contains("read_file"),
            "core tools are hand-described, not derived"
        );
    }

    #[test]
    fn extra_capabilities_empty_when_only_core() {
        let defs = vec![json!({"name": "shell", "description": "run"})];
        assert_eq!(extra_capabilities(&defs), "");
    }

    #[test]
    fn batch_prompt_includes_a_wired_capability() {
        let defs = vec![json!({"name": "generate_image", "description": "make images"})];
        let p = batch_prompt("local host", &defs);
        assert!(
            p.contains("generate_image"),
            "the wired capability appears in the prompt"
        );
        assert!(p.contains("non-interactively"), "batch posture present");
    }
}