Plugin System

Temps plugins come in two kinds: external plugins, which run as ordinary Temps services that Temps proxies requests to, and in-process plugins, Rust crates compiled into the temps binary. Temps itself is a modular monolith: every built-in feature, from the HTTP proxy to analytics to deployments, is an in-process plugin that implements the TempsPlugin trait.

To add a feature to your own instance without rebuilding Temps, write an external plugin; in TypeScript is the shortest path. Ready-made plugins are listed in the plugin catalogue, and the temps-plugin skill teaches a coding agent to build one. The external-plugin sections of this page describe v0.1.0-beta.67, where plugins run only as services; if you are upgrading from an earlier version, read Upgrading from earlier versions first. The rest of this page is the reference for in-process plugins: how services are registered, how dependencies are wired, how routes are exposed, and how to test the whole thing. For the design trade-offs behind this approach, see 4 plugin architectures compared.


Overview

A plugin is a self-contained unit that bundles four things:

  1. Services — the business logic layer (e.g. BackupService, DeployerService).
  2. Routes — Axum handlers exposed under a consistent URL prefix.
  3. OpenAPI schema — automatically merged into the global spec served at /api/api-docs/openapi.json (Swagger UI at /api/swagger-ui/).
  4. Lifecycle hooks — a two-phase init so plugins can cross-reference each other's services.

Plugins talk to each other only through the service registry. They never import each other's internal modules, which keeps the dependency graph flat and the build fast.

Why a plugin system?

  • Name
    Modularity
    Description

    Each crate owns its services, errors, handlers, and migrations. Adding a feature means adding a crate, not touching 20 files.

  • Name
    Type-safe DI
    Description

    The service registry is keyed by TypeId. require_service::<Arc<T>>() fails at startup with a clear error if a dependency is missing — never at request time.

  • Name
    Testability
    Description

    Services are constructed with Arc<T> and Arc<dyn Trait> dependencies, so tests inject mocks without a DI container.

  • Name
    OpenAPI out of the box
    Description

    Every plugin contributes its utoipa schemas. The global OpenAPI doc is the union of every registered plugin.

  • Name
    Zero runtime overhead
    Description

    Dispatch is a single Arc clone at startup. No reflection, no dynamic loading, no plugin FFI.


Example plugins

The easiest way to learn the plugin system is to read working code. Official plugins live in a dedicated monorepo at gotempsh/plugins — each one is a standalone Cargo crate you can clone, build, and hack on.

  • Name
    example-plugin
    Description

    A minimal "hello world" plugin with a web UI bundle. The shortest path to understanding the plugin protocol, the platform channel, and UI asset layout. View source →

  • Name
    lighthouse-plugin
    Description

    Runs Google Lighthouse audits after every successful deployment and tracks Core Web Vitals over time. Demonstrates deploy-event subscriptions and background workers. View source →

  • Name
    indexnow-plugin
    Description

    Automatically pings the IndexNow API (Bing, Yandex, Seznam) with the list of URLs changed in each deployment. Good template for search-engine integrations. View source →

  • Name
    google-indexing-plugin
    Description

    Notifies the Google Indexing API when pages are published or removed. Shows how to store and refresh a Google service-account credential inside plugin storage. View source →

Trying one

These are plugin projects in the repository, built as Cargo crates. Temps runs a plugin only as a service, so to try one you deploy it and add it as a plugin: pick a listing under Settings → Plugins, or use plugin add from the CLI, as described in Adding a plugin. Whether a plugin publishes a ready-made image is up to its author, so check its README for the image and the permissions it asks for.


External plugins (services)

Temps supports two kinds of plugins:

  • In-process plugins — Rust crates compiled into the temps binary, implementing the TempsPlugin trait. Everything from the rest of this page is about in-process plugins.
  • External plugins — a plugin is an ordinary Temps service: an app you deploy like any other, which an administrator then adds as a plugin. Build one with the Rust SDK (temps-plugin-sdk) or the TypeScript SDK (@temps-sdk/plugin). Since v0.1.0-beta.67 this is the only way an external plugin runs.

External plugins are the right choice when you:

  • Want to ship a plugin without forking or recompiling Temps itself.
  • Want to write it in TypeScript rather than Rust.
  • Are distributing a proprietary or commercial plugin as a container image.

How it works

  1. You deploy the plugin as a service, from a repository or, preferably, from an image. Every deployment receives PORT, TEMPS_API_URL and TEMPS_PLUGIN_SECRET, and the SDK reads them, so a plugin needs no extra configuration to be reachable.
  2. An administrator adds the service as a plugin. Temps reads its manifest with an authenticated GET /_temps/plugin/hello, then opens the platform channel (/_temps/channel) to the same container. Every request carries a secret in x-temps-auth-signature. The secret belongs to one deployment and only Temps can compute it, so a new build waiting for approval cannot pass as Temps to the approved one. A service that does not answer the hello is refused, with that reason.
  3. Temps proxies requests under /api/x/{plugin_name}/ to the plugin, and the plugin calls back into Temps over the channel, within the permissions you granted. Plugins can register routes, bundle a web UI, subscribe to deploy events, and persist data.
  4. Temps never runs plugin code. It starts no executable, mounts nothing and passes nothing on a command line; it attaches to the service's running container over the network.

A plugin is never given the control-plane database or the Temps data directory. A manifest that asks for either is refused, by the SDK at start and by Temps when it attaches. The plugin keeps its own data in the service's volume (/data by default, with a temporary directory and a warning when no volume is mounted) or in a managed database linked to the service. Temps does not create or link that database for you; the plugin list shows what is linked, or that nothing is.

