plugin

package
v0.28.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: Apache-2.0 Imports: 31 Imported by: 0 modules, 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 plugin reads and checks a Cartographer plugin: a folder or git repository with a cartographer-plugin.yaml manifest at its root. This part is pure data checking: the manifest, the version ranges it speaks, the contribution-point registry and the reader of an in-memory tree, and nothing that touches disk, git or the network.

Index

Constants

View Source
const (
	// ScriptEntry is the plugin's script at the root: the one file that says what
	// the plugin registers.
	ScriptEntry = "plugin.star"
	// LibDir holds the flat *.star files plugin.star may load.
	LibDir = "lib"
	// MaxScriptBytes caps one script file; MaxLibFiles the files of lib/.
	MaxScriptBytes = 256 << 10
	MaxLibFiles    = 32
)
View Source
const (
	// MaxFiles and MaxBytes bound the stored files of one plugin.
	MaxFiles = 2000
	MaxBytes = 8 << 20
)
View Source
const ManifestFile = "cartographer-plugin.yaml"

ManifestFile is the name of the manifest at a plugin's root.

View Source
const ProvidersDir = "providers"

ProvidersDir is the contribution point holding providers/<id>.yaml: an agent client described as data, a fork or in-house build of a built-in client.

View Source
const SchemaVersion = 1

SchemaVersion is the only manifest schema this version reads.

Variables

View Source
var (
	// ErrNotFetched: no tree is stored under that name and digest.
	ErrNotFetched = errors.New("plugin: not fetched")
	// ErrModified: the stored tree no longer has the digest it is named by.
	ErrModified = errors.New("plugin: stored tree was modified")
	// ErrInvalid: the stored tree has its digest but fails ReadTree.
	ErrInvalid = errors.New("plugin: stored tree is invalid")
)

The store is a re-fetchable cache under the user's cache directory:

plugins/<name>/<digest>/   exactly the files ReadTree validated, manifest included
plugins/.tmp-<name>-<n>/   a write in progress

A digest directory is immutable: its name is the digest of what it holds, and Open recomputes it. Put and GC are writers and run under the client lock (provisioning.LockClientState), held by the caller; Open takes no lock, so a read racing a write sees either state or ErrNotFetched.

Functions

func DiffPrint

func DiffPrint(w io.Writer, name string, d Delta)

DiffPrint writes d in plain words. A permission added is flagged with "!!" and listed first: it is the line the consent turns on. Every plugin-supplied string goes through esc.

func ExpandAnchor

func ExpandAnchor(env ProviderEnv, name string) (string, error)

ExpandAnchor returns the directory an anchor name ("home", "xdg_config", "app_data", "local_app_data", "documents") stands for, cleaned and in slash form. It lies inside the home directory or the call is an error; the part of the path below it is the caller's to validate.

func GlobMatch

func GlobMatch(glob, p string) bool

GlobMatch reports whether p, a path in the placeholder form ("{home}/notes/a.md"), matches glob, a manifest file glob. The dialect: the path is split on "/"; a segment of the glob is matched as path.Match does (* ? [..] within one segment, never across a "/"), and a segment that is exactly ** matches zero or more whole segments. Both are compared as written: the anchor is part of the first segment.

func IsLibPath

func IsLibPath(path string) bool

IsLibPath reports a path that names a loadable lib file.

func IsScriptPath

func IsScriptPath(path string) bool

IsScriptPath reports a path the tree reader treats as script territory: plugin.star itself or anything under lib/ (or a path that starts like them).

func Preview

func Preview(w io.Writer, p Plugin, in PreviewInfo, opts Options)

Preview prints what installing p would do, in plain words: every plugin-supplied string goes through esc, and each point prints its own contributions. The printed block is the record of what the user consented to.

func ProviderNameClashes

func ProviderNameClashes(specs []ProviderSpec) []string

ProviderNameClashes lists the providers of one plugin that share a name.

