pluginapi

package
v0.1.0-rc.6 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 19 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.

Documentation

Overview

Package pluginapi is the versioned, platform-neutral contract for built-in plugins. Sessions must honor context cancellation and must not leave goroutines behind.

Index

Constants

View Source
const (
	ActionExportThread  = "export_thread"
	ActionArchiveThread = "archive_thread"
	ActionDeleteThread  = "delete_thread"
	ActionSearchArchive = "search_archive"
	ActionSaveFile      = "save_thread_file"
)

Action identifiers.

View Source
const (
	ParamText    = "text"    // free text (may hold JSON or Markdown)
	ParamLink    = "link"    // an absolute URL, rendered as text
	ParamChannel = "channel" // a channel identifier
	ParamMessage = "message" // a message identifier inside a channel
	ParamUser    = "user"    // a user identifier
	ParamUsers   = "users"   // a list of user identifiers
	ParamCount   = "count"   // a non-negative integer
	ParamFlag    = "flag"    // true or false
)

Parameter types. A plugin maps each to its platform's closest type.

View Source
const (
	FormatAll      = "all"
	FormatJSON     = "json"
	FormatMarkdown = "markdown"
	FormatText     = "text"
)

Export formats accepted by ActionExportThread's format input.

View Source
const APIVersion = 1
View Source
const MaxErrorDetail = 400

MaxErrorDetail bounds an error cause shown to users or written to logs.

Variables

View Source
var ErrInvalid = errors.New("invalid content")
View Source
var ErrUnsupported = errors.New("unsupported capability")

Functions

func Redact

func Redact(s string, secrets ...string) string

Redact makes an error cause safe to display: it removes the given secret values and anything shaped like a credential, collapses whitespace and caps the length. It is idempotent.

func RedactingLogger

func RedactingLogger(base *slog.Logger, creds Credentials) *slog.Logger

RedactingLogger removes this workspace's resolved credential values from both messages and structured attributes, including nested groups and error values.

func Register

func Register(p Plugin)

func SchemaHelp

func SchemaHelp(raw json.RawMessage) []string

SchemaHelp returns the "x-help" keys of a form schema's properties.

func ValidateGuide

func ValidateGuide(p Plugin, extra ...string) error

ValidateGuide checks a SetupGuide for drift: unique keys, a title and numbered steps for every topic, an existing image with alt text, and that every help key referenced by the setup flow, its links, schema fields ("x-help"), permission groups and extra (for example cleanup help) exists.

func ValidateManifest

func ValidateManifest(m Manifest) error

func ValidateSchema

func ValidateSchema(raw json.RawMessage) error

ValidateSchema accepts only the form-rendering subset; parsing remains authoritative.

Types

type ActionAccess

type ActionAccess interface {
	// Member reports whether user is a member of channel.
	Member(ctx context.Context, user, channel string) (bool, error)
}

ActionAccess reports channel membership from the platform. Errors mean "unknown" and callers must deny.

type ActionComplete

type ActionComplete func(context.Context, ActionResult, error)

ActionComplete reports an action's outcome back to the platform. The host calls it exactly once; err's message is shown to the person who ran it and must be safe to display.

type ActionDispatcher

type ActionDispatcher interface {
	Dispatch(ActionRequest, ActionComplete)
}

ActionDispatcher is supplied by the host through Env.Actions when actions are enabled for a workspace. Dispatch must return promptly: the host runs the action on its own bounded pool, which may outlive the session (a delete suspends capture, which stops the session), and then calls complete. When the pool is full Dispatch rejects the request by calling complete with a "busy" error on the caller's goroutine before returning.

type ActionGuide

type ActionGuide struct {
	Title, Instructions, Requirements, Manifest string
	Links                                       []Link
	Steps                                       []ActionSpec
	// Help lists HelpTopic keys (SetupGuide) with step-by-step guidance for
	// each click in the platform's own UI, shown as "?" popovers.
	Help []string
}

ActionGuide is shown in Settings. Manifest, when set, is the full platform app configuration that also declares the actions. Steps repeats the actions with the titles the platform shows.

type ActionParam

type ActionParam struct {
	Name, Title, Description, Type string
	Required                       bool
	// Choices, when set, are the only accepted values of a text input.
	Choices []string
}

ActionParam is one typed input or output of an action.

type ActionRequest

