laravel-rust-studio 0.1.1

See what a running Laravel for Rust application did: requests with their queries, errors with their source lines, mail, queued jobs, and durable workflows. For you in the browser, and for coding agents over MCP.
Documentation
//! The documents that tell a coding agent Studio exists and how to use it: the skill, the
//! `llms.txt` index of its endpoints, and the command that installs the skill.

use std::fmt::Write as _;
use std::path::Path;

use laravel::console::{Console, clap, command};

/// The skill that teaches a coding agent to use Studio, with `{{studio}}` where the application's
/// Studio URL goes.
pub const SKILL_TEMPLATE: &str = include_str!("../resources/SKILL.md");

/// The skill, written for the Studio at `studio_url`, such as `http://127.0.0.1:8000/studio`.
#[must_use]
pub fn render_skill(studio_url: &str) -> String {
    SKILL_TEMPLATE.replace("{{studio}}", studio_url.trim_end_matches('/'))
}

/// The plain-text index of Studio's endpoints, served at `/studio/llms.txt`.
#[must_use]
pub fn render_llms_txt(studio_url: &str, app_name: &str, mcp_enabled: bool) -> String {
    let s = studio_url.trim_end_matches('/');
    let mut out = format!(
        "# Laravel Rust Studio — {app_name}\n\n\
         > Studio shows what this running Laravel for Rust application did: its requests, queries, errors, logs, \
         mail, queued jobs, and durable workflows, across the web server and its queue workers. It also acts on \
         workflows and failed jobs.\n\n\
         Every endpoint answers JSON. The `/api/agent/*` endpoints answer compact Markdown with `?format=markdown`.\n\
         A response's `X-Request-Id` header is its trace's ID: GET {s}/api/traces/<that id>.\n\
         The skill for coding agents is at {s}/skill.md.\n"
    );
    if mcp_enabled {
        let _ = writeln!(
            out,
            "The same tools are an MCP server (Streamable HTTP) at POST {s}/mcp."
        );
    }

    let section = |out: &mut String, title: &str, lines: &[(&str, &str)]| {
        let _ = writeln!(out, "\n## {title}\n");
        for (endpoint, description) in lines {
            let endpoint = endpoint.replace("{s}", s);
            let _ = writeln!(out, "- `{endpoint}`: {description}");
        }
    };

    section(
        &mut out,
        "Start here",
        &[
            (
                "GET {s}/api/agent/summary",
                "Health, the problems found, the latest requests, errors, workflow runs, failed jobs, and mail.",
            ),
            (
                "GET {s}/api/agent/diagnose",
                "Only the problems: errors and panics with their source line, N+1 and slow queries with the line that built them, slow requests, failed outgoing requests, failed and overdue workflow runs, failed jobs. Each says when it was last seen, and the ones from before the server last restarted are listed apart. `?since=60` keeps the problems seen in the last 60 seconds.",
            ),
            (
                "GET {s}/api/agent/last-request",
                "The latest request's span waterfall, queries, logs, and errors. `?path=/posts` picks the latest request to a path, `?method=POST` to a method.",
            ),
            (
                "GET {s}/api/agent/last-error",
                "The latest error or panic: type, message, causes, source line, request.",
            ),
            (
                "GET {s}/api/agent/last-mail",
                "The latest email or text message, with the links and codes in it. `?to=taylor@example.com` picks a recipient's.",
            ),
            (
                "GET {s}/api/agent/wait",
                "Waits for something to be captured and returns it: `?for=request|job|workflow|exception|mail|sms|log|activity`, `&contains=<words in the record, all of them>`, `&timeout=15` (seconds), `&lookback=10` (also accept records this recent).",
            ),
        ],
    );
    section(
        &mut out,
        "Telemetry",
        &[
            (
                "GET {s}/api/traces",
                "Requests, jobs, workflow advances, commands, and scheduled tasks. `?kind=request|job|workflow|command|schedule`, `?status=5xx|4xx|2xx|404`, `?slow=true`, `?errors=true`, `?search=`, `?limit=`.",
            ),
            (
                "GET {s}/api/traces/{id}",
                "One trace: its spans, queries with bindings and source lines, logs, errors, mail, cache operations, outgoing requests.",
            ),
            (
                "GET {s}/api/queries",
                "SQL queries. `?trace_id=`, `?slow=true`, `?writes=true`, `?duplicates=true` (N+1), `?app=true` (leave out the framework's own), `?search=`, `?limit=`.",
            ),
            ("GET {s}/api/exceptions", "Errors and panics. `?search=`, `?limit=`."),
            (
                "GET {s}/api/logs",
                "Log lines. `?trace_id=`, `?level=error|warn|info|debug`, `?search=`, `?limit=`.",
            ),
            (
                "GET {s}/api/mail",
                "Emails and text messages. `?kind=mail|sms`, `?search=`.",
            ),
            ("GET {s}/api/http-client", "Outgoing HTTP requests. `?trace_id=`."),
            ("GET {s}/api/cache", "Cache reads and writes. `?trace_id=`."),
            (
                "GET {s}/api/overview",
                "Totals and the latency series the dashboard draws.",
            ),
            (
                "GET {s}/api/system",
                "The application's name, environment, drivers, and Studio's settings.",
            ),
            (
                "GET {s}/api/stream",
                "Server-sent events: every record as it's captured.",
            ),
            (
                "POST {s}/api/clear",
                "Forget the captured telemetry. Workflow runs and failed jobs stay.",
            ),
        ],
    );
    section(
        &mut out,
        "Durable workflows",
        &[
            (
                "GET {s}/api/workflows",
                "Runs, newest first, with counts by status. `?status=pending|running|waiting|completed|failed|cancelled`, `?workflow=<name>`, `?attribute=name=value`, `?search=`, `?limit=`.",
            ),
            (
                "GET {s}/api/workflows/{id}",
                "One run: input, output, error, attributes, each step's output and tries, the tokens it waits for, and the values it was resumed with.",
            ),
            (
                "POST {s}/api/workflows/resume",
                "Give a waiting run its value. Body: `{\"token\": \"expenses.42.decision\", \"value\": <JSON>}`.",
            ),
            (
                "POST {s}/api/workflows/{id}/retry",
                "Continue a failed run from the step that failed.",
            ),
            (
                "POST {s}/api/workflows/{id}/cancel",
                "Cancel a run. Body: `{\"reason\": \"...\"}`, optional.",
            ),
            (
                "POST {s}/api/workflows/recover",
                "Queue the wake-ups of runs that are overdue.",
            ),
            (
                "POST {s}/api/workflows/prune",
                "Delete runs that finished long ago. Body: `{\"hours\": 24}`.",
            ),
        ],
    );
    section(
        &mut out,
        "Queues",
        &[
            (
                "GET {s}/api/queues",
                "Each queue's depth and whether it's paused, the waiting and delayed jobs, failed jobs, batches, and what workers ran lately.",
            ),
            (
                "GET {s}/api/queues/failed",
                "Failed jobs with their errors and payloads. `?search=`, `?limit=`.",
            ),
            ("POST {s}/api/queues/failed/{id}/retry", "Run a failed job again."),
            ("POST {s}/api/queues/failed/retry-all", "Run every failed job again."),
            ("DELETE {s}/api/queues/failed/{id}", "Delete a failed job."),
            (
                "POST {s}/api/queues/failed/flush",
                "Delete failed jobs. Body: `{\"hours\": 48}` keeps the newer ones.",
            ),
            ("POST {s}/api/queues/batches/{id}/cancel", "Cancel a batch."),
            (
                "POST {s}/api/queues/pause",
                "Pause a queue. Body: `{\"all\": true}` or `{\"connection\": \"database\", \"queue\": \"default\"}`.",
            ),
            ("POST {s}/api/queues/continue", "Resume a queue. Same body."),
            (
                "POST {s}/api/queues/restart",
                "Tell the workers to restart after their current job.",
            ),
        ],
    );

    out
}

/// Install the Studio skill for coding agents
#[derive(clap::Parser)]
#[command(name = "studio:skill")]
pub struct InstallSkill {
    /// Print the skill instead of writing `.agents/skills/laravel-rust-studio/SKILL.md`
    #[arg(long)]
    print: bool,
}

#[command]
impl InstallSkill {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        let config = laravel::config();
        let mount = config.section::<crate::StudioConfig>().mount_path();
        let skill = render_skill(&format!("{}{mount}", config.app.url.trim_end_matches('/')));
        if self.print {
            console.line(skill);
            return Ok(());
        }

        let directory = Path::new(".agents/skills/laravel-rust-studio");
        tokio::fs::create_dir_all(directory).await?;
        let file = directory.join("SKILL.md");
        tokio::fs::write(&file, skill).await?;
        console.success(format!("Skill written to `{}`.", file.display()));

        Ok(())
    }
}