basaltplugin

package module
v0.1.0-alpha.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 22 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

basalt-plugin-go

The Go SDK for BasaltDB plugins.

BasaltDB sits between an AI agent and a database. A plugin is a separate program the engine starts and calls. You write what the plugin does; the SDK speaks the protocol: the handshake, health checks, shutdown, message size limits, deadlines and the three transports.

The first kind of plugin is a notifier. It tells a person what an agent did, in the channel they already use: a chat room, a pager, a webhook, a message queue.

Full documentation: https://docs.basaltvault.app

The first release is v0.1.0-alpha. The API can still change before v1.0.0.

Install

You need Go 1.26 or later.

go get github.com/basaltdbhq/basalt-plugin-go@v0.1.0-alpha

The module path is all lower case.

The package name is basaltplugin, so import it by that name:

import basaltplugin "github.com/basaltdbhq/basalt-plugin-go"

A complete notifier

This is the whole program. It is also in examples/notifier.

package main

import (
	"context"
	"fmt"
	"os"

	basaltplugin "github.com/basaltdbhq/basalt-plugin-go"
)

type notifier struct{}

func (notifier) Info() basaltplugin.Info {
	return basaltplugin.Info{Name: "hello-notify", Version: "0.1.0"}
}

func (notifier) ObserveFeed(_ context.Context, b basaltplugin.FeedBatch) (int64, error) {
	for _, ev := range b.Events {
		held, ok := ev.Detail.(basaltplugin.WriteHeld)
		if !ok || ev.IsCheckSample() {
			continue
		}
		if _, err := fmt.Fprintf(os.Stderr, "%s: %d rows wait for approval\n", b.Agent, held.Rows); err != nil {
			return 0, err // the engine sends this batch again later
		}
	}
	return b.LastSeq(), nil
}

func (notifier) DeliverApproval(_ context.Context, n basaltplugin.Notice) error {
	if n.IsCheckSample() {
		return nil
	}
	_, err := fmt.Fprintln(os.Stderr, n.Headline, n.Instruction, n.Link)
	return err
}