func RangeMet

func RangeMet(rng, running string) (bool, error)

RangeMet reports whether the running Cartographer version satisfies rng. A running version that does not parse (a "dev" build) satisfies every range, and a pre-release or `git describe` build compares as its X.Y.Z core. A malformed range is an error.

func RangeMetOK

func RangeMetOK(rng, v string) bool

RangeMetOK is RangeMet with a malformed range counting as not met.

func Register

func Register(p Point)

Register adds a point. A duplicate or invalid Dir is an init-time programmer error and panics.

func State

func State(name string, e clientconfig.PluginEntry, s Store, opts Options) (Status, *Plugin)

State is the one rule that decides whether a plugin runs: every consumer calls it and nothing else. A plugin is active only when it is enabled, the user approved a digest, and the stored tree of that digest is intact and still valid (for example the running version still satisfies its `cartographer` range). Only an active plugin yields a *Plugin. A newer Installed digest never affects it: the approved tree is what runs.

func ToolName

func ToolName(plugin, tool string) string

ToolName is the name a plugin's tool is served and called by: <plugin>_<tool> with hyphens turned into underscores (a client's tool names are identifiers). The bridge, the approval-time `tools` hint, `plugin validate` and the approval preview all use this one function, so the name a user reads is the name `cartographer call` takes.

func ValidRange

func ValidRange(rng string) error

ValidRange reports why rng is not a version range, or nil.

Types

type Contribution

type Contribution struct {
	Point string // the point's Dir
	Kind  string // artifact kind: skill, agent, hook
	Name  string
	// Files are the artifact's files, paths relative to the artifact.
	Files []provisioning.ArtifactFile
	// Executable lists the paths (relative to the artifact) of every file with
	// the executable bit, for the install preview.
	Executable []string
	// Description is the frontmatter description of a skill or agent: what the
	// agent reads to decide to use it, so the install preview shows it.
	Description string
	// Command, Event and Requires are what a hook declares in hook.json.
	Command, Event string
	Requires       []string
	// Provider is the parsed descriptor of a providers/<id>.yaml; nil for every
	// other kind. A provider is registered with the registries, never installed
	// as an artifact.
	Provider *ProviderSpec
}

Contribution is what one folder entry of a point contributes: one skill, one agent, one hook.

type Delta

type Delta struct {
	Added, Removed []string
	Changed        []FileChange
	// OldVersion and NewVersion are the manifest versions.
	OldVersion, NewVersion string
	// OldDigest and NewDigest are the tree digests; DiffPrint shows 12 hex of each
	// when the versions are equal, so an edit without a bump is visible.
	OldDigest, NewDigest string
	// CartographerFrom and CartographerTo are the `cartographer` ranges, equal when unchanged.
	CartographerFrom, CartographerTo string
	// DependsAdded and DependsRemoved are "name range" lines; a changed range is one of each.
	DependsAdded, DependsRemoved []string
	// PermissionsAdded and PermissionsRemoved are one human line each.
	PermissionsAdded, PermissionsRemoved []string
	// PathsAdded and PathsRemoved are the provider destinations resolved on this machine.
	PathsAdded, PathsRemoved []string
}

Delta is what an update changes against the approved tree: the text the user reads before consenting. Everything in it is plugin-supplied, so DiffPrint escapes it.

func Diff

func Diff(old, next Plugin, env ProviderEnv) Delta

