piglet

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 43 Imported by: 0

Documentation

Overview

Package piglet provides piglet-based capability scoping for pig sessions.

D18: Stock Pig's generic `pig piglet` command and in-session capability scoping.

The package has two entry points:

  • RunCommand: pre-session CLI (pig piglet list|show|validate|schema|add|remove)
  • BuildExtension: in-session runtime scoping via extension.Extension

The extension reads a piglet YAML (from --piglet flag, PIG_PIGLET_PATH env, PIG_PIGLET_NAME env, or search paths), parses per-source tool scoping rules, and calls SetActiveTools to filter the tool set before the first agent turn.

Piglet is used by:

  • managed runtimes (mounted YAML through PIG_PIGLET_PATH)
  • local Pig invocations (--piglet flag or ~/.pig/piglets/<name>.yaml)

Piglet YAML schema types and parser.

A piglet is the complete agent definition: extensions with per-source capability scoping, MCP servers, skills, prompts, model config. The same YAML format is used locally (~/.pig/piglets/), on platform (ConfigMap from Agent CRD spec.piglet), and in independently published Piglet source.

Piglet is the agent-author scoping mechanism. A hosting platform may apply an additional administrative policy ceiling without rewriting the Piglet.

Index

Constants

View Source
const MCPAdapterExtensionName = "pig-mcp-adapter"

MCPAdapterExtensionName is the conventional owner of MCP tools.

View Source
const MCPSourcePrefix = "mcp:"

MCPSourcePrefix identifies tools registered by an MCP adapter for one server.

Variables

This section is empty.

Functions

func ActiveAgentEnvironmentIdentity

func ActiveAgentEnvironmentIdentity() string

ActiveAgentEnvironmentIdentity returns the already-verified active environment identity injected into the inner process, or empty for host execution. It never reads secret values.

func BuildExtensionWithPiglet

func BuildExtensionWithPiglet(initial *Piglet) extension.Extension

BuildExtensionWithPiglet returns an extension.Extension that applies Piglet-based tool scoping at runtime. The caller supplies the Piglet selected before extension loading. The extension applies tool scope on session_start and before_agent_start events. If the Piglet declares a systemPrompt, the extension returns it from before_agent_start so Pig core uses it as the session system prompt.

The returned Extension registers read-only /piglet inspection. Piglet selection/editing is deliberately not available in-session: a different composition is selected by a separate Pig invocation.

func BuildExtensionWithPigletTools

func BuildExtensionWithPigletTools(initial *Piglet, owner func(extension.ToolInfo) string) extension.Extension

BuildExtensionWithPigletTools is BuildExtensionWithPiglet with the owner of extension-registered tools: owner names the Piglet extension entry whose `tools` allowlist scopes a tool, or "" when no loaded extension registered it.

func DistributionOffline

func DistributionOffline() bool

DistributionOffline reports whether PI_OFFLINE or PIG_OFFLINE forbids the network access that remote Piglet distribution commands need.

func Resolve

func Resolve(nameOrPath string) (string, error)

Resolve finds a piglet by name, checking the resolution order:

  1. Explicit path (already absolute or relative)
  2. PIG_PIGLET_PATH env var
  3. PIG_PIGLET_NAME env var → search paths
  4. Workspace: .pig/piglets/<name>.yaml
  5. User: ~/.pig/piglets/<name>.yaml
  6. System: /etc/pig/piglets/<name>.yaml

func RunCommand

func RunCommand(args []string, stdout, stderr io.Writer) int

RunCommand handles `pig piglet <subcommand>`. Returns -1 if args do not match, 0 on success, and 1+ on error.

func SchemaJSON

func SchemaJSON() []byte

SchemaJSON returns the published Piglet JSON Schema v1 bytes.

func ScopeTools

func ScopeTools(piglet *Piglet, allTools []ToolInfo) []string

ScopeTools intersects registered tools with root and extension allowlists. Resource loading/discovery decides which extensions exist; this function does not use Piglet membership as a second discovery gate.

func ValidateAgainstSchema

func ValidateAgainstSchema(yamlBytes []byte) error

ValidateAgainstSchema checks Piglet YAML against the published JSON Schema closed vocabulary. It is the schema half of the schema/parser agreement; Go parsing (ParseBytes) adds the semantic checks the vocabulary schema cannot express.

