Write a native plugin ===================== A plugin adds a service to Guidedog. A build plugin can transform source text, transform a rendered HTML page, or supply static files. A publisher sends a finished site to a destination. These services use ordinary Odin procedure tables. This chapter builds a product badge. It replaces ``{{product}}`` in source text, adds a label to HTML pages, and supplies the label's CSS. GitHub Pages then shows how the same plugin foundation supports a service with external effects. .. note:: Build hooks are available from Guidedog 0.6.2. Earlier 0.6.x releases support publishers only. Use a 0.6.2 host or build it from this checkout before following the badge tutorial. 1. Understand the boundary -------------------------- ``plugins.Plugin`` describes the plugin. Its ``source``, ``html`` and ``assets`` procedures are optional. A nil procedure means that service is absent. ``load`` prepares private state; ``unload`` closes resources. The host owns the build. .. graphviz:: :class: graphviz-adaptive :caption: Build services precede publication. :alt: Source hooks precede parsing. HTML hooks and generated assets enter staging. Publication follows a successful build. digraph hooks { graph [rankdir=TB, bgcolor="transparent", pad="0.3", nodesep="0.4", ranksep="0.4"]; node [shape=box, style="rounded,filled", fillcolor="#edf5f2", color="#216553", fontname="Helvetica", fontcolor="#16382f", fontsize=12, margin="0.2,0.12"]; edge [color="#216553", fontname="Helvetica", fontcolor="#16382f", fontsize=10]; read [class="gd-input", label="Source text (RST / Markdown)", shape=note, fillcolor="#fbfaf3"]; source [class="gd-plugin", label=<process_source hook
Pre-parse text transformation>, style="rounded,dashed,filled", fillcolor="#fff9e6", color="#ca8a04", fontcolor="#854d0e"]; parse [label=<Parse and resolve references
Build flat preorder doctrees>, fillcolor="#edf5f2"]; render [label=<Render resolved documents
HTML or Typst PDF>, fillcolor="#edf5f2"]; html [class="gd-plugin", label=<process_html hook
Transform complete HTML text>, style="rounded,dashed,filled", fillcolor="#fff9e6", color="#ca8a04", fontcolor="#854d0e"]; assets [class="gd-plugin", label=<collect_assets hook
Custom files to _static/plugins/ID/>, style="rounded,dashed,filled", fillcolor="#fff9e6", color="#ca8a04", fontcolor="#854d0e"]; stage [label=<Stage and verify complete output
Write to .<target>.next>, fillcolor="#edf5f2"]; commit [label=<Publish local generation
Journaled generation switch>, shape=cylinder, fillcolor="#e0eee9"]; publish [class="gd-input", label=<Optional publisher service
(guidedog-pages or custom deployer)>, style="rounded,dashed,filled", fillcolor="#fbfaf3"]; assets -> read [style=dashed, label="setup first"]; read -> source -> parse -> render; render -> html -> stage; render -> stage [label="PDF / text"]; assets -> stage; stage -> commit -> publish; } Source hooks run before parsing each primary RST or Markdown document. They apply to PDF and text builds too. Includes remain the engine's responsibility. HTML hooks receive complete pages, including generated indexes and additional pages. Generated assets belong to HTML builders and live below ``_static/plugins/ID/``. The host collects them once during plugin setup, before reading documents. They are fixed for that build; source and HTML hooks cannot add later assets. A plugin table contains build hooks or a publisher, never both. Normal builds cannot invoke a publishing service. Installed plugins are trusted native programs; registration is explicit and pins the executable's SHA-256. It is not a sandbox. 2. Compile the working example ------------------------------ Start at the checkout root. Build Guidedog using the repository's build instructions, then use that host for this tutorial. The example package is ``examples/build-plugin/badge``; its executable entry point is one directory above. On macOS or Linux, run: .. code-block:: sh odin build examples/build-plugin -vet -strict-style -out:build/product-badge build/guidedog quickstart build/plugin-tutorial -q -p Orbit -a Team On Windows, run these commands in PowerShell: .. code-block:: powershell odin build examples/build-plugin -vet -strict-style -out:build/product-badge.exe build/guidedog.exe quickstart build/plugin-tutorial -q -p Orbit -a Team The compiler creates the executable in the first command. The second creates the documentation project. Registration follows after configuration. Users of a packaged plugin need no Odin compiler. 3. Select it for a project -------------------------- Replace ``build/plugin-tutorial/conf.toml`` with: .. code-block:: toml project = "Orbit" plugins = ["product-badge"] plugin_timeout = 60 [plugin_configs] product-badge = "badge.toml" Create ``build/plugin-tutorial/badge.toml``: .. code-block:: toml product = "Orbit" Replace ``build/plugin-tutorial/index.rst`` with: .. code-block:: rst Welcome ======= Hello {{product}}. Configuration paths are relative to the project configuration directory. Plugins run in the order listed in ``plugins``. Merely registering a program does not run it. Register after writing the configuration. Registration checks the build plugin in child processes before recording its checksum. On macOS or Linux: .. code-block:: sh build/guidedog plugin register product-badge ./build/product-badge \ --project=build/plugin-tutorial --config=badge.toml On Windows, use one PowerShell command: .. code-block:: powershell build/guidedog.exe plugin register product-badge ./build/product-badge.exe --project=build/plugin-tutorial --config=badge.toml 4. Build and observe -------------------- On macOS or Linux, run: .. code-block:: sh build/guidedog build html build/plugin-tutorial -W build/guidedog serve build/plugin-tutorial On Windows, run: .. code-block:: powershell build/guidedog.exe build html build/plugin-tutorial -W build/guidedog.exe serve build/plugin-tutorial Open the address printed by the server. The page says "Hello Orbit." and has an Orbit badge. Its stylesheet is ``_static/plugins/product-badge/banner.css``. Change the configured name to ``Comet`` and build again. Both the text and badge change. A further unchanged build writes no output files. 5. Read the implementation -------------------------- The complete package below is the source compiled in step 2. Download :download:`badge.odin <_static/repository/build-plugin.odin>` and :download:`main.odin <_static/repository/build-plugin-main.odin>` to keep a local copy. Keep their directory structure, or adjust the relative imports in your own project. .. literalinclude:: _static/repository/build-plugin.odin :language: odin ``plugin()`` is the public descriptor. ``load`` reads bounded UTF-8 configuration, checks its type and size, and allocates ``Settings`` in the session. The source hook checks expansion size before allocating. It replaces every marker, including markers inside code blocks; this is a text transformation, not a markup parser. The HTML hook escapes the label and inserts it before the last closing body tag. It uses ``assets_url`` supplied by the host, so nested pages link to the right CSS. This small example expects literal lowercase closing head and body tags. A plugin that rewrites arbitrary HTML should use a suitable parser and state its contract. The assets hook allocates its result array with ``ctx.allocator``. The CSS bytes are static. The SDK copies both paths and bytes into an owned result. Never return a slice pointing at a callback's local array. Session state must not retain hook inputs or hook-result allocations. The executable wrapper exposes the same descriptor over standard streams: .. literalinclude:: _static/repository/build-plugin-main.odin :language: odin ``serve_plugin`` handles negotiation and dispatch. Keep protocol output on stdout; write human logs to stderr. Return to ``main`` before ``os.exit`` so deferred cleanup runs. An embedded host instead passes the descriptor in ``project.Load_Options.plugins`` and selects its ID in the project's configuration. 6. Keep ownership and caching explicit -------------------------------------- .. list-table:: Build-plugin owners :header-rows: 1 * - Owner - Create - Release * - ``Plugin_Session`` - ``load_plugin`` - ``unload_plugin`` * - ``Text_Result`` - ``process_source`` or ``process_html`` - ``release_text`` * - ``Assets_Result`` - ``collect_assets`` - ``release_assets`` Cleanup accepts zero, failed and already released owners. Allocate returned data with the callback allocator. Check allocation errors; after helpers that hide those errors, check ``plugins.memory_refused(ctx.allocator)``. Return ``plugins.memory()`` when refused. Unload must tolerate a partially loaded session. Use ``read_plugin_config`` and ``read_plugin_file`` during load. They fingerprint the bytes actually read and declare dependencies. Keep loaded state unchanged throughout the build. If you read other files yourself, declare their paths in ``session.dependencies`` and append a fingerprint of the loaded values to ``session.cache_key``. Append selected environment values there too. Do not erase the fingerprints recorded by the SDK helpers or depend on undeclared changing data. The host includes identity, configuration, dependencies, cache key, builder, language and generated assets in cache invalidation. Each build gets private sessions. Reading workers serialize callback access; callbacks need not be thread safe. Native callbacks cannot be interrupted by a process deadline. Installed programs have a deadline per whole request, including pipe writes. .. graphviz:: :class: graphviz-adaptive :caption: Installed build-plugin lifecycle. Asset collection belongs to setup. :alt: Guidedog loads a plugin and collects HTML assets before reading sources. Hooks run during reading and rendering. Cleanup follows success or failure. digraph plugin_sequence { graph [rankdir=TB, bgcolor="transparent", pad="0.3", nodesep="0.4", ranksep="0.4"]; node [shape=box, style="rounded,filled", fillcolor="#edf5f2", color="#216553", fontname="Helvetica", fontcolor="#16382f", fontsize=12, margin="0.2,0.12"]; edge [color="#216553", fontname="Helvetica", fontcolor="#16382f", fontsize=10]; start [label=<Start private process
Handshake; verify identity and hooks>]; load [class="gd-plugin", label=<load_plugin
Read configuration; establish session>, style="rounded,dashed,filled", fillcolor="#fff9e6"]; assets [class="gd-plugin", label=<collect_assets
Once, for HTML builders only>, style="rounded,dashed,filled", fillcolor="#fff9e6"]; source [class="gd-plugin", label=<process_source
Before each primary source is parsed>, style="rounded,dashed,filled", fillcolor="#fff9e6"]; core [label=<Parse and resolve
Host owns the document graph>]; html [class="gd-plugin", label=<Render; process_html
HTML hooks receive complete pages>, style="rounded,dashed,filled", fillcolor="#fff9e6"]; commit [label=<Complete staging; commit
Only after successful validation>]; unload [class="gd-input", label=<unload_plugin
Cleanup also runs on failed builds>, shape=oval, fillcolor="#fbfaf3"]; start -> load -> assets -> source -> core -> html -> commit -> unload; core -> commit [label="PDF / text"]; } Text is limited to 8 MiB per hook. Each plugin may supply at most 256 assets and 16 MiB of asset bytes. Paths must be portable and relative. Duplicate names, case-only collisions, traversal and conflicts with project files are refused. ``--untrusted`` disables build plugins. Child-process memory is outside the host's build budget; native plugin code must still check allocations and its own limits. 7. Explain failures and test them --------------------------------- Return a ``Problem`` with a code, title, affected path, explanation, concrete correction and nonzero exit status. For example, ``product = 42`` is invalid; the badge explains that a string is required and suggests ``product = "Orbit"``. Markup diagnostics after expansion identify plugin-expanded input and show its actual excerpt. They do not pretend expanded line numbers belong to the original. Test the package directly and through its executable. Cover changed settings, unchanged rebuilds, nested links, invalid markup, asset collisions, cancellation, timeouts and allocation refusal. A failed build must preserve the previous site. The repository's build-plugin integration test compiles this exact example and checks HTML, directory HTML, single-page HTML, text and failed generations. 8. Add a publishing service --------------------------- GitHub Pages uses the same explicit descriptor foundation: .. code-block:: odin package main import "core:fmt" import "guidedog:pages" import "guidedog:plugins" main :: proc() { descriptor := plugins.publisher_plugin(pages.publisher()) fmt.println(descriptor.id) } Its ``Publisher`` supplies ``load``, ``plan``, ``publish``, ``status`` and ``recover``. A session owns configuration and credentials. A snapshot owns checked site files. A plan compares that snapshot with a target baseline. A result reports the verified outcome. Release each owner with its matching SDK procedure. Follow ``examples/pages-publisher/main.odin`` into ``lib/pages``: configuration and machine binding establish authority; planning reads the target; publishing writes a durable journal before one conditional Git push; status and recovery settle the outcome. Nothing in a source or HTML callback grants publication authority. A remote acceptance is not a live deployment. ``Accepted`` and ``Pending`` return 6; an uncertain write returns ``Unknown`` and 7, with status or recovery directions. Never retry an uncertain write blindly. See :doc:`howto/github-pages` for the complete user workflow, and the API reference for :odin:type:`~plugins.Publisher`. 9. Version and distribute the contract -------------------------------------- Build-plugin API 1.0 uses protocol ``guidedog-build-plugin`` 1.0. Publisher SDK 1.1 keeps ``guidedog-publisher`` protocol 1.0 and accepts SDK 1.0 publishers. These are separate contracts; older hosts reject build plugins rather than treating them as publishers. Product versions are separate from interface versions. Register each rebuilt executable deliberately. ``guidedog plugin inspect ID`` shows its kind and declared hooks. The public catalog describes plugins; it does not download, install or run them. Custom markup readers and renderers still use the compiled ``core.Registry`` API. Installed custom directives, roles and builders are not part of this build-hook interface. 10. Check a plugin before registering it ---------------------------------------- ``guidedog plugin check PATH --project=DIR --config=FILE`` exercises a build plugin without changing the registry. Registration runs the same checks automatically: two fresh loads, repeated source and HTML results, generated asset validation and cleanup. ``--timeout=SECONDS`` defaults to 60 per process request. Supply a real configuration when the plugin needs one. Relative configuration paths resolve from ``--project``; its default is the current directory. Passing checks demonstrates interoperability, not a proof of safety. Guidedog keeps checking every runtime response and runs installed plugins in separate processes. A crash, bounds failure or stalled process becomes a diagnostic and cannot publish an incomplete generation. Earlier publisher compatibility is no longer a release requirement; qualification checks demonstrate interoperability across process boundaries, while directly linked native callbacks remain trusted code. Generic checks never invoke a publisher. Qualify publishers with their own Odin tests and an explicitly configured dry run. A plugin that changes the parser, node model or builder itself belongs in a separate design; the modular libraries and source remain available for an application or a fork.