# Plugins Plugins are contributions declared by an [extension](extensions.md), not independently installed packages. [`Plugin`](../packages/albedo_sdk/src/albedo_sdk/extension.gleam) defines the host contracts. See the [SDK helper contracts](extensions.md#sdk-imports-and-native-bindings) for HTTP, subprocesses, cache expiry, and background jobs. The [extension API reference](../docs/extension-api.md) provides function-level documentation; [Write an extension](../docs/extensions.md) walks through a complete extension that uses the common contributions. ## Session contributions `ContextPlugin` loads workspace context. `ToolPlugin` declares instructions, tools, Python modules, and routes without allocating resources or doing I/O in the declaration. `ManagedPlugin` and `OwnedManagedPlugin` both prepare a session contribution from an `extension.Preparation`. It holds the preparation owner, the extension's [storage handle](extensions.md#extension-storage) in `storage`, the daemon's `letters`, session ID, and workspace, plus an `editor_overlay` callback that resolves the session's ACP editor overlay without allocating a client, an `intake_port` callback that reads the webhook intake's current port, a `preferences` callback that loads the session's [capability preferences](extensions.md#sdk-imports-and-native-bindings), which the host reads from `capabilities.json` and the session's saved choices, a `project_files` callback that answers the directory to read the workspace's project files from (a remote workspace's mirror, refreshed when stale), and an `instructions` callback that loads the instruction files the session selects. `OwnedManagedPlugin` is for resources that must survive handoff safely, which the owner adopts. A `ManagedPlugin` adopts nothing through the owner. The agents extension uses an owned contribution for a hook that reads `letters`, and the webhooks extension for routes and a command that show intake addresses. Both use the empty contribution's callbacks. The handle is bound to the prepared session, so it reads its history without a capability (see [extension capabilities](extensions.md#extension-capabilities)). `letters`, `editor_overlay`, and `intake_port` are [capabilities](extensions.md#extension-capabilities): the host denies each one the preparing extension does not declare in `uses`. `preferences`, `project_files`, and `instructions` are the session's own data, so every preparing extension gets them. `CommandPlugin` contributes session commands. `HookPlugin` contributes a static [hook](hooks.md), asked with the same `hook.Context` as a managed contribution's hook, so a hook that needs nothing prepared does not need a `ManagedPlugin`. See [extension.gleam](../packages/albedo_sdk/src/albedo_sdk/extension.gleam). [`composition.gleam`](../apps/albedo/src/albedo/composition/composition.gleam) collects these contributions in registry order. Managed contributions can observe session events, provide a hook that needs what preparation supplies, and define adoption and close callbacks. Observers run inside the session actor and must only send and return. Once a turn's inputs commit, it reports `TurnStarted` with its isolated letter ID if it has one, and it reports `TurnEnded` however it ends. Resource close callbacks must be idempotent. `OwnedManagedPlugin` returns `Result(Option(Owned), String)`. `extension.owned(contribution, adopt, close)` constructs the opaque value with both callbacks. `None` retains no resource or contribution. The opaque result prevents accidentally returning an ordinary contribution with default callbacks. Resource monitoring remains the allocator's responsibility. ## Record an external answer `ExternalAnswerPlugin` records the final assistant text for a successful turn that read one outside `Event` with `Alone` delivery. The callback receives the session ID, the inbox row ID, and the final text. Use the row ID to look up the original delivery in your extension's tables. The [session's turn completion](../apps/albedo/src/albedo/session.gleam) calls each active recorder inside the [completion transaction](../apps/albedo/src/albedo/history/conversation.gleam). Write only your extension's tables on the supplied connection. Leave network delivery to a separate worker after the commit. A recorder failure rolls back turn completion. ## Host route context [`host.Context`](../packages/albedo_sdk/src/albedo_sdk/host.gleam) supplies the store, the daemon's `inbox` and `letters`, session ID, workspace, and the loaded search, worktree, and image generation providers to kernel host routes. Its `storage` is the [storage handle](extensions.md#extension-storage) of the extension whose route runs, bound to the calling session. The composition sets it for each extension's routes, and replaces each [capability](extensions.md#extension-capabilities) the extension does not declare in `uses` with a denying stand-in. Every field below except the session ID, workspace, `progress`, `origins`, and `storage` is a capability. See [inbox](inbox.md#posting-an-input). Call `context.worktrees.remove(context.storage, cwd, target, force)` to remove a worktree. Core captures every declared extension's `FollowPlugin` callbacks when it supplies this capability, including disabled or quarantined extensions. Its `progress`, `read_shell_output`, and `send_mail` callbacks are bound to that session, as is its `session_state` command context. The `commands` route runs commands with that context, and the harness base's `cells.end_turn` (or `cells.no_reply` for older kernels) ends the turn quietly through it. `send_mail` sends an agent letter from the session through [`forwarding.send`](../apps/albedo/src/albedo/transfer/forwarding.gleam). `ask_moved` relays a call to the daemon a session moved to through [`moves.ask_moved`](../apps/albedo/src/albedo/transfer/moves.gleam). `correspondents` finds a session on another daemon that wrote to a caller, from the daemon's mail tables. Pass it to `family.locate` and `family.remote`. `control` is the daemon's session coordinator for the typed [`sdk/session_control`](../packages/albedo_sdk/src/albedo_sdk/session_control.gleam) functions. See [agents](agent-sessions.md). [`kernels.kernel_routes`](../apps/albedo/src/albedo/runtime/kernels.gleam) builds it from the same loaded `Cached` snapshot as the route composition. Reloads replace the callback for later calls. Calls already running keep their captured context, including the old workspace while a family move is deferred. Routes that need only these values can be static `ToolPlugin` contributions, as in [work](../extensions/work/src/albedo_ext_work/extension.gleam) and [paperclips](../extensions/paperclips/src/albedo_ext_paperclips/extension.gleam). Use `context.workspace` for their loaded workspace. The database's desired workspace and the process working directory can differ from it. ## Image generation drivers `ImagegenPlugin` contributes a named [`imagegen.Provider`](../packages/albedo_sdk/src/albedo_sdk/imagegen.gleam). Its `generate` callback receives validated reference images and the session, profile, and call identities. It returns encoded image data and optional request and generation identifiers. The shared [image generation extension](imagegen.md) owns driver selection and admission; Python owns local publication. Run the request once. Do not retry an uncertain outcome or fall back to another service. The callback runs in a cancellable worker, so keep sockets there and ensure any resource-owning child terminates when that worker dies. ## Owned worker helper [`worker.observer(owner, run, observed, wait_ms)`](../packages/albedo_sdk/src/albedo_sdk/worker.gleam) starts an owned worker with `worker.start` and returns its opaque `extension.Owned` contribution. The contribution starts from `extension.empty()`. Its `observe` sends `observed(handle, event)` to the worker inbox. Its `adopt` and `close` are the started worker callbacks. `observer` returns `Error(Nil)` when the worker does not start. The caller maps that error to its own startup message with `result.replace_error`. `wait_ms` is the startup wait passed to `worker.start`. ## Daemon contributions The same `Plugin` type declares provider and model catalogs, login, services, startup, migrations, settings, cleanup, state transfer, history and worktree following, and scheduled prompts. `ServicePlugin` defines an admission policy and a body limit for its routes. `MigrationPlugin` distinguishes schema migrations from data migrations, and each names itself and declares whether it is [breaking](extensions.md#migrations). `CleanPlugin` runs for installed extensions when a session is deleted, including extensions that are disabled. `StartupPlugin` receives an `extension.Startup` with the store, the extension's [storage handle](extensions.md#extension-storage), the daemon's `inbox`, and an `invalidate` callback. The inbox and `invalidate` are [capabilities](extensions.md#extension-capabilities) the extension declares in `uses`. A background service that starts there keeps that callback to notify clients after it commits a change. The callback returns the plugins that reach what it started, described below. `extension.install` quarantines an extension named after a settings section that the daemon passes as reserved, which [`core_settings.names`](../apps/albedo/src/albedo/settings/core_settings.gleam) lists. `FeaturePlugin` names the owner of a [shared library](extensions.md#shared-extension-libraries) the extension calls. It contributes nothing to a session. The host grants the extension's storage handle that owner, as [shared library tables](extensions.md#shared-library-tables) describes. See [extension.gleam](../packages/albedo_sdk/src/albedo_sdk/extension.gleam). The kernel's own tables, startup reconciliation, and session cleanup are not plugins. The [runtime owns them](kernel.md#ownership). `FollowPlugin` keeps an extension's rows in step with core changes that its rows depend on. Its callback receives a [`follow.Change`](../packages/albedo_sdk/src/albedo_sdk/follow.gleam) and the connection of the transaction that makes the change. An error rolls that change back. Every declared extension's follower runs in registry order, enabled for the session or not, and quarantined or not. A quarantined extension's tables can still hold rows that must follow the change. Skip when your tables do not exist, and ignore the changes your extension keeps nothing for. Core reads the list with `runtime.followers`. - `Forked` follows a fork or a rewind's archive copy, after the prefix is copied. See [`history.fork_in`](../apps/albedo/src/albedo/history/history.gleam). - `Truncated` follows a rewind, after the transcript tail is deleted. See [`history.remove_tail`](../apps/albedo/src/albedo/history/history.gleam). - `WorktreeCreated` follows a newly recorded worktree. - `WorktreeRemoved` follows worktree removal, after the checkout and its record are deleted. See [the worktree service](../apps/albedo/src/albedo/workspace/worktree.gleam), which extensions reach through the `worktrees` capability. `lcm-memory` follows forks and truncations for the LCM graph. `work` follows worktree removal for the work ledger. `links` checks legacy memberships after either change. `LinkedSummaryPlugin` tells a session what an extension knows about workspaces that just joined its workspace's [link group](workspaces.md#linked-workspaces). Its `summary` takes those workspaces and answers text that stands on its own after the links note's sentence, or `""` for nothing. Memory contributes the memory the session's next snapshot will hold for them. The links extension does not call it: it asks the host once for every session it tells, through `Daemon.linked_summaries` and under the `Sessions` [capability](extensions.md#extension-capabilities), then posts each note. The host's [`linked_summaries`](../apps/albedo/src/albedo/workspace/linked_summaries.gleam) reads every recipient's plugins in one runtime observation, from the extensions active in each loaded composition, in registry order. It then runs every plugin of every recipient side by side, outside the runtime actor, under one guardian process per call. The guardian traps exits and starts each plugin on a helper linked to itself, so a plugin that crashes, or whose linked child or port dies and takes it down, costs only its own answer; the caller only monitors the guardian. The caller collects answers for two seconds and then kills the guardian, whose helpers die with it, and a guardian whose caller stops kills itself and its helpers. The two seconds bound how long the caller waits for answers once the runtime has said which plugins apply, not the whole call: reading the plugins and starting the guardian come on top, and a busy scheduler stretches all of it. A plugin that fails or misses the deadline is left out and logged, and the notes are posted whatever the plugins did. A disabled or quarantined extension adds nothing. Neither does any extension of a session with no composition loaded, nor of any recipient when the runtime refuses or times out the read, for instance when its observation slots are full. Such a session learns of the joined workspaces from a composition prepared after the link. A preparation running when the link commits is usually refused rather than published, as [preparation and kernels](runtime.md#preparation-and-kernels) describes, but one can still publish the group it read, and a composition already loaded keeps its snapshot; both read the new group at the session's next open or reload. `SchedulePlugin` contributes a `due` callback, given the extension's storage handle, that returns the scheduled prompts due at a given time as [`extension.Due`](../packages/albedo_sdk/src/albedo_sdk/extension.gleam) values. The registry's dispatcher calls every declared extension's callback on its tick, quarantined ones included, and posts each prompt. The extension owns the timing and repetition. Each `Due` carries an `advance` callback that runs in the posting transaction and returns False when another tick already advanced the occurrence. See [inbox rows](inbox.md#rows). Startup callbacks run after the schema transaction commits. The host does not roll back an earlier successful startup if a later startup or dependency check fails. Extensions own the lifetime of long-lived startup resources. A startup callback returns the plugins that need what it started. Use this to hand a process handle to the extension's routes, service, commands, prepared contributions, or transfer adapter. Build those plugins inside the callback so their closures capture the handle. Install places them in the extension right after the `StartupPlugin`, and the host reads them from the installed list as it reads declared ones. Do not find a started process through a registered name or another process-wide lookup. The callback returns [`extension.Started`](../packages/albedo_sdk/src/albedo_sdk/extension.gleam) values. `StartedTool`, `StartedCommand`, `StartedManaged`, `StartedOwnedManaged`, `StartedService`, and `StartedTransfer` carry the payloads of `ToolPlugin`, `CommandPlugin`, `ManagedPlugin`, `OwnedManagedPlugin`, `ServicePlugin`, and `TransferPlugin`, and install converts each to that plugin. The host reads every other kind before startup or from the declarations, so the type has no variant for them and the compiler rejects returning one. Install checks the default selection again after startup, so a returned tool, command, route, or Python module that clashes quarantines its extension. Declarations that need no started resource stay in the static plugin list. The [Discord extension](discord.md#bot-process) returns its routes, service, and transfer adapter this way. The [image generation extension](imagegen.md#cancellation-and-recovery) returns the prepared contribution whose routes reach its call admission. ## Provider account and profile contributions Core reaches these provider contracts through the installed extensions, enabled or not. A quarantined extension contributes nothing, so its accounts are not polled for quota. Do not import a provider extension from core to reach the same behavior. - `QuotaPlugin` contributes a [`usage_feed.Source`](../packages/albedo_sdk/src/albedo_sdk/usage_feed.gleam). `accounts` lists the extension's sign-in accounts as `Target` values. `profile` maps a saved profile that names the extension to one `Target`, or `Error(Nil)`. Both receive the runtime's key environment for key account reads. `heal` runs after every report the feed returns for one of the source's targets. Use `accounts_source` for a source with only sign-in accounts, and `key_target` for an API key. See [quota](quota.md#accounts). - `ProfileModelPlugin` contributes a `ProfileModel` for saved profiles that name the extension. `efforts(home, profile, model)` replaces the catalog's effort list when it answers `Some`. `replay(profile, model, inputs)` refuses a model switch whose projected history the profile cannot replay. See [model efforts](models.md#profile-effort-and-replay-rules). - `KeyEnvironmentPlugin` names the environment variables that may hold an API key for an endpoint. The [runtime](../apps/albedo/src/albedo/runtime.gleam) composes every declared lookup into one `key_environment.KeyEnvironment`. It passes that value in `ModelContext.keys`, as the third argument of `ModelCatalog.list`, and to quota sources. Key account readers take it as an argument instead of reading shared state. See [typed key accounts](auth.md#typed-key-accounts). Helpers in [extension.gleam](../packages/albedo_sdk/src/albedo_sdk/extension.gleam) collect them: `quota_sources`, `profile_model`, and `key_environment`. ## Persisted extension settings Use [`settings.Section`](../packages/albedo_sdk/src/albedo_sdk/settings.gleam) for a typed section decoder and validation. `settings.update(section, encode, change)` performs a locked read-modify-write of that section without extension-owned native code. Follow the [typed update contract](settings.md#typed-extension-updates) for encoder overlays, pure callbacks, defaults, and failure behavior. Credentials and multi-document mutations retain specialized owners. ## MCP settings and editor probes `McpServersPlugin` supplies an [`McpServers`](../packages/albedo_sdk/src/albedo_sdk/extension.gleam) record for the daemon's `mcp` settings group and for ACP overlays. `names` lists configured server names. `validate` checks one server's saved definition and secrets without resolving environment references or starting anything. `check` starts an enabled server once and closes it. `signed_out` drops the tokens from a saved OAuth record. `EditorMcpPlugin` contributes `probe`, which starts an editor's candidate servers once and returns their catalogues without publishing them. The daemon looks these up with `extension.mcp_servers` and `extension.editor_mcp_probe` over the installed extensions, so a disabled MCP extension still answers. A quarantined one does not. The first contribution in registry order wins. See [MCP](mcp.md#configure-servers) and [ACP](acp.md#mcp-overlays) for what happens when none is installed. ## HTTP services `ServicePlugin` serves routes below `/extensions//` while the extension is enabled globally. Session selection does not control these routes. The [daemon ingress](../apps/albedo/src/albedo/lifecycle/server.gleam) applies the service's admission policy before calling its handler. After a successful feature write, use the supplied `Daemon.invalidate` callback to notify clients. A route that acts on a session its path names, such as the [run jobs](../extensions/run/src/albedo_ext_run/service.gleam) and [mail queue](../extensions/mail/src/albedo_ext_mail/queue.gleam) routes, reaches that session's state through `Daemon.session_state(id)`. A missing session answers `session unavailable`. See the [session data and effects contract](extensions.md#session-data-and-effects). `Daemon.control` is the session coordinator, as `host.Context.control` is for kernel routes. `Daemon.storage` is the serving extension's [storage handle](extensions.md#extension-storage). It is bound to no session, so a service reads the history of a session its path names only when its extension declares `History`. `Daemon.intake_port` reads the webhook intake's current port. Every `Daemon` field except `home`, `storage`, and `origins` is a [capability](extensions.md#extension-capabilities). `extension.service` replaces each one the serving extension does not declare in `uses` with a denying stand-in. [`service.json(body_limit, handle)`](../packages/albedo_sdk/src/albedo_sdk/service.gleam) supplies daemon-token authentication and a fixed body limit. Its handler receives the daemon, path segments below the mount, and a buffered `Request(BitArray)`. It returns a response or `http_api.Failure`. The adapter renders failures as problem responses and rejects negotiation that selects an event stream with `406 not_acceptable`. [`sdk/http_api`](../packages/albedo_sdk/src/albedo_sdk/http_api.gleam) owns the HTTP contract that extension services share with the daemon. It defines `Failure`, problem and bounded JSON replies, strict body and query decoding, `Accept` negotiation, preconditions, revision validators, and paging tokens. It ranks Accept headers with [`albedo_web/accept`](../packages/albedo_web/src/albedo_web/accept.gleam); a content validator is `albedo_web/etag.strong`, and a timestamp `albedo_clock.format_rfc3339`. The daemon's [HTTP adapter](../apps/albedo/src/albedo/http/http_api.gleam) imports these definitions and keeps session creation, input admission, ACP attachment, and daemon failure codes. Extensions import the SDK module, never the daemon adapter. Route dispatch, query and body decoding, and domain error mapping remain extension-owned. Services that stream, serve non-JSON content, or need different admission policies use [`extension.Service`](../packages/albedo_sdk/src/albedo_sdk/extension.gleam) directly. See [Expose a JSON service](../docs/extensions.md#expose-a-json-service) for registration steps. [`http_api.resource(url, etag, value)`](../packages/albedo_sdk/src/albedo_sdk/http_api.gleam) encodes resource envelopes. `revision_etag(namespace, id, revision)` formats integer-ID validators, and `notification(status)` encodes `NotRequested`, `Queued`, or `Failed(detail)`. Callers retain URL and payload selection, fingerprint inputs, notification effects, invalidation, transactions, and precondition checks. ## Client declarations [`client_api`](../packages/albedo_sdk/src/albedo_sdk/client_api.gleam) owns typed field kinds, declarative request bindings, and resource pages. `ClientPlugin` commands are validated during installation, before the extension initializer runs. A malformed command quarantines its extension with the command and field in the error. Installation behavior is owned by [`extension.install`](../packages/albedo_sdk/src/albedo_sdk/extension.gleam). After preparation, [composition](../apps/albedo/src/albedo/composition/composition.gleam) requires each client binding to name a command contributed by the same extension. A missing command makes that extension inactive for the session, closes its prepared contributions, and reports the extension and command names. Commands prepared by managed plugins are checked at this stage. Build page actions with `client_api.actions`, which returns validated `Actions` or an error naming the action. `Page` requires this validated value. JSON services return declaration failures as `500 invalid_client_declaration` instead of sending malformed controls to clients. Validation rejects repeated or empty field names, action names, and binding keys, choices on other field kinds, empty choice lists, incompatible defaults, malformed JSON pointers, undeclared form inputs, and unmatched path placeholders. A null default means no preset value. Displayed defaults may bind only to row or session data. Actual row and session values are resolved and checked by the clients when the user opens a form. These declaration checks do not authorize requests or validate submitted domain values. ## Related pages - [All topics](README.md) - [Change guidance](contributing.md) - [Extensions](extensions.md) - [Commands](commands.md) - [Settings](settings.md) - [The detached kernel](kernel.md) - [Sessions](sessions.md) - [Inbox](inbox.md) - [Worktrees](worktrees.md) - [Compaction](compaction.md)