type ActionRequest struct {
	Action        string
	Thread        Key
	Actor         string
	VerifiedActor string
	Access        ActionAccess
	Query         string
	Format        string
	Folder        string
	Limit         int
	OutputLimit   int
}

ActionRequest is one invocation, already translated by the plugin. Thread names the thread root (the plugin resolves replies to their root). OutputLimit is the platform's per-output size limit in bytes (0: none); the host fits long text outputs under it.

Actor is the person the automation names for this run. Whoever built the automation chooses it, so it only says whom to ask: hosts never authorize with it. VerifiedActor is set only when the platform itself attested who acted (for example the person who clicked a confirmation sent to Actor). Access, when set, answers who may read a channel; without it hosts treat every channel as unreadable. Hosts return content only to a VerifiedActor who is a member of the channel, public or private: automation platforms may let guests run automations, so a public channel is not proof that the person running one may read it.

type ActionResult

type ActionResult struct {
	Outputs map[string]any
}

ActionResult carries outputs keyed by ActionParam.Name; counts are int, flags bool and user lists []string.

type ActionSetup

type ActionSetup interface {
	ActionSetup([]ActionSpec) ActionGuide
}

ActionSetup is an optional Plugin extension describing how a person adds the actions to the platform's automation tool.

type ActionSpec

type ActionSpec struct {
	ID, Title, Description string
	Inputs, Outputs        []ActionParam
}

ActionSpec describes one action.

func Actions

func Actions() []ActionSpec

Actions lists the actions every host implements, in display order. Outputs are typed so later steps (of any app) can use them as variables.

type AgentSetup

type AgentSetup interface {
	SetupManifest() string
	AgentPrompt() string
}

AgentSetup is an optional Plugin extension that lets a coding agent run setup. SetupManifest returns the platform's app manifest (the single source for the wizard's create link and "chatkeeper setup <id> --print-manifest"). AgentPrompt is a copyable prompt the wizard shows; it must not contain credentials. Steps the platform cannot automate stay human clicks.

type ArchiveManifest

type ArchiveManifest struct {
	// CleanupProof links this generation to the journal whose receipts it folded.
	CleanupProof string            `json:"cleanup_proof,omitempty"`
	Schema       int               `json:"schema"`
	Platform     string            `json:"platform,omitempty"`
	TeamID       string            `json:"team_id"`
	Channel      string            `json:"channel"`
	RootTS       string            `json:"root_ts"`
	Permalink    string            `json:"permalink"`
	MessageCount int               `json:"message_count"`
	Objects      map[string]Object `json:"objects"`
	Files        []Attachment      `json:"files"`
	// Gaps lists items the source referenced but the capture could not store
	// (an unreadable file or author, for example). The rest of the thread is kept.
	Gaps []Gap `json:"gaps,omitempty"`
}

type Attachment

type Attachment struct {
	ID     string `json:"id"`
	Path   string `json:"path"`
	Name   string `json:"name"`
	Size   int64  `json:"size"`
	SHA256 string `json:"sha256"`
	URL    string `json:"url"`
}

type Blob

type Blob struct {
	Size   int64
	SHA256 string
	Data   []byte
	Source *FileSource
}

Blob carries inline bytes or a confined, verified local file reference. Both forms are plain serializable data; a future RPC adapter can stream refs.

func (Blob) Open

func (b Blob) Open() (io.ReadCloser, error)

Open rechecks size and digest on every use; the caller owns the returned handle. File references are opened through os.Root and all symlink components are refused.

type Capabilities

type Capabilities struct{ ReadHistory, Realtime, Delete bool }

type Channel

type Channel struct{ ID, Name string }

type ChannelInspector

type ChannelInspector interface {
	InspectChannels(context.Context, []string) ([]ChannelStatus, error)
}

ChannelInspector is an optional Session extension used by diagnostics.

type ChannelStatus

type ChannelStatus struct {
	ID, Name string
	Member   bool
	Problem  string
}

ChannelStatus reports whether the connected account can read a channel.

type Check

type Check struct {
	Label, Detail string
	OK            bool
	Optional      bool
}

Check is one line of a connection test result.

type Choice

type Choice struct {
	ID, Label           string
	Glyph, Image, Group string
	Keywords            string
}

Choice is a selectable option. Glyph, Image and Group are optional display hints (for example an emoji character, a custom image URL and a picker category).