func ValidateRemoteSource

func ValidateRemoteSource(raw string) error

ValidateRemoteSource checks that raw is an npm or Git source reference that carries no authentication material, so it can be published. Rejected references and parser diagnostics never enter its errors.

Types

type AgentEnvironment

type AgentEnvironment struct {
	Image        string                  `yaml:"image,omitempty"`
	DevContainer string                  `yaml:"devContainer,omitempty"`
	Source       string                  `yaml:"source,omitempty"`
	PigRuntime   *AgentPigRuntime        `yaml:"pigRuntime,omitempty"`
	Policy       *AgentEnvironmentPolicy `yaml:"policy,omitempty"`
	Workspace    *AgentWorkspace         `yaml:"workspace,omitempty"`
	Mounts       []AgentMount            `yaml:"mounts,omitempty"`
	Secrets      []AgentSecretBinding    `yaml:"secrets,omitempty"`
}

AgentEnvironment is a required whole-agent runtime when present. Exactly one source form is set; runtime and policy defaults are projected without rewriting the authored Piglet.

type AgentEnvironmentPolicy

type AgentEnvironmentPolicy struct {
	Preset string `yaml:"preset,omitempty"`
}

type AgentEnvironmentRuntimeOptions

type AgentEnvironmentRuntimeOptions struct {
	Engine     string
	Workspace  string
	Args       []string
	PigVersion string
	StateRoot  string
	UnsafeHost bool
	Commands   runtimeCommands
	IO         RuntimeIO
}

AgentEnvironmentRuntimeOptions are machine-local execution inputs. They are never serialized into a Piglet or included in its portable identity.

type AgentEnvironmentRuntimeResult

type AgentEnvironmentRuntimeResult struct {
	Continue bool
	Bypassed bool
	ExitCode int
}

AgentEnvironmentRuntimeResult tells the caller whether startup should continue in the current process or terminate with the child engine's status.

func RunAgentEnvironment

RunAgentEnvironment enters a supported required Piglet environment before model, session, extension, or tool initialization. The current slice supports direct-image Piglets in explicit image-runtime mode with standard policy. Every other environment form remains fail-closed.

type AgentMount

type AgentMount struct {
	Source   string `yaml:"source"`
	Target   string `yaml:"target"`
	ReadOnly bool   `yaml:"readonly,omitempty"`
}

AgentMount is one additional host bind exposed to the environment. Extra mounts are an elevated-policy capability because each one widens the host surface the agent can read or write.

func (*AgentMount) UnmarshalYAML

func (m *AgentMount) UnmarshalYAML(node *yaml.Node) error

type AgentPigRuntime

type AgentPigRuntime struct {
	Mode    string `yaml:"mode,omitempty"`
	Version string `yaml:"version,omitempty"`
}

type AgentSecretBinding

type AgentSecretBinding struct {
	SecretRef string            `yaml:"secretRef"`
	Target    AgentSecretTarget `yaml:"target"`
}

AgentSecretBinding maps one logical secret to a child environment target.

type AgentSecretTarget

type AgentSecretTarget struct {
	Env string `yaml:"env,omitempty"`
}

AgentSecretTarget currently supports child environment injection. File targets wait for the environment runtime materialization slice.

type AgentWorkspace

type AgentWorkspace struct {
	Folder   string `yaml:"folder,omitempty"`   // container path; default image WorkingDir then /workspace
	ReadOnly *bool  `yaml:"readonly,omitempty"` // nil = policy default (minimal read-only, else read-write)
}

AgentWorkspace selects where the invocation workspace lands inside the environment. The host source stays a machine-local execution input (default the current directory), so it is intentionally not a Piglet field.

func (*AgentWorkspace) UnmarshalYAML

func (w *AgentWorkspace) UnmarshalYAML(node *yaml.Node) error

type BuildSpec

type BuildSpec struct {
	Targets              []string `yaml:"targets,omitempty"`
	OutputName           string   `yaml:"outputName,omitempty"`
	ExtensionRealization string   `yaml:"extensionRealization,omitempty"`
}

