Commit e07418d9 authored by jan.koester's avatar jan.koester
Browse files

llms.txt: follow llmstxt.org, plain-text entries, cache output

Checkers reported the root llms.txt as not following the recommendations
and timed out fetching it.

- Add the recommended '> summary' blockquote after the H1 (SITE_DESCRIPTION
  config value, else a short generated summary).
- Strip HTML tags and decode common entities in titles/descriptions
  (post teasers contained <br/> and <a> markup), cap descriptions at
  200 characters, keep '[' ']' out of link text.
- Static pages: use og:title, then the page's first <h1>, before falling
  back to the humanized slug; prefer og:description over meta.
- Cache the rendered text per site for 5 minutes, send it compressed with
  Cache-Control: public, max-age=3600 and CORS *, so slow DB round trips
  no longer hit checker timeouts.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 8af1aa8a
Loading
Loading
Loading
Loading
+12 −3
Changes for plugins/staticpage/static.cpp: 12 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -157,14 +157,23 @@ namespace {
void blogi::StaticPage::GetLlmsLinks(const int tid,std::vector<blogi::LlmsLink> &links){
    dbpp::SQL sql;
    dbpp::DBResult res;
    sql << "select url,meta from static_content";
    sql << "select url,meta,og_title,og_description,text from static_content";
    int result = Args->database[tid]->exec(sql,res);
    for(int i=0; i<result; ++i){
        blogi::LlmsLink link;
        link.section = "Pages";
        link.title = humanizeSlug(res[i][0]);
        // Prefer a real title: og:title, then the page's first <h1>, then the slug.
        link.title = res[i][2];
        if(link.title.empty()){
            std::string text = res[i][4];
            size_t h = text.find("<h1");
            size_t gt = h==std::string::npos ? h : text.find('>', h);
            size_t e = gt==std::string::npos ? gt : text.find("</h1>", gt);
            if(e!=std::string::npos) link.title = text.substr(gt+1, e-gt-1);   // tags are stripped by llms.txt
        }
        if(link.title.empty()) link.title = humanizeSlug(res[i][0]);
        link.url = Args->config->absoluteurl(Args->config->buildurl("staticpage/"+res[i][0]));
        link.description = res[i][1];
        link.description = !res[i][3].empty() ? res[i][3] : res[i][1];
        links.push_back(std::move(link));
    }
}
+106 −8
Changes for src/blogi.cpp: 106 added lines, 8 removed lines.
Original line number Diff line number Diff line
@@ -88,6 +88,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "blogi.h"
#include "compress.h"
#include <cstring>
#include <chrono>
#include <map>
#include <mutex>

#define cookieid "2d1b0348-1491-11f0-8c81-3cecefce9ac2"

@@ -3224,11 +3228,88 @@ void blogi::Blogi::sitemapXML(libhttppp::HttpRequest &curreq, const int tid, con
// Root /llms.txt per https://llmstxt.org/: an H1 (site name, the spec's only
// mandatory section) followed by "## Section" link lists gathered from every
// plugin's GetLlmsLinks() override (e.g. static pages, blog posts).
namespace {
    // llms.txt is rebuilt from every plugin's DB rows; checkers fetch it with
    // short timeouts, so keep the rendered text per site for a few minutes.
    struct LlmsCacheEntry {
        std::chrono::steady_clock::time_point built;
        std::string body;
    };
    std::mutex llmsCacheMtx;
    std::map<std::string, LlmsCacheEntry> llmsCache;
    constexpr auto llmsCacheTtl = std::chrono::minutes(5);

    // Descriptions come from post teasers and page meta and may contain HTML
    // (<br/>, links). llms.txt is Markdown: drop tags, decode common entities.
    std::string llmsPlainText(const std::string &in) {
        std::string out;
        out.reserve(in.size());
        for (size_t i = 0; i < in.size(); ++i) {
            if (in[i] == '<') {
                size_t end = in.find('>', i);
                if (end == std::string::npos) break;
                out += ' ';
                i = end;
                continue;
            }
            if (in[i] == '&') {
                static const std::pair<const char *, const char *> ents[] = {
                    {"&amp;", "&"}, {"&lt;", "<"}, {"&gt;", ">"}, {"&quot;", "\""},
                    {"&#39;", "'"}, {"&apos;", "'"}, {"&nbsp;", " "}};
                bool done = false;
                for (const auto &e : ents) {
                    size_t l = std::strlen(e.first);
                    if (in.compare(i, l, e.first) == 0) {
                        out += e.second;
                        i += l - 1;
                        done = true;
                        break;
                    }
                }
                if (done) continue;
            }
            out += in[i];
        }
        return out;
    }

    // Keep one-line descriptions short; cut at a word boundary (UTF-8 safe).
    std::string llmsShorten(const std::string &text, size_t max) {
        if (text.size() <= max) return text;
        size_t cut = text.rfind(' ', max);
        if (cut == std::string::npos || cut < max / 2) {
            cut = max;
            while (cut > 0 && (static_cast<unsigned char>(text[cut]) & 0xC0) == 0x80) --cut;
        }
        return text.substr(0, cut) + "…";
    }
}

void blogi::Blogi::llmsTxtRoot(libhttppp::HttpRequest &curreq, const int tid, const std::string &sessionid, DomainContext &ctx)
{
    auto &PlgArgs = ctx.plgArgs;
    auto &BlogiPlg = ctx.plugins;

    auto sendLlms = [&curreq](const std::string &body) {
        libhttppp::HttpResponse curres;
        curres.setState(HTTP200);
        curres.setContentType("text/plain; charset=utf-8");
        curres.setHeaderData("Cache-Control")->push_back("public, max-age=3600");
        curres.setHeaderData("Access-Control-Allow-Origin")->push_back("*");
        sendCompressed(curreq, curres, body.c_str(), body.length());
    };

    const std::string cacheKey = PlgArgs->config->getsiteurl();
    {
        std::lock_guard<std::mutex> lk(llmsCacheMtx);
        auto it = llmsCache.find(cacheKey);
        if (it != llmsCache.end() && std::chrono::steady_clock::now() - it->second.built < llmsCacheTtl) {
            std::string body = it->second.body;
            sendLlms(body);
            return;
        }
    }

    std::vector<blogi::LlmsLink> links;
    for (const blogi::Plugin::PluginData *curplg = BlogiPlg->getFirstPlugin(); curplg; curplg = curplg->getNextPlg())
    {
@@ -3259,8 +3340,21 @@ void blogi::Blogi::llmsTxtRoot(libhttppp::HttpRequest &curreq, const int tid, co
    siteTitle = collapse(siteTitle);
    if (siteTitle.empty()) siteTitle = collapse(PlgArgs->config->getsiteurl());

    std::string siteDesc;
    try { getConfig(*PlgArgs->database[tid], "SITE_DESCRIPTION", siteDesc); } catch (...) {}
    siteDesc = collapse(llmsPlainText(siteDesc));

    std::stringstream out;
    out << "# " << siteTitle << "\n";
    out << "# " << siteTitle << "\n\n";
    // llmstxt.org: a blockquote with a short summary follows the H1.
    if (!siteDesc.empty()) {
        out << "> " << siteDesc << "\n";
    } else {
        size_t posts = 0, pages = 0;
        for (const auto &l : links) (collapse(l.section) == "Pages" ? pages : posts)++;
        out << "> Inhalte von " << siteTitle << ": " << posts << " Beiträge und "
            << pages << " Seiten. Jeder Link führt zur jeweiligen Seite.\n";
    }

    // Group by each plugin's declared section (e.g. "Pages", "Blog") in
    // first-seen order, matching the spec's "## Section" file-list shape.
@@ -3277,18 +3371,22 @@ void blogi::Blogi::llmsTxtRoot(libhttppp::HttpRequest &curreq, const int tid, co
    for (const auto &section : sectionOrder) {
        out << "\n## " << section << "\n\n";
        for (const auto *link : sections[section]) {
            std::string title = collapse(link->title);
            std::string title = collapse(llmsPlainText(link->title));
            // "[" / "]" in a title would end the Markdown link text early.
            for (auto &c : title) if (c == '[') c = '('; else if (c == ']') c = ')';
            out << "- [" << (title.empty() ? link->url : title) << "](" << link->url << ")";
            std::string desc = collapse(link->description);
            if (!desc.empty()) out << ": " << desc;
            std::string desc = llmsShorten(collapse(llmsPlainText(link->description)), 200);
            if (!desc.empty() && desc != title) out << ": " << desc;
            out << "\n";
        }
    }

    libhttppp::HttpResponse curres;
    curres.setState(HTTP200);
    curres.setContentType("text/plain; charset=utf-8");
    curres.send(curreq, out.str());
    const std::string body = out.str();
    {
        std::lock_guard<std::mutex> lk(llmsCacheMtx);
        llmsCache[cacheKey] = {std::chrono::steady_clock::now(), body};
    }
    sendLlms(body);
};

// /.well-known/ai-catalog.json (https://ai-catalog.io/spec/): lists the