Diff compares an approved tree with a newer one, resolving provider destinations against env (the machine's home).

func (Delta) Empty

func (d Delta) Empty() bool

Empty reports whether nothing the user would read differs.

type FileChange

type FileChange struct {
	Path             string
	OldSize, NewSize int
	// Mode is true when only the executable bit changed.
	Mode bool
}

FileChange is one file that differs between two trees.

type Files

type Files struct {
	Read  []string `yaml:"read"`
	Write []string `yaml:"write"`
}

Files holds the path globs a plugin asks to read and to write.

type Keep

type Keep struct{ Installed, Approved string }

Keep is what GC preserves for one configured plugin.

type Manifest

type Manifest struct {
	Schema       *int               `yaml:"schema"`
	Name         string             `yaml:"name"`
	Version      string             `yaml:"version"`
	DisplayName  string             `yaml:"display_name"`
	Description  string             `yaml:"description"`
	Cartographer string             `yaml:"cartographer"`
	Depends      map[string]string  `yaml:"depends"`
	Permissions  *Permissions       `yaml:"permissions"`
	Settings     map[string]Setting `yaml:"settings"`
}

Manifest is cartographer-plugin.yaml, schema 1.

func ParseManifest

func ParseManifest(data []byte, opts Options) (Manifest, []string)

ParseManifest reads and checks manifest bytes. The returned problems are every problem it can read (a YAML type error stops the semantic checks, which then run on the next call), each "path: reason" and sorted, except that an unmet `cartographer` range is checked before anything else and is then the only one.

type Options

type Options struct {
	// RunningVersion is the version of this binary, for the `cartographer` range.
	RunningVersion string
	// ReservedName reports a built-in command name a plugin must not take;
	// nil reserves none.
	ReservedName func(string) bool
	// CheckScripts loads the script files of a tree (plugin.star and lib/) and
	// returns why they do not, one problem each; nil checks nothing. It is a hook
	// because the Starlark runtime lives in internal/plugin/star, which imports
	// this package.
	CheckScripts func(files []TreeFile) []string
}

Options carries what the manifest check needs from its caller, so this package imports neither cmd nor the running binary's version.

type Permissions

type Permissions struct {
	KB    string   `yaml:"kb"`
	Net   []string `yaml:"net"`
	Files *Files   `yaml:"files"`
	Env   []string `yaml:"env"`
}

Permissions is what a plugin asks for. Here it is validated as data; nothing in this package enforces or grants it.

type Plugin

type Plugin struct {
	Manifest      Manifest
	Contributions map[string][]Contribution // by point Dir
	Artifacts     []provisioning.Artifact
	Files         []TreeFile // every stored file, manifest included, sorted by path
	Digest        string     // identifies the validated tree
}

Plugin is a validated plugin tree.

func ReadTree

func ReadTree(files []TreeFile, opts Options) (Plugin, []string)

ReadTree validates a plugin tree and returns every problem it finds, sorted. The result does not depend on the order of files.

func (Plugin) Providers

func (p Plugin) Providers(env ProviderEnv) []ResolvedProvider

Providers returns the providers of p resolved for env, in name order, with the reasons paths were left out kept in each one's LeftOut.

type Point

type Point struct {
	Dir  string // top-level folder name
	Side Side
	// Load validates the files under Dir (paths are tree-relative, so they start
	// with Dir+"/") and returns the contributions with every problem found.
	Load func(files []TreeFile) ([]Contribution, []string)
	// Preview prints what the install preview shows for one contribution.
	Preview func(w io.Writer, c Contribution)
	// Executable marks a point whose files run (hooks).
	Executable bool
}

Point is a place of the plugin tree that contributes something.

func RegisteredPoints

func RegisteredPoints() []Point

RegisteredPoints returns the points sorted by Dir.

type PreviewInfo

type PreviewInfo struct {
	Source, Ref, SHA string
	// Have reports the version of a configured plugin, for `depends`.
	Have func(name string) (string, bool)
}

PreviewInfo is what a preview needs besides the tree: where it came from and what the machine already has. Source must already be redacted by the caller.

type ProviderCell

type ProviderCell struct {
	Dir, File   []string // skill, agent and hook directory; instructions file
	AgentFormat string   // agent only; the file suffix follows from it
}

ProviderCell is one destination of a provider: a path relative to the home directory (global) or to a project root (project). No write cell lies under {documents}: only a detect dir takes that anchor.

type ProviderEnv

type ProviderEnv struct {
	GOOS, Home string
	Getenv     func(string) string
	// Documents answers the Documents folder of home; nil is
	// safewrite.DocumentsDir, the resolver Cline's hooks and rules use.
	Documents func(home string) string
}

ProviderEnv is what ResolveProvider reads from the machine; tests inject it.

func DefaultProviderEnv

func DefaultProviderEnv() ProviderEnv

DefaultProviderEnv is the machine ResolveProvider reads at run time.

type ProviderScope

type ProviderScope struct{ Skill, Agent, Instructions, Hook *ProviderCell }

ProviderScope is the cells of one scope. Hook is global only.

type ProviderSpec

type ProviderSpec struct {
	Schema      int    `yaml:"schema"`
	Name        string `yaml:"name"`
	DisplayName string `yaml:"display_name"`
	Base        string `yaml:"base"`
	Detect      struct {
		Binaries []string          `yaml:"binaries"`
		Dirs     osValue[[]string] `yaml:"dirs"`
	} `yaml:"detect"`
	Paths struct {
		Global  globalCells  `yaml:"global"`
		Project projectCells `yaml:"project"`
	} `yaml:"paths"`
	Capabilities map[string]string `yaml:"capabilities"`
	MCP          struct {
		Mode   string            `yaml:"mode"`
		Config osValue[string]   `yaml:"config"`
		Stale  osValue[[]string] `yaml:"stale"`
	} `yaml:"mcp"`
	InvokeHint string `yaml:"invoke_hint"`
}

ProviderSpec is a providers/<id>.yaml as written. It is built only by ParseProvider.

func ParseProvider

func ParseProvider(stem string, data []byte) (ProviderSpec, []string)

ParseProvider reads providers/<stem>.yaml: strict (size cap, no alias, one document, unknown key = error) and complete, every problem listed as "path: reason", sorted.

type ResolvedProvider

type ResolvedProvider struct {
	Name, DisplayName, Base string
	Binaries                []string
	DetectDirs              [][]string // home-relative; one segment may hold *
	Global, Project         ProviderScope
	MCPMode                 string
	MCPConfig               []string   // home-relative; nil keeps the base's file; one segment may hold *
	MCPStale                [][]string // home-relative
	Capabilities            map[string]string
	InvokeHint              string
	// LeftOut is the reasons ResolveProvider dropped paths, one per path: a
	// cell behind a link, a path outside its root. The caller says them; a
	// provider that lost a cell resolves all the same.
	LeftOut []string
}

ResolvedProvider is a providers/<id>.yaml resolved for one OS. Data only.

func ResolveProvider

func ResolveProvider(spec ProviderSpec, env ProviderEnv) (ResolvedProvider, []string)

ResolveProvider picks the per-OS values of spec, expands the anchors against env and returns the provider with the reasons paths were left out. A path outside its root, or one the walk from the root finds behind a link, is dropped with a reason, never an error, so the rest still resolves. Home-family anchors must stay inside the home directory (safewrite.CheckPath(home, path), the check the hook writers run); {documents} is read by detect dirs only, and counts when the Documents folder lies below home.

func (ResolvedProvider) Cells

Cells is what provisioning reads of the provider: its destination cells, the agent layout, the capability row and the invoke hint. active is the state of the plugin: an inactive provider's cells stay resolvable (what it installed is retired through them) but its hook directory leaves the dispatcher. The MCP file is a cell only when it is the provider's own literal file: the base's file is the base's, and a pattern is written by the registry's own expansion (configurator.Apply), never as a destination of the KB's MCP descriptors.

func (ResolvedProvider) Paths

func (r ResolvedProvider) Paths(home string) []string

Paths lists every path the provider resolved to on this machine, one "scope kind: path" line per cell, sorted: the global ones absolute, the project ones relative to a project root. It is what the install preview prints: the approval is of the tree, and these are the places it would write.

func (ResolvedProvider) Registration

func (r ResolvedProvider) Registration(origin string, active bool) configurator.PluginSpec

Registration is the registry entry of the provider, declared by plugin origin. An active provider is detected; an inactive one stays resolvable so what it installed can be retired.

type Setting

type Setting struct {
	Type        string `yaml:"type"`
	Default     any    `yaml:"default"`
	Description string `yaml:"description"`
}

Setting declares one user-settable value of the plugin.

type Side

type Side string

Side is where a contribution point is loaded.

const (
	// SideClient points are loaded by the client of the machine.
	SideClient Side = "client"
	// SideServer is declared and never loaded: a server does not run plugins.
	SideServer Side = "server"
)

type Source

type Source struct {
	Git    bool
	Remote string // git: the remote as typed, without the @ref
	Ref    string // git: branch, tag or full sha; empty means HEAD
	Path   string // folder: absolute, symlinks resolved
}

Source is where a plugin comes from: a git remote at a ref, or a folder.

func ParseSource

func ParseSource(s string) (Source, error)

ParseSource reads a source typed by the user (os.Args or their config, never a KB or a plugin). An existing directory is a folder, whatever it is called. Otherwise it is a git source: a URL with a scheme git accepts or an scp-like remote (host:path), optionally followed by @<ref>. The ref is split at the LAST @, and only when it lies after the URL's host (or the ':' of an scp-like remote) and the text after it holds neither ':' nor '/', so https://user@host and git@host:team/x.git stay whole and git@host:team/x.git@v1 has ref v1.

func (Source) String

func (s Source) String() string

String is the form recorded in the user's file.

type Status

type Status string

Status is where an installed plugin stands.

const (
	StatusActive     Status = "active"
	StatusPending    Status = "pending approval"
	StatusDisabled   Status = "disabled"
	StatusNotFetched Status = "not fetched"
	StatusModified   Status = "modified"
	StatusInvalid    Status = "invalid"
)

type Store

type Store struct{ Root string }

Store is the plugin cache rooted at Root.

func DefaultStore

func DefaultStore() (Store, error)

DefaultStore is <cache dir>/plugins, the cache dir being the update check's.

func (Store) GC

func (s Store) GC(keep map[string]Keep) error

GC removes every digest directory but the two of a configured plugin, and every plugin directory that is not configured. It is best effort: a failure is reported and the rest goes on. It never removes the approved tree, and it leaves alone a name that is not a valid plugin name. The caller holds the client lock.

func (Store) Open

func (s Store) Open(name, digest string, opts Options) (Plugin, error)

Open reads the stored tree back through ReadTree and compares its digest.

func (Store) Put

func (s Store) Put(name string, files []TreeFile, want string, opts Options) error

Put stores files under name after validating them: ReadTree must report no problem and the digest must be want. The tree is written to a temp directory, read back through ReadTree, checked against want again (the bytes validated are the bytes stored) and renamed into place, never over a directory that exists. An existing digest directory that verifies is kept; one that does not is a corrupt cache and is replaced. The caller holds the client lock.

type TreeFile

type TreeFile struct {
	Path       string // canonical slash form, relative to the plugin root
	Content    []byte
	Executable bool
	// Special marks a symlink or any non-regular file: always an error.
	Special bool
}

TreeFile is a file of a plugin tree in memory: what an acquisition produces and the store reads back.

func Fetch

func Fetch(ctx context.Context, s Source, tmpParent string) ([]TreeFile, string, error)

Fetch brings the files of the source into memory; nothing is stored. tmpParent holds the throwaway repository of a git fetch. A git source also returns the resolved 40-hex commit; a folder is a snapshot and returns "".

Directories

Path Synopsis
Package star runs the Starlark script of a plugin: plugin.star at the root and the lib/*.star files it loads.
Package star runs the Starlark script of a plugin: plugin.star at the root and the lib/*.star files it loads.

Jump to

Keyboard shortcuts

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