Packages

A layered agent framework for Elixir: structured output, tool-calling, streaming, stateful supervised agents, multi-agent sessions, durable persistence, compaction/cost/permissions and MCP — powered by the BEAM.

Current section

Files

Jump to
exagent docs markdown_formatter.exs
Raw

docs/markdown_formatter.exs

defmodule ExAgent.Docs.Markdown do
  @moduledoc false

  @root Path.expand("..", __DIR__)
  @llm_guides_dir Path.join(@root, "docs/guides/llm")
  @entry_points """
  ## Recommended LLM Entry Points

  Start with the surgical low-context path (`agents.md` + `usage-rules.md` + one matching skill or contract sheet). Use `llms-full.txt` only when you want a single-fetch bundle of the rules, skills, contracts and support limits (for exact per-function module docs, fetch `<Module>.md` from the Modules section below).

  - [Coding-agent manual](agents.md)
  - [Usage rules (LLM)](usage-rules.md)
  - [Tools and models contracts (LLM)](tools-and-models-contracts.md)
  - [Runtime and operations contracts (LLM)](runtime-and-ops-contracts.md)
  - [Supported features and API tiers](status.md)
  - [Known limits](known-limits.md)
  - [Single-fetch LLM reference bundle](llms-full.txt)
  """

  # ExDoc's public custom-formatter callback. Keep stock generation, then rebase
  # source-relative links for flattened Markdown. No changes to ExDoc, runtime
  # code, source snippets or the HTML/EPUB formatters.
  def run(config, modules, extras) do
    config = %{
      config
      | description:
          "ExAgent #{config.version}: usage guides and public API reference. " <>
            (config.description || "")
    }

    result = apply(ExDoc.Formatter.MARKDOWN, :run, [config, modules, extras])
    sources = Map.new(extras, &{Path.expand(&1.source_path), &1.id <> ".md"})
    pages = MapSet.new(Enum.map(extras ++ modules, &(&1.id <> ".html")))

    for extra <- extras do
      path = Path.join(config.output, extra.id <> ".md")
      File.write!(path, rebase(extra.source_doc, extra.source_path, sources, pages))
    end

    # Module documentation can reference extras by repository path (including
    # ExAgent's README-derived moduledoc). Rebase those stock Markdown files too.
    for module <- modules do
      path = Path.join(config.output, module.id <> ".md")

      File.write!(
        path,
        rebase(File.read!(path), module.source_path || "README.md", sources, pages)
      )
    end

    write_full_reference(config, modules, extras)
    add_entry_points(config.output)
    %{result | build: result.build ++ ["llms-full.txt"]}
  end

  defp write_full_reference(config, _modules, extras) do
    read_page = &File.read!(Path.join(config.output, &1 <> ".md"))
    read_source = &File.read!(Path.join(@root, &1))

    skills =
      @root
      |> Path.join("usage-rules/skills/*/SKILL.md")
      |> Path.wildcard()
      |> Enum.sort()
      |> Enum.map(&format_skill(File.read!(&1)))

    contracts =
      extras
      |> Enum.filter(&(Path.dirname(Path.expand(&1.source_path)) == @llm_guides_dir))
      |> Enum.sort_by(& &1.source_path)
      |> Enum.map(&demote_headings(read_page.(&1.id), 2))

    status_summary =
      read_page.("status")
      |> drop_markdown_section("Select the capability you need")
      |> demote_headings(2)

    sections =
      [
        {"Coding agent manual", [demote_headings(read_page.("agents"), 2)]},
        {"Usage rules", [demote_headings(read_source.("usage-rules.md"), 2)]},
        {"Skills", skills},
        {"Detailed contracts", contracts},
        {"Support and limits", [status_summary, demote_headings(read_page.("known-limits"), 2)]}
      ]
      |> Enum.reject(fn {_title, documents} -> documents == [] end)

    header = """
    # ExAgent #{config.version} — LLM Reference Bundle

    Stable APIs follow the published compatibility contract. Candidate APIs and options can change in minor releases. Check the member and option tier as well as the module tier.

    This single-fetch bundle includes the coding-agent manual, usage rules, all 11 skills, both detailed contract sheets, and the support/limits contract sections. It does not inline per-function module documentation or full human tutorials — use [llms.txt](llms.txt) to locate and fetch individual `<Module>.md` or guide `.md` pages.

    ## Contents
    """

    contents =
      Enum.map_join(sections, "\n", fn {title, _} ->
        anchor = title |> String.downcase() |> String.replace(" ", "-")
        "- [#{title}](##{anchor})"
      end)

    body =
      Enum.map_join(sections, "\n\n---\n\n", fn {title, documents} ->
        "## #{title}\n\n" <> Enum.map_join(documents, "\n\n---\n\n", &String.trim/1)
      end)

    File.write!(Path.join(config.output, "llms-full.txt"), [
      header,
      "\n",
      contents,
      "\n\n",
      body,
      "\n"
    ])
  end

  defp format_skill(markdown) do
    case Regex.run(~r/\A---\n(.*?)\n---\n(.*)\z/s, markdown) do
      [_, frontmatter, body] ->
        name =
          case Regex.run(~r/^name:\s*(.+)$/m, frontmatter) do
            [_, value] -> String.trim(value)
            _ -> "skill"
          end

        description =
          frontmatter
          |> String.replace(~r/^name:.*\n?/m, "")
          |> String.replace(~r/^description:\s*>?\s*\n?/m, "")
          |> String.split("\n")
          |> Enum.map(&String.trim/1)
          |> Enum.reject(&(&1 == ""))
          |> Enum.join(" ")

        "### Skill: `#{name}`\n\n> #{description}\n\n" <> demote_headings(String.trim(body), 3)

      _ ->
        demote_headings(String.trim(markdown), 2)
    end
  end

  defp drop_markdown_section(markdown, heading) do
    pattern = ~r/\n## #{Regex.escape(heading)}\n.*?(?=\n## |\z)/s
    Regex.replace(pattern, markdown, "\n")
  end

  defp demote_headings(markdown, offset) do
    {lines, _fence} =
      markdown
      |> String.split("\n")
      |> Enum.map_reduce(nil, fn line, fence ->
        marker = Regex.run(~r/^\s{0,3}(`{3,}|~{3,})/, line)

        cond do
          marker && is_nil(fence) ->
            [_, opening] = marker
            {line, opening}

          marker && fence && closes?(line, fence) ->
            {line, nil}

          fence ->
            {line, fence}

          true ->
            case Regex.run(~r/^(#+)\s+(.*)$/, line) do
              [_, hashes, rest] ->
                level = min(String.length(hashes) + offset, 6)
                {String.duplicate("#", level) <> " " <> rest, nil}

              _ ->
                {line, nil}
            end
        end
      end)

    Enum.join(lines, "\n")
  end

  defp add_entry_points(output) do
    path = Path.join(output, "llms.txt")
    [heading, description, navigation] = String.split(File.read!(path), "\n\n", parts: 3)
    File.write!(path, [heading, "\n\n", description, "\n\n", @entry_points, "\n", navigation])
  end

  # Tooling regression seam; this module never enters lib/.
  def rebase(markdown, source_path, sources, pages) do
    {lines, _fence} =
      markdown
      |> String.split("\n")
      |> Enum.map_reduce(nil, fn line, fence ->
        marker = Regex.run(~r/^\s{0,3}(`{3,}|~{3,})/, line)

        cond do
          marker && is_nil(fence) ->
            [_, opening] = marker
            {line, opening}

          marker && fence && closes?(line, fence) ->
            {line, nil}

          fence ->
            {line, fence}

          true ->
            {rebase_line(line, source_path, sources, pages), nil}
        end
      end)

    Enum.join(lines, "\n")
  end

  defp closes?(line, fence) do
    marker = String.first(fence)
    pattern = "^\\s{0,3}" <> marker <> "{" <> to_string(String.length(fence)) <> ",}\\s*$"
    Regex.match?(Regex.compile!(pattern), line)
  end

  defp rebase_line(line, source, sources, pages) do
    if Regex.match?(~r/^\[[^\]]+\]:\s*/, line) do
      rebase_text(line, source, sources, pages)
    else
      ~r/(`+[^`]*`+)/
      |> Regex.split(line, include_captures: true)
      |> Enum.map_join(fn part ->
        if String.starts_with?(part, "`"),
          do: part,
          else: rebase_text(part, source, sources, pages)
      end)
    end
  end

  defp rebase_text(text, source, sources, pages) do
    rewrite = &destination(&1, source, sources, pages)

    text =
      Regex.replace(~r/(\]\()([^\s)]+)(?=[\s)])/, text, fn _, prefix, path ->
        prefix <> rewrite.(path)
      end)

    text =
      Regex.replace(~r/^(\[[^\]]+\]:\s*)(\S+)/, text, fn _, prefix, path ->
        prefix <> rewrite.(path)
      end)

    Regex.replace(~r/(href=")([^"]+)(")/, text, fn _, prefix, path, suffix ->
      prefix <> rewrite.(path) <> suffix
    end)
  end

  defp destination(path, source, sources, pages) do
    uri = URI.parse(path)

    if uri.scheme || uri.host || is_nil(uri.path) || uri.path == "" do
      path
    else
      original = Path.expand(URI.decode(uri.path), Path.dirname(Path.expand(source)))

      target =
        Map.get(sources, original) ||
          Map.get(sources, Path.expand(URI.decode(uri.path))) ||
          if(MapSet.member?(pages, uri.path), do: String.replace_suffix(uri.path, ".html", ".md"))

      if target, do: URI.to_string(%{uri | path: target}), else: path
    end
  end
end