peen

package
v0.47.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 38 Imported by: 0

README

Embedding Peen

pkg/peen runs the durable agent engine inside a Go process. A Runtime owns SQLite, in-process workflow workers, jobs, child agents, event delivery and harness resolution. A Session addresses one conversation. The engine starts no HTTP listener or Servicepack services and reads no PEEN_ environment variables.

examples/embedding is a complete program that runs one turn against any OpenAI-compatible endpoint.

The embedding guide covers sessions, replay, subscriptions, custom tools, hooks, and filesystems. The option mapping lists the deployment equivalent of each option.

Documentation

Overview

Package peen embeds the durable agent engine inside a Go process.

Construct a Runtime with explicit Options, use Session handles to send, replay and control work, and call Close to release owned storage, jobs and child agents. Legacy Runtime methods address the initial workspace session.

Tools, hooks, models, harness layers, command execution and workspace filesystems can be supplied by the caller. SQLite and hook state remain separate from trusted harness configuration, with an in-memory option for ephemeral work. Live subscriptions include wake and child turns.

New starts no HTTP listener or Servicepack services and reads no PEEN_ environment settings. Public records belong to this package. See README.md and example_test.go for construction, extension and filesystem examples.

Index

Examples

Constants

View Source
const DefaultRootAgent = harness.CorePrefix + "general-purpose"

DefaultRootAgent is the agent an empty Options.RootAgent selects, Peen's core general-purpose agent.

View Source
const NoRootAgent = harness.NoRootAgent

NoRootAgent, as Options.RootAgent, runs the root with no agent instructions and every tool. No agent file can have this name.

Variables

View Source
var ErrClosed = commerr.ErrClosed

ErrClosed reports a call admitted after runtime shutdown began.

Functions

This section is empty.

Types

type AgentLimits added in v0.22.0

type AgentLimits struct {
	MaxDepth                 int
	MaxChildTurns            int
	MaxConcurrentRuns        int
	MaxEventCount            int
	MaxEventBytes            int
	MaxAdHocInstructionBytes int
}

AgentLimits bounds concurrent children, nesting and live event buffers.

type AgentListRequest added in v0.22.0

type AgentListRequest struct {
	PageRequest
	State            AgentRunState
	ParentAgentRunID string
}

AgentListRequest filters runs by state, including waiting, and direct parent.

type AgentRun added in v0.22.0

type AgentRun struct {
	AgentRunID            string             `json:"agentRunId"`
	AllowedTools          []string           `json:"allowedTools"`
	CancelRequested       bool               `json:"cancelRequested"`
	CompletionTokenCount  int64              `json:"completionTokenCount"`
	Definition            AgentRunDefinition `json:"definition"`
	Depth                 int64              `json:"depth"`
	EndedAt               *time.Time         `json:"endedAt,omitempty"`
	EventCount            int64              `json:"eventCount"`
	FailureClassification string             `json:"failureClassification"`
	FailureDetail         string             `json:"failureDetail"`
	FinishReason          string             `json:"finishReason"`
	Instructions          string             `json:"instructions"`
	Model                 string             `json:"model"`
	ModelReference        string             `json:"modelReference"`
	Name                  string             `json:"name"`
	ParentAgentRunID      *string            `json:"parentAgentRunId,omitempty"`
	ParentToolCallID      *string            `json:"parentToolCallId,omitempty"`
	ParentTurnID          string             `json:"parentTurnId"`
	PromptTokenCount      int64              `json:"promptTokenCount"`
	Question              *string            `json:"question,omitempty"`
	RequestID             string             `json:"requestId"`
	ResponseMessages      []any              `json:"responseMessages"`
	ResponseText          string             `json:"responseText"`
	ResponseThinking      string             `json:"responseThinking"`
	SessionID             string             `json:"sessionId"`
	StartedAt             time.Time          `json:"startedAt"`
	State                 AgentRunState      `json:"state"`
	SystemPrompt          string             `json:"systemPrompt"`
	Task                  string             `json:"task"`
	Waiting               bool               `json:"waiting"`

	WorkerGenerationID *string `json:"workerGenerationId,omitempty"`
	Workspace          string  `json:"workspace"`
}

type AgentRunCancelResponse added in v0.22.0

type AgentRunCancelResponse struct {
	AgentRunID      string        `json:"agentRunId"`
	CancelRequested bool          `json:"cancelRequested"`
	State           AgentRunState `json:"state"`
}

type AgentRunCompaction added in v0.22.0

type AgentRunCompaction struct {
	AgentRunID         string    `json:"agentRunId"`
	CreatedAt          time.Time `json:"createdAt"`
	DirectFromSequence int64     `json:"directFromSequence"`
	DirectToSequence   int64     `json:"directToSequence"`
	FromMessageID      string    `json:"fromMessageId"`
	FromSequence       int64     `json:"fromSequence"`
	ID                 string    `json:"id"`
	InputTokenCount    int64     `json:"inputTokenCount"`
	Model              string    `json:"model"`
	ParentCompactionID *string   `json:"parentCompactionId,omitempty"`
	PromptHash         string    `json:"promptHash"`
	SessionID          string    `json:"sessionId"`
	SourceMessageCount int64     `json:"sourceMessageCount"`
	Summary            string    `json:"summary"`
	SummaryTokenCount  int64     `json:"summaryTokenCount"`
	ToMessageID        string    `json:"toMessageId"`
	ToSequence         int64     `json:"toSequence"`
}

type AgentRunCompactionPage added in v0.22.0

type AgentRunCompactionPage struct {
	Compactions []AgentRunCompaction `json:"compactions"`
	HasMore     bool                 `json:"hasMore"`
	Limit       int32                `json:"limit"`
	Offset      int32                `json:"offset"`
}

type AgentRunDefinition added in v0.22.0

type AgentRunDefinition string

AgentRunDefinition identifies a finite value in durable replay or control.

type AgentRunEvent added in v0.22.0

type AgentRunEvent struct {
	CreatedAt time.Time       `json:"createdAt"`
	Payload   *map[string]any `json:"payload,omitempty"`
	Sequence  int64           `json:"sequence"`
	Type      string          `json:"type"`
}

type AgentRunEventPage added in v0.22.0

type AgentRunEventPage struct {
	AgentRunID string          `json:"agentRunId"`
	Events     []AgentRunEvent `json:"events"`
	HasMore    bool            `json:"hasMore"`
	NextCursor int64           `json:"nextCursor"`
	State      AgentRunState   `json:"state"`
}

type AgentRunMessage added in v0.22.0

type AgentRunMessage struct {
	AgentRunID   string            `json:"agentRunId"`
	CompactionID *string           `json:"compactionId,omitempty"`
	Content      string            `json:"content"`
	CreatedAt    time.Time         `json:"createdAt"`
	ID           string            `json:"id"`
	Incomplete   bool              `json:"incomplete"`
	IsError      bool              `json:"isError"`
	Model        *string           `json:"model,omitempty"`
	Role         MessageRole       `json:"role"`
	Sequence     int64             `json:"sequence"`
	SessionID    string            `json:"sessionId"`
	Thinking     *string           `json:"thinking,omitempty"`
	ToolCallID   *string           `json:"toolCallId,omitempty"`
	ToolCalls    *[]map[string]any `json:"toolCalls,omitempty"`
}

type AgentRunMessagePage added in v0.22.0

type AgentRunMessagePage struct {
	HasMore  bool              `json:"hasMore"`
	Limit    int32             `json:"limit"`
	Messages []AgentRunMessage `json:"messages"`
	Offset   int32             `json:"offset"`
}

type AgentRunPage added in v0.22.0

type AgentRunPage struct {
	Agents  []AgentRun `json:"agents"`
	HasMore bool       `json:"hasMore"`
	Limit   int32      `json:"limit"`
	Offset  int32      `json:"offset"`
}

type AgentRunState added in v0.22.0

type AgentRunState string

AgentRunState identifies a finite value in durable replay or control.

const (
	AgentRunStateCancelled AgentRunState = AgentRunState(
		api.AgentRunStateCancelled,
	)
	AgentRunStateCompleted AgentRunState = AgentRunState(
		api.AgentRunStateCompleted,
	)
	AgentRunStateFailed AgentRunState = AgentRunState(
		api.AgentRunStateFailed,
	)
	AgentRunStateInterrupted AgentRunState = AgentRunState(
		api.AgentRunStateInterrupted,
	)
	AgentRunStateRunning AgentRunState = AgentRunState(
		api.AgentRunStateRunning,
	)
)

AgentRunStateWaiting filters waiting runs, whose stored state is running.

type Agents added in v0.22.0

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

Agents addresses the children belonging to one session.