type CleanupBoundary

type CleanupBoundary interface {
	CleanupBoundary(Workspace, ArchiveManifest) string
}

CleanupBoundary validates source-specific workspace identity offline.

type CleanupConfigurator

type CleanupConfigurator interface {
	CleanupSetup(context.Context, Workspace, Env) (CleanupSetup, error)
	TestCleanupCredential(context.Context, Workspace, Env, string, bool) error
}

type CleanupError

type CleanupError struct{ Status, Reason string }

CleanupStatus classifies safe mutation failures without leaking transport details.

func (*CleanupError) Error

func (e *CleanupError) Error() string

type CleanupOffline

type CleanupOffline interface {
	CleanupReason(Workspace, Message) string
}

CleanupOffline checks platform policy without credentials or network access.

type CleanupPolicy

type CleanupPolicy struct {
	Approval      *Trigger
	Scope         string
	Every         time.Duration
	ScheduleSince time.Time
	Enabled       bool
	AllowOthers   bool
	OwnOnly       bool
	MinAge        time.Duration
	TokenEnv      string
}

type CleanupSetup

type CleanupSetup struct {
	Title, WizardTitle, Instructions, Details, OAuthURL string
	Members, Reactions                                  []Choice
	// Help lists HelpTopic keys (see SetupGuide); OAuthHelp is the key shown
	// next to the OAuthURL link.
	Help      []string
	OAuthHelp string
}

type ConfirmError

type ConfirmError struct{ Prompt string }

ConfirmError is returned to the plugin (through ActionComplete) when an action needs a platform-attested person: the plugin asks Actor to confirm in the platform and dispatches the request again with VerifiedActor set to whoever confirmed, or reports the step failed. Prompt says what the person is approving and must be safe to display.

func NeedsConfirmation

func NeedsConfirmation(err error) (*ConfirmError, bool)

NeedsConfirmation reports whether err asks for a confirmation.

func (*ConfirmError) Error

func (e *ConfirmError) Error() string

type ContentHooks

type ContentHooks interface {
	Validate(context.Context, Snapshot) error
	Text(context.Context, Message, map[string]Message) (string, error)
	Author(context.Context, Message) (string, error)
}

type CopyText

type CopyText struct{ Label, Value string }

CopyText is a value the user copies into the platform's own settings, such as a permission name or a configuration document. Values containing a newline render as a collapsible block.

type Credentials

type Credentials map[string]string

func (Credentials) Format

func (Credentials) Format(s fmt.State, _ rune)

func (Credentials) LogValue

func (Credentials) LogValue() slog.Value

func (Credentials) MarshalJSON

func (Credentials) MarshalJSON() ([]byte, error)

type Env

type Env struct {
	Credentials Credentials
	Log         *slog.Logger
	HTTP        *http.Client
	StateDir    string
	Now         func() time.Time
	// Actions is set when the workspace enables workflow steps.
	Actions ActionDispatcher
	// Vault, when set, keeps short-lived secrets in the app's credential
	// store (keychain or the private secrets file), scoped to the workspace.
	Vault Vault
}

type Event

type Event struct{ Channel, RootTS, Kind, ItemTS string }

Event is a capture hint. ItemTS, when set and different from RootTS, names the message inside the thread that a reaction event was about (a reply); the runtime re-reads it through ItemReader before it may authorize an archive.

type EventSink

type EventSink func(Event) bool

type FileSource

type FileSource struct{ Root, Path string }

type Gap

type Gap struct {
	Kind    string `json:"kind"`
	ID      string `json:"id,omitempty"`
	Message string `json:"message,omitempty"`
	Reason  string `json:"reason"`
}

Gap is one referenced item that is missing from an archive, with a short, credential-free reason suitable for display.

type HelpImage

type HelpImage struct{ Image, Alt string }

HelpImage is an extra image of a HelpTopic.

type HelpSpan

type HelpSpan struct {
	Text string
	Bold bool
}

HelpSpan is one run of HelpTopic text; Bold marks a ** delimited label.

func HelpText

func HelpText(s string) []HelpSpan

HelpText splits help text on ** into plain and bold runs.

type HelpTopic

type HelpTopic struct {
	Key, Title   string
	Steps        []string
	Mistakes     []string
	Image, Alt   string
	More         []HelpImage
	Illustration bool
}

