agent

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2026 License: MIT Imports: 39 Imported by: 0

Documentation

Overview

Package agent owns Peen's transport-independent agent runtime.

Index

Constants

View Source
const (

	// EventTypeTurnStarted marks durable turn initialization.
	EventTypeTurnStarted = "turn.started"
	// EventTypeUserMessageCreated records a durably accepted user message.
	EventTypeUserMessageCreated = "user_message.created"
	// EventTypeUserMessageQueued records an accepted message waiting for an
	// active turn's next eligible provider round.
	EventTypeUserMessageQueued = "user_message.queued"
	// EventTypeTextDelta carries one assistant text fragment.
	EventTypeTextDelta = "text.delta"
	// EventTypeThinkingDelta carries one assistant reasoning fragment.
	EventTypeThinkingDelta = "thinking.delta"
	// EventTypeProviderRetry records a retriable upstream attempt.
	EventTypeProviderRetry = "provider.retry"
	// EventTypeToolUse carries one requested tool call.
	EventTypeToolUse = "tool.use"
	// EventTypeToolResult carries the outcome of one tool call.
	EventTypeToolResult = "tool.result"
	// EventTypeSessionEvents carries session events delivered to the model.
	EventTypeSessionEvents = "session.events"
	// EventTypeTurnCompleted marks a completed durable turn.
	EventTypeTurnCompleted = "turn.completed"
	// EventTypeTurnFailed marks a non-cancellation failed turn.
	EventTypeTurnFailed = "turn.failed"
	// EventTypeTurnCancelled marks a cancelled durable turn.
	EventTypeTurnCancelled = "turn.cancelled"
	// EventTypeAgentRunStarted marks a durable child-agent run before it asks
	// a provider for work.
	EventTypeAgentRunStarted = "agent.run.started"
	// EventTypeAgentRunTextDelta carries one child-agent text fragment.
	EventTypeAgentRunTextDelta = "agent.run.text.delta"
	// EventTypeAgentRunThinkingDelta carries a child-agent reasoning fragment.
	EventTypeAgentRunThinkingDelta = "agent.run.thinking.delta"
	// EventTypeAgentRunToolUse carries one tool call made by a child agent.
	EventTypeAgentRunToolUse = "agent.run.tool.use"
	// EventTypeAgentRunToolResult carries one child-tool result.
	EventTypeAgentRunToolResult = "agent.run.tool.result"
	// EventTypeAgentRunAssistantMessage records an assembled child message.
	EventTypeAgentRunAssistantMessage = "agent.run.assistant.message"
	// EventTypeAgentRunMessageInjected records a child tool-injected message.
	EventTypeAgentRunMessageInjected = "agent.run.message.injected"
	// EventTypeAgentRunProviderRetry records a retry within a child request.
	EventTypeAgentRunProviderRetry = "agent.run.provider.retry"
	// EventTypeAgentRunCompleted marks a successfully completed child.
	EventTypeAgentRunCompleted = "agent.run.completed"
	// EventTypeAgentRunFailed marks a failed child run.
	EventTypeAgentRunFailed = "agent.run.failed"
	// EventTypeAgentRunCancelled marks a separately cancelled child run.
	EventTypeAgentRunCancelled = "agent.run.cancelled"
)

Variables