Redeploys, restarts and idle stops are followed, not configured:

  • Redeploy or container restart. The channel closes. Temps attaches again only to the build you approved (see Updates wait for approval).
  • Temps restart. The plugin keeps running and accepts a new channel.
  • Idle stop. If the service stops when idle, the plugin keeps its routes, navigation and subscriptions and is shown as stopped, not failed. The next authenticated request, or an event it is subscribed to and granted, starts it. An anonymous request never starts a plugin.
  • One replica. A plugin has one channel, so Temps attaches to one container.

Adding a plugin

Add, update, disable and remove plugins in the console under Settings → Plugins, or with the CLI. These actions need an instance administrator, and adding a plugin, approving an update and enabling a disabled plugin make Temps ask you to confirm your identity again. Disabling does not.

  • In the console. Add plugin takes an image and does everything in one click: it creates the service, deploys the image, waits until it is live and adds it as a plugin, showing each step. A step that fails says why, keeps the service that was created and is retried from where it stopped. The form shows the equivalent command. Its other choice adds a service that is already deployed. The form creates a new service only; deploying another image to a plugin's service is done from that service's page or with the CLI, where it waits for approval.
  • From a catalogue listing. The catalogue under Settings → Plugins lists repositories. Each listing links to its source at the listed commit and to the new-service flow with the repository filled in; nothing is installed from the catalogue itself. A listing that carries an image, named by digest, is added from that image. A catalogue listing is not a security audit: read the source before you grant a plugin any permissions.
  • With the CLI. These commands need CLI 0.2.0-beta.5 or later, which bunx @temps-sdk/cli runs today:
CommandWhat it does
plugin add --image <image>Creates a service for an image in a registry the server pulls from, deploys it, waits until it is live and adds it as a plugin. A tag is accepted with a warning, because a tag can be moved: use a digest.
plugin add --local-image <image>The same, with an image from your local Docker, which the CLI uploads to the server. No registry is needed.
plugin add --buildBuilds the Dockerfile in the current directory (--dockerfile, --context), uploads the image and adds it. The service is named after the directory unless you give --name.
plugin add ... --project <service>Deploys a new image to a service that is already a plugin. It adds nothing: the deployment is an update that waits for approval, and the command prints what waits and how to approve it.
plugin add-service --project <id> --environment <id>Makes an already deployed service a plugin. It starts with no permissions.
plugin servicesLists plugins, the service each runs as and whether it is running, a page at a time (--page, --page-size, --name). Also lists plugins that no longer run, with the reason.
plugin remove <name>Removes a plugin and revokes its permissions. Its service and the files it stored are kept; stop or delete the service from its own page.

For a service Temps creates, --port defaults to 8080 and --health-check-path to /health, and --timeout (300 seconds) is how long to wait for the deployment to be live. Use --name to name the new service and -e to choose the environment (default production).

An image is the preferred way to add a plugin. It is what was published, with nothing built on the server from a repository's default branch, and an image named by digest cannot change after you reviewed it. When Temps pulls a registry image it records the content the reference resolved to, and a tag moved to other content cannot change what runs: containers are created only by a deployment, so deploying the moved tag is a new deployment, which waits for approval.

Adding a plugin pins the build that runs at that moment and opens its permission screen. The plugin has no permissions until you allow some there. Every plugin added this way has the community tier, which is the least access. Nothing in the API can set a higher tier.

While a service is a plugin, the deployment token Temps hands to every deployment (TEMPS_API_TOKEN) authenticates nothing for that service.

A plugin is code you chose to run. It cannot reach the control-plane database or the Temps data directory, and it can only call Temps with the permissions you grant. But its container is a normal deployment: unless you narrow the environment's network policy, which starts open, it can connect out freely. The permission screen shows the outbound profile that is actually enforced.

Permissions and plugin identity

Each external plugin has an identity of its own in Temps, and nothing is granted to it by default. The permission screen is built from what the plugin's manifest asks for, in plain words, plus any permission it still holds but no longer asks for, so you can take it away. It also shows the routes the plugin serves without a Temps session, the platform events it subscribes to, and what its container may connect to (the outbound profile of its environment, open, restricted or none, with a link to the network policy). You can change or revoke permissions later, including permissions the plugin lists as required. Temps grants only what the running plugin also declares.

A plugin name belongs to whatever was installed under it first. A service never takes over the name, and the grants, of a plugin from another source, and a service that starts declaring a different plugin name is refused until you remove the plugin and add the service again.

PermissionWhat it allows
Use AISend plugin content to the AI provider you configured in the AI gateway. Limited by a daily call count (default 100, up to 10,000) and a maximum output size per call (default 1,024 tokens, up to 4,096).
Read services, environments, deploymentsRead that metadata across the whole instance.
Receive platform eventsReceive subscribed service, deployment and domain events across the whole instance.
Read supported API resourcesMake supported API reads on behalf of the signed-in user who called the plugin, within that user's own permissions.
Change supported API resourcesMake supported API writes on behalf of that user, within that user's permissions, and only in the areas and services you choose. The areas are Services, Environments and Deployments (--write projects environments deployments in the CLI). With no area chosen, nothing can change. You can also limit the changes to 1 to 100 existing services (--write-project); without that, every service. A plugin limited to some services cannot create services. It does not grant AI or credential access.