HelpTopic is step-by-step guidance for one action the user performs in the platform's own UI, shown in a "?" popover. Text wrapped in ** renders bold (use it for exact button and field labels); nothing else is interpreted, so content is always escaped plain text. Image names a file in HelpAssets and Alt describes it; More adds further images shown in order. Illustration marks drawn mocks instead of real screenshots.

func (HelpTopic) Images

func (t HelpTopic) Images() []HelpImage

Images lists every image of the topic, Image first.

type Identity

type Identity struct{ TeamID, UserID string }

type ItemReader

type ItemReader interface {
	Item(ctx context.Context, channel, rootTS, ts string) (Root, error)
}

ItemReader is an optional Session extension for realtime reply reactions: it re-reads the reactions on one message of a thread and must verify that the message belongs to rootTS. It returns a zero Root when the message is gone.

type Key

type Key struct{ Channel, RootTS string }
type Link struct{ Label, URL, Help string }

Link opens a page in the platform's own UI. Help optionally names a HelpTopic key (see SetupGuide) shown as a "?" next to the link.

type Manifest

type Manifest struct {
	ID, Name, Version string
	APIVersion        int
	Capabilities      Capabilities
	ClaimsLegacy      bool

	DefaultReactions []string
}

type Message

type Message map[string]any

type Object

type Object struct {
	Size   int64  `json:"size"`
	SHA256 string `json:"sha256"`
}

type Permission

type Permission struct {
	Name, Where, Why string
}

Permission is one grant the platform asks for. Where says where the user adds it in the platform's settings; Why is a one-line plain-language reason.

type PermissionGroup

type PermissionGroup struct {
	Feature, Summary string
	Required         bool
	Permissions      []Permission
	Help             []string
}

PermissionGroup is the set of grants one feature needs. Help lists HelpTopic keys explaining how to add them.

type Plugin

type Plugin interface {
	Manifest() Manifest
	ConfigSchema() json.RawMessage
	CredentialSchema() json.RawMessage
	ParseWorkspace(context.Context, json.RawMessage, Credentials) (Settings, error)
	ValidateWorkspaces(context.Context, []Settings) error
	SetupFlow() []SetupStep
	NewSession(context.Context, Workspace, Env) (Session, error)
	NewCleanupDriver(context.Context, Workspace, Env) (CleanupDriver, error)
	Content() ContentHooks
}

func Legacy

func Legacy() (Plugin, bool)

func Lookup

func Lookup(id string) (Plugin, bool)

func Plugins

func Plugins() []Plugin

type Reaction

type Reaction struct {
	Name  string
	Users []string
	Count int
}

type ReactionRenderer

type ReactionRenderer interface {
	Reactions(context.Context, Message) ([]ReactionView, error)
}

ReactionRenderer is an optional ContentHooks extension for viewers.

type ReactionView

type ReactionView struct {
	Name, Glyph, Image string
	// MatchNames are trigger names that match this reaction, supplied by the platform.
	MatchNames []string
	Count      int
}

ReactionView describes a stored reaction for display.

type RealtimeReporter

type RealtimeReporter interface {
	RealtimeStatus() (connected bool, detail string)
}

RealtimeReporter is an optional Session extension describing the live event connection. Detail is a short user-facing explanation.

type ReplyInspector

type ReplyInspector interface {
	ReplyReactions(context.Context, []RootRef, []string) ([]ReplyReaction, error)
}

ReplyInspector is an optional Session extension: it lists reactions placed on replies of the given roots so diagnostics can explain why they never match.

type ReplyReaction

type ReplyReaction struct {
	Channel, RootTS, TS, Name string
}

ReplyReaction is a reaction on a non-root message, reported by diagnostics only.

type Root

type Root struct {
	TS, ThreadTS string
	Reactions    []Reaction
	Raw          Message
}

type RootRef

type RootRef struct {
	Channel, RootTS string
	Reactions       []Reaction
	Replies         int
}

type Session

type Session interface {
	Capabilities() Capabilities
	VerifyIdentity(context.Context) (Identity, error)
	Channels(context.Context) ([]Channel, error)
	History(context.Context, string, string) ([]RootRef, error)
	Root(context.Context, string, string) (Root, error)
	Snapshot(context.Context, string, Root, *Snapshot) (Snapshot, error)
	Start(context.Context, EventSink) error
	Stop(context.Context) error
	Reconfigure(context.Context, Workspace) (bool, error)
}

