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.
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.
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:
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:
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:
project = "Orbit"
plugins = ["product-badge"]
plugin_timeout = 60
[plugin_configs]
product-badge = "badge.toml"
Create build/plugin-tutorial/badge.toml:
product = "Orbit"
Replace build/plugin-tutorial/index.rst with:
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:
build/guidedog plugin register product-badge ./build/product-badge \
--project=build/plugin-tutorial --config=badge.toml
On Windows, use one PowerShell command:
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:
build/guidedog build html build/plugin-tutorial -W
build/guidedog serve build/plugin-tutorial
On Windows, run:
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
badge.odin and
main.odin to keep a local copy.
Keep their directory structure, or adjust the relative imports in your own project.
// A build plugin: typed source and HTML hooks, plus a generated CSS asset.
// Compile from the checkout root:
// odin build examples/build-plugin -out:build/product-badge
package product_badge
import "core:fmt"
import "core:strings"
import "../../../lib/plugins"
import "../../../lib/toml"
Settings :: struct { product: string }
// plugin describes services. Nil procedures mean services this plugin does not offer.
plugin :: proc() -> plugins.Plugin {
return {id = "product-badge", name = "Product badge", version = "1.0.0",
api = plugins.PLUGIN_API_VERSION, load = load, source = source,
html = html, assets = assets}
}
load :: proc(ctx: ^plugins.Plugin_Load_Context) -> plugins.Problem {
text, problem := plugins.read_plugin_config(ctx)
if problem.exit != 0 do return problem
root, error := toml.parse(text)
path := ctx.session.options.config
if error.line != 0 do return {"badge.toml", "Cannot read the badge settings",
fmt.aprintf("%s:%d", path, error.line), error.message,
"Write product = \"Orbit\" in this TOML file.", 2}
product := toml.get(&root, "product")
if product == nil || product.kind != .String || len(product.text) == 0 ||
len(product.text) > 256 || strings.contains_any(product.text, "\r\n\x00") {
return {"badge.product", "The product name is missing or invalid", path,
"product must be a nonempty string on one line, at most 256 bytes long.",
"Set product = \"Orbit\" in this file.", 2}
}
settings, err := new(Settings, ctx.allocator)
if err != nil do return plugins.memory()
settings.product = product.text // the session owns the configuration's parsed text.
ctx.session.data = settings
return {}
}
source :: proc(ctx: ^plugins.Source_Context) -> plugins.Problem {
settings := (^Settings)(ctx.session.data)
marker :: "{{product}}"
count := strings.count(ctx.input.text, marker)
growth := len(settings.product) - len(marker)
if growth > 0 && count > (plugins.MAX_PLUGIN_TEXT - len(ctx.input.text)) / growth {
return {"badge.source-size", "The expanded source would be too large", ctx.input.path,
"Replacing every product marker would exceed the 8 MiB source limit.",
"Use fewer markers, a shorter product name, or split the document.", 2}
}
text, _ := strings.replace_all(ctx.input.text, "{{product}}", settings.product,
ctx.allocator)
if plugins.memory_refused(ctx.allocator) do return plugins.memory()
ctx.text = text
return {}
}
html :: proc(ctx: ^plugins.Html_Context) -> plugins.Problem {
settings := (^Settings)(ctx.session.data)
if !strings.contains(ctx.input.text, "</head>") ||
!strings.contains(ctx.input.text, "</body>") {
return {"badge.html", "The badge needs a complete HTML page", ctx.input.path,
"The selected template has no closing head or body tag.",
"Add </head> and </body> to the template, or disable product-badge for this build.", 2}
}
label := escape_html(settings.product)
css := fmt.aprintf("<link rel=\"stylesheet\" href=\"%sbanner.css\">\n</head>",
ctx.input.assets_url)
badge := fmt.aprintf("<aside class=\"product-badge\" aria-label=\"Product\">%s</aside>" +
"\n</body>", label)
growth := len(css) + len(badge) - len("</head></body>")
if growth > plugins.MAX_PLUGIN_TEXT - len(ctx.input.text) do return {
"badge.html-size", "The badge would exceed the HTML limit", ctx.input.path,
"This page has no room for the generated label and stylesheet link.",
"Split this page or shorten the configured product name.", 2}
head := replace_once(ctx.input.text, "</head>", css)
ctx.text = replace_once(head, "</body>", badge)
if plugins.memory_refused(ctx.allocator) do return plugins.memory()
return {}
}
replace_once :: proc(text, marker, replacement: string) -> string {
at := strings.last_index(text, marker)
return strings.concatenate({text[:at], replacement, text[at + len(marker):]})
}
CSS :: ".product-badge { border-inline-start: 3px solid #216553; " +
"padding: .5rem 1rem; margin: 1rem; font-weight: 700; }\n"
assets :: proc(ctx: ^plugins.Assets_Context) -> plugins.Problem {
files, err := make([]plugins.Plugin_Asset, 1, ctx.allocator)
if err != nil do return plugins.memory()
files[0] = {path = "banner.css", data = transmute([]u8)string(CSS)}
ctx.assets = files // collect_assets returns its own copy, including the static bytes.
return {}
}
escape_html :: proc(text: string) -> string {
escaped, _ := strings.replace_all(text, "&", "&")
escaped, _ = strings.replace_all(escaped, "<", "<")
escaped, _ = strings.replace_all(escaped, ">", ">")
return escaped
}
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:
// Compile from the checkout root. This entry point adapts an ordinary Odin package
// to the installed-plugin protocol; embedded applications import badge directly.
package main
import "core:fmt"
import "core:os"
import "../../lib/plugins"
import "badge"
run :: proc() -> int {
if len(os.args) == 2 && os.args[1] == plugins.PROTOCOL_FLAG {
return plugins.serve_plugin(badge.plugin(), os.stdin, os.stdout)
}
fmt.eprintln("Run this plugin through guidedog build with plugins = [\"product-badge\"].")
return 2
}
main :: proc() { os.exit(run()) }
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¶
| 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.
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:
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 Publish to GitHub Pages for the
complete user workflow, and the API reference for 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.