func (Agents) Cancel added in v0.22.0

func (a Agents) Cancel(
	ctx context.Context, runID string,
) (AgentRunCancelResponse, error)

Cancel stops one child and its descendants without stopping the root.

func (Agents) Compaction added in v0.22.0

func (a Agents) Compaction(
	ctx context.Context,
	runID, compactionID string,
) (AgentRunCompaction, error)

Compaction reads a child's summary only when both IDs belong to the session.

func (Agents) Compactions added in v0.22.0

func (a Agents) Compactions(
	ctx context.Context,
	runID string,
	request PageRequest,
) (AgentRunCompactionPage, error)

Compactions reads the child's independent summary lineage.

func (Agents) Events added in v0.22.0

func (a Agents) Events(
	ctx context.Context,
	runID string,
	request CursorRequest,
) (AgentRunEventPage, error)

Events follows the child's durable event sequence.

func (Agents) Get added in v0.22.0

func (a Agents) Get(ctx context.Context, runID string) (AgentRun, error)

Get reads one child, refusing IDs belonging to another session.

func (Agents) List added in v0.22.0

func (a Agents) List(
	ctx context.Context, request AgentListRequest,
) (AgentRunPage, error)

List reads children and their pending questions.

func (Agents) Messages added in v0.22.0

func (a Agents) Messages(
	ctx context.Context,
	runID string,
	request PageRequest,
) (AgentRunMessagePage, error)

Messages reads the child's own conversation in sequence order.

func (Agents) Send added in v0.22.0

func (a Agents) Send(
	ctx context.Context, runID, message string,
) (MessageResult, error)

Send queues a user message into a running child's inbox.

type AuditLogOptions added in v0.22.0

type AuditLogOptions struct {
	Enabled   bool
	Directory string
	Retention time.Duration
}

AuditLogOptions enables a private daily JSON trace alongside Logger. Empty Directory uses StateDirectory/logs. Retention defaults to 14 days.

type CancelResult

type CancelResult struct {
	CancelRequested bool
}

CancelResult reports whether a cancel request was accepted.

type Compaction added in v0.22.0

type Compaction struct {
	CreatedAt          time.Time `json:"createdAt"`
	FromMessageID      string    `json:"fromMessageId"`
	FromSequence       int64     `json:"fromSequence"`
	ID                 string    `json:"id"`
	InputTokenCount    int64     `json:"inputTokenCount"`
	Model              string    `json:"model"`
	ParentCompactionID *string   `json:"parentCompactionId,omitempty"`
	PromptHash         string    `json:"promptHash"`
	SessionID          string    `json:"sessionId"`
	SourceMessageCount int64     `json:"sourceMessageCount"`
	Summary            string    `json:"summary"`
	SummaryTokenCount  int64     `json:"summaryTokenCount"`
	ToMessageID        string    `json:"toMessageId"`
	ToSequence         int64     `json:"toSequence"`
}

type CompactionMode

type CompactionMode string

CompactionMode selects what happens when a turn's transcript exceeds Options.MaxContextTokens.

const (
	// CompactionModeDropOldest evicts whole conversation units. It is the
	// effective mode when Options.CompactionMode is empty.
	CompactionModeDropOldest CompactionMode = "drop-oldest"
	// CompactionModeSummarize replaces an eligible completed prefix with a
	// durable summary produced by CompactionModel.
	CompactionModeSummarize CompactionMode = "summarize"
)

type CompactionPage added in v0.22.0

type CompactionPage struct {
	Compactions []Compaction `json:"compactions"`
	HasMore     bool         `json:"hasMore"`
	Limit       int32        `json:"limit"`
	Offset      int32        `json:"offset"`
}

type ContextManifestEntry added in v0.22.0

type ContextManifestEntry struct {
	Kind     string `json:"kind"`
	Name     string `json:"name"`
	Source   string `json:"source"`
	Priority int    `json:"priority"`
	Hash     string `json:"hash"`
}

ContextManifestEntry identifies one harness source used by a turn.

type ContextSnapshot added in v0.22.0

type ContextSnapshot struct {
	CreatedAt       time.Time              `json:"createdAt"`
	Hash            string                 `json:"hash"`
	Manifest        []ContextManifestEntry `json:"manifest"`
	ResolvedContent string                 `json:"resolvedContent"`
}

type CursorRequest added in v0.22.0

type CursorRequest struct {
	Cursor int64
	Limit  int
}

CursorRequest selects a bounded window after an event or output sequence.

type Delivery added in v0.22.0

type Delivery string

Delivery identifies a finite value in durable replay or control.

type Event

type Event struct {
	SessionID string
	RequestID string
	Type      string
	Payload   json.RawMessage
}

Event is one transport-neutral Chatz-compatible essessey event, or one of Peen's own turn lifecycle events, produced while a turn runs. Type is the wire event name and Payload is its JSON-encoded body.

type EventLimits added in v0.22.0

type EventLimits struct {
	MaxPendingPerSession int
	MaxSummaryBytes      int
	MaxDataBytes         int
	SubscriberBuffer     int
}

EventLimits bounds notice data and live subscription buffers.

type EventSink

type EventSink func(Event) error

EventSink observes Stream's events in the order Peen produces them. Returning an error aborts the active turn.

type FS added in v0.22.0

type FS interface {
	FSReader
	FSWriter
}

FS is the caller-owned workspace filesystem. Virtual paths are relative and slash-separated. Atomic mutations must preserve complete contents and exclusive operations must never overwrite an existing destination.

type FSReader added in v0.22.0

type FSReader interface {
	Stat(string) (fs.FileInfo, error)
	Lstat(string) (fs.FileInfo, error)
	ReadDir(string) ([]fs.DirEntry, error)
	Open(string) (fs.File, error)
	ReadFile(string) ([]byte, error)
	RealPath(string) (string, error)
}

FSReader supplies metadata, bounded reads and canonical path identity.

type FSWriter added in v0.22.0

type FSWriter interface {
	CreateExclusive(string, []byte, fs.FileMode) error
	WriteFileAtomic(string, []byte, fs.FileMode) error
	MkdirAll(string, fs.FileMode) error
	Remove(string) error
	RemoveAll(string) error
	RenameNoReplace(string, string) error
	Chmod(string, fs.FileMode) error
}

FSWriter preserves atomic and exclusive mutation guarantees.

type HarnessAgent added in v0.22.0

type HarnessAgent struct {
	Name         string
	Description  string
	Source       string
	Instructions string
	AllowedTools []string
	Hash         string
}

type HarnessEventHandler added in v0.22.0

type HarnessEventHandler struct {
	Type         string
	Agent        string
	Delivery     string
	Source       string
	Instructions string
	Hash         string
}

type HarnessHook added in v0.22.0

type HarnessHook struct {
	Name        string              `json:"name"`
	Event       string              `json:"event"`
	Match       HarnessHookMatch    `json:"match,omitzero"`
	Actions     []HarnessHookAction `json:"actions"`
	Source      string              `json:"source"`
	Priority    int                 `json:"priority"`
	ConfigLayer bool                `json:"configLayer"`
	Hash        string              `json:"hash"`
}

Hook is one ordered matcher group from a layered hooks.yaml document. ConfigLayer is true only for PEEN_CONFIG_DIR's hook document.

type HarnessHookAction added in v0.22.0

type HarnessHookAction struct {
	Name        string            `yaml:"name" json:"name,omitempty"`
	Type        string            `yaml:"type" json:"type"`
	When        HarnessHookMatch  `yaml:"when" json:"when,omitzero"`
	Command     string            `yaml:"command" json:"command,omitempty"`
	Args        []string          `yaml:"args" json:"args,omitempty"`
	Environment map[string]string `yaml:"environment" json:"environment,omitempty"` //nolint:lll // Immutable schema tags.
	WorkingDir  string            `yaml:"workingDir" json:"workingDir,omitempty"`   //nolint:lll // Immutable schema tags.
	Timeout     string            `yaml:"timeout" json:"timeout,omitempty"`
	Message     string            `yaml:"message" json:"message,omitempty"`
	MessageFile string            `yaml:"messageFile" json:"messageFile,omitempty"` //nolint:lll // Immutable schema tags.
	EventType   string            `yaml:"eventType" json:"eventType,omitempty"`
	Summary     string            `yaml:"summary" json:"summary,omitempty"`
	Data        map[string]any    `yaml:"data" json:"data,omitempty"`
	Delivery    string            `yaml:"delivery" json:"delivery,omitempty"`
	Reason      string            `yaml:"reason" json:"reason,omitempty"`
	OnFailure   string            `yaml:"onFailure" json:"onFailure,omitempty"`
}