type Settings

type Settings json.RawMessage

type SetupGuide

type SetupGuide interface {
	Permissions() []PermissionGroup
	HelpTopics() []HelpTopic
	HelpAssets() fs.FS
}

SetupGuide is an optional Plugin extension: a "what this connection needs" summary and "?" help for every action performed in the platform's own UI. HelpAssets holds the images HelpTopic.Image refers to; the host serves them itself, so they must be bundled with the plugin.

type SetupState

type SetupState map[string]json.RawMessage

type SetupStep

type SetupStep struct {
	ID, Title, Kind, Body string
	Links                 []Link
	Copy                  []CopyText
	Upgrade               string
	Schema                json.RawMessage
	Run                   func(context.Context, SetupState, json.RawMessage, Env) (StepResult, error)
	Prepare               func(context.Context, SetupState, Env) (StepResult, error)
	Test                  func(context.Context, SetupState, json.RawMessage, Env) (StepResult, error)
	Skip, SkipNote        string
	// Help lists HelpTopic keys shown with this step (see SetupGuide). A
	// schema property can also carry "x-help": "<key>" for a "?" by its field.
	Help []string
}

SetupStep is one wizard page. Run validates a submission. Optional hooks: Prepare runs when the page is shown (dynamic links, choices); Test runs the "Test connection" action without advancing. Skip, when set, labels an explicit fallback action that clears this step's secret fields and then calls Run. Copy lists values shown with a copy button. Upgrade, when set, labels a dashboard action that reopens this step for an existing workspace whose secret fields from this step are unset; Prepare, Test and Run then receive the workspace's settings as SetupState and its saved credentials.

type Snapshot

type Snapshot struct {
	// RawDocuments contains original transport response bytes; Prepare seals them into Documents.
	RawDocuments map[string][]byte
	// CleanupStatus summarizes the journal state for archive readers.
	CleanupStatus string `json:"cleanup_status,omitempty"`
	// SourceDeletedAt projects verified journal and persisted deletion markers.
	SourceDeletedAt map[string]string `json:"source_deleted_at,omitempty"`
	Manifest        ArchiveManifest
	Messages        []Message
	Users           map[string]Message
	// RawUsers retains optional malformed non-author metadata without rendering it.
	RawUsers  map[string]any
	Blobs     map[string]Blob
	Documents map[string][]byte
}

type StepResult

type StepResult struct {
	OK          bool
	FieldErrors map[string]string
	Messages    []string
	Data        json.RawMessage
	Choices     []Choice
	// Links and Checks are optional: Prepare may compute links from earlier
	// steps, and Test/Run may report itemized connection results.
	Links  []Link
	Checks []Check
}

type Trigger

type Trigger struct {
	Reactions []string `json:"reactions" yaml:"reactions"`
	Who       string   `json:"who" yaml:"who"`
	Owners    []string `json:"owners" yaml:"owners"`
	Match     string   `json:"match,omitempty" yaml:"match,omitempty"`
}

Trigger selects roots to archive. Match "all" (the default, kept for legacy configurations) requires every listed reaction; "any" requires at least one.

type Vault

type Vault interface {
	Get(name string) (string, error)
	Set(name, value string) error
	Delete(name string) error
	// List returns the stored names that start with prefix.
	List(prefix string) ([]string, error)
}

Vault stores secrets a plugin must keep across a restart, never in its state folder. Names match [A-Za-z0-9_]+; Get returns "" for a missing name.

type Workspace

type Workspace struct {
	Cleanup               CleanupPolicy
	ID, Platform, Storage string
	Channels              []string
	AutoChannels          bool
	Trigger               Trigger
	PollInterval          time.Duration
	Settings              Settings
	// WorkflowSteps exposes Actions() to the platform's automation tool.
	WorkflowSteps bool
	// ExportDir is where workflow steps save thread files (default: app home/exports).
	ExportDir string
}

func (Workspace) CleanupApproval

func (w Workspace) CleanupApproval() Trigger

CleanupApproval requires explicit deletion approval; archive reactions never authorize deletion.

Directories

Path Synopsis
Package plugintest checks contract-v1 manifests, schemas and lifecycle behavior.
Package plugintest checks contract-v1 manifests, schemas and lifecycle behavior.

Jump to

Keyboard shortcuts

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