Reads are not narrowed by areas or services: they keep their instance-wide meaning. Set permissions from the CLI with plugin grants get <name> and plugin grants set <name> (--grant, --write, --write-project, --ai-daily-calls, --ai-max-tokens, or --clear to revoke everything).

A plugin can act for a user only while that user's request is in flight: Temps hands the plugin a short-lived proof tied to the user's session or API key, and re-checks that user's current permissions when the plugin uses it.

Updates wait for approval

A plugin's service can be redeployed by anyone who may deploy it, and a new build is new code holding the plugin's permissions, so the build is part of what you approve.

  • Temps attaches only to the build you approved. Restarting the same deployment, or starting it again after an idle stop, is the same build and needs nothing.
  • Any other build is an update that waits. Temps stays disconnected from it and an audit entry (EXTERNAL_PLUGIN_UPDATE_HELD) is written once. The plugin keeps its routes and navigation and is listed as waiting, and requests to it are answered with the reason. The plugin list shows what the waiting build newly asks for compared with the approved one: permissions, classes of API calls, public routes and event subscriptions, and the permissions it no longer asks for.
  • Nothing applies an update automatically, including one that asks for nothing more. Deploying a plugin's service therefore disconnects the plugin until you approve the new build. A rollback made by deploying an old commit again is a new build that waits; pointing the service back at the approved deployment is not.

bunx @temps-sdk/cli plugin update <name> shows the build the plugin is pinned to and the update that waits, with what it asks for. plugin approve-update <name> --deployment <id> --review <review> approves exactly the build you reviewed; the --review value is the one plugin update printed. If the service runs another build by the time you approve, nothing is attached and the new build waits for a review of its own. Approving needs an instance administrator and a recent identity check.

Approving an update allows nothing new. It changes which build runs as the plugin; permissions the update newly asks for appear on the permission screen, switched off. There is no reject action: an update you do not approve keeps waiting, and you either roll the service back to the approved deployment, which ends the wait, or remove the plugin.

Switching a plugin off, limits and the audit trail

  • Switch. plugin disable <name> cuts a plugin off at once: no request is forwarded, no event is delivered, none of its AI tools are offered, and it can make no call to Temps. It stays listed as disabled, and requests to it are answered with the reason. Its service keeps running, with its own outbound access and database; stop it from the service's page. plugin enable <name> lets it connect again with the permissions it had, and needs a recent identity check. Enabling does not start a service that stopped for being idle; the next request does.
  • Limits. A plugin's container is its service's container, so its memory and CPU limits are the service's. A new service starts with the platform's default memory limit, 512 MB. plugin limits <name> shows the memory and CPU that apply to the deployment the plugin is attached or pinned to, and says so when memory is not capped; change them in the service's environment resources.
  • Audit trail. Each call a plugin makes that changes something and reaches the platform's handler is recorded as EXTERNAL_PLUGIN_CHANGE_MADE (the handler answered 2xx) or EXTERNAL_PLUGIN_CHANGE_REFUSED, naming the user it acted for, the plugin, the method, the path and the status. There is no rate limit on a plugin's calls to Temps; they are bounded by its permissions, its write scope and its AI call quota.
  • The plugin's page. Temps serves a plugin's page sandboxed, without allow-same-origin, so its scripts cannot reach the console's window or storage, and the requests they make carry no session cookie.

AI tools

A plugin can offer API operations to the AI assistant as tools (from v0.1.0-beta.62). The tools are off for every plugin until an administrator turns on Allow AI chat to use these tools in the plugin's settings. Read tools are GET operations. Write tools go through the same confirmation step as any other write the assistant proposes, they run with the permissions of the user who is chatting, and each plugin write is recorded in the audit log. Approving a new build of the plugin turns AI access off again until you re-enable it.

In TypeScript, wrap your plugin with createToolPlugin (in @temps-sdk/plugin 0.1.0-beta.3 or later) and register each tool. Check the caller's permissions in the handler, as you would in any route:

import { createManifest, createToolPlugin, runPlugin, type TempsPlugin } from '@temps-sdk/plugin'
import { z } from 'zod'

const base: TempsPlugin = {
  manifest: () => createManifest('reports', '0.1.0').build(),
  handler: () => (_request, response) => {
    response.writeHead(404)
    response.end()
  },
}

const plugin = createToolPlugin(base)
plugin.tool({
  name: 'reports',
  description: 'List reports for a project',
  method: 'GET',
  input: z.object({ project_id: z.number().int() }),
  handler: async (input) => ({ reports: [], project_id: input.project_id }),
})

await runPlugin(plugin)

method defaults to POST, which needs write approval, and path defaults to /tools/<name>. In any language, mark an operation in your OpenAPI document with the x-temps-ai-tool extension; operations without it are never offered to the assistant.

Plugin events in chat

From v0.1.0-beta.63 a plugin can tell an AI chat when something it manages has changed. In a chat, open the Watches panel and describe what to follow and what to do when it changes. A watch names a plugin, an event source and a subject, with an optional filter, and has one of two modes:

  • Notify adds a notification to the chat when a matching event arrives.
  • Wake sends the assistant a message so it responds on its own, using the read tools you already have access to. The event grants no new permissions and any write still needs your confirmation.

A chat can hold up to 32 watches, and you can pause, resume or remove each one. Temps checks access again when it delivers an event, so a watch is blocked if its owner has lost access to the resource, if the plugin is removed or its AI tools are turned off, or if you approved a new build of the plugin since you created it. Only the chat's owner can manage its watches, from a console session. The panel lists only plugins that publish events and have AI tools enabled; otherwise it says that no plugin has watch sources enabled.