HarnessHookAction is one ordered operation in a hook group. Command is an executable path or name, never shell source; Args are passed verbatim. Timeout is a Go duration string such as "30s" bounding one command action; empty takes the runner's default.

type HarnessHookInputMatch added in v0.22.0

type HarnessHookInputMatch struct {
	Exists *bool  `json:"exists,omitempty" yaml:"exists"`
	Equals any    `json:"equals,omitempty" yaml:"equals"`
	Regex  string `json:"regex,omitempty"  yaml:"regex"`
}

type HarnessHookMatch added in v0.22.0

type HarnessHookMatch struct {
	Tool       string                           `json:"tool,omitempty"`
	Path       string                           `json:"path,omitempty"`
	Extensions []string                         `yaml:"extensions" json:"extensions,omitempty"` //nolint:lll // Immutable schema tags.
	Root       string                           `json:"root,omitempty"`
	Input      map[string]HarnessHookInputMatch `json:"input,omitempty"`
}

HarnessHookMatch selects hook actions by their structured invocation context. Every populated field is required to match.

type HarnessInstruction added in v0.22.0

type HarnessInstruction struct {
	Kind     string
	Source   string
	Priority int
	Content  string
	Hash     string
	Scope    string
	Name     string
	Paths    []string
	Base     string
}

HarnessInstruction is one AGENTS.md or rule file. A rule with Paths stays out of the system prompt and reaches the model after a file tool touches a file matching one of them, relative to Base. Content never holds a rule's frontmatter.

type HarnessLayer added in v0.22.0

type HarnessLayer struct{ Files map[string]string }

HarnessLayer is an immutable set of relative source files, including AGENTS.md and .agents rules, skills, agents, event handlers and hooks. Layers follow workspace files in order, so later custom names take priority.

type HarnessLimits added in v0.22.0

type HarnessLimits struct {
	MaxFiles             int
	MaxInstructions      int
	MaxSkills            int
	MaxAgents            int
	MaxEventHandlers     int
	MaxHooks             int
	MaxDirectoryEntries  int
	MaxFileBytes         int64
	MaxTotalContextBytes int64
}

HarnessLimits bounds discovery and context assembled from harness files.

type HarnessSkill added in v0.22.0

type HarnessSkill struct {
	Name          string
	Description   string
	Source        string
	Directory     string
	Hash          string
	Metadata      map[string]any
	Homepage      string
	Permissions   map[string]any
	UserInvocable bool
	License       string
	Compatibility string
	AllowedTools  string
}

type HarnessSnapshot added in v0.22.0

type HarnessSnapshot struct {
	Hash          string
	Workspace     string
	Instructions  []HarnessInstruction
	Skills        []HarnessSkill
	Agents        []HarnessAgent
	EventHandlers []HarnessEventHandler
	Warnings      []HarnessWarning
	Hooks         []HarnessHook
	Manifest      []ContextManifestEntry
}

HarnessSnapshot is the context resolved for one workspace.

type HarnessWarning added in v0.22.0

type HarnessWarning struct {
	Kind   string
	Source string
	Reason string
}

type HookHandler added in v0.22.0

type HookHandler func(context.Context, HookInvocation) (HookOutcome, error)

type HookInvocation added in v0.22.0

type HookInvocation struct {
	Event          string          `json:"event"`
	SessionID      string          `json:"sessionId"`
	RequestID      string          `json:"requestId"`
	TurnID         string          `json:"turnId"`
	AgentRunID     *string         `json:"agentRunId,omitempty"`
	Tool           string          `json:"tool,omitempty"`
	CallID         string          `json:"callId,omitempty"`
	Workspace      string          `json:"workspace"`
	Paths          []string        `json:"paths,omitempty"`
	Input          json.RawMessage `json:"input,omitempty"`
	Result         json.RawMessage `json:"result,omitempty"`
	Error          string          `json:"error,omitempty"`
	StateDirectory string          `json:"stateDirectory,omitempty"`
	ContextTokens  int             `json:"contextTokens"`
}

HookInvocation carries the same lifecycle identity and input as file hooks.

type HookOutcome added in v0.22.0

type HookOutcome struct {
	Deny       string
	Injections []string
	Events     []NoticeRequest
}

HookOutcome denies, injects context or publishes external notice data. Returning an error stops the hook boundary. File-hook denials run first.

type HostFS added in v0.22.0

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

HostFS preserves the host account's access. It is not a directory jail.

func OSFS added in v0.22.0

func OSFS(dir string) (*HostFS, error)

OSFS selects host access and ancestor harness discovery above dir.

func (HostFS) Chmod added in v0.22.0

func (a HostFS) Chmod(
	name string, mode fs.FileMode,
) error

func (HostFS) CreateExclusive added in v0.22.0

func (a HostFS) CreateExclusive(
	name string, data []byte, mode fs.FileMode,
) error

func (HostFS) Lstat added in v0.22.0

func (a HostFS) Lstat(
	name string,
) (fs.FileInfo, error)

func (HostFS) MkdirAll added in v0.22.0

func (a HostFS) MkdirAll(
	name string, mode fs.FileMode,
) error

func (HostFS) Open added in v0.22.0

func (a HostFS) Open(
	name string,
) (fs.File, error)

func (HostFS) ReadDir added in v0.22.0

func (a HostFS) ReadDir(
	name string,
) ([]fs.DirEntry, error)

func (HostFS) ReadFile added in v0.22.0

func (a HostFS) ReadFile(
	name string,
) ([]byte, error)

func (HostFS) RealPath added in v0.22.0

func (a HostFS) RealPath(
	name string,
) (string, error)

func (HostFS) Remove added in v0.22.0

func (a HostFS) Remove(
	name string,
) error

func (HostFS) RemoveAll added in v0.22.0

func (a HostFS) RemoveAll(
	name string,
) error

func (HostFS) RenameNoReplace added in v0.22.0

func (a HostFS) RenameNoReplace(
	source, destination string,
) error

func (HostFS) Stat added in v0.22.0

func (a HostFS) Stat(
	name string,
) (fs.FileInfo, error)

func (HostFS) WriteFileAtomic added in v0.22.0

func (a HostFS) WriteFileAtomic(
	name string, data []byte, mode fs.FileMode,
) error

type Image added in v0.38.0

type Image struct {
	// MediaType is image/png, image/jpeg, image/gif, or image/webp, and must
	// match the bytes.
	MediaType string
	// Data is the raw image, not base64.
	Data []byte
}

Image is one PNG, JPEG, GIF, or WebP image a message carries.

type Job added in v0.22.0

type Job struct {
	Command            string     `json:"command"`
	Directory          string     `json:"directory"`
	EndedAt            *time.Time `json:"endedAt,omitempty"`
	ExitCode           int64      `json:"exitCode"`
	FailureDetail      string     `json:"failureDetail"`
	JobID              string     `json:"jobId"`
	PID                int64      `json:"pid"`
	Purpose            string     `json:"purpose"`
	SessionID          string     `json:"sessionId"`
	StartedAt          time.Time  `json:"startedAt"`
	State              JobState   `json:"state"`
	ToolCallID         *string    `json:"toolCallId,omitempty"`
	TurnID             string     `json:"turnId"`
	WorkerGenerationID *string    `json:"workerGenerationId,omitempty"`
}

type JobListRequest added in v0.22.0

type JobListRequest struct {
	PageRequest
	State JobState
}

JobListRequest filters a bounded job page by optional state.

type JobOutput added in v0.22.0

type JobOutput struct {
	HasMore    bool            `json:"hasMore"`
	JobID      string          `json:"jobId"`
	Lines      []JobOutputLine `json:"lines"`
	NextCursor int64           `json:"nextCursor"`
	State      JobState        `json:"state"`
}

type JobOutputLine added in v0.22.0

type JobOutputLine struct {
	Content   string    `json:"content"`
	CreatedAt time.Time `json:"createdAt"`
	ID        string    `json:"id"`
	JobID     string    `json:"jobId"`
	Sequence  int64     `json:"sequence"`
	SessionID string    `json:"sessionId"`
	Stream    JobStream `json:"stream"`
}

type JobOutputRequest added in v0.22.0

type JobOutputRequest struct {
	CursorRequest
	Stream JobStream
}

JobOutputRequest selects stdout, stderr or both in durable sequence order.

type JobPage added in v0.22.0

type JobPage struct {
	HasMore bool  `json:"hasMore"`
	Jobs    []Job `json:"jobs"`
	Limit   int32 `json:"limit"`
	Offset  int32 `json:"offset"`
}

type JobSignal added in v0.22.0

type JobSignal string

