Write an extension #
Use this guide to add capabilities through an extension. Read the extension reference, plugin contracts, and shared contribution rules before choosing an owner.
Follow the SDK import contract when choosing shared helpers, daemon imports, and native bindings. The extension API reference covers every public SDK function and explains how to build the searchable reference with exact signatures.
Build a command extension #
This example adds commands.greet(name) to the model's Python namespace. It
reads a declared prefix setting and returns a greeting. It needs no new
Erlang, actor, database table, or provider credentials.
Extensions are compiled into Albedo. Adding a source file does not install it into an already running daemon, and the SDK is currently part of this repository rather than a separately versioned package.
Create src/albedo/harness/extensions/greeting/extension.gleam:
import albedo/harness/sdk/command
import albedo/harness/sdk/extension
import albedo/harness/sdk/settings
import gleam/dict
import gleam/dynamic/decode
import gleam/json
import gleam/option.{None}
import gleam/result
pub fn extension() -> extension.Extension {
extension.Extension(
name: "greeting",
description: "A configurable greeting command.",
requires: ["commands"],
plugins: [
extension.SettingsPlugin(settings.declaration(configuration())),
extension.CommandPlugin([greet()]),
],
initialise: extension.no_initialise,
)
}
fn configuration() -> settings.Section(String) {
let prefix =
settings.text(
"prefix",
"Greeting prefix",
"Text before the person's name.",
"Hello",
)
settings.section(
"greeting",
"Greeting",
settings.Tools,
[settings.field(prefix)],
{
use value <- settings.value(prefix)
decode.success(value)
},
fn(value) { Ok(value) },
)
}
fn greet() -> command.Command {
command.Command(
name: "/greet",
description: "Return a greeting for a person.",
arguments: [command.Argument("name", "The person's name.", True, [])],
model_callable: True,
user_turn: False,
page: False,
skill_activation: None,
run: fn(_context, _caller, arguments) {
use name <- result.try(
dict.get(arguments, "name")
|> result.replace_error("name is required"),
)
use prefix <- result.map(settings.load_section(configuration()))
command.Data(json.string(prefix <> ", " <> name <> "!"))
},
)
}
The owners are sdk/command for
command dispatch, sdk/settings for
settings validation and persistence, and the new greeting module for the
command's behavior. The commands dependency supplies the Python binding.
Add this import to
src/albedo/harness/extensions.gleam:
import albedo/harness/extensions/greeting/extension as greeting
Add greeting.extension() to the first list in declared(). Leave the
default_enabled list unchanged for an opt-in extension. Compile it:
nix develop -c gleam check
The command reads settings when invoked. The declaration only builds values, so
a sealed build does not freeze a developer's home or environment into the
extension. settings.load_section validates the saved section and returns the
default prefix when the section or key is missing. Invalid saved settings return
an error instead of silently replacing them.
After rebuilding and starting that build, enable greeting for a session
through /extensions. The model can then run:
await commands.greet("Ada")
# "Hello, Ada!"
CommandPlugin supplies the model command contract. To expose a human resource
operation in the clients, also declare its HTTP operation with
ClientPlugin. Do not assume that a slash name
alone supplies a client HTTP endpoint.
Exercise the command without a live provider #
Create test/e2e/greeting_test.py while developing this example. The
shared harness supplies the real daemon and Python
kernel, with a local scripted provider:
"""Exercise the greeting command through the model's Python binding."""
import unittest
from harness import Albedo, Provider, cell_output, exclusive, python, text
def scripted(request):
if request["input"][-1].get("type") == "function_call_output":
return text("done")
return python('print(await commands.greet("Ada"))')
class GreetingTests(unittest.TestCase):
@exclusive
def test_greeting_uses_saved_settings(self):
provider = Provider(scripted)
self.addCleanup(provider.close)
with Albedo(
provider,
protocol="responses",
prepare=lambda app: app.write_extensions({"greeting": {"prefix": "Hi"}}),
) as app:
session = app.session()
app.patch_session(
session, {"selection": {"extensions": {"greeting": True}}}
)
app.prompt(session, "greet Ada").close()
app.idle(session)
outputs = [
cell_output(item["output"])
for entry in provider.requests
for item in entry["request"]["input"]
if item.get("type") == "function_call_output"
]
self.assertIn("Hi, Ada!\n", outputs)
The test is exclusive because it writes global extension settings before daemon startup. Run it from the repository root with a compiled snapshot and CLI:
nix develop
scratch=$(mktemp -d /tmp/albedo-greeting.XXXXXX)
ALBEDO_TEST_DAEMON=$(test/snapshot-daemon.sh "$scratch/daemon")
export ALBEDO_TEST_DAEMON
go -C cli build -o bin/albedo ./cmd/albedo
python3 test/e2e/run.py greeting_test.py
test/reap-daemons.sh "$scratch"
exit
Run the cleanup command even if the scenario fails. The scenario checks that selection, settings, the command declaration, host dispatch, and Python binding work together. For a production extension, replace the greeting scenario with its useful behavior and relevant failure or cleanup cases. Follow the test policy.
Choose the contributions #
Declare the extension's name, description, requirements, plugins, and
initializer with
extension.Extension. Keep
declarations free of I/O and environment capture. A sealed build caches them.
Choose plugin types from the current Plugin definition instead of copying an
old inventory. Use ToolPlugin for static instructions, tools, Python modules,
and host routes. Use ManagedPlugin when a contribution must be prepared before
use. Use OwnedManagedPlugin when allocated resources must survive preparation
handoff safely. If a route needs only the values on host.Context, keep the
route in ToolPlugin and do not add a managed contribution that only returns
routes.
Keep schema, data migrations, deletion cleanup, and transfer behavior with the extension that owns the data. See migrations and extension lifecycle rules.
Connect host routes #
Use host.Route for Python-to-host
calls. A route receives host.Context, a method string, and dynamically typed
arguments. It returns JSON or an error pair. The context supplies the store, the
session ID, the loaded workspace, and the providers from the active composition.
Use its supplied callbacks for progress and captured user-command output. Other
session operations and durable observations use the
typed SDK APIs.
Declare routes that need only context values in ToolPlugin. Follow the
work route, which
passes context.store and context.workspace to its handler.
Paperclips also
passes context.session. Use this loaded workspace instead of querying session
settings or reading the process working directory. See the
context snapshot contract.
Resolve providers from the supplied context. Do not capture the installation registry as a substitute for the active session composition. Keep HTTP service admission separate from session host routes. The extension HTTP contract describes caller permissions, conditional edits, and notifications.
Declare client operations #
Use ClientPlugin for human commands that read or change an HTTP resource.
Start with
client_api.operation_defaults,
then override the bindings and result constraints the operation needs. Reuse
text_field, integer_field, choice_field, and form_body when their
defaults fit. Preserve custom labels, defaults, validators, and success
statuses. Use a FieldKind variant when constructing a field directly. Build
resource-page actions with client_api.actions and propagate its error before
encoding the page. See
client declaration checks.
Follow the work declaration and its page actions. Keep model host routes separate from HTTP operations. Read client API ownership for transport, recovery, and authorization boundaries.
Prepare session contributions #
Follow the
schedule extension
for a managed contribution that builds a command from the supplied store and
session ID. Start from extension.empty() and fill the contribution fields you
need.
For an OwnedManagedPlugin whose worker only observes session events, use
worker.observer. Pass the
preparation owner, the worker loop, the message constructor that wraps a session
handle and event, and the startup wait in milliseconds. Wrap its owned result in
Some and map its Error(Nil) to the extension startup message:
worker.observer(owner, run, Observed, 5000)
|> result.map(Some)
|> result.replace_error("the worker did not start")
observer builds the managed contribution from extension.empty(). Use
worker.start when other callbacks need the worker inbox, then attach its
lifecycle with extension.owned(contribution, started.adopt, started.close).
Return Ok(None) only when preparation retains no resource or contribution. See
the
owned worker helper reference.
Keep event observers short. They run inside the session actor, so send work to its owner and return instead of blocking. Run command handlers outside the actor whose state operations they call. See plugin contracts and commands.
Give allocated resources an explicit cleanup owner. Make close callbacks idempotent. For owned preparation, establish lifecycle monitors before readiness and complete adoption before publication. Preserve saved selection when applying it fails. The shared lifecycle rules describe the required failure boundaries.
Report hooks #
If the contribution steers turns, add a hook to its managed value. Use
hook.Event and hook.Verdict and the
hook reference for events, merge rules, refusal
behavior, and output visibility. A hook that only observes work must send the
event to its owner and return hook.proceed promptly.
For calls inside Python cells, use
albedo_plugins.hook. Use
reported(name, fields) when method parameters map to hook arguments, or
around(name, arguments, run) for an asynchronous callback. Execute with the
rewritten arguments, not the original arguments. Use before and after when
completion must be reported separately.
For command-hook configuration, inspect the parser in
albedo_hook_command.py. The
hook reference describes command
execution and failure behavior. Command hooks are not a fail-closed security
boundary.
Expose a JSON service #
For a buffered JSON API authenticated with the daemon token, import
harness/sdk/service as
http_service. Add its result to the extension's plugin list:
extension.ServicePlugin(http_service.json(65_536, service.dispatch))
Choose a body limit for the service's operations. Implement
service.dispatch(daemon, path, request) with a
Result(Response(mist.ResponseData), http_api.Failure) return value. Keep route
matching, query and body decoding, and domain error mapping there. Follow the
work service and reuse
the decoders in http_api.
Read the HTTP service contract for
negotiation and admission behavior. Use extension.Service directly when routes
need streaming, non-JSON responses, different authentication, or different body
limits per route.
Register and check the extension #
Add the constructor to
extensions.declared. Set its default
selection there only if the feature should be enabled by default. Keep discovery
read-only and ensure failed preparation leaves no callable contributions from
the rejected bundle.
Exercise the externally visible change through the shared daemon harness. Cover the relevant activation, failure, and cleanup paths. Update the canonical feature page with the behavior, limits, and guidance callers need, then follow the repository checks.