BuildSpec defines portable build defaults. Builder selection and verification policy remain execution inputs and are intentionally not serialized here. pig additive (D18): Piglets own Pig's additive artifact build defaults. BuildSpec carries portable build defaults only. Delivery tier, strictness, update endpoint, release version, builder, credentials, and verification are execution or publication inputs, not portable Piglet source.

type Discovery

type Discovery struct {
	Extensions []string `yaml:"extensions,omitempty"`
	Skills     []string `yaml:"skills,omitempty"`
}

Discovery selects ambient Resource scopes by kind. Explicit Piglet entries are independent of discovery. Nil and empty lists both mean no ambient Resources in an active Piglet.

type EffectiveResolution

type EffectiveResolution struct {
	Piglet          *Piglet        `json:"-"`
	Lineage         []LineageEntry `json:"lineage"`
	SourceDigest    string         `json:"sourceDigest"`
	EffectiveDigest string         `json:"effectiveDigest"`
	GraphDigest     string         `json:"graphDigest"`
}

EffectiveResolution is a source Piglet resolved through its exact base lineage. Piglet contains no release/build/extends/remove metadata.

func ResolveEffective

func ResolveEffective(path string) (*EffectiveResolution, error)

ResolveEffective resolves with no workspace anchor. Piglets that require a workspace:-anchored field fail until the caller supplies one explicitly.

func ResolveEffectiveWithOptions

func ResolveEffectiveWithOptions(path string, options ResolveOptions) (*EffectiveResolution, error)

ResolveEffectiveWithOptions resolves path's typed extends lineage and deterministic merge algebra. Each source's Piglet-owned local paths are anchored before merge, so inherited resources are never re-anchored to a child directory.

pig additive (D18): additive Piglet derivation and exact lineage.

type ExtendsSpec

type ExtendsSpec struct {
	Source     string      `yaml:"source"`
	Version    string      `yaml:"version,omitempty"`
	AllowWiden bool        `yaml:"allowWiden,omitempty"`
	Remove     *RemoveSpec `yaml:"remove,omitempty"`
}

ExtendsSpec selects one base Piglet source plus an optional author version constraint. Resolution pins the exact content digest in lineage.

type ExtensionEntry

type ExtensionEntry struct {
	Name    string    `yaml:"name"`
	Origins []string  `yaml:"origins,omitempty"`
	Tools   *[]string `yaml:"tools,omitempty"`
}

ExtensionEntry selects one extension and optionally limits its model tools. A nil Tools pointer means every registered tool; a non-nil empty slice means none.

func (*ExtensionEntry) UnmarshalYAML

func (e *ExtensionEntry) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML handles the bare extension-name shorthand.

type LineageEntry

type LineageEntry struct {
	Source  string `json:"source"`
	Version string `json:"version,omitempty"`
	Digest  string `json:"digest"`
}

LineageEntry pins one source in an effective Piglet's inheritance chain.

type ModelConfig

type ModelConfig struct {
	Provider      string `yaml:"provider,omitempty"`
	Name          string `yaml:"name,omitempty"`
	ContextWindow int    `yaml:"contextWindow,omitempty"`
	Thinking      string `yaml:"thinking,omitempty"`
}

ModelConfig specifies the model to use.

type Piglet

type Piglet struct {
	Name         string              `yaml:"name"`
	Description  string              `yaml:"description,omitempty"`
	Extends      *ExtendsSpec        `yaml:"extends,omitempty"`
	BuiltinTools *[]string           `yaml:"tools,omitempty"`
	Packages     map[string]string   `yaml:"packages,omitempty"`
	Extensions   []ExtensionEntry    `yaml:"extensions,omitempty"`
	Skills       []SkillEntry        `yaml:"skills,omitempty"`
	Discovery    *Discovery          `yaml:"discovery,omitempty"`
	SystemPrompt *PromptRef          `yaml:"systemPrompt,omitempty"`
	AgentEnv     *AgentEnvironment   `yaml:"agentEnv,omitempty"`
	Model        *ModelConfig        `yaml:"model,omitempty"`
	Build        *BuildSpec          `yaml:"build,omitempty"`
	Release      *ReleaseSpec        `yaml:"release,omitempty"`
	Secrets      []SecretDeclaration `yaml:"secrets,omitempty"`
	// contains filtered or unexported fields
}