To publish events, the plugin declares each event type in its manifest (a type name, a title, scalar attributes and which of them can be filtered) and sends events through the platform channel with a stable event ID, retrying the same ID until Temps acknowledges it. This is available in the Rust SDK (temps-plugin-sdk, publish_watch_event); the TypeScript SDK does not support it yet.

External plugins in TypeScript (beta)

@temps-sdk/plugin builds external plugins in TypeScript. It is in beta: the beta tag is 0.1.0-beta.67, and the npm latest tag still points at the older 0.1.0-beta.1, so install it with @beta or pin the version. Start from the scaffold, which writes a runnable project with a Dockerfile that runs the plugin on Bun:

bunx @temps-sdk/cli plugin init route-checker --name route-checker
cd route-checker
bunx @temps-sdk/cli plugin dev --exec bun -- run src/index.ts   # a simulated host, no Temps server
bunx @temps-sdk/cli plugin add --build                          # on a Temps instance

--name is the plugin's name: lowercase letters, digits and inner dashes, 64 characters at most. Add --rust for a Rust project. The command refuses an existing directory. The scaffold's src/index.ts is the whole plugin:

import { runPlugin, createManifest, createEmbeddedUiHandler } from "@temps-sdk/plugin";
import type { EmbeddedAssets, RequestHandler, TempsPlugin } from "@temps-sdk/plugin";
import pkg from "../package.json";
import { page } from "./page";

export function manifest() {
  return createManifest(pkg.temps.name, pkg.version)
    .displayName(pkg.temps.title)
    .description(pkg.description)
    .addNav(pkg.temps.title, "puzzle", "/ui/", { section: "platform", order: 50 })
    .ui({ entry_js: "/ui/app.js", css: [], routes: [{ path: "/ui/", title: pkg.temps.title }] })
    .build();
}
// ... embedded assets for the page, then:

export function handler(): RequestHandler {
  const serveUi = createEmbeddedUiHandler(assets);
  return (req, res) => {
    if (req.method === "GET" && serveUi(req, res)) return;
    res.writeHead(404, { "Content-Type": "application/json; charset=utf-8" });
    res.end(JSON.stringify({ error: "Not found" }));
  };
}

export const plugin: TempsPlugin = { manifest, handler, embeddedUiAssets: () => assets };

if (import.meta.main) await runPlugin(plugin);

The handler receives requests with the /x/{plugin_name}/ prefix already stripped, and context.temps is a client for the platform channel, limited to the permissions you granted. In package.json, temps.name, the manifest's name and the version must agree; list the host permissions the plugin asks for in the manifest. plugin dev runs the plugin against a simulated local host with a UI preview and events, and plugin build compiles a TypeScript plugin into an executable for plugin dev only; Temps itself no longer runs executables.

Publishing a plugin

The plugin init project contains the source, a Dockerfile, a .dockerignore that keeps .env, .npmrc and key files out of the image, a README, and a .github/workflows/publish-image.yml workflow. Publishing is a Git tag:

  1. Commit the lockfile, set repository in the plugin's manifest file, then push a tag that names the version: git tag v0.1.0 && git push origin v0.1.0.
  2. The Publish image workflow builds the image, pushes it to ghcr.io under the repository's name and prints in its summary what to share. A new package on ghcr.io starts private: make it public once, in the package's settings.
  3. Anyone can then add the plugin with the printed line, bunx @temps-sdk/cli plugin add --image ghcr.io/<owner>/<repository>@sha256:<digest>.
  4. Optionally, list it in the catalogue under Settings → Plugins by opening a pull request to gotempsh/plugins that adds registry/<name>.json with the image and commit the summary prints.

temps plugin publish was removed in v0.1.0-beta.67, together with the npm packaging, ownership check and review submission only it used. Running it publishes nothing and says how a plugin is published now.

Upgrading from earlier versions

v0.1.0-beta.67 made running as a service the only way an external plugin runs, and the release notes mark it as a breaking change. If you upgrade from v0.1.0-beta.63 or earlier:

  • An executable plugin stops running. A plugin that an earlier version installed as an executable does not start after the upgrade. Temps runs nothing from it; it lists the plugin on Settings → Plugins and in plugin services as retired, with the reason, until you remove it. To migrate, deploy the plugin as a service, remove the retired entry, then add the service. The files the plugin stored on the server are kept and not moved.
  • The old ways to install are gone. There is no Install from file, no install from a GitHub repository, no plugin update by rebuilding, no isolation setting, and no plugin install or plugin install-local. CLI 0.2.0-beta.5 has plugin add and plugin approve-update instead. For a server before v0.1.0-beta.67, run the older CLI (bunx @temps-sdk/cli@0.2.0-beta.1 plugin install <repository>).
  • The plugin launcher is ignored. --plugin-launcher and TEMPS_PLUGIN_LAUNCHER are still accepted so an existing unit file does not stop the server, but they are ignored with a warning: Temps starts no plugin executable, so there is nothing to run as another user.
  • Change permissions need an area. An existing grant to change API resources has no area after the upgrade, so the plugin changes nothing until you choose what it may change.
  • The SDKs. Use @temps-sdk/plugin@beta and the matching temps-plugin-sdk, which start as a service.

In-process plugins: the TempsPlugin trait

The TempsPlugin trait

Every plugin implements this trait. Only name and register_services are required — the rest are opt-in.

pub trait TempsPlugin: Send + Sync {
    /// Unique identifier, used in logs and error messages.
    fn name(&self) -> &'static str;