View Source
var (
	// ErrInvalidModelReference reports a malformed provider/model value.
	ErrInvalidModelReference = errors.New("invalid qualified model reference")
	// ErrModelUnavailable reports a model discovery did not find.
	ErrModelUnavailable = errors.New("configured model is unavailable")
	// ErrEventsUnavailable reports a runtime built without an event bus.
	ErrEventsUnavailable = errors.New("session events are not configured")
	// ErrContextBudgetTooLarge reports a configured request budget larger
	// than the selected model's published context window.
	ErrContextBudgetTooLarge = errors.New(
		"context budget exceeds the model's context window",
	)

	// ErrInvalidAgentRunOptions reports unusable agent run registry
	// construction options.
	ErrInvalidAgentRunOptions = errors.New("invalid agent run registry options")
	// ErrInvalidAgentRunLimits reports a limit set that cannot bound agent
	// run work.
	ErrInvalidAgentRunLimits = errors.New("invalid agent run limits")
	// ErrAgentSpecificationInvalid reports a launch_agent call naming zero
	// or both of agent and agentDefinition.
	ErrAgentSpecificationInvalid = errors.New(
		"agent specification is invalid",
	)
	// ErrAgentDefinitionTooLarge reports an ad-hoc agentDefinition whose
	// instructions exceed the configured byte bound.
	ErrAgentDefinitionTooLarge = errors.New(
		"ad-hoc agent definition is too large",
	)
	// ErrAgentDepthExceeded reports a launch_agent call that would exceed
	// the configured maximum child agent depth.
	ErrAgentDepthExceeded = errors.New("child agent depth limit exceeded")
	// ErrTooManyAgentRuns reports a session already running its configured
	// maximum number of concurrent agent runs.
	ErrTooManyAgentRuns = errors.New("too many concurrent agent runs")

	// ErrInvalidCompactionOptions reports compaction settings that cannot
	// bound a summarization call.
	ErrInvalidCompactionOptions = errors.New("invalid compaction options")
	// ErrCompactionPromptInvalid reports a COMPACTION.md the deployment
	// supplied but that cannot be used as summarizer instructions.
	ErrCompactionPromptInvalid = errors.New("invalid compaction prompt")
	// ErrSystemPromptInvalid reports a SYSTEM.md or APPEND_SYSTEM.md the
	// deployment supplied but that cannot be used as a system prompt.
	ErrSystemPromptInvalid = errors.New("invalid system prompt file")
	// ErrSystemPromptTooLarge reports request-supplied prompt text over the
	// configured byte bound.
	ErrSystemPromptTooLarge = errors.New("system prompt exceeds its limit")
	// ErrMessageTooLarge reports a caller message over the configured byte
	// bound.
	ErrMessageTooLarge = errors.New("message exceeds its limit")
	// ErrCompactionPlanMismatch reports an assembled transcript that no
	// longer matches the reconstruction plan, so no durable range can be
	// named for it.
	ErrCompactionPlanMismatch = errors.New(
		"transcript no longer matches the reconstruction plan",
	)
	// ErrCompactionUnavailable reports that no eligible completed prefix
	// frees enough context for the configured summary allowance.
	ErrCompactionUnavailable = errors.New(
		"no eligible history can be compacted",
	)
	// ErrCompactionEmptySummary reports a summarization call that produced
	// no usable summary.
	ErrCompactionEmptySummary = errors.New("compaction produced no summary")
	// ErrCompactionInsufficient reports a transcript still over budget after
	// its summary replaced the covered prefix.
	ErrCompactionInsufficient = errors.New(
		"transcript is still over budget after compaction",
	)
)

Functions

func LoadCompactionPrompt

func LoadCompactionPrompt(configDirectory string) (string, error)

LoadCompactionPrompt returns the summarizer instructions for a deployment.

An absent COMPACTION.md uses the embedded default. A present one must be non-empty and within the byte bound, because a summarizer with no usable instructions produces a summary that silently replaces real history.

func LoadSystemPrompt

func LoadSystemPrompt(configDirectory string) (string, error)

LoadSystemPrompt assembles the deployment prompt from the configuration directory: the embedded default, replaced by SYSTEM.md when present, then extended by APPEND_SYSTEM.md when present.

Both files are optional. A present one must be non-empty and within the byte bound, because a deployment that meant to shape the agent and instead silently shipped an empty file is worse than one that fails to start.

func NewDriver

func NewDriver(upstream config.Upstream) (elelem.Driver, error)

NewDriver builds one environment-isolated Elelem provider driver.

Types

type API

API is Peen's transport-neutral core contract. HTTP and embedding adapters depend on this surface rather than runtime storage internals.

It is composed from one interface per concern so a consumer that only needs part of it, such as a future public facade, can depend on the narrow piece instead of the whole runtime.

type AgentRun

type AgentRun struct {
	ID               uuid.UUID
	SessionID        uuid.UUID
	ParentTurnID     uuid.UUID
	ParentAgentRunID *uuid.UUID
	ParentToolCallID string
	RequestID        uuid.UUID
	Name             string
	Definition       AgentRunDefinition
	Depth            int
	StartedAt        time.Time
	// contains filtered or unexported fields
}

AgentRun is one execution of a named or ad-hoc child agent launched by launch_agent. The identity fields are set once at creation and never change; state and EndedAt are read and written through mu so a concurrent reader never observes a torn update.

func (*AgentRun) AppendStoredEvent added in v0.4.0

func (a *AgentRun) AppendStoredEvent(event AgentRunEvent)

AppendStoredEvent refreshes the in-process convenience buffer from an event that SQLite already committed. The database remains the replay source.

func (*AgentRun) Done

func (a *AgentRun) Done() <-chan struct{}

Done reports the channel this package closes exactly once, the moment the run leaves AgentRunStateRunning.

func (*AgentRun) ReadEvents

func (a *AgentRun) ReadEvents(
	cursor, maxEvents int,
) ([]AgentRunEvent, int, int)

ReadEvents returns a bounded window of this run's recent events, so a caller can follow a child in flight without waiting for it to finish.

func (*AgentRun) Snapshot

func (a *AgentRun) Snapshot() AgentRunSnapshot

Snapshot copies every field a caller outside this package may read, so a future HTTP handler never touches an AgentRun's internal locks directly.

type AgentRunDefinition

type AgentRunDefinition = string