Piglet is the top-level piglet YAML structure.

func Clone

func Clone(p *Piglet) *Piglet

Clone returns an independent Piglet value while preserving its resolved source anchors. Runtime caches and locks are intentionally reset.

func Parse

func Parse(path string) (*Piglet, error)

Parse reads and validates a piglet YAML file.

func ParseBytes

func ParseBytes(data []byte) (*Piglet, error)

ParseBytes parses and validates piglet YAML from bytes. Unknown keys are rejected to catch typos and unsupported fields early.

func (*Piglet) EffectiveAgentEnvironment

func (p *Piglet) EffectiveAgentEnvironment() *AgentEnvironment

EffectiveAgentEnvironment applies semantic defaults without mutating source.

func (*Piglet) ResolutionIdentity

func (p *Piglet) ResolutionIdentity() ([]LineageEntry, string, string)

ResolutionIdentity returns copies of the exact lineage and effective/graph digests attached by ResolveEffective. Source-only Piglets return zero values.

func (*Piglet) SourcePath

func (p *Piglet) SourcePath() string

SourcePath returns the parsed Piglet source path when available.

func (*Piglet) Validate

func (p *Piglet) Validate() error

Validate checks the piglet for schema violations.

func (*Piglet) ValidateAgentEnvironmentLaunch

func (p *Piglet) ValidateAgentEnvironmentLaunch() error

ValidateAgentEnvironmentLaunch reports whether the current runtime slice can launch this Piglet without inspecting machine-local engine availability.

func (*Piglet) ValidateAgentEnvironmentRuntime

func (p *Piglet) ValidateAgentEnvironmentRuntime() error

ValidateAgentEnvironmentRuntime blocks a Piglet Binary build until the builder can preserve and execute the required whole-process environment. Launch support is checked separately because runtime slices can land before portable Binary/Image execution.

type PigletInfo

type PigletInfo struct {
	Name        string
	Description string
	Path        string
	Location    string // "workspace", "user", "system", or "binary"
	Records     []RecordInfo
}

PigletInfo describes discovered Piglet source and Binary facets.

func List

func List() ([]PigletInfo, error)

List returns all discoverable Piglet rows, merging source and managed Piglet Binary records. Malformed state is an error. pig additive (D41): Piglet inventory includes Piglet Binary facets.

type PromptRef

type PromptRef struct {
	File string `yaml:"file,omitempty"`
	Text string `yaml:"text,omitempty"`
}

PromptRef is either a file path or inline text.

type RecordComponent

type RecordComponent struct {
	Kind            string
	Name            string
	Realization     string
	Materialization string
}

RecordComponent is one executable component's realization and materialization as recorded in a managed Piglet resolution record's component plan.

type RecordInfo

type RecordInfo struct {
	Path                string
	ResolutionPath      string
	ArtifactPath        string
	PigletDigest        string
	ReleaseVersion      string
	Target              string
	ArtifactDigest      string
	VerificationOK      bool
	ComponentPlanDigest string
	ResolutionDigest    string
	BinaryDigest        string
	CurrentPath         string
	Components          []RecordComponent
}

RecordInfo describes one managed Piglet Binary record/artifact facet.

type ReleaseSpec

type ReleaseSpec struct {
	Version string `yaml:"version,omitempty"`
}

ReleaseSpec carries Piglet release identity, separate from portable build defaults. release.version is the distributed artifact's SemVer.

type RemoveSpec

type RemoveSpec struct {
	Packages   []string `yaml:"packages,omitempty"`
	Extensions []string `yaml:"extensions,omitempty"`
	Skills     []string `yaml:"skills,omitempty"`
}

RemoveSpec names inherited collection members removed before child replacement/addition.

type ResolveOptions

type ResolveOptions struct {
	Workspace string
}

ResolveOptions supplies machine-local anchors that are not portable Piglet identity.

type ResolvedAgentEnvironment

type ResolvedAgentEnvironment struct {
	Form  string
	Value string
}

ResolvedAgentEnvironment identifies the concrete image or Dev Container selected by a Piglet environment source.

func ResolveAgentEnvironment

func ResolveAgentEnvironment(p *Piglet) (*ResolvedAgentEnvironment, error)