    /// Phase 1: register the services this plugin provides.
    /// Called for every plugin BEFORE any `initialize_plugin_services` is called.
    fn register_services<'a>(
        &'a self,
        context: &'a ServiceRegistrationContext,
    ) -> Pin<Box<dyn Future<Output = Result<(), PluginError>> + Send + 'a>>;

    /// Phase 2 (optional): initialize services that depend on
    /// services from OTHER plugins. All registrations are complete
    /// by the time this runs.
    fn initialize_plugin_services<'a>(
        &'a self,
        _context: &'a PluginContext,
    ) -> Pin<Box<dyn Future<Output = Result<(), PluginError>> + Send + 'a>> {
        Box::pin(async move { Ok(()) })
    }

    /// Configure HTTP routes for this plugin (optional).
    fn configure_routes(&self, _ctx: &PluginContext) -> Option<PluginRoutes> {
        None
    }

    /// Configure public HTTP routes that bypass auth middleware (optional).
    fn configure_public_routes(&self, _ctx: &PluginContext) -> Option<PluginRoutes> {
        None
    }

    /// Contribute to the global OpenAPI schema (optional).
    fn openapi_schema(&self) -> Option<OpenApi> {
        None
    }

    /// Configure middleware for this plugin (optional).
    fn configure_middleware(&self, _ctx: &PluginContext) -> Option<PluginMiddlewareCollection> {
        None
    }
}

Two-phase initialization

The registration context enforces a strict ordering that makes circular dependencies impossible:

Diagram: Phase 1 — Register, PluginA.register_services(), PluginB.register_services(), PluginC.register_services(), Phase 2 — Initialize, PluginA.initialize(), PluginB.initialize(), PluginC.initialize(), Phase 3 — Route & Serve, configure_routes() for all, openapi_schema() for all, Server accepts...

During Phase 1, each plugin registers the services it owns. It may require_service to pull in core dependencies (database, config) but MUST NOT look up services from other plugins — they may not be registered yet.

During Phase 2, the registry is frozen. Plugins can safely cross-reference each other, because every service is guaranteed to exist. This is where a plugin wires, say, its notification sender into the audit service.


Lifecycle

Sequence diagram: Bootstrap, Plugin, ServiceRegistry, Handler, Service

Key invariants:

  • require_service fails fast with a clear error if the dependency was never registered. This is how Temps catches configuration mistakes at startup instead of at 3am.
  • Services are stored as Arc<T>. Every clone is cheap. Never pass the raw registry into handlers — pass the specific Arc<Service> instance.
  • Routes are configured once at startup. You cannot mount new routes at runtime.

Build your first plugin

This walks through creating a minimal "pings" plugin that exposes POST /api/pings and stores a row in the database. It shows every layer: crate, error type, service, handler, plugin.

1. Create the crate

Add it to the workspace in Cargo.toml:

[workspace]
members = [
    # ...
    "crates/temps-pings",
]

And in crates/temps-pings/Cargo.toml:

[package]
name = "temps-pings"
version.workspace = true
edition.workspace = true

[dependencies]
temps-core = { path = "../temps-core" }
temps-entities = { path = "../temps-entities" }
axum = { workspace = true }
sea-orm = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
utoipa = { workspace = true }

2. Define a typed error enum

Every crate owns its error type. Include IDs in messages so logs are greppable.

// crates/temps-pings/src/error.rs
use thiserror::Error;

#[derive(Error, Debug)]
pub enum PingError {
    #[error("Ping {ping_id} not found")]
    NotFound { ping_id: i32 },

    #[error("Validation error: {message}")]
    Validation { message: String },

    #[error("Database error: {0}")]
    Database(#[from] sea_orm::DbErr),
}

3. Write the service

The service owns business logic. Handlers NEVER touch the database directly.

// crates/temps-pings/src/service.rs
use std::sync::Arc;
use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, Set};
use temps_entities::pings::{self, Entity as Ping};
use crate::error::PingError;

pub struct PingService {
    db: Arc<DatabaseConnection>,
}

impl PingService {
    pub fn new(db: Arc<DatabaseConnection>) -> Self {
        Self { db }
    }

    pub async fn create(&self, message: String) -> Result<pings::Model, PingError> {
        if message.trim().is_empty() {
            return Err(PingError::Validation {
                message: "message cannot be empty".into(),
            });
        }

        let model = pings::ActiveModel {
            message: Set(message),
            ..Default::default()
        }
        .insert(self.db.as_ref())
        .await?;

        Ok(model)
    }

    pub async fn get(&self, ping_id: i32) -> Result<pings::Model, PingError> {
        Ping::find_by_id(ping_id)
            .one(self.db.as_ref())
            .await?
            .ok_or(PingError::NotFound { ping_id })
    }
}

4. Write the handler

Handlers handle auth, DTOs, audit, and HTTP mapping — nothing else.

// crates/temps-pings/src/handlers.rs
use std::sync::Arc;
use axum::{extract::{Path, State}, http::StatusCode, Json};
use serde::{Deserialize, Serialize};
use temps_core::problemdetails::{self, Problem};
use utoipa::ToSchema;
use crate::{error::PingError, service::PingService};

#[derive(Clone)]
pub struct PingAppState {
    pub ping_service: Arc<PingService>,
}

#[derive(Deserialize, ToSchema)]
pub struct CreatePingRequest { pub message: String }

#[derive(Serialize, ToSchema)]
pub struct PingResponse { pub id: i32, pub message: String }

