peen

package
v0.29.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 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.

Construct and close

Build an Elelem client with your chosen provider, then supply it under a qualified model reference:

runtime, err := peen.New(peen.Options{
    ConfigDirectory: "/srv/peen/config",
    StateDirectory:  "/srv/peen/state",
    Workspace:       "/srv/project",
    RootAgent:       "core:general-purpose",
    Models: map[string]peen.ModelClient{
        "provider/model": {Client: client, Model: model},
    },
    DefaultModel: "provider/model",
})
if err != nil {
    return err
}

The config directory must exist. SQLite and hook state live in StateDirectory; leaving it empty uses ConfigDirectory with a -state suffix. Equal, nested or symlink-overlapping config and state directories fail validation. Workspace selects the initial session; leaving it empty captures the working directory once.

Call runtime.Close(ctx) after the last operation. Close refuses new work, waits for active calls, pauses unfinished workflows, stops jobs, drains its workflow workers, and closes SQLite, subscriptions and the private audit sink. If the context expires, Close cancels admitted calls and leaves resources available for a later Close to finish cleanup. Repeated successful calls are harmless. Each concurrent caller observes its own deadline. A synchronous event sink must return before its turn can finish; call Close outside a sink.

If New fails during workflow startup, it cancels admitted work, drains started workers and releases owned storage and telemetry before returning the error. Cleanup still runs when durable recovery or pausing fails.

InMemoryStore: true uses the production SQLite schema in memory. Hook state uses a private temporary directory removed on Close. Runtime does not close caller-owned model clients, command runners or filesystems.

Sessions and messages

runtime.OpenSession(ctx, peen.OpenSessionOptions{Workspace: path}) creates or resumes the session keyed by the canonical workspace. runtime.ResumeSession(ctx, id) requires an existing record. runtime.Session(id) creates a handle; the next operation validates its ID and existence. runtime.ListSessions(ctx, peen.PageRequest{Limit: 50}) lists durable session metadata.

session, err := runtime.OpenSession(ctx, peen.OpenSessionOptions{
    Workspace: "/srv/another-project",
})
if err != nil {
    return err
}
result, err := session.Send(ctx, peen.MessageRequest{
    Message:         "inspect the project",
    Model:           "provider/model",
    ReasoningEffort: "low",
}, nil)

Send accepts an optional model, reasoning effort, system prompt, UUID request ID and To child run ID. Settings apply to a new root turn. A message delivered to an active turn or child's inbox returns Queued: true and an empty answer. Queued input cannot override turn settings. Roots, children and grandchildren use the same durable workflow schedule. Startup restores unfinished work from saved context and accepted inbox messages. Stop preserves its pause until explicit continuation; an unrelated new request can start another turn. See child recovery.

SystemPrompt uses PromptModeAppend or PromptModeReplace for one message. BaseSystemPrompt and AppendSystemPrompt configure the runtime; absent values retain the deployment prompt files and embedded default. An explicit AppendSystemPrompt replaces file-based append text while preserving the selected base. CompactionPrompt configures the summarizer.

A sink passed to Send receives ordered events for that turn. Returning an error aborts the turn. Legacy Runtime.Message, Stream, ListMessages, Details and Cancel address the initial session.

Replay and control

All record types belong to pkg/peen. Reads return bounded pages with HasMore; increment Offset by the returned page size until it is false. Zero limit takes the default. Negative limits, offsets and cursors fail validation.

Surface Methods
Session state Details, Cancel, Messages, Turns, Events
Compaction and prompts Compactions, Compaction, ContextSnapshot, PromptSnapshot
Provider work ModelRuns, ModelRunCalls
Notices PublishEvent, Notices
session.Jobs() List, Output, Signals, Signal
session.Agents() List, Get, Events, Messages, Compactions, Compaction, Cancel, Send

Job output and child events use sequence cursors; continue from NextCursor. Job signals accept stop or kill. Agent filters include waiting, interrupted and a direct parent run ID or root. Every record lookup checks the owning session. Cancel pauses unfinished session workflows and interrupts their activities. Paused work stays stopped until explicit continuation, while unrelated messages may start another turn. Cancelling an active foreground command kills its process group; commands whose running job handles already returned stay detached until signalled or the runtime closes.

Filters and controls accept the owned constants directly, including JobStateExited, JobStreamStdout, JobSignalStop, AgentRunStateCompleted and DeliveryQueue. AgentRunStateWaiting selects waiting children; their stored state remains AgentRunStateRunning.

PublishEvent validates the external event type, delivery mode, summary and data bounds. External events cannot impersonate reserved job or agent notices. Model cost amounts are decimal strings; optional timestamps and IDs remain optional in replay records.

Live subscriptions

session.Subscribe(ctx) validates the session and returns a Subscription whose Events channel receives subsequent root, wake and child events, including children that outlive their launching turn. Each event carries its session and request IDs. Subscriptions are independent of a Send sink.

Call subscription.Close() when finished. Slow readers lose events once the configured buffer fills; Dropped counts the loss. Recover persisted records through Events and the child replay methods. Runtime.Close closes all subscription channels without waiting for readers. Cancelling the context used to create a subscription does not close it.

The root's ask tool publishes question.asked. Read it through Subscribe and answer with a later Send. Child questions appear in agent records and events; use To or Agents.Send to answer the child. See agent messaging.

Extension points

Options.Tools supplies custom Go handlers with a name, description and self-contained JSON object schema. Peen validates the schema at construction and each call's arguments before the handler runs. A custom tool with a built-in name replaces it. Hooks, tool timeouts, metrics, result bounds and agent allowed-tools apply to custom tools too. Session tools sendMessage, waitMessages, stopAgent, ask, searchExecutions, readExecution, resumeExecution and resolveExecutionActivity remain reserved and available independently of workspace tool restrictions. DisableTools removes selected workspace tools.

Options.Hooks maps a lifecycle event to a Go callback. File actions execute first, then the callback. Return HookOutcome with a denial, injected messages or external notices. A callback error denies the operation. Inputs contain the same lifecycle IDs, paths and JSON payloads as file hooks. See hook events and actions.

Options.ModelResolver resolves qualified model references at turn time. It replaces the static map and must return a non-nil client and a model ID. Default and compaction references are validated during construction.

Options.Harness supplies immutable maps of relative filenames to content. Each layer may contain AGENTS.md, .agents/rules/, skills, agents, event handlers and hooks.yaml; later layers override earlier names. runtime.Harness(ctx, workspace) returns the resolved instructions, catalogue, hooks, manifest and warnings. Memory layers follow filesystem discovery. Runtime turns and changeDirectory resolve only the current directory and its ancestors. runtime.Harness keeps its explicit inspection behavior, including scoped descendant AGENTS.md files. See directory changes. Skill content is retained in the resolved snapshot; sibling resources must also be available through the workspace filesystem if a tool needs them.

Options.CommandRunner supplies a commander.Commander used for commands, supervised jobs and executable hook actions. The implementation owns execution isolation, honours cancellation for hook commands, and closes its output streams after completion. Hook output is collected with bounded buffers. Jobs retain the normal lifecycle, durable output and signal handling.

Filesystems

Adapter Behavior
peen.OSFS(directory) Full host filesystem access, with directory as the default workspace. Ancestor harness layers apply.
peen.RootFS(directory) os.Root confines reads and atomic mutations to the directory. Absolute paths and root escapes fail. The caller closes the adapter after the runtime.
peen.FromIOFS(files) Read-only adapter for io/fs.FS. The underlying filesystem defines its own containment. os.DirFS alone does not prevent symlink escapes.

Supply an adapter as Options.Filesystem. A virtual filesystem also requires a stable WorkspaceID for durable session identity. File tools and harness discovery use relative paths under its root. Configuration, SQLite, hook state and audit files stay in host directories. No ancestor above a virtual root enters the harness. Opening another logical workspace ID with the same runtime addresses the same supplied filesystem with an independent transcript.

Virtual workspace SYSTEM.md, APPEND_SYSTEM.md and COMPACTION.md are read through the adapter. Explicit prompt values take precedence. Process and job tools and executable hook actions are disabled for a virtual workspace unless CommandRunner is supplied. A custom runner is responsible for mapping relative paths to its own execution environment.

Custom writable adapters must implement atomic replacement and exclusive creation or rename, preserve file modes, return standard io/fs errors, and provide a stable RealPath for aliases. File tools retain their read-before-change ledger and stale-content hashes.

Limits and telemetry

The option mapping lists deployment equivalents and defaults. ToolLimits, AgentLimits, HarnessLimits and EventLimits expose the corresponding in-process bounds. Zero values use their runtime defaults. Individual options cover concurrency, queue sizes, turn and tool timeouts, stored messages, prompt size, compaction and wake rates. AskTimeout: 0 has no independent timeout. MaxConcurrentTurns and MaxEventWakesPerHour accept a negative value to disable their bound. A submitted root retains its turn slot if its caller cancels without Stop. Restored roots acquire the same shared capacity before preparing work. Completion and explicit pause release that capacity; children keep their separate run limit.

DisabledCoreSkills and DisabledCoreAgents remove selected embedded definitions. Logger selects a runtime-local slog sink while preserving request and session scope. AuditLog enables a private daily JSON sink with a whole-day retention duration. MetricsRegisterer receives an owned Peen collector which Close unregisters. Separate runtimes need separate registries, or registerers with distinct constant labels, to avoid duplicate descriptors.

See the executable examples in example_test.go and development checks.

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

This section is empty.

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"`
	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
}

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 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
}

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 (
	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
	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.
	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 package default.
	MaxContextTokens int
	// OutputReserveTokens is the room kept for the reply inside
	// MaxContextTokens; the prompt gets the rest. Zero takes the package
	// default of 4096.
	OutputReserveTokens int
	// TurnTimeout bounds one turn's provider call. Zero takes the package
	// default.
	TurnTimeout 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
	// MaxStoredMessageBytes bounds one durable transcript row. Zero takes the
	// internal default.
	MaxStoredMessageBytes 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 reserves bounded space for the summary. Zero
	// takes the internal default.
	CompactionOutputTokens int
	// CompactionTimeout bounds the separate summarization call. Zero takes
	// the internal default.
	CompactionTimeout time.Duration

	// 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 tool call, hooks included. Zero takes the
	// internal default.
	ToolTimeout time.Duration
	// MaxToolResultTokens bounds one tool result before it enters context.
	// Zero takes the internal default.
	MaxToolResultTokens int
	// HookCommandTimeout bounds one executable hook action. 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
	MaxCommandTimeout     time.Duration
	MaxJobOutputLines     int
	MaxReadJobOutputLines int
	WaitJobTimeout        time.Duration
	MaxWaitJobTimeout     time.Duration
	JobStopGracePeriod    time.Duration
	MaxListJobs           int
}

ToolLimits bounds file, patch, command and job operations. Zero fields use the same defaults as the controller.

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