JobSignal identifies a finite value in durable replay or control.

type JobSignalRecord added in v0.22.0

type JobSignalRecord struct {
	Accepted       bool      `json:"accepted"`
	ID             string    `json:"id"`
	JobID          string    `json:"jobId"`
	RequestedAt    time.Time `json:"requestedAt"`
	SessionID      string    `json:"sessionId"`
	Signal         JobSignal `json:"signal"`
	StateAtRequest JobState  `json:"stateAtRequest"`
}

type JobSignalRecordPage added in v0.22.0

type JobSignalRecordPage struct {
	HasMore        bool              `json:"hasMore"`
	Job            Job               `json:"job"`
	Limit          int32             `json:"limit"`
	Offset         int32             `json:"offset"`
	SignalRequests []JobSignalRecord `json:"signalRequests"`
}

type JobSignalResponse added in v0.22.0

type JobSignalResponse struct {
	JobID     string   `json:"jobId"`
	Signalled bool     `json:"signalled"`
	State     JobState `json:"state"`
}

type JobState added in v0.22.0

type JobState string

JobState identifies a finite value in durable replay or control.

const (
	JobStateExited JobState = JobState(
		api.JobStateExited,
	)
	JobStateFailed JobState = JobState(
		api.JobStateFailed,
	)
	JobStateInterrupted JobState = JobState(
		api.JobStateInterrupted,
	)
	JobStateRunning JobState = JobState(
		api.JobStateRunning,
	)
	JobStateSignalled JobState = JobState(
		api.JobStateSignalled,
	)
)

type JobStream added in v0.22.0

type JobStream string

JobStream identifies a finite value in durable replay or control.

const (
	JobStreamStderr JobStream = JobStream(
		api.JobOutputLineStreamStderr,
	)
	JobStreamStdout JobStream = JobStream(
		api.JobOutputLineStreamStdout,
	)
)

type Jobs added in v0.22.0

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

Jobs addresses process jobs owned by one session.

func (Jobs) List added in v0.22.0

func (j Jobs) List(
	ctx context.Context,
	request JobListRequest,
) (JobPage, error)

List reads jobs and their final state after a restart.

func (Jobs) Output added in v0.22.0

func (j Jobs) Output(
	ctx context.Context,
	jobID string,
	request JobOutputRequest,
) (JobOutput, error)

Output reads persisted output without waiting for the process to finish.

func (Jobs) Signal added in v0.22.0

func (j Jobs) Signal(
	ctx context.Context,
	jobID string,
	signal JobSignal,
) (JobSignalResponse, error)

Signal requests stop or kill and records even a no-op against an ended job.

func (Jobs) Signals added in v0.22.0

func (j Jobs) Signals(
	ctx context.Context,
	jobID string,
	request PageRequest,
) (JobSignalRecordPage, error)

Signals reads the job's durable signal history.

type ListMessagesRequest

type ListMessagesRequest struct {
	// Limit bounds the page size. Zero takes the internal default.
	Limit int
	// Offset skips this many messages from the start of Order's direction.
	Offset int
	// Order selects pagination direction. Empty takes MessageOrderAsc.
	Order MessageOrder
}

ListMessagesRequest describes one bounded transcript page request.

It names no session: this runtime reads its own workspace's transcript.

type ListMessagesResult

type ListMessagesResult struct {
	Items   []Message
	Limit   int
	Offset  int
	HasMore bool
}

ListMessagesResult is one complete limit-offset transcript page.

type Message

type Message struct {
	ID         string
	Sequence   int64
	Role       MessageRole
	Content    string
	CreatedAt  time.Time
	Workspace  string
	Model      string
	Thinking   string
	ToolCallID string
	ToolCalls  []MessageToolCall
	IsError    bool
	Incomplete bool
}

Message is one durable transcript record.

type MessageOrder

type MessageOrder string

MessageOrder controls transcript pagination direction.

const (
	MessageOrderAsc  MessageOrder = "asc"
	MessageOrderDesc MessageOrder = "desc"
)

type MessageRequest

type MessageRequest struct {
	Model           string
	ReasoningEffort string
	RequestID       string
	To              string
	// Message is the user's text. It must not be empty or whitespace-only.
	Message string
	// SystemPrompt overrides or extends the base system prompt for only this
	// message.
	SystemPrompt *SystemPrompt
	// Images follow Message in the turn's first user message. Only a message
	// that starts a turn may carry them, and only for a model that accepts
	// image input. Peen refuses them otherwise.
	Images []Image
}

MessageRequest describes one user message and its optional per-message settings.

type MessageResult

type MessageResult struct {
	Message string
	// Queued reports that an active turn accepted the message. Message is empty
	// because the original turn owns the eventual model response.
	Queued bool
}

MessageResult carries a final answer or acceptance into an active turn.

type MessageRole

type MessageRole string

MessageRole classifies who or what produced a transcript message.

const (
	// MessageRoleSystem is a notice Peen added to the conversation, such as
	// how the previous turn ended.
	MessageRoleSystem    MessageRole = "system"
	MessageRoleUser      MessageRole = "user"
	MessageRoleAssistant MessageRole = "assistant"
	MessageRoleTool      MessageRole = "tool"
)

type MessageToolCall

type MessageToolCall struct {
	ID        string
	Name      string
	Arguments map[string]any
}

MessageToolCall is one tool call an assistant message requested.

type ModelCall added in v0.22.0

type ModelCall struct {
	BilledCostAmount        string           `json:"billedCostAmount"`
	CacheReadTokens         int64            `json:"cacheReadTokens"`
	CacheWriteLongTTLTokens int64            `json:"cacheWriteLongTtlTokens"`
	CacheWriteTokens        int64            `json:"cacheWriteTokens"`
	CompletedAt             *time.Time       `json:"completedAt,omitempty"`
	CompletionTokens        int64            `json:"completionTokens"`
	CostKnown               bool             `json:"costKnown"`
	FailureClassification   string           `json:"failureClassification"`
	FailureDetail           string           `json:"failureDetail"`
	FinishReason            string           `json:"finishReason"`
	ID                      string           `json:"id"`
	ModelRunID              string           `json:"modelRunId"`
	PromptTokens            int64            `json:"promptTokens"`
	ReasoningTokens         int64            `json:"reasoningTokens"`
	RequestMessages         []any            `json:"requestMessages"`
	RequestTools            []any            `json:"requestTools"`
	ResponseCostAmount      string           `json:"responseCostAmount"`
	ResponseMessage         *map[string]any  `json:"responseMessage"`
	ResponseModelID         string           `json:"responseModelId"`
	ResponseUsage           map[string]any   `json:"responseUsage"`
	RetryAttemptCount       int64            `json:"retryAttemptCount"`
	RetryAttempts           []map[string]any `json:"retryAttempts"`
	RetryCostAmount         string           `json:"retryCostAmount"`
	Round                   int64            `json:"round"`
	SessionID               string           `json:"sessionId"`
	StartedAt               time.Time        `json:"startedAt"`
	State                   ModelCallState   `json:"state"`
	TotalAttempts           int64            `json:"totalAttempts"`
	TotalTokens             int64            `json:"totalTokens"`
	WastedCompletionTokens  int64            `json:"wastedCompletionTokens"`
	WastedPromptTokens      int64            `json:"wastedPromptTokens"`
	WastedTotalTokens       int64            `json:"wastedTotalTokens"`
}

type ModelCallPage added in v0.22.0

type ModelCallPage struct {
	Calls    []ModelCall `json:"calls"`
	HasMore  bool        `json:"hasMore"`
	Limit    int32       `json:"limit"`
	ModelRun ModelRun    `json:"modelRun"`
	Offset   int32       `json:"offset"`
}

type ModelCallState added in v0.22.0

type ModelCallState string

ModelCallState identifies a finite value in durable replay or control.

const (
	ModelCallStateCancelled ModelCallState = ModelCallState(
		api.ModelCallStateCancelled,
	)
	ModelCallStateCompleted ModelCallState = ModelCallState(
		api.ModelCallStateCompleted,
	)
	ModelCallStateFailed ModelCallState = ModelCallState(
		api.ModelCallStateFailed,
	)
	ModelCallStateInterrupted ModelCallState = ModelCallState(
		api.ModelCallStateInterrupted,
	)
	ModelCallStateRunning ModelCallState = ModelCallState(
		api.ModelCallStateRunning,
	)
)

type ModelClient

type ModelClient struct {
	Client *elelem.Client
	Model  elelem.Model
}

ModelClient is one already-resolved Elelem model made available under a qualified "name/model" reference.

Options.Models is this deployment's named Elelem upstream registry: the caller has already built or discovered the client, and Peen only resolves DefaultModel and CompactionModel references against the map it is given.