AgentRunDefinition names whether a run's child came from a stored agent file or an inline ad-hoc definition. It is an alias because it carries no behavior and crosses the JSON tool boundary as a plain string. surface (AgentRun, AgentRunState, AgentRunRegistry, ...) as a deliberately consistent family, and to match tools.JobState/ tools.JobRegistry's naming shape; the stutter is a direct consequence of the type also being called AgentRun*, in a package named agent.

const (
	// AgentRunDefinitionStored marks a run launched from an effective agent
	// in the resolved catalogue.
	AgentRunDefinitionStored AgentRunDefinition = "stored"
	// AgentRunDefinitionAdHoc marks a run launched from a caller-supplied
	// inline definition never written to disk.
	AgentRunDefinitionAdHoc AgentRunDefinition = "ad-hoc"
)

type AgentRunEvent

type AgentRunEvent struct {
	Sequence  int
	Type      string
	Payload   json.RawMessage
	CreatedAt time.Time
}

AgentRunEvent is one event captured in an agent run's ring buffer, in the same type/payload shape the top-level turn's own tool blocks use.

type AgentRunLimits

type AgentRunLimits struct {
	// MaxDepth bounds how many launch_agent calls may nest: the root turn is
	// depth 0, its first child is depth 1, and so on.
	MaxDepth int
	// MaxChildTurns bounds one child conversation's own tool rounds,
	// independent of the parent turn's MaxToolRounds.
	MaxChildTurns int
	// MaxConcurrentRuns bounds how many agent runs may be simultaneously
	// running for one session.
	MaxConcurrentRuns int
	// MaxEventCount bounds how many events one run's ring buffer retains.
	MaxEventCount int
	// MaxEventBytes bounds the same buffer's total payload bytes; whichever
	// bound is hit first evicts the oldest event.
	MaxEventBytes int
	// MaxAdHocInstructionBytes bounds an inline agentDefinition's
	// instructions. This MUST equal the effective harness.Limits.MaxFileBytes
	// bound applied to stored agent files, so ad-hoc and stored agents share
	// one instruction-byte limit. The caller constructing both limit structs
	// is responsible for passing the same configured value to each; this
	// package cannot enforce that on its own because harness and agent share
	// no config source.
	MaxAdHocInstructionBytes int
}

AgentRunLimits bounds launch_agent work. Zero fields take the default.

func DefaultAgentRunLimits

func DefaultAgentRunLimits() AgentRunLimits

DefaultAgentRunLimits returns the bounded defaults every deployment starts from.

type AgentRunRegistry

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

AgentRunRegistry owns every agent run for one session, deliberately outliving any single turn so a caller can list, follow, and cancel a run after the turn that launched it has moved on. It mirrors tools.JobRegistry's shape: an ID, a bounded per-run ring buffer, cancellation, and completion publishing.

func NewAgentRunRegistry

func NewAgentRunRegistry(
	sessionID uuid.UUID,
	publisher events.Publisher,
	limits AgentRunLimits,
) (*AgentRunRegistry, error)

NewAgentRunRegistry builds a session-scoped agent run registry. publisher may be nil, meaning completion events are not published.

func (*AgentRunRegistry) Cancel

func (r *AgentRunRegistry) Cancel(id uuid.UUID) (AgentRunSnapshot, bool)

Cancel signals one run to stop without affecting any other run or the parent turn. Idempotent: an unknown, already cancelled, or already completed run reports its current state rather than failing. found is false only when id names no run this registry has ever started.

func (*AgentRunRegistry) Finish

func (r *AgentRunRegistry) Finish(
	ctx context.Context,
	run *AgentRun,
	state AgentRunState,
)

Finish records one run's terminal state and publishes its completion event exactly once. ctx is used only for logging a publish failure; the write to the bus never fails the caller.

func (*AgentRunRegistry) Get

func (r *AgentRunRegistry) Get(id uuid.UUID) (*AgentRun, bool)

Get looks up one run by ID within this session's registry.

func (*AgentRunRegistry) List

func (r *AgentRunRegistry) List() []*AgentRun

List returns every run this registry has ever started, in no particular order.

func (*AgentRunRegistry) Start

func (r *AgentRunRegistry) Start(
	ctx context.Context,
	input StartAgentRunInput,
	persist ...func(*AgentRun) error,
) (*AgentRun, context.Context, error)

Start registers one agent run in AgentRunStateRunning and returns it along with a context descending from ctx. Cancelling ctx (the parent turn ending) cancels the returned context too, so the whole child tree stops; cancelling only this run later, through Cancel, leaves ctx and every sibling run alone. An error means the session is already at its concurrent-run bound.

type AgentRunSnapshot

type AgentRunSnapshot struct {
	ID                 uuid.UUID
	SessionID          uuid.UUID
	ParentTurnID       uuid.UUID
	ParentAgentRunID   *uuid.UUID
	ParentToolCallID   string
	RequestID          uuid.UUID
	Name               string
	Definition         AgentRunDefinition
	Depth              int
	State              AgentRunState
	StartedAt          time.Time
	EndedAt            time.Time
	EventBufferedCount int
	EventDroppedCount  int
}

AgentRunSnapshot is one point-in-time, race-free view of an agent run.

type AgentRunState

type AgentRunState = string

AgentRunState names the lifecycle stage of one launch_agent run. It is an alias because it carries no behavior and crosses the JSON tool boundary as a plain string.

const (
	// AgentRunStateRunning marks a run whose child conversation has not yet
	// finished.
	AgentRunStateRunning AgentRunState = "running"
	// AgentRunStateCompleted marks a run that returned a final answer.
	AgentRunStateCompleted AgentRunState = "completed"
	// AgentRunStateFailed marks a run that ended in an error other than
	// cancellation.
	AgentRunStateFailed AgentRunState = "failed"
	// AgentRunStateCancelled marks a run stopped by its own cancellation or
	// by the parent turn's context ending.
	AgentRunStateCancelled AgentRunState = "cancelled"
)

type AssembleOptions

type AssembleOptions struct {
	// Runtime carries the tuning and the model resolver. Store and Resolver
	// are filled in by Assemble, so a caller leaves them zero.
	Runtime RuntimeOptions

	// HarnessLimits bounds filesystem-derived context. Zero fields take the
	// harness package defaults.
	HarnessLimits harness.Limits

	// StoreOptions carries the store's own bounds and its clock and ID seams.
	StoreOptions session.Options
}

AssembleOptions builds a runtime over one configuration directory.

type Assembled

type Assembled struct {
	Runtime *Runtime
	Store   *session.Store
	Handle  *db.Handle
}

Assembled is one wired runtime and the resources whose lifetime it shares.

The caller owns closing Handle. Store is returned because a service needs it for lifecycle work the runtime does not expose.

func Assemble

func Assemble(
	ctx context.Context,
	options AssembleOptions,
) (*Assembled, error)

Assemble opens the durable store, settles anything a previous process left running, and wires one runtime over both.

This exists because there are two callers, the HTTP service and the public facade, and they had each grown their own copy of this sequence. Two construction paths for one runtime is how a setting gets wired in one place and forgotten in the other, which is the shape of most of the defects this project has had. Anything that must be true of every runtime, such as recovering interrupted turns before serving, belongs here so neither caller can omit it.

The model resolver is deliberately NOT built here: a service discovers models from configured providers, and an embedding Go program supplies its own clients. That difference is real, so it stays with the callers.

type DriverFactory

type DriverFactory func(config.Upstream) (elelem.Driver, error)

DriverFactory builds a driver for one validated provider configuration.

type Event

type Event struct {
	Type              string
	Payload           json.RawMessage
	RequestID         uuid.UUID
	TriggeringEventID uuid.UUID
}

Event is one transport-neutral visible agent event.

type EventSink

type EventSink func(Event) error

EventSink observes events as Peen produces them. Returning an error aborts the active turn so a disconnected streaming transport can stop provider work.

type HarnessResolver

type HarnessResolver interface {
	Resolve(workspace string) (harness.Snapshot, error)
}

HarnessResolver resolves the layered agent context for one workspace.

type MessageAPI

type MessageAPI interface {
	SessionID() uuid.UUID
	RunMessage(
		ctx context.Context,
		request MessageRequest,
		requestID uuid.UUID,
		sink EventSink,
	) (*MessageRunResult, error)
	ListMessages(
		ctx context.Context,
		params api.ListMessagesParams,
	) (*api.MessagePage, error)
}

MessageAPI runs turns and reads the durable transcript.

type MessageRequest added in v0.3.0

type MessageRequest struct {
	Message       string               `json:"message"`
	Model         *string              `json:"model,omitempty"`
	SystemPrompt  *MessageSystemPrompt `json:"systemPrompt,omitempty"`
	SourceEventID uuid.UUID            `json:"-"`
}

MessageRequest is the WebSocket message.send payload accepted by Peen. It stays transport-neutral so embedding callers and the live socket share one validation and turn-conversion path.

type MessageRunResult

type MessageRunResult struct {
	SessionID uuid.UUID
	Queued    bool
	Text      string
}

MessageRunResult carries the durable session identity and completed output.

type MessageSystemPrompt added in v0.3.0

type MessageSystemPrompt struct {
	Content string     `json:"content"`
	Mode    PromptMode `json:"mode"`
}

MessageSystemPrompt is one non-persistent prompt override for a turn.

type ModelClient

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

ModelClient is one discovered, provider-qualified Elelem model.

type ModelResolver

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

ModelResolver resolves a qualified provider/model reference.

type ProcessJobAPI

type ProcessJobAPI interface {
	ListSessionJobs(
		ctx context.Context,
		sessionID uuid.UUID,
		params api.ListSessionJobsParams,
	) (*api.JobPage, error)
	ReadSessionJobOutput(
		ctx context.Context,
		sessionID uuid.UUID,
		jobID uuid.UUID,
		params api.ReadSessionJobOutputParams,
	) (*api.JobOutput, error)
	ListSessionJobSignalRequests(
		ctx context.Context,
		sessionID uuid.UUID,
		jobID uuid.UUID,
		params api.ListSessionJobSignalRequestsParams,
	) (*api.JobSignalRecordPage, error)
	SignalSessionJob(
		ctx context.Context,
		sessionID uuid.UUID,
		jobID uuid.UUID,
		request api.JobSignalRequest,
	) (*api.JobSignalResponse, error)
}

ProcessJobAPI observes and stops the commands a session started.

type PromptMode

type PromptMode string

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

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

type Registry

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

Registry contains only models confirmed by their providers' ListModels APIs.

func NewRegistry

func NewRegistry(
	ctx context.Context,
	options RegistryOptions,
) (*Registry, error)

NewRegistry discovers models from every usable provider. Unselected provider failures are logged and skipped. The main and compaction references must resolve, and must accept the configured budget, before startup may continue.

func NewStaticRegistry

func NewStaticRegistry(models map[string]ModelClient) (*Registry, error)

NewStaticRegistry supplies a deterministic model seam for unit and integration tests. Every key must be a valid unique qualified reference.

func (*Registry) ResolveModel

func (r *Registry) ResolveModel(qualifiedModel string) (ModelClient, error)

ResolveModel returns the exact discovered client and raw provider model ID.

type RegistryOptions

type RegistryOptions struct {
	Upstreams []config.Upstream

	// DefaultModel and CompactionModel must both resolve, and both must
	// accept MaxContextTokens, before startup may continue. An empty
	// CompactionModel takes DefaultModel.
	DefaultModel    string
	CompactionModel string

	// MaxContextTokens is the deployment's request budget. It supplies the
	// context size for a model whose driver publishes none, and it may not
	// exceed the window of a model that publishes one.
	MaxContextTokens int

	// Factory builds one provider's driver. Nil uses NewDriver.
	Factory DriverFactory
}

RegistryOptions describes one deployment's model discovery.

type RunAPI

type RunAPI interface {
	ListSessionAgentRuns(
		ctx context.Context,
		sessionID uuid.UUID,
		params api.ListSessionAgentRunsParams,
	) (*api.AgentRunPage, error)
	ListSessionAgentRunEvents(
		ctx context.Context,
		sessionID uuid.UUID,
		agentRunID uuid.UUID,
		params api.ListSessionAgentRunEventsParams,
	) (*api.AgentRunEventPage, error)
	GetSessionAgentRun(
		ctx context.Context,
		sessionID uuid.UUID,
		agentRunID uuid.UUID,
	) (*api.AgentRun, error)
	CancelSessionAgentRun(
		ctx context.Context,
		sessionID uuid.UUID,
		agentRunID uuid.UUID,
	) (*api.AgentRunCancelResponse, error)
}

RunAPI observes and cancels the child agent runs a session launched.

type Runtime

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

Runtime executes durable transport-neutral Peen turns.

func NewRuntime

func NewRuntime(ctx context.Context, options RuntimeOptions) (*Runtime, error)

NewRuntime validates the dependencies shared by every Peen turn.

func (*Runtime) CancelSession

func (r *Runtime) CancelSession(
	ctx context.Context,
	sessionID uuid.UUID,
) (*api.CancelResponse, error)

CancelSession requests cancellation for the session's active turn.

func (*Runtime) CancelSessionAgentRun

func (r *Runtime) CancelSessionAgentRun(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
) (*api.AgentRunCancelResponse, error)

CancelSessionAgentRun cancels one child agent without ending its parent turn. Cancelling an unknown, completed, or already cancelled run reports the current state rather than failing, matching POST /v1/session/cancel.

func (*Runtime) GetSessionAgentRun added in v0.4.0

func (r *Runtime) GetSessionAgentRun(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
) (*api.AgentRun, error)

GetSessionAgentRun reads every durable detail of one child run.

func (*Runtime) GetSessionCompaction added in v0.4.0

func (r *Runtime) GetSessionCompaction(
	ctx context.Context,
	sessionID uuid.UUID,
	compactionID uuid.UUID,
) (*api.Compaction, error)

GetSessionCompaction reads one immutable summary record and its parent link.

func (*Runtime) GetSessionContextSnapshot added in v0.4.0

func (r *Runtime) GetSessionContextSnapshot(
	ctx context.Context,
	sessionID uuid.UUID,
	hash string,
) (*api.ContextSnapshot, error)

GetSessionContextSnapshot reads the exact resolved context used by this session.

func (*Runtime) GetSessionPromptSnapshot added in v0.4.0

func (r *Runtime) GetSessionPromptSnapshot(
	ctx context.Context,
	sessionID uuid.UUID,
	hash string,
) (*api.PromptSnapshot, error)

GetSessionPromptSnapshot reads the exact effective prompt used by this session.

func (*Runtime) ListMessages

func (r *Runtime) ListMessages(
	ctx context.Context,
	params api.ListMessagesParams,
) (*api.MessagePage, error)

ListMessages reads one durable transcript page as the public API model.

func (*Runtime) ListSessionAgentRunEvents

func (r *Runtime) ListSessionAgentRunEvents(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
	params api.ListSessionAgentRunEventsParams,
) (*api.AgentRunEventPage, error)

ListSessionAgentRunEvents follows one child through its complete SQLite replay log. The in-memory buffer never answers this read path.

func (*Runtime) ListSessionAgentRuns

func (r *Runtime) ListSessionAgentRuns(
	ctx context.Context,
	sessionID uuid.UUID,
	params api.ListSessionAgentRunsParams,
) (*api.AgentRunPage, error)

ListSessionAgentRuns reports the child agents a session has launched, newest first, with the same bounded limit/offset paging as GET /v1/messages. A session that never launched one returns an empty list rather than an error.

func (*Runtime) ListSessionCompactions added in v0.4.0

func (r *Runtime) ListSessionCompactions(
	ctx context.Context,
	params api.ListSessionCompactionsParams,
) (*api.CompactionPage, error)

ListSessionCompactions returns every stored summary record for replay.

func (*Runtime) ListSessionEvents

func (r *Runtime) ListSessionEvents(
	ctx context.Context,
	params api.ListSessionEventsParams,
) (*api.TranscriptEventPage, error)

ListSessionEvents returns SQLite-backed protocol events, never an in-memory stream or queue view.

func (*Runtime) ListSessionJobSignalRequests added in v0.4.0

func (r *Runtime) ListSessionJobSignalRequests(
	ctx context.Context,
	sessionID uuid.UUID,
	jobID uuid.UUID,
	params api.ListSessionJobSignalRequestsParams,
) (*api.JobSignalRecordPage, error)

ListSessionJobSignalRequests reads every accepted and no-op signal request from SQLite. This makes an old session inspectable after its processes have exited or Peen has restarted.

func (*Runtime) ListSessionJobs

func (r *Runtime) ListSessionJobs(
	ctx context.Context,
	sessionID uuid.UUID,
	params api.ListSessionJobsParams,
) (*api.JobPage, error)

ListSessionJobs reads the canonical SQLite job history, newest first.

func (*Runtime) ListSessionModelRunCalls added in v0.4.0

func (r *Runtime) ListSessionModelRunCalls(
	ctx context.Context,
	sessionID uuid.UUID,
	modelRunID uuid.UUID,
	params api.ListSessionModelRunCallsParams,
) (*api.ModelCallPage, error)

ListSessionModelRunCalls returns each durable provider request and response that belongs to one logical model invocation.

func (*Runtime) ListSessionModelRuns added in v0.4.0

func (r *Runtime) ListSessionModelRuns(
	ctx context.Context,
	params api.ListSessionModelRunsParams,
) (*api.ModelRunPage, error)

ListSessionModelRuns returns every durable model invocation in a session.

func (*Runtime) ListSessionNotices added in v0.4.0

func (r *Runtime) ListSessionNotices(
	ctx context.Context,
	params api.ListSessionNoticesParams,
) (*api.SessionNoticePage, error)

ListSessionNotices returns durable notice history without consuming it.

func (*Runtime) ListSessionTurns added in v0.4.0

func (r *Runtime) ListSessionTurns(
	ctx context.Context,
	params api.ListSessionTurnsParams,
) (*api.TurnPage, error)

ListSessionTurns returns the complete durable turn lifecycle.

func (*Runtime) PublishEvent

func (r *Runtime) PublishEvent(
	ctx context.Context,
	notice events.Notice,
) (events.Notice, error)

PublishEvent records an event for one existing session. When the event asks to wake the session and a handler declares what to do with that type, it also starts a turn so the agent acts on it without anyone sending a message.

Everything that prevents a wake degrades to a queued delivery rather than an error: a busy session, an unhandled type, or a session over its wake rate all leave the event waiting for the next turn.

func (*Runtime) PublishSessionNotice added in v0.4.0

func (r *Runtime) PublishSessionNotice(
	ctx context.Context,
	sessionID uuid.UUID,
	request api.SessionNoticeRequest,
) (*api.SessionNotice, error)

PublishSessionNotice records an outside report against a session. The reserved-prefix rule is applied here rather than on the bus, because Peen's own producers legitimately publish job and agent types and only an external caller must be stopped from forging them.

func (*Runtime) ReadSessionJobOutput

func (r *Runtime) ReadSessionJobOutput(
	ctx context.Context,
	sessionID uuid.UUID,
	jobID uuid.UUID,
	params api.ReadSessionJobOutputParams,
) (*api.JobOutput, error)

ReadSessionJobOutput replays immutable SQLite output in observed order.

func (*Runtime) Run

func (r *Runtime) Run(
	ctx context.Context,
	input TurnRequest,
) (*TurnResult, error)

Run resolves context, records the turn, and runs the selected Elelem model.

func (*Runtime) RunMessage added in v0.2.0

func (r *Runtime) RunMessage(
	ctx context.Context,
	request MessageRequest,
	requestID uuid.UUID,
	sink EventSink,
) (*MessageRunResult, error)

RunMessage runs one completed agent turn while forwarding each visible event to sink. A nil sink is useful to an embedding that needs durable results but no live event transport.

func (*Runtime) Session

func (r *Runtime) Session(
	ctx context.Context,
	sessionID uuid.UUID,
) (*api.Session, error)

Session reads one durable session and its current in-process turn state.

func (*Runtime) SessionID added in v0.7.0

func (r *Runtime) SessionID() uuid.UUID

SessionID returns the durable session assigned to this runtime's startup workspace.

func (*Runtime) ShutdownJobs

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

ShutdownJobs stops every supervised process this runtime started. Jobs are children of this process, so none may silently outlive the service.

func (*Runtime) SignalSessionJob

func (r *Runtime) SignalSessionJob(
	ctx context.Context,
	sessionID uuid.UUID,
	jobID uuid.UUID,
	request api.JobSignalRequest,
) (*api.JobSignalResponse, error)

SignalSessionJob stops a live process while preserving a durable record of every accepted or no-op request. A process that is no longer live cannot be signalled again, but its row and the no-op request remain inspectable.

type RuntimeOptions

type RuntimeOptions struct {
	Store            *session.Store
	Resolver         HarnessResolver
	Models           ModelResolver
	RootAgent        string
	DefaultModel     string
	DefaultWorkspace string
	MaxContextTokens int
	TurnTimeout      time.Duration

	// BaseSystemPrompt overrides the deployment prompt. Empty reads SYSTEM.md
	// and APPEND_SYSTEM.md from ConfigDirectory and otherwise takes the
	// embedded default.
	BaseSystemPrompt string

	// MaxSystemPromptBytes bounds a request's own prompt text. Zero takes the
	// package default.
	MaxSystemPromptBytes int

	// MaxConcurrentTurns bounds turns running at once across every session.
	// Zero takes the package default; negative disables the bound.
	MaxConcurrentTurns int

	// MaxMessageBytes bounds one caller-supplied message. Zero takes the
	// package default.
	MaxMessageBytes int

	// MaxQueuedUserMessages bounds user messages accepted while a session's
	// turn is active. Zero takes the package default.
	MaxQueuedUserMessages int

	// CompactionMode selects what happens when a request exceeds
	// MaxContextTokens. Empty takes drop-oldest, which installs no Peen hook
	// and lets Elelem evict whole conversation units from that request.
	CompactionMode config.CompactionMode
	// CompactionModel is the qualified model the summarizer runs on. Empty
	// takes DefaultModel.
	CompactionModel string
	// 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 package default.
	CompactionOutputTokens int
	// CompactionTimeout bounds the separate summarization call. Zero takes
	// the package default.
	CompactionTimeout time.Duration

	// ToolLimits bounds every host tool result. Zero fields take the package
	// defaults.
	ToolLimits tools.Limits
	// MaxToolRounds bounds how many tool rounds one turn may run.
	MaxToolRounds int
	// MaxConcurrentTools bounds parallel tool execution inside one round.
	MaxConcurrentTools int
	// ToolTimeout bounds one tool call, hooks included.
	ToolTimeout time.Duration
	// MaxToolResultTokens bounds one tool result before it enters context.
	MaxToolResultTokens int
	// EnableWorkspaceHooks opts into executable hook actions found in workspace
	// layers. Config-directory hooks always run.
	EnableWorkspaceHooks bool
	// HookCommandTimeout bounds one executable hook action. Zero takes the
	// hook package default.
	HookCommandTimeout time.Duration
	// MaxHookCommandOutput bounds combined stdout or stderr from one executable
	// hook action. Zero takes the hook package default.
	MaxHookCommandOutput int

	// MaxEventWakesPerHour bounds how often events may start turns for one
	// session. Zero or negative disables the bound.
	MaxEventWakesPerHour int

	// Events delivers notices the agent did not ask about: a finished process
	// job, a finished child agent, or an outside report. A nil bus disables
	// delivery, which is what an embedding caller that wants none gets.
	Events *events.Bus
	// Metrics records bounded runtime telemetry. A nil value disables metrics
	// for embedding callers that do not expose an operator scrape endpoint.
	Metrics *metrics.Metrics

	// AgentLimits bounds launch_agent: child depth and turns, concurrent runs
	// per session, and the agent run event ring buffer. Zero fields take the
	// package defaults.
	AgentLimits AgentRunLimits

	// ConfigDirectory is PEEN_CONFIG_DIR. The runtime uses it to resolve
	// harness configuration; durable agent state always lives in SQLite.
	ConfigDirectory string
}

RuntimeOptions supplies Peen's transport-independent turn dependencies.

type SessionAPI

type SessionAPI interface {
	Session(ctx context.Context, sessionID uuid.UUID) (*api.Session, error)
	CancelSession(
		ctx context.Context,
		sessionID uuid.UUID,
	) (*api.CancelResponse, error)
}

SessionAPI reads session metadata and stops an active turn.

type SessionNoticeAPI added in v0.4.0

type SessionNoticeAPI interface {
	ListSessionNotices(
		ctx context.Context,
		params api.ListSessionNoticesParams,
	) (*api.SessionNoticePage, error)
	PublishSessionNotice(
		ctx context.Context,
		sessionID uuid.UUID,
		request api.SessionNoticeRequest,
	) (*api.SessionNotice, error)
}

SessionNoticeAPI reads and publishes durable external and worker notices.

type SessionReplayAPI added in v0.4.0

type SessionReplayAPI interface {
	ListSessionEvents(
		ctx context.Context,
		params api.ListSessionEventsParams,
	) (*api.TranscriptEventPage, error)
	ListSessionTurns(
		ctx context.Context,
		params api.ListSessionTurnsParams,
	) (*api.TurnPage, error)
	ListSessionCompactions(
		ctx context.Context,
		params api.ListSessionCompactionsParams,
	) (*api.CompactionPage, error)
	GetSessionCompaction(
		ctx context.Context,
		sessionID uuid.UUID,
		compactionID uuid.UUID,
	) (*api.Compaction, error)
	ListSessionModelRuns(
		ctx context.Context,
		params api.ListSessionModelRunsParams,
	) (*api.ModelRunPage, error)
	ListSessionModelRunCalls(
		ctx context.Context,
		sessionID uuid.UUID,
		modelRunID uuid.UUID,
		params api.ListSessionModelRunCallsParams,
	) (*api.ModelCallPage, error)
	GetSessionContextSnapshot(
		ctx context.Context,
		sessionID uuid.UUID,
		hash string,
	) (*api.ContextSnapshot, error)
	GetSessionPromptSnapshot(
		ctx context.Context,
		sessionID uuid.UUID,
		hash string,
	) (*api.PromptSnapshot, error)
}

SessionReplayAPI reads every SQLite-backed record needed to reconstruct a session.

type StartAgentRunInput

type StartAgentRunInput struct {
	ID               uuid.UUID
	ParentTurnID     uuid.UUID
	ParentAgentRunID *uuid.UUID
	ParentToolCallID string
	RequestID        uuid.UUID
	Name             string
	Definition       AgentRunDefinition
	Depth            int
	StartedAt        time.Time
}

StartAgentRunInput describes one launch_agent invocation about to run.

type TurnOrigin

type TurnOrigin struct {
	EventID   uuid.UUID
	EventType string
}

TurnOrigin records why a turn exists when no user asked for one. A reader looking at a session cannot otherwise tell which of several queued events caused a turn to start.

type TurnRequest

type TurnRequest struct {
	SessionID        *uuid.UUID
	RequestID        uuid.UUID
	Message          string
	Workspace        string
	Model            string
	SystemPrompt     string
	SystemPromptMode PromptMode
	OnEvent          EventSink
	SourceEventID    uuid.UUID

	// Origin is set only for a turn an event started. A caller-sent message
	// leaves it nil.
	Origin *TurnOrigin
}

TurnRequest describes one user message and its optional per-turn settings.

type TurnResult

type TurnResult struct {
	SessionID uuid.UUID
	Created   bool
	// Queued reports that the input was accepted by a currently active turn.
	// A queued result has no final model output because the original turn owns
	// the next eligible provider round.
	Queued   bool
	Text     string
	Thinking string
	Model    string
	Events   []Event

	// FinishReason, HasToolCalls, and OutputTokens describe how the turn
	// ended. The stream epilogue reports them, so a client can tell a
	// complete answer from one the provider cut off, rather than being told
	// every turn ended cleanly.
	FinishReason elelem.FinishReason
	HasToolCalls bool
	OutputTokens int64
}

TurnResult contains the durable session identity and the final agent output.

Jump to

Keyboard shortcuts

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