impl From<temps_entities::pings::Model> for PingResponse {
    fn from(m: temps_entities::pings::Model) -> Self {
        Self { id: m.id, message: m.message }
    }
}

// Map domain errors to HTTP responses. Every variant explicitly.
impl From<PingError> for Problem {
    fn from(err: PingError) -> Self {
        match err {
            PingError::NotFound { .. } => problemdetails::new(StatusCode::NOT_FOUND)
                .with_title("Ping Not Found")
                .with_detail(err.to_string()),
            PingError::Validation { .. } => problemdetails::new(StatusCode::BAD_REQUEST)
                .with_title("Validation Error")
                .with_detail(err.to_string()),
            PingError::Database(_) => problemdetails::new(StatusCode::INTERNAL_SERVER_ERROR)
                .with_title("Internal Server Error")
                .with_detail(err.to_string()),
        }
    }
}

#[utoipa::path(
    post, path = "/api/pings", tag = "Pings",
    request_body = CreatePingRequest,
    responses(
        (status = 201, body = PingResponse),
        (status = 400, body = ProblemDetails),
    ),
)]
pub async fn create_ping(
    State(state): State<PingAppState>,
    Json(req): Json<CreatePingRequest>,
) -> Result<(StatusCode, Json<PingResponse>), Problem> {
    let ping = state.ping_service.create(req.message).await?;
    Ok((StatusCode::CREATED, Json(ping.into())))
}

#[utoipa::path(get, path = "/api/pings/{id}", tag = "Pings")]
pub async fn get_ping(
    State(state): State<PingAppState>,
    Path(id): Path<i32>,
) -> Result<Json<PingResponse>, Problem> {
    let ping = state.ping_service.get(id).await?;
    Ok(Json(ping.into()))
}

5. Implement TempsPlugin

This is the glue.

// crates/temps-pings/src/plugin.rs
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use sea_orm::DatabaseConnection;
use temps_core::plugin::{
    PluginContext, PluginError, PluginRoutes,
    ServiceRegistrationContext, TempsPlugin,
};
use crate::{
    handlers::{create_ping, get_ping, PingAppState},
    service::PingService,
};

pub struct PingsPlugin;

impl TempsPlugin for PingsPlugin {
    fn name(&self) -> &'static str { "pings" }

    fn register_services<'a>(
        &'a self,
        ctx: &'a ServiceRegistrationContext,
    ) -> Pin<Box<dyn Future<Output = Result<(), PluginError>> + Send + 'a>> {
        Box::pin(async move {
            // `require_service` panics with a clear startup error if the
            // DB plugin hasn't registered the connection yet.
            let db = ctx.require_service::<Arc<DatabaseConnection>>();
            ctx.register_service(Arc::new(PingService::new(db)));
            Ok(())
        })
    }

    fn configure_routes(&self, ctx: &PluginContext) -> Option<PluginRoutes> {
        // `get_service` returns `Option<Arc<T>>` — use it (not `require_service`)
        // wherever a missing dependency should degrade to "no routes" instead of a panic.
        let ping_service = ctx.get_service::<Arc<PingService>>()?;
        let state = PingAppState { ping_service };

        let router = axum::Router::new()
            .route("/pings", axum::routing::post(create_ping))
            .route("/pings/{id}", axum::routing::get(get_ping))
            .with_state(state);

        Some(PluginRoutes::new(router))
    }

    fn openapi_schema(&self) -> Option<utoipa::openapi::OpenApi> {
        Some(crate::api_doc::ApiDoc::openapi())
    }
}

6. Register the plugin

In temps-bootstrap (or wherever your plugin list lives):

let plugins: Vec<Box<dyn TempsPlugin>> = vec![
    Box::new(temps_auth::AuthPlugin::new(auth_config)),
    Box::new(temps_pings::PingsPlugin),
    // ...
];

That's it — the platform handles registration, routing, and OpenAPI merging.


Service registration

require_service vs get_service

// get_service: returns Option<Arc<T>>. Use when the dependency is optional.
let emails: Option<Arc<EmailService>> = ctx.get_service();

// require_service: returns Result<Arc<T>, PluginError>.
// Fails plugin init with a descriptive error. Use for mandatory deps.
let db: Arc<DatabaseConnection> = ctx.require_service()?;

Rule of thumb: if your plugin cannot function without the dependency, use require_service. If it can degrade gracefully (e.g. "email notifications disabled when email plugin missing"), use get_service.

Type-keyed lookup

The registry is keyed by TypeId, not by name. That means:

  • One instance per type. Registering Arc<MyService> twice overwrites the first.
  • Different types are distinct entries. Arc<PingService> and Arc<dyn PingSender> are separate, even if PingService implements PingSender.

If you want to expose both the concrete type and a trait object, register both:

let svc: Arc<PingService> = Arc::new(PingService::new(db));
ctx.register_service(svc.clone());
ctx.register_service(svc as Arc<dyn PingSender>);

Registration flow

Diagram: Inputs from registry, Arc<DatabaseConnection>, Arc<EncryptionService>, Arc<dyn NotificationService>, Service construction, Arc::new(BackupService::new(db, enc, notif)), Registration, ctx.register_service(service), Available to all plugins in phase 2 and beyond