type ModelResolver added in v0.22.0

type ModelResolver interface {
	ResolveModel(string) (ModelClient, error)
}

ModelResolver resolves models at turn time. Returned clients must be non-nil.

type ModelRun added in v0.22.0

type ModelRun struct {
	AgentRunID            *string        `json:"agentRunId,omitempty"`
	BilledCostAmount      string         `json:"billedCostAmount"`
	CompletedAt           *time.Time     `json:"completedAt,omitempty"`
	ConnectionName        string         `json:"connectionName"`
	CostKnown             bool           `json:"costKnown"`
	FailureClassification string         `json:"failureClassification"`
	FailureDetail         string         `json:"failureDetail"`
	FinishReason          string         `json:"finishReason"`
	ID                    string         `json:"id"`
	ModelReference        string         `json:"modelReference"`
	RequestSettings       map[string]any `json:"requestSettings"`
	RequestedModelID      string         `json:"requestedModelId"`
	ResponseCostAmount    string         `json:"responseCostAmount"`
	ResponseInjections    []any          `json:"responseInjections"`
	ResponseMessages      []any          `json:"responseMessages"`
	ResponseModelID       string         `json:"responseModelId"`
	ResponseText          string         `json:"responseText"`
	ResponseThinking      string         `json:"responseThinking"`
	ResponseUsage         map[string]any `json:"responseUsage"`
	RetryCostAmount       string         `json:"retryCostAmount"`
	SessionID             string         `json:"sessionId"`
	Stage                 ModelRunStage  `json:"stage"`
	StartedAt             time.Time      `json:"startedAt"`
	State                 ModelRunState  `json:"state"`
	TurnID                string         `json:"turnId"`
}

type ModelRunPage added in v0.22.0

type ModelRunPage struct {
	HasMore   bool       `json:"hasMore"`
	Limit     int32      `json:"limit"`
	ModelRuns []ModelRun `json:"modelRuns"`
	Offset    int32      `json:"offset"`
}

type ModelRunStage added in v0.22.0

type ModelRunStage string

ModelRunStage identifies root, child or summarization provider work.

const (
	ModelRunStageTurn ModelRunStage = ModelRunStage(
		api.ModelRunStageTurn,
	)
	ModelRunStageChild ModelRunStage = ModelRunStage(
		api.ModelRunStageChild,
	)
	ModelRunStageCompaction ModelRunStage = ModelRunStage(
		api.ModelRunStageCompaction,
	)
)

type ModelRunState added in v0.22.0

type ModelRunState string

ModelRunState identifies a finite value in durable replay or control.

const (
	ModelRunStateCancelled ModelRunState = ModelRunState(
		api.ModelRunStateCancelled,
	)
	ModelRunStateCompleted ModelRunState = ModelRunState(
		api.ModelRunStateCompleted,
	)
	ModelRunStateFailed ModelRunState = ModelRunState(
		api.ModelRunStateFailed,
	)
	ModelRunStateInterrupted ModelRunState = ModelRunState(
		api.ModelRunStateInterrupted,
	)
	ModelRunStateRunning ModelRunState = ModelRunState(
		api.ModelRunStateRunning,
	)
)

type NoticeRequest added in v0.22.0

type NoticeRequest struct {
	Type     string
	Summary  string
	Data     map[string]any
	Delivery Delivery
}

NoticeRequest publishes external data. Reserved job and agent types are refused; wake delivery still requires a matching event handler.

type OpenSessionOptions added in v0.22.0

type OpenSessionOptions struct {
	Workspace string
}

OpenSessionOptions selects an existing workspace directory.

type Options

type Options struct {
	// StateDirectory holds SQLite and hook state separately from harness
	// configuration. Empty uses ConfigDirectory with a "-state" suffix.
	StateDirectory string
	// Workspace selects the initial session. Empty captures the working
	// directory once when New runs.
	Workspace string
	// InMemoryStore keeps the transcript in memory. Hook state uses a private
	// temporary directory removed by Close.
	InMemoryStore      bool
	BaseSystemPrompt   string
	AppendSystemPrompt string
	AskTimeout         time.Duration
	DisabledCoreSkills []string
	DisabledCoreAgents []string
	// DisableCoreInstructions leaves Peen's embedded AGENTS.md out of every
	// system prompt.
	DisableCoreInstructions bool
	// DisableBaseSystemPrompt leaves out the embedded base prompt when
	// BaseSystemPrompt is empty and ConfigDirectory has no SYSTEM.md.
	DisableBaseSystemPrompt bool
	// AutoEvolve tells the agent to save the skills and rules it learns in
	// the workspace's .agents/learned. LearnedDirectory is the global learned
	// directory every session reads, .agents/learned inside ConfigDirectory
	// when empty. WritableLearnedDirectory also tells the agent it may save
	// there, which changes what every other session loads.
	AutoEvolve               bool
	LearnedDirectory         string
	WritableLearnedDirectory bool
	ToolLimits               ToolLimits
	AgentLimits              AgentLimits
	HarnessLimits            HarnessLimits
	EventLimits              EventLimits
	Tools                    []Tool
	DisableTools             []string
	ModelResolver            ModelResolver
	Hooks                    map[string]HookHandler
	Filesystem               FS
	WorkspaceID              string
	Harness                  []HarnessLayer
	Logger                   *slog.Logger
	MetricsRegisterer        prometheus.Registerer
	AuditLog                 AuditLogOptions
	CommandRunner            commander.Commander
	// ConfigDirectory must already exist. It holds the optional SYSTEM.md,
	// APPEND_SYSTEM.md, COMPACTION.md and trusted harness files.
	ConfigDirectory string
	// RootAgent names the base agent definition every session starts from.
	// Empty takes DefaultRootAgent. NoRootAgent runs the root with no agent
	// instructions and every tool.
	RootAgent string

	// Models is this deployment's named Elelem upstream registry. Every
	// qualified "name/model" reference DefaultModel or CompactionModel may
	// select must be a key here.
	Models map[string]ModelClient
	// DefaultModel is the qualified reference the main agent runs on. It must
	// be a key in Models.
	DefaultModel string
	// CompactionModel is the qualified reference the summarizer runs on.
	// Empty takes DefaultModel. A non-empty value must be a key in Models.
	CompactionModel string

	// MaxContextTokens bounds one request's whole context, prompt and reply
	// together. Zero takes the smaller window of DefaultModel and
	// CompactionModel, or 32768 when neither publishes one.
	MaxContextTokens int
	// OutputReserveTokens is the room kept for the reply inside
	// MaxContextTokens; the prompt gets the rest. Every turn request sends it
	// as the output limit, reasoning included. Zero takes DefaultModel's
	// output limit, or 16384 when it publishes none, capped at a quarter of
	// the context.
	OutputReserveTokens int
	// ResumeAfterCrash lets work a previous process left unfinished continue
	// by itself when the runtime starts. False, the default, pauses it until
	// a turn resumes it.
	ResumeAfterCrash bool
	// ModelRequestTimeout bounds each model request, a turn's rounds and a
	// compaction summary alike. A turn has no overall time limit. Zero takes
	// the package default.
	ModelRequestTimeout time.Duration
	// MaxConcurrentTurns bounds turns running at once across every session.
	// Zero takes the internal default; negative disables the bound.
	MaxConcurrentTurns int
	// MaxMessageBytes bounds one caller-supplied message. Zero takes the
	// internal default.
	MaxMessageBytes int
	// MaxQueuedUserMessages bounds messages accepted while a session's turn is
	// active. Zero takes the internal default.
	MaxQueuedUserMessages int
	// MaxSystemPromptBytes bounds one caller-supplied system prompt. Zero
	// takes the internal default.
	MaxSystemPromptBytes int
	// MaxSystemPromptPercent refuses a turn whose assembled system prompt,
	// estimated in tokens, is over this share of MaxContextTokens. Zero takes
	// the internal default of 50; negative turns the check off.
	MaxSystemPromptPercent int
	// MaxStoredMessageBytes bounds one durable transcript row. Zero takes the
	// internal default.
	MaxStoredMessageBytes int
	// MaxImagesPerMessage bounds the images one message carries. Zero takes
	// the internal default of 4.
	MaxImagesPerMessage int
	// MaxImageBytes bounds one image, in a message or one readFile call reads.
	// Zero takes the internal default of 5 MiB. ToolLimits.MaxImageBytes, when
	// set, bounds readFile instead.
	MaxImageBytes int

	// CompactionMode selects what happens over budget. Empty takes
	// CompactionModeDropOldest.
	CompactionMode CompactionMode
	// CompactionPrompt overrides the summarizer instructions. Empty reads
	// COMPACTION.md from ConfigDirectory and otherwise takes the embedded
	// default.
	CompactionPrompt string
	// CompactionOutputTokens caps the space a summary gets. Zero takes the
	// internal default.
	CompactionOutputTokens int
	// CompactionSummaryPercent is the share of MaxContextTokens a summary
	// gets, up to CompactionOutputTokens, from 1 to 50. Zero takes the
	// internal default.
	CompactionSummaryPercent int

	// MaxToolRounds bounds how many tool rounds one turn may run. Zero takes
	// the internal default.
	MaxToolRounds int
	// MaxConcurrentTools bounds parallel tool execution inside one round.
	// Zero takes the internal default.
	MaxConcurrentTools int
	// ToolTimeout bounds one call of any tool except runCommand and waitJob,
	// hooks included. Those two are bounded by the wait they ask for. Zero
	// takes the internal default.
	ToolTimeout time.Duration
	// MaxToolResultTokens bounds one tool result before it enters context.
	// Zero takes the internal default.
	MaxToolResultTokens int
	// MaxTurnTokens fails a turn, or a child agent's run, before a model
	// round once its rounds have billed this many tokens. Zero sets no
	// limit.
	MaxTurnTokens int64
	// HookCommandTimeout bounds an executable hook action that sets no
	// timeout of its own. Zero takes the internal default.
	HookCommandTimeout time.Duration
	// MaxHookCommandOutput bounds stdout or stderr from an executable hook
	// action. Zero takes the internal default.
	MaxHookCommandOutput int

	// MaxEventWakesPerHour bounds how often an external event may start a
	// turn for one session. Zero takes the deployment default; negative
	// disables the bound.
	MaxEventWakesPerHour int

	// Clock and NewID are deterministic seams for tests. Nil takes time.Now
	// and uuid.New respectively.
	Clock func() time.Time
	NewID func() uuid.UUID
}