func main() {
	if err := basaltplugin.Serve(context.Background(), notifier{}); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

What it does:

  • Info names the plugin. The name and version must equal the manifest's.
  • ObserveFeed gets one agent's events, in order: writes applied, refused or held, approvals signed, reverts. They hold metadata only, never a row value or a statement. Return the Seq of the last event you handled; b.LastSeq() means all of them. Return an error and the engine sends the same events again later.
  • DeliverApproval gets a notice that something waits for the person: a held write, a prepared revert, or a replaced link.
  • Serve runs until the engine stops the plugin.

The SDK declares a hook for each of the two interfaces the plugin implements. Implement only one and it declares only that one.

Write nothing to stdout. On the default transport, stdout carries the protocol. Use stderr for your own output.

Check it with basalt plugin check

basalt plugin check starts your plugin the way the engine does, runs the handshake and a health check, sends each hook a fixed sample, and stops it. It needs no database.

You need a basalt binary that has the basalt plugin commands. Engine releases up to v0.0.1-alpha.2 do not have them yet; until the next release, build the engine from source (see the engine's README). The steps below are for an engine in same-user mode: its engine.json has "mode": "SAME_USER" and lists the agent you pass to --agents. trust, add and enable each ask you to confirm.

  1. Build the plugin into a directory of its own:

    go build -o hello-notify/bin/hello-notify .
    
  2. Write hello-notify/basalt-plugin.json. The files entry holds the SHA-256 of the binary (shasum -a 256 hello-notify/bin/hello-notify). The name, the version and the hooks must equal what the plugin says about itself, or the engine refuses it.

    {
      "manifestVersion": 1, "name": "hello-notify", "version": "0.1.0", "publisher": "You",
      "protocol": ["basalt-plugin/1"],
      "hooks": {
        "feed.observe": { "contract": "feed/1" },
        "approval.deliver": { "contract": "deliver/1" }
      },
      "endpoint": { "local": { "transport": "jsonrpc-stdio", "command": "bin/hello-notify" } },
      "files": { "bin/hello-notify": "sha256:<hash of the binary>" },
      "network": { "egress": [] }
    }
    
  3. Make a signing key and sign the plugin:

    basalt plugin keygen --out keys
    basalt plugin sign hello-notify --key keys/<key id>.key
    
  4. Trust your key on your own engine:

    basalt plugin trust keys/<key id>.pub
    
  5. Install the plugin for the agents it should serve, and turn it on:

    basalt plugin add hello-notify --agents product_a
    basalt plugin enable hello-notify
    
  6. Check it:

    basalt plugin check hello-notify
    

    It prints one line for the handshake and one per hook:

    plugin hello-notify/default: initialize 3ms, health READY 1ms
    plugin hello-notify/default: approval.deliver 1ms
    plugin hello-notify/default: feed.observe lastSeq 2 1ms
    

The samples check sends answer true to IsCheckSample(). Answer them like any other event, but do not post them to a person.

Start from the template

template/main.go is a feed observer with a -transport flag and the manifest it needs in its comment. Copy the file into your own module, change the name and version, and make ObserveFeed do what your plugin does.

What to know before you ship

  • Events arrive at least once. After a crash, a restart or a failed call the engine sends them again. Two events with the same Source and ID are the same event: dedup by that pair.
  • Skip what you do not know. A later engine may send an event type this SDK does not know (Detail is nil, Seq is set) or a notice of an unknown Kind. Skip it and still count it as handled.
  • Forward events unchanged. Every event is a CloudEvents 1.0 event. Raw() returns its exact JSON bytes; send those to a broker or a webhook, not a re-encoding.
  • Escape text for your channel. Headlines, table names and agent names are plain text. An agent names its own tables, so escape your chat's markup (mentions, links, emphasis) before you post.
  • A notice's link can hold the request. A long link carries the statement, its parameters and the affected rows. Anyone who can read where you deliver the notice can read them. The link grants no power: approving still needs the person's passkey.
  • Errors stay in the plugin. The SDK never sends a handler's error text to the engine, because it may hold a value. Write reasons to stderr.

The package documentation covers each of these, the optional Initializer, HealthChecker and Shutdowner interfaces, and remote plugins over TLS.

Transports

You write no transport code. The manifest's endpoint.local.transport says how the engine reaches the plugin, and Serve follows.

Manifest transport What to do
jsonrpc-stdio Nothing. It is the default.
jsonrpc-unix Nothing. The engine sets BASALT_PLUGIN_SOCKET and Serve listens on it.
connectrpc Pass basaltplugin.WithTransport(basaltplugin.ConnectRPC). A plain gRPC client works too.

A plugin on another host serves ConnectRPC over TLS on a listener you supply, with WithListener and WithBearerToken.

Packages

Import path What it is
github.com/basaltdbhq/basalt-plugin-go Package basaltplugin: the SDK. Most plugins need only this.
.../protocol The protocol's JSON message types and limits, for code that speaks the protocol itself.
.../proto/basalt/plugin/v1 and .../pluginv1connect The generated ConnectRPC service, basalt.plugin.v1.PluginService, and its .proto file.

Protocol and versions

The engine defines the plugin protocol: its contract, its JSON schemas and the service definition. This module holds copies of what it needs: the .proto file under proto/ (it differs from the engine's only in its header comment and go_package), the message types in protocol/, and the contract's samples under testdata/. They were taken from BasaltDB commit d2fd2b9c340e, which is not yet in a tagged engine release.

This module's major version follows the protocol's. Every v0 and v1 release speaks basalt-plugin/1; a new protocol major version means a new module major version. The event type names (dev.basaltdb.*) are the engine's and do not change with this module's version.

Develop

make help    # every target
make fmt     # gofumpt and goimports; commit what it changes
make ci      # tidy check, vet, lint (golangci-lint pinned in ./bin) and the tests with the race detector
make proto   # regenerate the Go code from the .proto file (needs protoc)

Code rules for contributors and coding agents: AGENTS.md.

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package basaltplugin serves a Basalt plugin. A plugin author writes what the plugin does; the SDK speaks the protocol.

The SDK answers initialize (with version negotiation), health and shutdown, enforces the 4 MiB message cap in both directions, applies the entry's per-call deadline to the context of every call, keeps at most four hook calls running at once (health and shutdown are answered beside them), and exits cleanly on shutdown. It never logs, never reads the environment beyond SocketEnv, and puts no value from a message in any error.

Write a notifier

A notifier tells a person what an agent did, in the channel they already use. It implements one or both of two interfaces, and the SDK declares the matching hooks for it:

  • FeedObserver (feed.observe): the agent's ledger events, in order, as typed values. Metadata only, never a row value, a statement or an intent, so they are safe to store or forward.
  • ApprovalDeliverer (approval.deliver): a notice that a write waits for the person's approval, a revert waits for their signature, or the link to one was replaced, with the link the agent was handed.

A complete notifier (chat stands for your channel's client). The package's name is basaltplugin, so import it by that name:

import basaltplugin "github.com/basaltdbhq/basalt-plugin-go"

type notifier struct{ out *chat.Client }

func (notifier) Info() basaltplugin.Info { return basaltplugin.Info{Name: "chat-notify", Version: "0.1.0"} }

func (n notifier) ObserveFeed(ctx context.Context, b basaltplugin.FeedBatch) (int64, error) {
	for _, ev := range b.Events {
		held, ok := ev.Detail.(basaltplugin.WriteHeld)
		if !ok || ev.IsCheckSample() {
			continue // another type, one this SDK does not know, or check's sample
		}
		text := fmt.Sprintf("%s: %d rows held", chat.Escape(b.Agent), held.Rows)
		if err := n.out.Post(ctx, ev.Source+"/"+ev.ID, text); err != nil {
			return 0, err // the engine sends this batch again later
		}
	}
	return b.LastSeq(), nil
}

func (n notifier) DeliverApproval(ctx context.Context, x basaltplugin.Notice) error {
	switch x.Kind {
	case basaltplugin.KindApprovalRequested, basaltplugin.KindRevertRequested, basaltplugin.KindLinkReplaced:
	default:
		return nil // a kind this SDK does not know: skip it
	}
	if x.IsCheckSample() || time.Now().After(x.ExpiresAt) {
		return nil
	}
	text := chat.Escape(x.Headline) + "\n" + x.Instruction
	if x.Link != "" {
		text += "\n" + x.Link
		if x.LinkOpens == basaltplugin.LinkOpensEngineComputer {
			text += "\n(This link opens only on the computer Basalt runs on.)"
		}
	}
	return n.out.Post(ctx, x.Source+"/"+x.ID, text)
}

func main() { /* basaltplugin.Serve(ctx, notifier{...}), as the template does */ }

Its manifest declares both hooks, with their contracts. The SDK declares a hook for every interface the plugin implements, so the manifest must list exactly those: implement ApprovalDeliverer without listing approval.deliver and the engine refuses the plugin at initialize.

"hooks": { "feed.observe": { "contract": "feed/1" }, "approval.deliver": { "contract": "deliver/1" } }

What to know:

  • At least once. An event or a notice can arrive again: after a crash, a restart or a failed call, and a notice up to four times. Two with the same Source and ID are the same: dedup by that pair, as the example does by posting with Source and ID as the message key.
  • The answer to a batch. Return the Seq of the last event you handled: b.LastSeq() for all of them, or an earlier one, and the engine sends the rest again. The SDK refuses to send a Seq that is not one of the batch's; an error, a panic, a late answer or a refused one makes the engine send the same events again later. Nothing in Basalt waits for a notifier.
  • Skip what you do not know. A later engine may send a Type this SDK does not know (Detail is nil, Seq is set) or a field it does not know (ignored). Skip the event and still count it as handled; skip a notice of an unknown Kind.
  • Forward unchanged. Every event is a CloudEvents 1.0 event. Raw returns its exact JSON bytes, so a plugin that passes events to a message broker or a webhook sends Raw, never a JSON encoding of FeedEvent or Notice.
  • Plain text. Headline, Table, Agent and every other string are the engine's or the database's text, and an agent names its own tables. The engine keeps them to one plain line, but a chat's own markup (mentions such as @everyone or <!channel>, emphasis, links) is yours to escape before you post. A notice's link opens anywhere (LinkOpensAnywhere) or only on the computer Basalt runs on (LinkOpensEngineComputer): say so when you show it. With no link, Instruction tells the person to ask the agent.
  • Samples. basalt plugin check sends a fixed batch and notice for which IsCheckSample is true. Answer them as any other, but do not post them to a person or keep them for dedup.
  • What you get is what the engine sends. The SDK passes events and notices on as they arrive; it is the engine that keeps row values, statements, intents and other agents out of them.

A notice carries exactly the link the agent's own answer handed over. A short link carries only a secret that opens the approval page. A long link carries the whole request inside it: the statement, its parameters, the intent and the affected rows, values included. So anyone who can read where you deliver a notice can read the request, and a plugin that forwards notices to a message broker puts that link into the broker's log, readable by whoever can read that log for as long as it keeps it. The link grants no power over the action: approving still needs the person's passkey. Every other field of a notice, and every feed event, holds no value, statement or intent.

From zero to a served plugin

The template (directory template, package main) is a feed observer that writes one line per event to stderr, with a transport flag and the manifest it needs. Copy template/main.go into a module of your own that requires this one (go get github.com/basaltdbhq/basalt-plugin-go). The steps below are for same-user mode: engine.json has "mode": "SAME_USER" and lists the agent you pass to --agents, and trust, add and enable ask for a yes at the prompt.

  1. Build it, from your module: go build -o hello-feed/bin/hello-feed .
  2. Write hello-feed/basalt-plugin.json. The template's comment has a manifest to start from. Its "files" entry holds the binary's SHA-256 (shasum -a 256 hello-feed/bin/hello-feed), and its name, version and hooks must equal what Info and the interfaces the plugin implements say, or the engine refuses the plugin at initialize.
  3. Make a key and sign: basalt plugin keygen --out KEYDIR, then basalt plugin sign hello-feed --key KEYDIR/KEYID.key.
  4. Trust your key on your own engine: basalt plugin trust KEYDIR/KEYID.pub.
  5. Install and turn it on, for the agents it should serve: basalt plugin add hello-feed --agents product_a, then basalt plugin enable hello-feed.
  6. Check it: basalt plugin check hello-feed. It starts the plugin, runs initialize and health, sends each declared notifier hook a fixed sample, and sends shutdown. It prints one line for initialize and health and one per hook: "plugin hello-feed/default: initialize 3ms, health READY 1ms" "plugin hello-feed/default: feed.observe lastSeq 2 1ms"

In same-user mode (the foreground engine, for development and CI) all of this runs as your user under the engine's config directory.

Choosing a transport

The author writes no transport code. The manifest's endpoint.local.transport says how the engine starts and reaches the plugin, and Serve follows:

  • jsonrpc-stdio: the default when SocketEnv is not set. The engine speaks JSON-RPC on the plugin's stdin and stdout. Write nothing else to stdout.
  • jsonrpc-unix: the default when SocketEnv is set. The engine starts the plugin with that one environment variable, the absolute path of a socket; Serve listens on it.
  • connectrpc: pass WithTransport(ConnectRPC). With SocketEnv set, Serve serves ConnectRPC and gRPC over h2c on that socket, so a plain gRPC client works too.

One binary can serve all three: read a flag, put it in the manifest's "args", and pass basaltplugin.WithTransport(basaltplugin.Transport(flagValue)), as the template does.

A remote plugin (the manifest's endpoint.remote) serves ConnectRPC on a listener the author supplies, over TLS:

l, err := tls.Listen("tcp", ":8443", &tls.Config{Certificates: certs})
...
basaltplugin.Serve(ctx, p, basaltplugin.WithListener(l, tlsConfig), basaltplugin.WithBearerToken(token))

The engine requires TLS and checks the certificate against the endpoint's host. WithBearerToken makes the server require the "Authorization: Bearer" header the engine sends when the entry has a credential file.

Optional behavior

Plugin has one method. The SDK looks for more with type assertions, so a plugin implements only what it needs:

  • Initializer receives the entry's config and limits at initialize.
  • HealthChecker reports NOT_READY when it returns an error.
  • Shutdowner runs before the shutdown reply, to flush or release.
  • FeedObserver and ApprovalDeliverer, above, serve the notifier hooks.

Handlers receive a context that ends at the call's deadline and must return when it does. A hook handler that does not keeps its slot until it returns: a later hook call waits for a slot until its own deadline and is then answered deadline exceeded, and health and shutdown are still answered. An error a handler returns is not sent to the engine (it may hold a value): the engine sees a failed call, and a plugin that wants a reason writes it to its own stderr. A notifier handler that panics fails its call the same way, and the plugin goes on serving.

Hooks

The SDK declares a hook in initialize only for a plugin that implements its interface, so adding a hook to the SDK never changes a plugin written before it. The notifier hooks have interfaces; wire.detect and classify.suggest do not yet. Until the interface for your hook exists, declare it with WithHooks. WithHooks refuses to declare a hook that has an interface the plugin does not implement (ErrHookNotImplemented). How a hook is added to the SDK is described on hookSpec.

Index

Constants

View Source
const (
	HookFeedObserve     = "feed.observe"
	HookApprovalDeliver = "approval.deliver"

	ContractFeed    = "feed/1"
	ContractDeliver = "deliver/1"
)

The hooks the SDK has interfaces for, and the message contract of each.

View Source
const (
	TypeWriteApplied   = "dev.basaltdb.write.applied"
	TypeWriteRefused   = "dev.basaltdb.write.refused"
	TypeWriteHeld      = "dev.basaltdb.write.held"
	TypeApprovalSigned = "dev.basaltdb.approval.signed"
	TypeRevertPrepared = "dev.basaltdb.revert.prepared"
	TypeRevertSigned   = "dev.basaltdb.revert.signed"
	TypeRevertApplied  = "dev.basaltdb.revert.applied"
	TypeRevertRejected = "dev.basaltdb.revert.rejected"
	TypeFeedSkipped    = "dev.basaltdb.feed.skipped"

	TypeApprovalRequested = "dev.basaltdb.approval.requested"
	TypeRevertRequested   = "dev.basaltdb.revert.requested"
	TypeLinkReplaced      = "dev.basaltdb.link.replaced"
)

The CloudEvents type of every event the engine sends. A feed event's type names what happened to the agent's data or its approvals; a notice's type is one no feed event uses, so the two are never mistaken for each other.

View Source
const (
	InstructionWriteAnywhere        = "Open the link to review the held write and approve it with your passkey."
	InstructionWriteEngineComputer  = "Open the link on the computer Basalt runs on to review the held write and approve it with your passkey."
	InstructionWriteNoLink          = "Ask the agent for the link to review the held write and approve it with your passkey."
	InstructionRevertAnywhere       = "Open the link to review the revert and sign it with your passkey."
	InstructionRevertEngineComputer = "Open the link on the computer Basalt runs on to review the revert and sign it with your passkey."
	InstructionRevertNoLink         = "Ask the agent for the link to review the revert and sign it with your passkey."
)

The six sentences a notice's Instruction can be: by item (a held write or a revert) and by where its link opens, or with no link.

View Source
const (
	// MaxMessageBytes is the largest message either side may send.
	MaxMessageBytes = protocol.MaxMessageBytes
	// MaxInFlight is the number of hook calls the engine keeps open on a
	// plugin. health and shutdown are not counted: each has a slot of its own.
	MaxInFlight = protocol.MaxInFlight
)

Limits every connection runs under, from the protocol.

View Source
const CheckInstallID = "00000000-0000-0000-0000-000000000000"

CheckInstallID is the install id of the samples basalt plugin check sends. No install has it, so an event with it is a sample: handle it, but do not keep it for dedup.

View Source
const Protocol = protocol.Version1

Protocol is the protocol version this SDK speaks.

View Source
const SocketEnv = "BASALT_PLUGIN_SOCKET"

SocketEnv is the one environment variable a local socket plugin is started with: the absolute path of the Unix socket it listens on. It is the engine's documented socket handover, repeated here so the SDK imports nothing of the engine.

Variables

View Source
var (
	// ErrBadPlugin: the plugin's Info has no name or no version.
	ErrBadPlugin = errors.New("basaltplugin: the plugin needs a name and a version")
	// ErrNoSocket: a socket transport was chosen and SocketEnv is not set.
	ErrNoSocket = errors.New("basaltplugin: " + SocketEnv + " is not set to an absolute socket path")
	// ErrTLSRequired: a ConnectRPC listener that is not a Unix socket was
	// given without a TLS configuration. The engine always uses TLS for a
	// remote plugin.
	ErrTLSRequired = errors.New("basaltplugin: a listener that is not a unix socket needs a TLS configuration")
	// ErrMessageTooLarge: the engine sent a message over MaxMessageBytes on
	// the stdio transport. The stream cannot be resynchronised, so Serve ends.
	ErrMessageTooLarge = errors.New("basaltplugin: a message was over the size cap")
	// ErrHookNotImplemented: WithHooks declares a hook the SDK has an
	// interface for (FeedObserver, ApprovalDeliverer), and the plugin does
	// not implement it. The engine would call the hook and get "method not
	// found" every time. Implement the interface; the SDK then declares the
	// hook itself.
	ErrHookNotImplemented = errors.New("basaltplugin: WithHooks declares a hook whose interface the plugin does not implement")
	// ErrTransport: the options name a transport that cannot be served as
	// asked.
	ErrTransport = errors.New("basaltplugin: the transport options do not fit together")
)

Errors Serve returns.

Functions

func Serve

func Serve(ctx context.Context, p Plugin, opts ...Option) error

Serve runs the plugin until the engine sends shutdown, the engine closes the connection (stdio), or ctx ends, and then returns. It answers initialize, health and shutdown itself, enforces the 4 MiB message cap in both directions and the per-call deadline, and starts no work beyond what the engine asked for. A plugin author writes no protocol code.

Serve returns nil for a clean end: a shutdown, a closed stdin, a cancelled ctx. It returns the plugin's own Shutdown error if there was one, and an error when it could not start serving (a missing socket variable, a socket that cannot be created) or, on stdio, when the engine sent a message over the cap. A plugin's main normally ends with:

if err := sdk.Serve(ctx, p, opts...); err != nil {
	fmt.Fprintln(os.Stderr, err)
	os.Exit(1)
}

Serve reads one environment variable, SocketEnv, and only when it serves a socket. It never logs, and no error it returns or sends carries a value from a message.

Types

type ApprovalDeliverer

type ApprovalDeliverer interface {
	DeliverApproval(ctx context.Context, notice Notice) error
}

ApprovalDeliverer is implemented by a plugin that delivers approval notices (approval.deliver, contract deliver/1) to the person: a held write, a prepared revert or a replaced link.

DeliverApproval returns nil once the notice is delivered. An error is a failed try: the engine tries a notice up to four times over about a minute, then drops it. It never sends one past its ExpiresAt. Skip a notice whose Kind you do not know.

type ApprovalSigned

type ApprovalSigned struct {
	ChangeID   string `json:"changeId"`
	ApprovalID string `json:"approvalId"`
}

ApprovalSigned: the person signed a held write (TypeApprovalSigned).

type CloudEvent

type CloudEvent struct {
	SpecVersion string
	// ID is unique per Source and stable across redelivery.
	ID string
	// Source names the database's guard install: urn:uuid:<installId>.
	Source string
	// Type is one of the Type constants, or a type this SDK does not know.
	Type string
	// Time is when it happened; zero when the event has none (the
	// skipped-ahead marker).
	Time time.Time
	// Subject is the agent's name.
	Subject         string
	DataContentType string
	// Data is the event's data object as it arrived.
	Data json.RawMessage
	// contains filtered or unexported fields
}

CloudEvent is the envelope of every event the engine sends: a CloudEvents 1.0 event in its JSON form. A plugin that forwards events to a message broker or a webhook sends Raw, which is the event exactly as it arrived.

Events arrive at least once. Two events with the same Source and ID are the same event: dedup by that pair.

func (CloudEvent) IsCheckSample

func (e CloudEvent) IsCheckSample() bool

IsCheckSample reports whether the event is one of the fixed samples basalt plugin check sends (its install id is CheckInstallID). Answer it as any other, but do not post it to a person or keep it for dedup.

func (CloudEvent) Raw

func (e CloudEvent) Raw() []byte

Raw returns the event's exact JSON bytes, as the engine sent them. Forward these, not a JSON encoding of the Go value: FeedEvent and Notice are not CloudEvents in their JSON form.

type FeedBatch

type FeedBatch struct {
	Agent  string
	Events []FeedEvent
}

FeedBatch is one feed.observe call: events of one agent, in ascending Seq, at most 100.

func (FeedBatch) LastSeq

func (b FeedBatch) LastSeq() int64

LastSeq is the Seq of the batch's last event: the answer of a plugin that handled all of it.

type FeedDetail

type FeedDetail interface {
	// contains filtered or unexported methods
}

FeedDetail is the typed data of a feed event. Switch on its type.

type FeedEvent

type FeedEvent struct {
	CloudEvent
	// InstallID is the agent's database's guard install.
	InstallID string
	// Seq is the event's position in the database's ledger. Sequences are
	// shared by the database's agents, so one agent's events skip numbers.
	Seq int64
	// Agent is the agent's name.
	Agent string
	// Detail is the event's typed data: one of WriteApplied, WriteRefused,
	// WriteHeld, ApprovalSigned, RevertPrepared, RevertSigned,
	// RevertApplied, RevertRejected or FeedSkipped, chosen by Type. It is
	// nil for a Type this SDK does not know: skip such an event, and
	// still count it as handled.
	Detail FeedDetail
}

FeedEvent is one feed event. It holds metadata only: ids, the operation, the table, row counts, an error code, an expiry. Never a row value, a key, a statement, an intent or a link, so it is safe to store or forward.

type FeedObserver

type FeedObserver interface {
	ObserveFeed(ctx context.Context, batch FeedBatch) (lastSeq int64, err error)
}

FeedObserver is implemented by a plugin that observes the feed (feed.observe, contract feed/1): what an agent did to data and what happened to its approvals and reverts.

ObserveFeed gets one agent's events, in order, and returns the Seq of the last event it handled. Return batch.LastSeq() once you handled them all, or the Seq of the last one you handled, and the engine sends the rest again. The SDK answers only a Seq that is one of the batch's: any other, or an error, is a failed call, and the engine sends the same events again after a backoff. Events arrive at least once: dedup by Source and ID.

Skip an event whose Detail is nil (a type this SDK does not know) or that you do not need, and still count it as handled.

type FeedSkipped

type FeedSkipped struct {
	AfterSeq int64 `json:"afterSeq"`
}

FeedSkipped is the skipped-ahead marker (TypeFeedSkipped): the ledger's retention deleted events after AfterSeq before they were delivered. The agent's events with AfterSeq < seq <= the marker's Seq may be gone; how many, if any, is not known. Acknowledge it like any event.

type HealthChecker

type HealthChecker interface {
	Health(ctx context.Context) error
}

HealthChecker is implemented by a plugin that can be unready. A nil error answers READY, an error answers NOT_READY. A plugin without it is always READY once it runs.

type HookDecl

type HookDecl = protocol.HookDecl

HookDecl is what a plugin declares for one hook: the same object as one entry of the manifest's hooks. It is the protocol package's type.

type Info

type Info struct {
	Name    string
	Version string
	// Model is optional.
	Model *Model
}

Info is what a plugin tells the engine about itself. Name, Version and the hooks it declares must equal the installed manifest exactly, or the engine refuses the plugin.

type Init

type Init struct {
	// Protocol is the version negotiated for this connection.
	Protocol string
	// Hooks are the hooks the engine will call: the manifest's.
	Hooks []string
	// Config is the entry's config from engine.json, {} when it has none. It
	// is never a secret.
	Config json.RawMessage
	// TimeoutMs is the deadline of every call, in milliseconds. The SDK
	// already applies it to the context each method receives.
	TimeoutMs int
}

Init is what the engine sends in initialize.

type Initializer

type Initializer interface {
	Initialize(ctx context.Context, in Init) error
}

Initializer is implemented by a plugin that needs its config, or has to load something before it can answer. Returning an error refuses the connection; the error's text is not sent to the engine (it may hold a value), so a plugin that wants a reason writes it to its own stderr.

type LinkOpens

type LinkOpens string

LinkOpens is where a notice's link opens.

const (
	// LinkOpensAnywhere: the portal; the link opens on any device.
	LinkOpensAnywhere LinkOpens = "ANYWHERE"
	// LinkOpensEngineComputer: the engine's local pages; the link opens
	// only on the computer Basalt runs on. Say so when you show it.
	LinkOpensEngineComputer LinkOpens = "ENGINE_COMPUTER"
)

Where a link opens.

type Model

type Model = protocol.Model

Model names the model behind a plugin, when it has one. The engine records the name and version in the ledger.

type Notice

type Notice struct {
	CloudEvent
	Kind  NoticeKind
	Agent string
	// Exactly one of ApprovalID (a held write) and RevertID (a revert) is set.
	ApprovalID string
	RevertID   string
	// Headline is the item in one line, plain text: show it as text, never
	// parse it or render it as markup.
	Headline  string
	ExpiresAt time.Time
	// Link is empty when the agent's answer had no link that stands alone;
	// Instruction then says to ask the agent.
	Link      string
	LinkOpens LinkOpens
	// Instruction is what the person does: one of the Instruction
	// constants.
	Instruction string
}

Notice is one approval.deliver call: something waits for the person. It is one-shot: never replayed from a cursor, and useless after ExpiresAt. A failed try is tried again, up to four times, with the same ID: dedup by Source and ID, as for feed events.

Link is the link the agent's own answer handed over, byte for byte. A long link carries the whole request inside it (the statement, its parameters, the intent and the affected rows, values included), so whoever can read where you deliver it can read the request. A plugin that forwards notices to a message broker puts that link into the broker's log, for as long as the broker keeps it. Every other field holds no value, statement or intent.

type NoticeKind

type NoticeKind string

NoticeKind is what a notice is about.

const (
	// KindApprovalRequested: the engine held a write (TypeApprovalRequested).
	KindApprovalRequested NoticeKind = "APPROVAL_REQUESTED"
	// KindRevertRequested: the engine prepared a revert (TypeRevertRequested).
	KindRevertRequested NoticeKind = "REVERT_REQUESTED"
	// KindLinkReplaced: the agent asked for a new link for a held write or
	// a revert; the earlier link no longer works (TypeLinkReplaced).
	KindLinkReplaced NoticeKind = "LINK_REPLACED"
)

The notice kinds.

type Op

type Op string

Op is the operation of a write.

const (
	OpInsert Op = "INSERT"
	OpUpdate Op = "UPDATE"
	OpDelete Op = "DELETE"
	// OpOther is a refused statement that is none of the three.
	OpOther Op = "OTHER"
)

The operations.

type Option

type Option func(*config)

Option changes how Serve runs.

func WithBearerToken

func WithBearerToken(token string) Option

WithBearerToken makes the ConnectRPC server refuse any call that does not carry "Authorization: Bearer <token>", the header the engine sends when the entry has an auth.credentialFile. The plugin supplies the token itself; the SDK never reads one from the environment. Use it with a remote listener.

func WithHooks

func WithHooks(h map[string]HookDecl) Option

WithHooks declares exactly these hooks, replacing what the SDK finds from the interfaces the plugin implements. Use it to declare a hook whose SDK interface does not exist yet (the engine still checks the declaration against the manifest), or to declare fewer hooks than the plugin implements. The declaration must equal the manifest's hooks. A hook that has an SDK interface (FeedObserver, ApprovalDeliverer) can be declared only by a plugin that implements it; Serve returns ErrHookNotImplemented otherwise.

func WithListener

func WithListener(l net.Listener, tlsConfig *tls.Config) Option

WithListener serves ConnectRPC on a listener the plugin supplies, for a plugin that runs on another host (or any plugin that picks its own socket). tlsConfig carries the plugin's certificate and is required unless l is a Unix socket: the engine refuses a remote endpoint without TLS and checks the certificate against the URL's host. Serve clones the configuration, sets a TLS 1.2 minimum when it has none, and offers HTTP/2. WithListener implies ConnectRPC; combining it with another transport is an error.

func WithTransport

func WithTransport(t Transport) Option

WithTransport chooses the transport. Without it, Serve speaks JSON-RPC on a Unix socket when SocketEnv is set and JSON-RPC on stdio when it is not, which is how the engine starts a plugin whose manifest says jsonrpc-stdio or jsonrpc-unix. A plugin whose manifest says connectrpc passes ConnectRPC.

The simplest way to cover every manifest with one binary is to read the transport from the command's arguments, which the manifest sets, as the template does.

type Plugin

type Plugin interface {
	Info() Info
}

Plugin is the one interface every plugin implements.

It is deliberately small. Everything else is an optional interface the SDK looks for with a type assertion: the lifecycle ones below (Initializer, HealthChecker, Shutdowner) and, as each hook's messages land, one interface per hook. A plugin implements only what it needs, and a new hook never adds a method to Plugin, so a plugin written today still compiles and runs when the SDK learns a new hook.

type RevertApplied

type RevertApplied struct {
	ChangeID string `json:"changeId"`
	RevertID string `json:"revertId"`
}

RevertApplied: a revert was applied (TypeRevertApplied).

type RevertPrepared

type RevertPrepared struct {
	RevertID string `json:"revertId"`
}

RevertPrepared: a revert was prepared for the person to sign (TypeRevertPrepared).

type RevertRejected

type RevertRejected struct {
	RevertID string `json:"revertId"`
}

RevertRejected: the person rejected a revert (TypeRevertRejected).

type RevertSigned

type RevertSigned struct {
	ChangeID string `json:"changeId"`
	RevertID string `json:"revertId"`
}

RevertSigned: the person signed a large revert's plan (TypeRevertSigned).

type Shutdowner

type Shutdowner interface {
	Shutdown(ctx context.Context) error
}

Shutdowner is implemented by a plugin that must flush or release something before it exits. It runs when the engine sends shutdown, before the reply. Serve returns its error (after the reply has been sent).

type Transport

type Transport string

Transport is a way to carry the protocol. The values are the transport names a manifest's endpoint uses.

const (
	// JSONRPCStdio: newline-delimited JSON-RPC 2.0 on stdin and stdout. The
	// plugin must write nothing else to stdout.
	JSONRPCStdio Transport = "jsonrpc-stdio"
	// JSONRPCUnix: the same messages on a Unix socket at the path in SocketEnv.
	JSONRPCUnix Transport = "jsonrpc-unix"
	// ConnectRPC: the basalt.plugin.v1.PluginService service, served as
	// ConnectRPC and gRPC over HTTP/2. On a Unix socket at the path in
	// SocketEnv it is plain h2c, for a local plugin. On a listener given with
	// WithListener it is a remote plugin, over TLS.
	ConnectRPC Transport = "connectrpc"
)

The transports Serve can speak.

type WriteApplied

type WriteApplied struct {
	ChangeID string `json:"changeId"`
	// RunID and TaskID are empty when the write ran outside a run or task.
	RunID  string `json:"runId"`
	TaskID string `json:"taskId"`
	Op     Op     `json:"op"`
	// Table is the statement's own table, empty when it changed no row. It
	// is the database's text: show it as plain text, never as markup.
	Table string `json:"table"`
	// Rows is the rows written, cascades included.
	Rows         int64 `json:"rows"`
	CascadedRows int64 `json:"cascadedRows"`
}

WriteApplied: a write was applied (TypeWriteApplied).

type WriteHeld

type WriteHeld struct {
	ChangeID   string    `json:"changeId"`
	ApprovalID string    `json:"approvalId"`
	RunID      string    `json:"runId"`
	TaskID     string    `json:"taskId"`
	Op         Op        `json:"op"`
	Rows       int64     `json:"rows"`
	ExpiresAt  time.Time `json:"expiresAt"`
}

WriteHeld: a write was held for the person's approval (TypeWriteHeld). It names no table.

type WriteRefused

type WriteRefused struct {
	ChangeID string `json:"changeId"`
	RunID    string `json:"runId"`
	TaskID   string `json:"taskId"`
	Op       Op     `json:"op"`
	// ReasonCode is the refusal's error code, empty when it has none from
	// the contract's table.
	ReasonCode string `json:"reasonCode"`
}

WriteRefused: a write was refused (TypeWriteRefused).

Directories

Path Synopsis
examples
notifier command
Command notifier is a complete Basalt notifier in about twenty lines: it writes one line to stderr for every write that waits for approval and for every approval notice.
Command notifier is a complete Basalt notifier in about twenty lines: it writes one line to stderr for every write that waits for approval and for every approval notice.
proto
Package protocol holds the Go types for the Basalt plugin protocol messages that every transport carries: initialize, health and shutdown, the notifier hooks, and the hooks declaration shared with the manifest.
Package protocol holds the Go types for the Basalt plugin protocol messages that every transport carries: initialize, health and shutdown, the notifier hooks, and the hooks declaration shared with the manifest.
Command template is the smallest plugin that passes `basalt plugin check`: a feed observer that writes one line per event to stderr.
Command template is the smallest plugin that passes `basalt plugin check`: a feed observer that writes one line per event to stderr.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL