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 ¶
- Variables
- type AgentLimits
- type AgentListRequest
- type AgentRun
- type AgentRunCancelResponse
- type AgentRunCompaction
- type AgentRunCompactionPage
- type AgentRunDefinition
- type AgentRunEvent
- type AgentRunEventPage
- type AgentRunMessage
- type AgentRunMessagePage
- type AgentRunPage
- type AgentRunState
- type Agents
- func (a Agents) Cancel(ctx context.Context, runID string) (AgentRunCancelResponse, error)
- func (a Agents) Compaction(ctx context.Context, runID, compactionID string) (AgentRunCompaction, error)
- func (a Agents) Compactions(ctx context.Context, runID string, request PageRequest) (AgentRunCompactionPage, error)
- func (a Agents) Events(ctx context.Context, runID string, request CursorRequest) (AgentRunEventPage, error)
- func (a Agents) Get(ctx context.Context, runID string) (AgentRun, error)
- func (a Agents) List(ctx context.Context, request AgentListRequest) (AgentRunPage, error)
- func (a Agents) Messages(ctx context.Context, runID string, request PageRequest) (AgentRunMessagePage, error)
- func (a Agents) Send(ctx context.Context, runID, message string) (MessageResult, error)
- type AuditLogOptions
- type CancelResult
- type Compaction
- type CompactionMode
- type CompactionPage
- type ContextManifestEntry
- type ContextSnapshot
- type CursorRequest
- type Delivery
- type Event
- type EventLimits
- type EventSink
- type FS
- type FSReader
- type FSWriter
- type HarnessAgent
- type HarnessEventHandler
- type HarnessHook
- type HarnessHookAction
- type HarnessHookInputMatch
- type HarnessHookMatch
- type HarnessInstruction
- type HarnessLayer
- type HarnessLimits
- type HarnessSkill
- type HarnessSnapshot
- type HarnessWarning
- type HookHandler
- type HookInvocation
- type HookOutcome
- type HostFS
- func (a HostFS) Chmod(name string, mode fs.FileMode) error
- func (a HostFS) CreateExclusive(name string, data []byte, mode fs.FileMode) error
- func (a HostFS) Lstat(name string) (fs.FileInfo, error)
- func (a HostFS) MkdirAll(name string, mode fs.FileMode) error
- func (a HostFS) Open(name string) (fs.File, error)
- func (a HostFS) ReadDir(name string) ([]fs.DirEntry, error)
- func (a HostFS) ReadFile(name string) ([]byte, error)
- func (a HostFS) RealPath(name string) (string, error)
- func (a HostFS) Remove(name string) error
- func (a HostFS) RemoveAll(name string) error
- func (a HostFS) RenameNoReplace(source, destination string) error
- func (a HostFS) Stat(name string) (fs.FileInfo, error)
- func (a HostFS) WriteFileAtomic(name string, data []byte, mode fs.FileMode) error
- type Job
- type JobListRequest
- type JobOutput
- type JobOutputLine
- type JobOutputRequest
- type JobPage
- type JobSignal
- type JobSignalRecord
- type JobSignalRecordPage
- type JobSignalResponse
- type JobState
- type JobStream
- type Jobs
- func (j Jobs) List(ctx context.Context, request JobListRequest) (JobPage, error)
- func (j Jobs) Output(ctx context.Context, jobID string, request JobOutputRequest) (JobOutput, error)
- func (j Jobs) Signal(ctx context.Context, jobID string, signal JobSignal) (JobSignalResponse, error)
- func (j Jobs) Signals(ctx context.Context, jobID string, request PageRequest) (JobSignalRecordPage, error)
- type ListMessagesRequest
- type ListMessagesResult
- type Message
- type MessageOrder
- type MessageRequest
- type MessageResult
- type MessageRole
- type MessageToolCall
- type ModelCall
- type ModelCallPage
- type ModelCallState
- type ModelClient
- type ModelResolver
- type ModelRun
- type ModelRunPage
- type ModelRunStage
- type ModelRunState
- type NoticeRequest
- type OpenSessionOptions
- type Options
- type PageRequest
- type PromptMode
- type PromptSnapshot
- type ReadOnlyFS
- func (a ReadOnlyFS) Chmod(name string, mode fs.FileMode) error
- func (a ReadOnlyFS) CreateExclusive(name string, data []byte, mode fs.FileMode) error
- func (a ReadOnlyFS) Lstat(name string) (fs.FileInfo, error)
- func (a ReadOnlyFS) MkdirAll(name string, mode fs.FileMode) error
- func (a ReadOnlyFS) Open(name string) (fs.File, error)
- func (a ReadOnlyFS) ReadDir(name string) ([]fs.DirEntry, error)
- func (a ReadOnlyFS) ReadFile(name string) ([]byte, error)
- func (a ReadOnlyFS) RealPath(name string) (string, error)
- func (a ReadOnlyFS) Remove(name string) error
- func (a ReadOnlyFS) RemoveAll(name string) error
- func (a ReadOnlyFS) RenameNoReplace(source, destination string) error
- func (a ReadOnlyFS) Stat(name string) (fs.FileInfo, error)
- func (a ReadOnlyFS) WriteFileAtomic(name string, data []byte, mode fs.FileMode) error
- type RootedFS
- func (a RootedFS) Chmod(name string, mode fs.FileMode) error
- func (r *RootedFS) Close() error
- func (a RootedFS) CreateExclusive(name string, data []byte, mode fs.FileMode) error
- func (a RootedFS) Lstat(name string) (fs.FileInfo, error)
- func (a RootedFS) MkdirAll(name string, mode fs.FileMode) error
- func (a RootedFS) Open(name string) (fs.File, error)
- func (a RootedFS) ReadDir(name string) ([]fs.DirEntry, error)
- func (a RootedFS) ReadFile(name string) ([]byte, error)
- func (a RootedFS) RealPath(name string) (string, error)
- func (a RootedFS) Remove(name string) error
- func (a RootedFS) RemoveAll(name string) error
- func (a RootedFS) RenameNoReplace(source, destination string) error
- func (a RootedFS) Stat(name string) (fs.FileInfo, error)
- func (a RootedFS) WriteFileAtomic(name string, data []byte, mode fs.FileMode) error
- type Runtime
- func (r *Runtime) Cancel(ctx context.Context) (CancelResult, error)
- func (r *Runtime) Close(ctx context.Context) error
- func (r *Runtime) Details(ctx context.Context) (SessionDetails, error)
- func (r *Runtime) Harness(ctx context.Context, workspace string) (HarnessSnapshot, error)
- func (r *Runtime) ListMessages(ctx context.Context, request ListMessagesRequest) (ListMessagesResult, error)
- func (r *Runtime) ListSessions(ctx context.Context, request PageRequest) (SessionPage, error)
- func (r *Runtime) Message(ctx context.Context, request MessageRequest) (MessageResult, error)
- func (r *Runtime) OpenSession(ctx context.Context, options OpenSessionOptions) (*Session, error)
- func (r *Runtime) ResumeSession(ctx context.Context, id string) (*Session, error)
- func (r *Runtime) Session(id string) *Session
- func (r *Runtime) Stream(ctx context.Context, request MessageRequest, sink EventSink) (MessageResult, error)
- type Session
- func (s *Session) Agents() Agents
- func (s *Session) Cancel(ctx context.Context) (CancelResult, error)
- func (s *Session) Compaction(ctx context.Context, compactionID string) (Compaction, error)
- func (s *Session) Compactions(ctx context.Context, page PageRequest) (CompactionPage, error)
- func (s *Session) ContextSnapshot(ctx context.Context, hash string) (ContextSnapshot, error)
- func (s *Session) Details(ctx context.Context) (SessionDetails, error)
- func (s *Session) Events(ctx context.Context, page PageRequest) (TranscriptEventPage, error)
- func (s *Session) ID() string
- func (s *Session) Jobs() Jobs
- func (s *Session) Messages(ctx context.Context, request ListMessagesRequest) (ListMessagesResult, error)
- func (s *Session) ModelRunCalls(ctx context.Context, runID string, page PageRequest) (ModelCallPage, error)
- func (s *Session) ModelRuns(ctx context.Context, page PageRequest) (ModelRunPage, error)
- func (s *Session) Notices(ctx context.Context, page PageRequest) (SessionNoticePage, error)
- func (s *Session) PromptSnapshot(ctx context.Context, hash string) (PromptSnapshot, error)
- func (s *Session) PublishEvent(ctx context.Context, request NoticeRequest) (SessionNotice, error)
- func (s *Session) Send(ctx context.Context, request MessageRequest, sink EventSink) (MessageResult, error)
- func (s *Session) Subscribe(ctx context.Context) (*Subscription, error)
- func (s *Session) Turns(ctx context.Context, page PageRequest) (TurnPage, error)
- type SessionDetails
- type SessionNotice
- type SessionNoticePage
- type SessionPage
- type Subscription
- type SystemPrompt
- type Tool
- type ToolInput
- type ToolLimits
- type ToolResult
- type TranscriptEvent
- type TranscriptEventPage
- type Turn
- type TurnPage
- type TurnState
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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.
const ( AgentRunDefinitionAdHoc AgentRunDefinition = AgentRunDefinition( api.AgentRunDefinitionAdHoc, ) AgentRunDefinitionStored AgentRunDefinition = AgentRunDefinition( api.AgentRunDefinitionStored, ) )
type AgentRunEvent ¶ added in v0.22.0
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 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, ) )
const AgentRunStateWaiting AgentRunState = AgentRunState( api.ListSessionAgentRunsParamsStateWaiting, )
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
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
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.
type AuditLogOptions ¶ added in v0.22.0
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
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.
const ( DeliveryQueue Delivery = Delivery( api.SessionNoticeDeliveryQueue, ) DeliveryWake Delivery = Delivery( api.SessionNoticeDeliveryWake, ) )
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 ¶
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
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 HarnessEventHandler ¶ added in v0.22.0
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 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 HarnessLayer ¶ added in v0.22.0
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 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 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 (HostFS) CreateExclusive ¶ added in v0.22.0
func (HostFS) RenameNoReplace ¶ added in v0.22.0
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 JobOutputRequest ¶ added in v0.22.0
type JobOutputRequest struct {
CursorRequest
Stream JobStream
}
JobOutputRequest selects stdout, stderr or both in durable sequence order.
type JobSignal ¶ added in v0.22.0
type JobSignal string
JobSignal identifies a finite value in durable replay or control.
const ( JobSignalKill JobSignal = JobSignal( api.JobSignalRequestSignalKill, ) JobSignalStop JobSignal = JobSignal( api.JobSignalRequestSignalStop, ) )
type JobSignalRecord ¶ added in v0.22.0
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 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) 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 ¶
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 ¶
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 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 ¶
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 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
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 turn's request budget. Zero takes the
// package default.
MaxContextTokens 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
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 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) CreateExclusive ¶ added in v0.22.0
func (ReadOnlyFS) RenameNoReplace ¶ added in v0.22.0
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
RootFS confines operations through os.Root, including symlink traversal.
func (RootedFS) CreateExclusive ¶ added in v0.22.0
func (RootedFS) RenameNoReplace ¶ added in v0.22.0
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 (*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
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
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
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
ResumeSession requires an existing durable session.
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
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
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
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) 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
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.
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 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 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 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, ) )