Options supplies Peen's explicit runtime dependencies and validated values.

New never reads environment variables, starts Servicepack, opens an HTTP listener, or touches global state; every dependency arrives here.

type PageRequest added in v0.22.0

type PageRequest struct {
	Limit  int
	Offset int
}

PageRequest selects a bounded limit/offset page. Zero limit uses the default.

type PromptMode

type PromptMode string

PromptMode controls how a per-message system prompt changes the base prompt.

const (
	// PromptModeAppend adds the supplied prompt after the base prompt.
	PromptModeAppend PromptMode = "append"
	// PromptModeReplace replaces the base prompt for only the current
	// message.
	PromptModeReplace PromptMode = "replace"
)

type PromptSnapshot added in v0.22.0

type PromptSnapshot struct {
	CreatedAt       time.Time `json:"createdAt"`
	EffectivePrompt string    `json:"effectivePrompt"`
	Hash            string    `json:"hash"`
}

type ReadOnlyFS added in v0.22.0

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

ReadOnlyFS rejects mutations; the underlying source owns symlink behavior.

func FromIOFS added in v0.22.0

func FromIOFS(source fs.FS) (*ReadOnlyFS, error)

FromIOFS adapts an io/fs tree. os.DirFS alone is not a symlink jail. Nil interfaces and source pointers return fs.ErrInvalid.

Example
package main

import (
	"fmt"
	"testing/fstest"

	"github.com/psyb0t/peen/pkg/peen"
)

func main() {
	files, err := peen.FromIOFS(fstest.MapFS{
		"README.md": {Data: []byte("virtual workspace")},
	})
	if err != nil {
		fmt.Println(err)

		return
	}
	data, err := files.ReadFile("README.md")
	if err != nil {
		fmt.Println(err)

		return
	}
	fmt.Println(string(data))
}
Output:
virtual workspace

func (ReadOnlyFS) Chmod added in v0.22.0

func (a ReadOnlyFS) Chmod(
	name string, mode fs.FileMode,
) error

func (ReadOnlyFS) CreateExclusive added in v0.22.0

func (a ReadOnlyFS) CreateExclusive(
	name string, data []byte, mode fs.FileMode,
) error

func (ReadOnlyFS) Lstat added in v0.22.0

func (a ReadOnlyFS) Lstat(
	name string,
) (fs.FileInfo, error)

func (ReadOnlyFS) MkdirAll added in v0.22.0

func (a ReadOnlyFS) MkdirAll(
	name string, mode fs.FileMode,
) error

func (ReadOnlyFS) Open added in v0.22.0

func (a ReadOnlyFS) Open(
	name string,
) (fs.File, error)

func (ReadOnlyFS) ReadDir added in v0.22.0

func (a ReadOnlyFS) ReadDir(
	name string,
) ([]fs.DirEntry, error)

func (ReadOnlyFS) ReadFile added in v0.22.0

func (a ReadOnlyFS) ReadFile(
	name string,
) ([]byte, error)

func (ReadOnlyFS) RealPath added in v0.22.0

func (a ReadOnlyFS) RealPath(
	name string,
) (string, error)

func (ReadOnlyFS) Remove added in v0.22.0

func (a ReadOnlyFS) Remove(
	name string,
) error

func (ReadOnlyFS) RemoveAll added in v0.22.0

func (a ReadOnlyFS) RemoveAll(
	name string,
) error

func (ReadOnlyFS) RenameNoReplace added in v0.22.0

func (a ReadOnlyFS) RenameNoReplace(
	source, destination string,
) error

func (ReadOnlyFS) Stat added in v0.22.0

func (a ReadOnlyFS) Stat(
	name string,
) (fs.FileInfo, error)

func (ReadOnlyFS) WriteFileAtomic added in v0.22.0

func (a ReadOnlyFS) WriteFileAtomic(
	name string, data []byte, mode fs.FileMode,
) error

type RootedFS added in v0.22.0

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

RootedFS owns an os.Root jail. Close it after all runtimes using it close.

func RootFS added in v0.22.0

func RootFS(dir string) (*RootedFS, error)

RootFS confines operations through os.Root, including symlink traversal.

func (RootedFS) Chmod added in v0.22.0

func (a RootedFS) Chmod(
	name string, mode fs.FileMode,
) error

func (*RootedFS) Close added in v0.22.0

func (r *RootedFS) Close() error

func (RootedFS) CreateExclusive added in v0.22.0

func (a RootedFS) CreateExclusive(
	name string, data []byte, mode fs.FileMode,
) error

func (RootedFS) Lstat added in v0.22.0

func (a RootedFS) Lstat(
	name string,
) (fs.FileInfo, error)

func (RootedFS) MkdirAll added in v0.22.0

func (a RootedFS) MkdirAll(
	name string, mode fs.FileMode,
) error

func (RootedFS) Open added in v0.22.0

func (a RootedFS) Open(
	name string,
) (fs.File, error)

func (RootedFS) ReadDir added in v0.22.0

func (a RootedFS) ReadDir(
	name string,
) ([]fs.DirEntry, error)

func (RootedFS) ReadFile added in v0.22.0

func (a RootedFS) ReadFile(
	name string,
) ([]byte, error)

func (RootedFS) RealPath added in v0.22.0

func (a RootedFS) RealPath(
	name string,
) (string, error)

func (RootedFS) Remove added in v0.22.0

func (a RootedFS) Remove(
	name string,
) error

func (RootedFS) RemoveAll added in v0.22.0

func (a RootedFS) RemoveAll(
	name string,
) error

func (RootedFS) RenameNoReplace added in v0.22.0

func (a RootedFS) RenameNoReplace(
	source, destination string,
) error

func (RootedFS) Stat added in v0.22.0

func (a RootedFS) Stat(
	name string,
) (fs.FileInfo, error)

func (RootedFS) WriteFileAtomic added in v0.22.0

func (a RootedFS) WriteFileAtomic(
	name string, data []byte, mode fs.FileMode,
) error

type Runtime

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

Runtime owns storage and execution for one or more durable sessions. Call Close after the last operation to release its resources. Runtime values must not be copied after construction.

func New

func New(options Options) (*Runtime, error)

New builds one Runtime from explicit, validated dependencies.

func (*Runtime) Cancel

func (r *Runtime) Cancel(ctx context.Context) (CancelResult, error)

Cancel requests cancellation of this workspace's active turn and every child agent still running in it. It is idempotent: with no active turn and no running child it reports CancelRequested false rather than failing.

func (*Runtime) Close added in v0.22.0

func (r *Runtime) Close(ctx context.Context) error

Close drains work and releases SQLite. Once closing starts, new calls fail with ErrClosed. If ctx expires, admitted work is cancelled; call Close again to finish cleanup after it ends. Repeated successful closes are harmless.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	"github.com/psyb0t/elelem"
	"github.com/psyb0t/elelem/elelemtest"
	"github.com/psyb0t/peen/pkg/peen"
)

func exampleOptions() (peen.Options, func(), error) {
	directory, err := os.MkdirTemp("", "peen-example-")
	if err != nil {
		return peen.Options{}, nil, err
	}
	cleanup := func() {
		if err := os.RemoveAll(directory); err != nil {
			fmt.Println(err)
		}
	}

	return peen.Options{
		ConfigDirectory: directory,
		RootAgent:       "core:general-purpose",
		InMemoryStore:   true,
		Models: map[string]peen.ModelClient{
			"example/model": {
				Client: elelem.New(elelemtest.NewScriptedDriver(
					elelemtest.Text("example reply"),
				)),
				Model: elelem.Model{ID: "model"},
			},
		},
		DefaultModel: "example/model",
	}, cleanup, nil
}

func closeExample(runtime *peen.Runtime) {
	if err := runtime.Close(context.Background()); err != nil {
		fmt.Println(err)
	}
}

func main() {
	options, cleanup, err := exampleOptions()
	if err != nil {
		fmt.Println(err)

		return
	}
	defer cleanup()
	runtime, err := peen.New(options)
	if err != nil {
		fmt.Println(err)

		return
	}
	closeExample(runtime)
	_, err = runtime.Message(context.Background(), peen.MessageRequest{
		Message: "after cleanup",
	})
	fmt.Println(errors.Is(err, peen.ErrClosed))
}
Output:
true

func (*Runtime) Details added in v0.8.0

func (r *Runtime) Details(ctx context.Context) (SessionDetails, error)

Details reads this workspace's read-only metadata.

func (*Runtime) Harness added in v0.22.0

func (r *Runtime) Harness(
	ctx context.Context,
	workspace string,
) (HarnessSnapshot, error)

Harness rebuilds the snapshot using the same resolver as the next turn.

func (*Runtime) ListMessages

func (r *Runtime) ListMessages(
	ctx context.Context,
	request ListMessagesRequest,
) (ListMessagesResult, error)

ListMessages reads one bounded page of this workspace's transcript.

func (*Runtime) ListSessions added in v0.22.0

func (r *Runtime) ListSessions(
	ctx context.Context, request PageRequest,
) (SessionPage, error)

ListSessions reads every session in this runtime's store.

func (*Runtime) Message

func (r *Runtime) Message(
	ctx context.Context,
	request MessageRequest,
) (MessageResult, error)

Message runs one durable turn to completion and returns its final answer.

func (*Runtime) OpenSession added in v0.22.0

func (r *Runtime) OpenSession(
	ctx context.Context,
	options OpenSessionOptions,
) (*Session, error)

OpenSession creates or resumes the session keyed by the canonical workspace.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"testing/fstest"

	"github.com/psyb0t/elelem"
	"github.com/psyb0t/elelem/elelemtest"
	"github.com/psyb0t/peen/pkg/peen"
)

func exampleOptions() (peen.Options, func(), error) {
	directory, err := os.MkdirTemp("", "peen-example-")
	if err != nil {
		return peen.Options{}, nil, err
	}
	cleanup := func() {
		if err := os.RemoveAll(directory); err != nil {
			fmt.Println(err)
		}
	}

	return peen.Options{
		ConfigDirectory: directory,
		RootAgent:       "core:general-purpose",
		InMemoryStore:   true,
		Models: map[string]peen.ModelClient{
			"example/model": {
				Client: elelem.New(elelemtest.NewScriptedDriver(
					elelemtest.Text("example reply"),
				)),
				Model: elelem.Model{ID: "model"},
			},
		},
		DefaultModel: "example/model",
	}, cleanup, nil
}

func closeExample(runtime *peen.Runtime) {
	if err := runtime.Close(context.Background()); err != nil {
		fmt.Println(err)
	}
}

func main() {
	options, cleanup, err := exampleOptions()
	if err != nil {
		fmt.Println(err)

		return
	}
	defer cleanup()
	files, err := peen.FromIOFS(fstest.MapFS{})
	if err != nil {
		fmt.Println(err)

		return
	}
	options.Filesystem = files
	options.WorkspaceID = "initial-workspace"
	runtime, err := peen.New(options)
	if err != nil {
		fmt.Println(err)

		return
	}
	defer closeExample(runtime)
	session, err := runtime.OpenSession(context.Background(), peen.OpenSessionOptions{
		Workspace: "another-workspace",
	})
	if err != nil {
		fmt.Println(err)

		return
	}
	result, err := session.Send(context.Background(), peen.MessageRequest{
		Message: "inspect",
	}, nil)
	if err != nil {
		fmt.Println(err)

		return
	}
	fmt.Println(result.Message)
}
Output:
example reply

func (*Runtime) ResumeSession added in v0.22.0

func (r *Runtime) ResumeSession(
	ctx context.Context,
	id string,
) (*Session, error)

ResumeSession requires an existing durable session.

func (*Runtime) Session

func (r *Runtime) Session(id string) *Session

Session makes a handle without opening storage. Methods validate its ID.

func (*Runtime) Stream

func (r *Runtime) Stream(
	ctx context.Context,
	request MessageRequest,
	sink EventSink,
) (MessageResult, error)

Stream runs one durable turn, delivering each event to sink as Peen produces it, then returns the same final answer Message would. It shares the same execution pipeline as Message; only event delivery differs.

type Session added in v0.22.0

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

Session addresses one durable conversation owned by a Runtime.

func (*Session) Agents added in v0.22.0

func (s *Session) Agents() Agents

Agents returns this session's child-agent control surface.

func (*Session) Cancel added in v0.22.0

func (s *Session) Cancel(ctx context.Context) (CancelResult, error)

Cancel stops the active turn and running children, leaving jobs independent.

func (*Session) Compaction added in v0.22.0

func (s *Session) Compaction(
	ctx context.Context,
	compactionID string,
) (Compaction, error)

Compaction reads a summary only when it belongs to this session.

func (*Session) Compactions added in v0.22.0

func (s *Session) Compactions(
	ctx context.Context, page PageRequest,
) (CompactionPage, error)

Compactions reads the root conversation's immutable summary lineage.

func (*Session) ContextSnapshot added in v0.22.0

func (s *Session) ContextSnapshot(
	ctx context.Context,
	hash string,
) (ContextSnapshot, error)

ContextSnapshot reads a harness snapshot referenced by this session.

func (*Session) Details added in v0.22.0

func (s *Session) Details(ctx context.Context) (SessionDetails, error)

Details reads session metadata without changing it.

func (*Session) Events added in v0.22.0

func (s *Session) Events(
	ctx context.Context, page PageRequest,
) (TranscriptEventPage, error)

Events reads persisted protocol events without consuming notices.

func (*Session) ID added in v0.22.0

func (s *Session) ID() string

ID returns the session's durable identifier.

func (*Session) Jobs added in v0.22.0

func (s *Session) Jobs() Jobs

Jobs returns this session's process control surface.

func (*Session) Messages added in v0.22.0

func (s *Session) Messages(
	ctx context.Context, request ListMessagesRequest,
) (ListMessagesResult, error)

Messages reads a page of the root conversation.

func (*Session) ModelRunCalls added in v0.22.0

func (s *Session) ModelRunCalls(
	ctx context.Context,
	runID string,
	page PageRequest,
) (ModelCallPage, error)

ModelRunCalls reads individual provider rounds belonging to this session.

func (*Session) ModelRuns added in v0.22.0

func (s *Session) ModelRuns(
	ctx context.Context, page PageRequest,
) (ModelRunPage, error)

ModelRuns reads provider work and its usage and cost records.

func (*Session) Notices added in v0.22.0

func (s *Session) Notices(
	ctx context.Context, page PageRequest,
) (SessionNoticePage, error)

Notices reads external, job and child-agent reports without consuming them.

func (*Session) PromptSnapshot added in v0.22.0

func (s *Session) PromptSnapshot(
	ctx context.Context,
	hash string,
) (PromptSnapshot, error)

PromptSnapshot reads an effective prompt referenced by this session.

func (*Session) PublishEvent added in v0.22.0

func (s *Session) PublishEvent(
	ctx context.Context, request NoticeRequest,
) (SessionNotice, error)

PublishEvent stores a report and wakes an idle session when its handler asks.

func (*Session) Send added in v0.22.0

func (s *Session) Send(
	ctx context.Context,
	request MessageRequest,
	sink EventSink,
) (MessageResult, error)

Send runs or queues a message. Settings apply only to a new root turn.