Common pitfalls

  • Name
    Looking up other-plugin services in Phase 1
    Description

    A plugin's register_services runs in registration order. If you look up a service from another plugin here, that plugin might not have registered yet. Move the lookup to initialize.

  • Name
    Storing the registry in the service
    Description

    Never pass &ServiceRegistry or ServiceRegistrationContext into a service constructor. Resolve dependencies explicitly and pass Arc<T> values.

  • Name
    Using Option<T> for required deps
    Description

    If the plugin can't work without a service, make it non-optional in the constructor signature. Let startup fail loudly.

  • Name
    Sharing deps via accessor methods
    Description

    Don't expose fn db(&self) -> &DatabaseConnection on services. Each component that needs the DB should receive its own Arc<DatabaseConnection> clone.


Route configuration

URL conventions

PrefixUse
/api/admin/*Admin-only APIs, guarded by permission_guard!(auth, SystemAdmin) etc.
/api/<plugin>/*Plugin-owned APIs (e.g. /api/backups, /api/pings).
/api/public/*Unauthenticated public endpoints.
/api/_temps/*Reserved for internal Temps use.

Declare plugin routes without the /api prefix (e.g. /pings, not /api/pings). The plugin listener nests every plugin route under /api globally, so the served path becomes /api/pings. See the API Reference for where the prefix is applied.

Path parameters

Always use Axum's {param} syntax, never :param:

.route("/pings/{id}", axum::routing::get(get_ping))
.route("/projects/{project_id}/backups/{backup_id}", ...)

Per-plugin state

Each plugin builds its own AppState struct containing the Arc<Service> instances it needs, and attaches it via .with_state(...). This keeps routers decoupled — a plugin's state doesn't leak into other plugins.

#[derive(Clone)]
pub struct PingAppState {
    pub ping_service: Arc<PingService>,
    pub audit_service: Arc<AuditService>,
}

Middleware

Apply auth, request-ID, and tracing middleware at the plugin-router level, not on individual routes:

let router = axum::Router::new()
    .route("/pings", axum::routing::post(create_ping))
    .route_layer(axum::middleware::from_fn(require_auth))
    .with_state(state);

OpenAPI integration

Each plugin defines its own utoipa ApiDoc and returns it from openapi_schema. The bootstrap layer merges every plugin's schema into a single spec served at /api/api-docs/openapi.json, with Swagger UI at /api/swagger-ui/. Both require an authenticated session or API key.

// crates/temps-pings/src/api_doc.rs
use utoipa::OpenApi;
use crate::handlers::{CreatePingRequest, PingResponse};

#[derive(OpenApi)]
#[openapi(
    paths(
        crate::handlers::create_ping,
        crate::handlers::get_ping,
    ),
    components(schemas(CreatePingRequest, PingResponse)),
    tags((name = "Pings", description = "Ping endpoints")),
)]
pub struct ApiDoc;

Tips:

  • Use tag = "Pings" consistently on every #[utoipa::path(...)] macro so endpoints group correctly in Swagger UI.
  • Document every response code your handler can produce, including 401, 403, and the RFC 7807 Problem schema for errors.
  • Re-export shared response types (like ProblemDetails) from temps-core so every plugin references the same schema.

Testing plugins

Unit-test the service

Use MockDatabase from Sea-ORM to test happy paths and every error variant:

#[cfg(test)]
mod tests {
    use super::*;
    use sea_orm::{DatabaseBackend, MockDatabase};

    #[tokio::test]
    async fn create_rejects_empty_message() {
        let db = MockDatabase::new(DatabaseBackend::Postgres).into_connection();
        let svc = PingService::new(Arc::new(db));

        let err = svc.create("   ".into()).await.unwrap_err();
        assert!(matches!(err, PingError::Validation { .. }));
    }

    #[tokio::test]
    async fn get_returns_not_found_for_missing_id() {
        let db = MockDatabase::new(DatabaseBackend::Postgres)
            .append_query_results(vec![Vec::<pings::Model>::new()])
            .into_connection();
        let svc = PingService::new(Arc::new(db));

        let err = svc.get(42).await.unwrap_err();
        assert!(matches!(err, PingError::NotFound { ping_id: 42 }));
    }
}

Contract-test the HTTP layer

Drive the Axum router directly with tower::ServiceExt::oneshot:

let app = PingsPlugin.configure_routes(&ctx).unwrap().into_router();
let response = app
    .oneshot(Request::post("/api/pings")
        .header("content-type", "application/json")
        .body(r#"{"message":"hi"}"#.into()).unwrap())
    .await.unwrap();
assert_eq!(response.status(), StatusCode::CREATED);

Built-in plugins

Temps ships with 40+ plugins. These are the most commonly extended:

  • Name
    AuthPlugin
    Description

    Session management, JWT issuance, and the RequireAuth extractor used by every write handler.

  • Name
    ProxyPlugin
    Description

    Pingora-backed HTTP/HTTPS router. Handles TLS termination and analytics capture.

  • Name
    DeployerPlugin
    Description

    Container builds and deploys. Depends on GitService, BlobService, LogService.

  • Name
    DomainsPlugin
    Description

    DNS provisioning and Let's Encrypt certificate management.

  • Name
    AnalyticsPlugin
    Description

    Event ingestion, sessions, funnels, and session replay.

  • Name
    BackupPlugin
    Description

    Scheduled and on-demand backups of managed Postgres, MariaDB, MongoDB, Redis and S3/MinIO services and the control-plane database, written to an S3 target.

  • Name
    ErrorTrackingPlugin
    Description

    Sentry-compatible ingest endpoint and issue management.

  • Name
    BlobPlugin / KVPlugin
    Description

    Object storage and a Redis-backed KV store, exposed as platform services.

  • Name
    AuditPlugin
    Description

    Searchable audit log of write operations across the platform. Premium: tamper-evident hash chaining.

Plugin dependency graph (abridged)

Diagram: Core (Database, Config, Auth), ProxyPlugin, AnalyticsPlugin, DeployerPlugin, DomainsPlugin, BackupPlugin, AuditPlugin

Injecting plugins from another binary

Everything above assumes you add your plugin to the OSS plugin list and rebuild the temps binary. But you can also reuse the entire CLI from an out-of-tree binary — one that wraps the same subcommands while registering its own additional plugins. This is exactly how the Enterprise Edition binary (temps-ee/apps/temps-cli) layers EE plugins on top of OSS without forking the CLI.

The library entrypoint

temps-cli builds both a binary and a library target. The binary (src/main.rs) is a thin delegate:

// crates/temps-cli/src/main.rs
fn main() -> anyhow::Result<()> {
    temps_cli::run(Vec::new())
}

The library (crates/temps-cli/src/lib.rs) exposes the full subcommand surface so another crate can call into it:

ItemSignaturePurpose
Clipub struct CliThe clap parser (log flags + command).
Commandspub enum CommandsEvery subcommand (Serve, Proxy, Setup, …).
dispatchpub fn dispatch(cli: Cli, extra_plugins: Vec<Box<dyn TempsPlugin>>) -> anyhow::Result<()>Routes a parsed Cli to its command. extra_plugins is forwarded to serve only.
runpub fn run(extra_plugins: Vec<Box<dyn TempsPlugin>>) -> anyhow::Result<()>Parses args, installs tracing + the rustls crypto provider, then dispatches.

The [lib] target is declared in crates/temps-cli/Cargo.toml:

[lib]
name = "temps_cli"
path = "src/lib.rs"

An EE-bundled binary then becomes its own thin delegate that passes a non-empty plugin vec:

// temps-ee/apps/temps-cli/src/main.rs (illustrative)
fn main() -> anyhow::Result<()> {
    temps_cli::run(vec![
        Box::new(temps_ee_teams::TeamsPlugin::new()),
        // ... other EE plugins
    ])
}

Where extra plugins get registered

dispatch forwards extra_plugins only to temps serve — every other subcommand has no plugin lifecycle and ignores them. Inside serve, the plumbing is:

  • ServeCommand::execute() is just self.execute_with_extra_plugins(Vec::new()).
  • ServeCommand::execute_with_extra_plugins(extra_plugins) carries the vec into ConsoleApiParams, which has a public field extra_plugins: Vec<Box<dyn TempsPlugin>> (OSS callers pass an empty vec).
  • The console registers these plugins last — after every OSS plugin and immediately before plugin_manager.initialize_plugins().

Because they register last, extra plugins can resolve any OSS service via require_service in their register_services and initialize phases. They observe the full OSS service registry, so an EE plugin can wrap or extend OSS services without the OSS crates knowing it exists.

Sandbox API URL resolution

A related fix lives in the agent-workflow sandbox. When the platform launches a sandbox container for an agent run, it injects a TEMPS_API_URL env var so the in-sandbox CLI can reach the control plane. That value is now resolved in this priority order:

PrioritySource
1The TEMPS_INTERNAL_API_URL process env var, if set.
2The platform's configured external_url (from settings), trailing slash trimmed, if non-empty.
3The hard-coded fallback http://host.docker.internal:3000.

Previously the resolution fell straight from (1) to the host.docker.internal:3000 fallback. Adding the external_url step means remote and production control planes reach the API on agent-workflow runs without operators having to set TEMPS_INTERNAL_API_URL explicitly.


Best practices

  1. One crate per plugin. Keeps compile times fast and boundaries clean.
  2. Typed errors, not anyhow. Define a domain error enum per crate, with #[from] for common conversions and structured fields for context.
  3. Services own transactions. Handlers call one service method per request. If a handler needs to coordinate multiple services, add a method to the service layer instead.
  4. Audit every write. In handlers, call audit_service.create_audit_log(...) after successful POST/PATCH/DELETE. Log-but-continue on audit failures.
  5. Mask secrets in responses. Never serialize raw API keys, tokens, or passwords. Use "***" masking in the response DTO.
  6. Paginate everything. Default 20, max 100, sorted by created_at DESC. See the architecture guide for the standard pagination helper.
  7. Test Docker-backed code gracefully. If a test requires Docker, skip at runtime with a log message instead of #[ignore]. Keeps CI green on machines without Docker.

Troubleshooting

PluginError::ServiceNotFound { service_type: "Arc<X>" } at startup

A plugin called require_service::<Arc<X>>() but no plugin registered that type. Check:

  • Is the providing plugin in your plugin list, before the consumer?
  • Did you register as the right type? Arc<X> and Arc<dyn Trait> are separate keys.
  • Are you looking up in register_services instead of initialize? The providing plugin may register later in Phase 1 — move the lookup to Phase 2.

Routes return 404 in production but work in tests

configure_routes returned None because a require_service call failed. Scan startup logs for WARN/ERROR lines from your plugin and confirm its dependencies registered.

OpenAPI docs missing your endpoints

  • Did you implement openapi_schema? It defaults to None.
  • Is every handler decorated with #[utoipa::path(...)] and listed in paths(...) on the ApiDoc?
  • Are request/response types listed in components(schemas(...))?

Panic: thread 'main' panicked at 'already borrowed: BorrowMutError'

You're trying to register a service from inside a handler or background task. Registration is only valid during Phase 1. Move the call back into register_services.


Last updated

Was this page helpful?