ResolveAgentEnvironment validates and materializes the optional environment. It does not start an engine or execute lifecycle commands.

type ResolvedExtension

type ResolvedExtension struct {
	Entry  ExtensionEntry
	Path   string // Resolved filesystem path
	Origin string // The first typed origin that resolved successfully.
}

ResolvedExtension is an extension with its origin resolved to a concrete path.

func ResolveExtensions

func ResolveExtensions(p *Piglet) ([]ResolvedExtension, []error)

ResolveExtensions resolves all extension origins to concrete filesystem paths. pig additive (D18): Package and typed-source origins use the generic side-effect-free install materializer before member selection. Returns resolved extensions and any errors for unresolvable entries.

type ResolvedPackage

type ResolvedPackage struct {
	Alias  string
	Source string
	Root   string
}

func ResolvePackages

func ResolvePackages(p *Piglet) ([]ResolvedPackage, error)

ResolvePackages materializes every declared Package without mutating Package settings and returns its canonical root for lock/record construction.

type ResolvedSecrets

type ResolvedSecrets struct {
	// contains filtered or unexported fields
}

ResolvedSecrets contains transient secret values for immediate consumers. It must never be serialized, logged, placed in records/sessions, or returned by inspection APIs.

func ResolveRequiredSecrets

func ResolveRequiredSecrets(ctx context.Context, p *Piglet) (*ResolvedSecrets, error)

ResolveRequiredSecrets resolves every logical secret consumed by the agent environment. Unused declarations remain inspectable without requiring machine-local availability.

func (*ResolvedSecrets) AgentEnvironment

func (r *ResolvedSecrets) AgentEnvironment(p *Piglet) (map[string]string, error)

AgentEnvironment returns child environment variables for declared bindings. Values are copied so callers may zero their map without mutating the resolver.

func (*ResolvedSecrets) Clear

func (r *ResolvedSecrets) Clear()

Clear overwrites transient values and drops references after immediate use.

func (*ResolvedSecrets) RuntimeEnvironment

func (r *ResolvedSecrets) RuntimeEnvironment() (map[string]string, error)

RuntimeEnvironment carries resolved logical values into a verified inner Pig process without exposing values on argv. Keys reveal no logical names.

type ResolvedSkill

type ResolvedSkill struct {
	Entry  SkillEntry
	Path   string // Resolved filesystem path
	Origin string // The first typed origin that resolved successfully.
}

ResolvedSkill is a skill with its origin resolved to a concrete path.

func ResolveSkills

func ResolveSkills(p *Piglet) ([]ResolvedSkill, []error)

ResolveSkills resolves all skill origins to concrete filesystem paths.

type RuntimeIO

type RuntimeIO struct {
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
	TTY    bool
}

RuntimeIO supplies the streams inherited by the container engine.

type SecretDeclaration

type SecretDeclaration struct {
	Name string       `yaml:"name"`
	From SecretSource `yaml:"from"`
}

SecretDeclaration declares a logical secret name and exactly one machine- local source. Values never enter portable Piglet state.

type SecretSource

type SecretSource struct {
	Env  string `yaml:"env,omitempty"`
	File string `yaml:"file,omitempty"`
	Ref  string `yaml:"ref,omitempty"`
}

SecretSource is the closed env|file|ref source union.

type SkillEntry

type SkillEntry struct {
	Name        string   `yaml:"name"`
	Origins     []string `yaml:"origins,omitempty"` // Required unless Content is embedded.
	Description string   `yaml:"description,omitempty"`
	Content     string   `yaml:"content,omitempty"`
}

SkillEntry represents a skill with an origin.

func (*SkillEntry) UnmarshalYAML

func (s *SkillEntry) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML handles the bare skill-name shorthand.

type ToolInfo

type ToolInfo struct {
	Name   string
	Source string
}

ToolInfo is the minimal metadata needed for Piglet tool scoping.

Directories

Path Synopsis
Package artifact defines executable Piglet component plans and artifact records.
Package artifact defines executable Piglet component plans and artifact records.
Package release verifies and installs signed Piglet Binary releases.
Package release verifies and installs signed Piglet Binary releases.
Package signature signs and verifies Piglet Binaries.
Package signature signs and verifies Piglet Binaries.

Jump to

Keyboard shortcuts

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