func (*Session) Subscribe added in v0.22.0

func (s *Session) Subscribe(ctx context.Context) (*Subscription, error)

Subscribe validates the session and receives subsequent durable events. The caller owns closing the subscription; it does not keep Runtime.Close waiting for a consumer that stopped reading.

func (*Session) Turns added in v0.22.0

func (s *Session) Turns(
	ctx context.Context,
	page PageRequest,
) (TurnPage, error)

Turns reads the durable turn history, newest first.

type SessionDetails

type SessionDetails struct {
	ID                 string
	Agent              string
	Model              string
	Workspace          string
	CreatedAt          time.Time
	UpdatedAt          time.Time
	LastMessageAt      *time.Time
	MessageCount       int64
	CompletedTurnCount int64
	ActiveTurn         bool
}

SessionDetails reports durable identity, metadata and active work.

type SessionNotice added in v0.22.0

type SessionNotice struct {
	CreatedAt time.Time       `json:"createdAt"`
	Data      *map[string]any `json:"data,omitempty"`
	Delivery  Delivery        `json:"delivery"`
	ID        string          `json:"id"`
	Source    string          `json:"source"`
	Summary   string          `json:"summary"`
	Type      string          `json:"type"`
}

type SessionNoticePage added in v0.22.0

type SessionNoticePage struct {
	HasMore bool            `json:"hasMore"`
	Limit   int32           `json:"limit"`
	Notices []SessionNotice `json:"notices"`
	Offset  int32           `json:"offset"`
}

type SessionPage added in v0.22.0

type SessionPage struct {
	Items   []SessionDetails
	Limit   int
	Offset  int
	HasMore bool
}

SessionPage lists durable session metadata in newest-updated order.

type Subscription added in v0.22.0

type Subscription struct {
	Events <-chan Event
	// contains filtered or unexported fields
}

Subscription receives live events across root, wake and child turns. Slow readers lose events; Dropped reports that loss so callers can replay durable records. Close releases the subscription without cancelling work.

func (*Subscription) Close added in v0.22.0

func (s *Subscription) Close()

func (*Subscription) Dropped added in v0.22.0

func (s *Subscription) Dropped() uint64

type SystemPrompt

type SystemPrompt struct {
	Content string
	Mode    PromptMode
}

SystemPrompt overrides or extends the base system prompt for one message.

type Tool added in v0.22.0

type Tool struct {
	Name            string
	Description     string
	ArgumentsSchema json.RawMessage
	Handler         func(context.Context, ToolInput) (ToolResult, error)
}

Tool supplies a JSON object schema and a Go handler. Names matching built-in workspace tools replace them. Messaging names remain reserved.

Example
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/psyb0t/elelem"
	"github.com/psyb0t/elelem/elelemtest"
	"github.com/psyb0t/peen/pkg/peen"
)

func exampleOptions() (peen.Options, func(), error) {
	directory, err := os.MkdirTemp("", "peen-example-")
	if err != nil {
		return peen.Options{}, nil, err
	}
	cleanup := func() {
		if err := os.RemoveAll(directory); err != nil {
			fmt.Println(err)
		}
	}

	return peen.Options{
		ConfigDirectory: directory,
		RootAgent:       "core:general-purpose",
		InMemoryStore:   true,
		Models: map[string]peen.ModelClient{
			"example/model": {
				Client: elelem.New(elelemtest.NewScriptedDriver(
					elelemtest.Text("example reply"),
				)),
				Model: elelem.Model{ID: "model"},
			},
		},
		DefaultModel: "example/model",
	}, cleanup, nil
}

func closeExample(runtime *peen.Runtime) {
	if err := runtime.Close(context.Background()); err != nil {
		fmt.Println(err)
	}
}

func main() {
	options, cleanup, err := exampleOptions()
	if err != nil {
		fmt.Println(err)

		return
	}
	defer cleanup()
	options.Tools = []peen.Tool{{
		Name:            "projectInfo",
		Description:     "Returns project metadata.",
		ArgumentsSchema: json.RawMessage(`{"type":"object"}`),
		Handler: func(context.Context, peen.ToolInput) (peen.ToolResult, error) {
			return peen.ToolResult{Content: "metadata"}, nil
		},
	}}
	options.Hooks = map[string]peen.HookHandler{
		"preToolUse": func(context.Context, peen.HookInvocation) (peen.HookOutcome, error) {
			return peen.HookOutcome{}, nil
		},
	}
	options.Harness = []peen.HarnessLayer{{Files: map[string]string{
		"AGENTS.md": "Check project metadata before editing.",
	}}}
	runtime, err := peen.New(options)
	if err != nil {
		fmt.Println(err)

		return
	}
	defer closeExample(runtime)
	fmt.Println("extensions configured")
}
Output:
extensions configured

type ToolInput added in v0.22.0

type ToolInput struct {
	Name      string
	CallID    string
	Arguments json.RawMessage
}

type ToolLimits added in v0.22.0

type ToolLimits struct {
	MaxListEntries        int
	MaxListDepth          int
	MaxSearchMatches      int
	MaxSearchFileBytes    int64
	MaxReadBytes          int
	MaxReadLines          int
	MaxWriteBytes         int
	MaxEdits              int
	MaxDiffBytes          int
	MaxPatchBytes         int
	MaxPatchFiles         int
	MaxPatchHunks         int
	MaxPatchChangedBytes  int
	MaxRemoveEntries      int
	MaxCommandOutputBytes int
	CommandTimeout        time.Duration
	MaxJobOutputLines     int
	MaxReadJobOutputLines int
	WaitJobTimeout        time.Duration
	JobStopGracePeriod    time.Duration
	MaxListJobs           int
	MaxImageBytes         int
	// MaxFetchBytes bounds how much of a response body webFetch reads.
	MaxFetchBytes int
	// MaxPDFBytes bounds a PDF readFile reads to extract its text.
	MaxPDFBytes int
}

ToolLimits bounds file, patch, command and job operations. Zero fields use the same defaults as the controller. CommandTimeout and WaitJobTimeout are the waits runCommand and waitJob use when a call passes no timeout; a call may ask for any wait.

type ToolResult added in v0.22.0

type ToolResult struct {
	Content  string
	IsError  bool
	Metadata map[string]any
}

type TranscriptEvent added in v0.22.0

type TranscriptEvent struct {
	CreatedAt          time.Time      `json:"createdAt"`
	ID                 string         `json:"id"`
	ParentToolCallID   *string        `json:"parentToolCallId,omitempty"`
	Payload            map[string]any `json:"payload"`
	RequestID          string         `json:"requestId"`
	Sequence           int64          `json:"sequence"`
	SessionID          string         `json:"sessionId"`
	TurnID             string         `json:"turnId"`
	Type               string         `json:"type"`
	WorkerGenerationID *string        `json:"workerGenerationId,omitempty"`
}

type TranscriptEventPage added in v0.22.0

type TranscriptEventPage struct {
	Events  []TranscriptEvent `json:"events"`
	HasMore bool              `json:"hasMore"`
	Limit   int32             `json:"limit"`
	Offset  int32             `json:"offset"`
}

type Turn added in v0.22.0

type Turn struct {
	CancelRequested       bool       `json:"cancelRequested"`
	CompletedAt           *time.Time `json:"completedAt,omitempty"`
	ContextSnapshotHash   *string    `json:"contextSnapshotHash,omitempty"`
	FailureClassification string     `json:"failureClassification"`
	ID                    string     `json:"id"`
	PromptSnapshotHash    *string    `json:"promptSnapshotHash,omitempty"`
	RequestID             string     `json:"requestId"`
	SessionID             string     `json:"sessionId"`
	StartedAt             time.Time  `json:"startedAt"`
	State                 TurnState  `json:"state"`
	Workspace             string     `json:"workspace"`
}

type TurnPage added in v0.22.0

type TurnPage struct {
	HasMore bool   `json:"hasMore"`
	Limit   int32  `json:"limit"`
	Offset  int32  `json:"offset"`
	Turns   []Turn `json:"turns"`
}

type TurnState added in v0.22.0

type TurnState string

TurnState identifies a finite value in durable replay or control.

const (
	TurnStateCancelled TurnState = TurnState(
		api.TurnStateCancelled,
	)
	TurnStateCompleted TurnState = TurnState(
		api.TurnStateCompleted,
	)
	TurnStateFailed TurnState = TurnState(
		api.TurnStateFailed,
	)
	TurnStateInterrupted TurnState = TurnState(
		api.TurnStateInterrupted,
	)
	TurnStateRunning TurnState = TurnState(
		api.TurnStateRunning,
	)
)

Jump to

Keyboard shortcuts

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