Documentation
¶
Overview ¶
Package agent owns Peen's transport-independent agent runtime.
Index ¶
- Constants
- Variables
- func ConfiguredToolLimits(deployment config.Config) tools.Limits
- func EventBusOptions(deployment config.Config, metricRegistry *metrics.Metrics) events.Options
- func EventTypes() []string
- func HarnessLimits() harness.Limits
- func HarnessOptions(deployment config.Config) ([]harness.ResolverOption, error)
- func LoadCompactionPrompt(configDirectory string) (string, error)
- func LoadSystemPrompt(configDirectory string) (string, error)
- func NewDriver(upstream config.Upstream) (elelem.Driver, error)
- func NewWorkflowWorker(ctx context.Context, runtime *Runtime, storage backend.Backend, ...) (*workflowworker.Worker, error)
- func SessionNoticeModelToAPI(notice *models.SessionNotice) (api.SessionNotice, error)
- func SessionToAPI(stored *models.Session, activeTurn bool) api.Session
- func ValidateAgentRunLimits(limits AgentRunLimits) error
- func WorkspaceToolNames() []string
- type API
- type AgentRun
- type AgentRunDefinition
- type AgentRunEvent
- type AgentRunLimits
- type AgentRunRegistry
- func (r *AgentRunRegistry) Cancel(id uuid.UUID) (AgentRunSnapshot, bool)
- func (r *AgentRunRegistry) CancelRunning() int
- func (r *AgentRunRegistry) CancelTurn(turnID uuid.UUID) int
- func (r *AgentRunRegistry) Deliver(ctx context.Context, id uuid.UUID, text string) error
- func (r *AgentRunRegistry) Finish(ctx context.Context, run *AgentRun, result AgentRunResult)
- func (r *AgentRunRegistry) Get(id uuid.UUID) (*AgentRun, bool)
- func (r *AgentRunRegistry) List() []*AgentRun
- func (r *AgentRunRegistry) Start(ctx context.Context, input StartAgentRunInput, ...) (*AgentRun, context.Context, error)
- func (r *AgentRunRegistry) Wait(ctx context.Context) error
- type AgentRunResult
- type AgentRunSnapshot
- type AgentRunState
- type AssembleOptions
- type Assembled
- type DriverFactory
- type Event
- type EventSink
- type HarnessResolver
- type MessageAPI
- type MessageImage
- type MessageRequest
- type MessageRunResult
- type MessageSystemPrompt
- type ModelAPI
- type ModelCatalog
- type ModelClient
- type ModelResolver
- type ProcessJobAPI
- type PromptMode
- type Registry
- type RegistryOptions
- type RunAPI
- type Runtime
- func (r *Runtime) BeginOperation(ctx context.Context) (context.Context, func(), error)
- func (r *Runtime) CancelAgentRuns(ctx context.Context, sessionID uuid.UUID) int
- func (r *Runtime) CancelLocalAgentRun(sessionID, agentRunID uuid.UUID) bool
- func (r *Runtime) CancelSession(ctx context.Context, sessionID uuid.UUID) (*api.CancelResponse, error)
- func (r *Runtime) CancelSessionAgentRun(ctx context.Context, sessionID uuid.UUID, agentRunID uuid.UUID) (*api.AgentRunCancelResponse, error)
- func (r *Runtime) GetSessionAgentRun(ctx context.Context, sessionID uuid.UUID, agentRunID uuid.UUID) (*api.AgentRun, error)
- func (r *Runtime) GetSessionAgentRunCompaction(ctx context.Context, sessionID uuid.UUID, agentRunID uuid.UUID, ...) (*api.AgentRunCompaction, error)
- func (r *Runtime) GetSessionCompaction(ctx context.Context, sessionID uuid.UUID, compactionID uuid.UUID) (*api.Compaction, error)
- func (r *Runtime) GetSessionContextSnapshot(ctx context.Context, sessionID uuid.UUID, hash string) (*api.ContextSnapshot, error)
- func (r *Runtime) GetSessionPromptSnapshot(ctx context.Context, sessionID uuid.UUID, hash string) (*api.PromptSnapshot, error)
- func (r *Runtime) ListMessages(ctx context.Context, params api.ListMessagesParams) (*api.MessagePage, error)
- func (r *Runtime) ListModels() api.ModelList
- func (r *Runtime) ListSessionAgentRunCompactions(ctx context.Context, sessionID uuid.UUID, agentRunID uuid.UUID, ...) (*api.AgentRunCompactionPage, error)
- func (r *Runtime) ListSessionAgentRunEvents(ctx context.Context, sessionID uuid.UUID, agentRunID uuid.UUID, ...) (*api.AgentRunEventPage, error)
- func (r *Runtime) ListSessionAgentRunMessages(ctx context.Context, sessionID uuid.UUID, agentRunID uuid.UUID, ...) (*api.AgentRunMessagePage, error)
- func (r *Runtime) ListSessionAgentRuns(ctx context.Context, sessionID uuid.UUID, ...) (*api.AgentRunPage, error)
- func (r *Runtime) ListSessionCompactions(ctx context.Context, params api.ListSessionCompactionsParams) (*api.CompactionPage, error)
- func (r *Runtime) ListSessionEvents(ctx context.Context, params api.ListSessionEventsParams) (*api.TranscriptEventPage, error)
- func (r *Runtime) ListSessionFeed(ctx context.Context, params api.ListSessionFeedParams) (*session.FeedPage, int32, error)
- func (r *Runtime) ListSessionJobSignalRequests(ctx context.Context, sessionID uuid.UUID, jobID uuid.UUID, ...) (*api.JobSignalRecordPage, error)
- func (r *Runtime) ListSessionJobs(ctx context.Context, sessionID uuid.UUID, params api.ListSessionJobsParams) (*api.JobPage, error)
- func (r *Runtime) ListSessionModelRunCalls(ctx context.Context, sessionID uuid.UUID, modelRunID uuid.UUID, ...) (*api.ModelCallPage, error)
- func (r *Runtime) ListSessionModelRuns(ctx context.Context, params api.ListSessionModelRunsParams) (*api.ModelRunPage, error)
- func (r *Runtime) ListSessionNotices(ctx context.Context, params api.ListSessionNoticesParams) (*api.SessionNoticePage, error)
- func (r *Runtime) ListSessionTurns(ctx context.Context, params api.ListSessionTurnsParams) (*api.TurnPage, error)
- func (r *Runtime) PauseSessionWorkflows(ctx context.Context) (bool, error)
- func (r *Runtime) PublishEvent(ctx context.Context, notice events.Notice) (events.Notice, error)
- func (r *Runtime) PublishSessionNotice(ctx context.Context, sessionID uuid.UUID, request api.SessionNoticeRequest) (*api.SessionNotice, error)
- func (r *Runtime) ReadSessionJobOutput(ctx context.Context, sessionID uuid.UUID, jobID uuid.UUID, ...) (*api.JobOutput, error)
- func (r *Runtime) ResolveHarness(workspace string) (harness.Snapshot, error)
- func (r *Runtime) Run(ctx context.Context, input TurnRequest) (*TurnResult, error)
- func (r *Runtime) RunMessage(ctx context.Context, request MessageRequest, requestID uuid.UUID, ...) (*MessageRunResult, error)
- func (r *Runtime) Session(ctx context.Context, sessionID uuid.UUID) (*api.Session, error)
- func (r *Runtime) SessionID() uuid.UUID
- func (r *Runtime) SetWakeRunner(runner WakeRunner)
- func (r *Runtime) Shutdown(ctx context.Context) error
- func (r *Runtime) ShutdownAgentRuns(ctx context.Context) error
- func (r *Runtime) ShutdownJobs(ctx context.Context) error
- func (r *Runtime) SignalSessionJob(ctx context.Context, sessionID uuid.UUID, jobID uuid.UUID, ...) (*api.JobSignalResponse, error)
- type RuntimeOptions
- type SessionAPI
- type SessionNoticeAPI
- type SessionReplayAPI
- type StartAgentRunInput
- type TurnOrigin
- type TurnRequest
- type TurnResult
- type WakeRunner
Constants ¶
const ( // EventTypeTurnStarted marks durable turn initialization. EventTypeTurnStarted = "turn.started" // EventTypeUserMessageCreated records a durably accepted user message. EventTypeUserMessageCreated = session.EventTypeUserMessageCreated // EventTypeUserMessageQueued records an accepted message waiting for an // active turn's next eligible provider round. EventTypeUserMessageQueued = session.EventTypeUserMessageQueued // EventTypeUserMessageDelivered records a queued message reaching the // model at the active turn's next provider round, under the request ID it // was sent with. EventTypeUserMessageDelivered = session.EventTypeUserMessageDelivered // EventTypeSkillInjected records a skill message, or the note that a // skill is already loaded, reaching the model right after the user // message that named the skill. EventTypeSkillInjected = session.EventTypeSkillInjected // 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" // EventTypeHarnessWarning records ignored optional harness configuration. EventTypeHarnessWarning = "harness.warning" // EventTypeMCPStatus reports the session's MCP servers at turn start. EventTypeMCPStatus = "mcp.status" // EventTypeTurnCompleted marks a completed durable turn. EventTypeTurnCompleted = "turn.completed" // EventTypeTurnFailed marks a non-cancellation failed turn. EventTypeTurnFailed = session.EventTypeTurnFailed // EventTypeTurnCancelled marks a cancelled durable turn. EventTypeTurnCancelled = session.EventTypeTurnCancelled // 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 = session.EventTypeAgentRunCompleted // EventTypeAgentRunFailed marks a failed child run. EventTypeAgentRunFailed = session.EventTypeAgentRunFailed // EventTypeAgentRunCancelled marks a separately cancelled child run. EventTypeAgentRunCancelled = session.EventTypeAgentRunCancelled // EventTypeAgentRunMessageQueued records a message accepted into a // running child's inbox. EventTypeAgentRunMessageQueued = "agent.run.message.queued" // EventTypeAgentRunMessageDelivered records a queued message reaching // the child's model at its next provider round. EventTypeAgentRunMessageDelivered = "agent.run.message.delivered" // EventTypeAgentRunMessageUndelivered records a queued message the // child ended before reading. EventTypeAgentRunMessageUndelivered = "agent.run.message.undelivered" // EventTypeAgentRunQuestion records a question a child asked with ask. // The child waits until a later EventTypeAgentRunAnswer. EventTypeAgentRunQuestion = events.TypeAgentRunQuestion // EventTypeAgentRunAnswer records that a child's ask ended, answered or // timed out. EventTypeAgentRunAnswer = "agent.run.answer" // EventTypeQuestionAsked records a question the root conversation asked // the user with ask. The user's next message is the answer. EventTypeQuestionAsked = "question.asked" // EventTypeQuestionAnswered records that the root's ask ended, answered // or timed out. EventTypeQuestionAnswered = "question.answered" )
const SystemAgentScopeKey = "system_agent"
SystemAgentScopeKey marks a system worker's logging scope.
Variables ¶
var ( // ErrTurnTokenLimit reports a turn, or a child agent's run, whose rounds // have billed PEEN_MAX_TURN_TOKENS. It is always joined with // commerr.ErrOutOfRange. ErrTurnTokenLimit = errors.New("the turn reached its token limit") // ErrInvalidModelReference reports a malformed provider/model value. ErrInvalidModelReference = errors.New("invalid qualified model reference") ErrModelUnavailable = errors.New("configured model is unavailable") 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 launchAgent 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 launchAgent 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", ) // 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 ConfiguredToolLimits ¶ added in v0.8.0
ConfiguredToolLimits maps the deployment's tool bounds onto the tool package. These are resource and context bounds, never permission gates.
func EventBusOptions ¶ added in v0.8.0
EventBusOptions maps the deployment's event bounds onto the event package.
func EventTypes ¶ added in v0.19.0
func EventTypes() []string
EventTypes lists every transcript event type the runtime emits.
func HarnessLimits ¶ added in v0.8.0
HarnessLimits is the single place the harness bounds are decided, so the resolver and anything derived from them cannot disagree.
func HarnessOptions ¶ added in v0.18.0
func HarnessOptions( deployment config.Config, ) ([]harness.ResolverOption, error)
HarnessOptions maps the deployment's disabled core skills, agents, and instructions onto the harness resolver. The controller and every worker build their resolver from it, so both see the same harness.
func LoadCompactionPrompt ¶
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 ¶
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 NewWorkflowWorker ¶ added in v0.25.0
func NewWorkflowWorker( ctx context.Context, runtime *Runtime, storage backend.Backend, generationID, sessionID uuid.UUID, sink EventSink, ) (*workflowworker.Worker, error)
NewWorkflowWorker assembles native session tasks without starting them. Cancel the startup context and drain tasks before closing storage.
func SessionNoticeModelToAPI ¶ added in v0.26.0
func SessionNoticeModelToAPI( notice *models.SessionNotice, ) (api.SessionNotice, error)
SessionNoticeModelToAPI maps one stored notice onto its API representation. It is exported so the live feed renderer builds a notice.created frame from the exact same mapping GET /api/v1/session/notices returns, rather than keeping a second one that could drift from it.
func SessionToAPI ¶ added in v0.8.0
SessionToAPI maps one durable session onto its API representation. It is exported so the control surface reports a session in exactly the shape the session endpoints already return, rather than keeping a second mapping that could drift from this one.
func ValidateAgentRunLimits ¶ added in v0.22.0
func ValidateAgentRunLimits(limits AgentRunLimits) error
ValidateAgentRunLimits validates bounds before the first child is launched.
func WorkspaceToolNames ¶ added in v0.22.0
func WorkspaceToolNames() []string
WorkspaceToolNames lists built-ins that an embedding caller may disable. Messaging remains outside this list and is always available.
Types ¶
type API ¶
type API interface {
MessageAPI
ModelAPI
SessionAPI
SessionReplayAPI
SessionNoticeAPI
ProcessJobAPI
RunAPI
}
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 launchAgent. 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 ¶
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 launchAgent 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 launchAgent work. Zero fields take the default.
func ConfiguredAgentRunLimits ¶ added in v0.8.0
func ConfiguredAgentRunLimits(deployment config.Config) AgentRunLimits
ConfiguredAgentRunLimits maps the deployment's child-agent bounds onto the runtime. Without this the env vars parse and validate but never reach launchAgent, so an operator would set them and see nothing change.
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) CancelRunning ¶ added in v0.21.0
func (r *AgentRunRegistry) CancelRunning() int
CancelRunning stops every running child in the session and reports how many it signalled.
func (*AgentRunRegistry) CancelTurn ¶ added in v0.21.0
func (r *AgentRunRegistry) CancelTurn(turnID uuid.UUID) int
CancelTurn stops every running child the turn turnID started, directly or through its descendants, and reports how many it signalled.
func (*AgentRunRegistry) Deliver ¶ added in v0.21.0
Deliver puts one rendered message in a running child's inbox. It fails with commerr.ErrNotFound when this registry never started id, and with session.ErrAgentRunFinished when the run has ended.
func (*AgentRunRegistry) Finish ¶
func (r *AgentRunRegistry) Finish( ctx context.Context, run *AgentRun, result AgentRunResult, )
Finish records one run's terminal state and, for a child of the root conversation, publishes its completion event exactly once. A deeper run reports to its parent run's inbox instead, which its launcher handles. ctx is used only for the publish and its logging. The publish 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 the context it runs under. That context keeps ctx's values but not its cancellation: a child outlives the tool call and the turn that launched it, and stops only through this registry, by Cancel, CancelTurn, CancelRunning, or its parent run ending. An error means the session is already at its concurrent-run bound.
type AgentRunResult ¶ added in v0.21.0
type AgentRunResult struct {
State AgentRunState
Response string
FailureDetail string
}
AgentRunResult is how one run ended and what it answered.
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 launchAgent 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 {
InMemoryStore bool
// Runtime carries the tuning and the model resolver. Store and Resolver
// are filled in by Assemble, so a caller leaves them zero.
Runtime RuntimeOptions
// StateDirectory is where SQLite lives. It is required and deliberately
// separate from Runtime.ConfigDirectory, which is the harness directory a
// Docker worker receives read-only: durable state inside that directory
// would travel into every worker along with it.
//
// A direct pkg/peen runtime owns both and passes its one directory here,
// because it has no worker to hand a mount to.
StateDirectory string
// HarnessLimits bounds filesystem-derived context. Zero fields take the
// harness package defaults.
HarnessLimits harness.Limits
// HarnessOptions adjusts the harness resolver, for example to disable
// core skills and agents.
HarnessOptions []harness.ResolverOption
// StoreOptions carries the store's own bounds and its clock and ID seams.
StoreOptions session.Options
// ResumeAfterCrash lets work a previous process left unfinished continue
// by itself. False, the default, pauses it until a turn resumes it.
ResumeAfterCrash bool
}
AssembleOptions builds a runtime over one configuration directory.
type Assembled ¶
type Assembled struct {
Runtime *Runtime
Store *session.Store
Handle *db.Handle
// contains filtered or unexported fields
}
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.
func (*Assembled) NewSessionRuntime ¶ added in v0.25.0
func (a *Assembled) NewSessionRuntime( ctx context.Context, sessionID uuid.UUID, ) (*Runtime, error)
NewSessionRuntime shares assembly dependencies and the global turn limit. The caller owns its shutdown; it does not own the shared storage handle.
type DriverFactory ¶
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 ¶
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 ¶
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 MessageImage ¶ added in v0.38.0
type MessageImage = session.MessageImage
MessageImage is one image a message carries: its media type and raw bytes.
type MessageRequest ¶ added in v0.3.0
type MessageRequest struct {
ExpectedStopRevision *int64 `json:"-"`
Message string `json:"message"`
Model *string `json:"model,omitempty"`
ReasoningEffort *string `json:"reasoningEffort,omitempty"`
SystemPrompt *MessageSystemPrompt `json:"systemPrompt,omitempty"`
// Images follow the message text, only for a model that accepts image
// input. A queued message or one to a child carries them too.
Images []MessageImage `json:"images,omitempty"`
// To sends the message to a running child agent's inbox instead of the
// root conversation. The child reads it after its current tool call. A
// message to a child starts no turn and cannot carry turn settings.
To *uuid.UUID `json:"to,omitempty"`
// System says the client meant to address the system session. The router
// refuses a mismatch in either direction.
System bool `json:"-"`
// SessionID routes the turn to one durable session. The transport sets it
// from the session the client named, never from the message body, so a
// message cannot redirect itself to another session. An unknown ID fails
// while the turn's session is resolved, before any turn record exists.
SessionID *uuid.UUID `json:"-"`
SourceEventID uuid.UUID `json:"-"`
// Origin is set only for a turn a session event started. Like SessionID
// it never comes from a message body, so a client cannot pass its own
// message off as a woken turn.
Origin *TurnOrigin `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 ¶
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 ModelAPI ¶ added in v0.12.0
ModelAPI exposes the configured model catalogue without reaching a provider. Provider discovery already happened during controller startup, so a client sees exactly the references a turn can resolve without spending a model call.
type ModelCatalog ¶ added in v0.12.0
type ModelCatalog interface {
ModelResolver
ListModels() api.ModelList
}
ModelCatalog is a resolver that can also expose its startup-discovered public metadata. Minimal embedding resolvers need only implement ModelResolver and consequently expose no catalogue.
type ModelClient ¶
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) ListModels ¶ added in v0.12.0
ListModels returns startup-discovered, non-secret model metadata in a deterministic order. The qualified name is intentionally the same string a caller passes as a one-turn model override, so a UI never has to assemble a provider reference from separate display fields.
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)
// A child agent's transcript and compaction lineage are separate durable
// records from the session's, so they are read through the agent run.
ListSessionAgentRunMessages(
ctx context.Context,
sessionID uuid.UUID,
agentRunID uuid.UUID,
params api.ListSessionAgentRunMessagesParams,
) (*api.AgentRunMessagePage, error)
ListSessionAgentRunCompactions(
ctx context.Context,
sessionID uuid.UUID,
agentRunID uuid.UUID,
params api.ListSessionAgentRunCompactionsParams,
) (*api.AgentRunCompactionPage, error)
GetSessionAgentRunCompaction(
ctx context.Context,
sessionID uuid.UUID,
agentRunID uuid.UUID,
compactionID uuid.UUID,
) (*api.AgentRunCompaction, 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) BeginOperation ¶ added in v0.22.0
BeginOperation prevents admission after shutdown and tracks storage users. The caller must invoke finish after its last access to runtime resources.
func (*Runtime) CancelAgentRuns ¶ added in v0.21.0
CancelAgentRuns stops every running child agent in one session and reports how many it signalled. Each child records its own cancellation as it ends.
func (*Runtime) CancelLocalAgentRun ¶ added in v0.21.0
CancelLocalAgentRun stops one running child this runtime holds, without recording anything durably. It reports whether the child was running here. A controller records the request itself and then reaches the worker running the child through this.
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 and stops every child agent still running in it, including children of turns that already ended.
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 /api/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) GetSessionAgentRunCompaction ¶ added in v0.11.0
func (r *Runtime) GetSessionAgentRunCompaction( ctx context.Context, sessionID uuid.UUID, agentRunID uuid.UUID, compactionID uuid.UUID, ) (*api.AgentRunCompaction, error)
GetSessionAgentRunCompaction reads one immutable child compaction owned by both the session and the agent 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) ListModels ¶ added in v0.12.0
ListModels returns the model catalogue available to this runtime. A normal controller supplies Registry, while a minimal embedding may deliberately supply only a resolver and therefore publishes an empty catalogue rather than guessing at model metadata.
func (*Runtime) ListSessionAgentRunCompactions ¶ added in v0.11.0
func (r *Runtime) ListSessionAgentRunCompactions( ctx context.Context, sessionID uuid.UUID, agentRunID uuid.UUID, params api.ListSessionAgentRunCompactionsParams, ) (*api.AgentRunCompactionPage, error)
ListSessionAgentRunCompactions returns one child's compaction lineage, newest first.
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) ListSessionAgentRunMessages ¶ added in v0.11.0
func (r *Runtime) ListSessionAgentRunMessages( ctx context.Context, sessionID uuid.UUID, agentRunID uuid.UUID, params api.ListSessionAgentRunMessagesParams, ) (*api.AgentRunMessagePage, error)
ListSessionAgentRunMessages returns one child agent run's own durable transcript, oldest first, with the same bounded limit/offset paging the session transcript uses.
The rows are the child's, never the session's, so a caller reading them can never see parent transcript records through this route.
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 /api/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) ListSessionFeed ¶ added in v0.26.0
func (r *Runtime) ListSessionFeed( ctx context.Context, params api.ListSessionFeedParams, ) (*session.FeedPage, int32, error)
ListSessionFeed returns a page of a session's merged feed sequence as the store holds it, never converted to the API shape here.
The HTTP layer renders each item with the same function it uses for a live frame, so a replayed row and the frame a connected client saw for it can never read differently. Converting here would create a second renderer.
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) PauseSessionWorkflows ¶ added in v0.25.0
PauseSessionWorkflows retains unfinished work and cancels its activities. It releases the current root turn so another request can start new work.
func (*Runtime) PublishEvent ¶
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) ResolveHarness ¶ added in v0.22.0
ResolveHarness returns a fresh snapshot without running a provider call.
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.
A message for a session whose turn is running or starting joins that turn's queue and returns at once with Queued set. Messages for one session are admitted one at a time, but only until each is admitted: a started turn lets the next message in once its opening events are out and its queue accepts messages, not when it ends.
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) SessionID ¶ added in v0.7.0
SessionID returns the durable session assigned to this runtime's configured workspace, which a turn uses when the caller names no session.
It is uuid.Nil on a control-surface runtime, which has no configured workspace. A caller that gets uuid.Nil must name the session it means.
func (*Runtime) SetWakeRunner ¶ added in v0.15.1
func (r *Runtime) SetWakeRunner(runner WakeRunner)
SetWakeRunner routes woken turns through runner instead of this runtime. Without one, the runtime runs woken turns itself, which is right only when it is the process that runs the session's turns.
func (*Runtime) Shutdown ¶ added in v0.22.0
Shutdown refuses new work, drains admitted calls, then stops children and jobs. A deadline cancels admitted calls and leaves resources open for retry.
func (*Runtime) ShutdownAgentRuns ¶ added in v0.21.0
ShutdownAgentRuns stops every running child agent this runtime started and waits for each to record how it ended, or for ctx to end. Children run on goroutines of this process, so none may outlive it unrecorded.
func (*Runtime) ShutdownJobs ¶
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 {
// WorkflowManaged leaves child recovery to the native workflow worker.
WorkflowManaged bool
Logger *slog.Logger
CommandRunner commander.Commander
Filesystem workspacefs.FS
VirtualFilesystem bool
DisableProcessTools bool
HookCallback hooks.Callback
HookCommandRunner hooks.CommandRunner
Tools []elelem.Tool
DisableTools []string
// MCP holds the session's MCP server connections. Its ready servers'
// tools join every agent's tool set. Nil means no MCP. The caller owns
// it and closes it after Shutdown.
MCP *mcptools.Manager
// ObserveEvent receives durable root and child events independently of a
// single turn's sink. It must return promptly and must not block producers.
ObserveEvent func(uuid.UUID, Event)
// Store is the durable surface this runtime writes through. The control
// plane passes its SQLite store; a worker passes the protocol-backed one,
// which forwards every record to the controller.
Store session.Storage
Resolver HarnessResolver
Models ModelResolver
RootAgent string
DefaultModel string
// WorkerGenerationID names the worker process this runtime runs inside, so
// every turn, event, job, and child run it records says which process
// produced it. The direct pkg/peen form leaves it zero.
WorkerGenerationID uuid.UUID
// DefaultWorkspace opens one session as the runtime is built and makes it
// the session a turn runs against when the caller names none. It is how an
// embedding Go program gets a one-workspace runtime from pkg/peen.
//
// The control surface leaves it empty. That runtime starts with no session
// rows, and every turn must name the session it belongs to, because a
// controller serves many workspaces and must not guess which one a client
// meant.
DefaultWorkspace string
// StartupSessionID attaches this runtime to a session that already exists.
// A worker gets it from the launch document, because its controller
// resolved the workspace and created the session before the worker
// started. Resolving a workspace is a control-plane operation, so a worker
// that tried to open one would be refused.
StartupSessionID uuid.UUID
// MaxContextTokens is the whole context window a request may use, prompt
// and reply together.
MaxContextTokens int
// OutputReserveTokens is the room kept for the reply inside
// MaxContextTokens, so the prompt gets the difference. Zero keeps none.
OutputReserveTokens int
// ModelRequestTimeout bounds each model request: a turn's rounds and a
// compaction summary. A turn has no overall time limit.
ModelRequestTimeout 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
AppendSystemPrompt string
// DisableBaseSystemPrompt leaves out the embedded default, so an empty
// BaseSystemPrompt with no SYSTEM.md gives an empty base prompt.
DisableBaseSystemPrompt bool
// AutoEvolve adds a section telling the agent to save skills and rules it
// learns in the workspace's .agents/learned, and in LearnedDirectory when
// WritableLearnedDirectory is set. WritableConfigDirectory also tells it
// that it may change the files in ConfigDirectory.
AutoEvolve bool
LearnedDirectory string
WritableLearnedDirectory bool
WritableConfigDirectory bool
// MaxSystemPromptBytes bounds a request's own prompt text. Zero takes the
// package default.
MaxSystemPromptBytes int
// MaxSystemPromptPercent refuses a turn or a child launch whose assembled
// system prompt, estimated in tokens, is over this share of
// MaxContextTokens. Zero takes the package default; negative turns the
// check off.
MaxSystemPromptPercent int
// MaxImagesPerMessage and MaxImageBytes bound the images one message or
// one readFile call carries. Zero takes the package default.
MaxImagesPerMessage int
MaxImageBytes 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 caps the space a summary gets. Zero takes the
// package default.
CompactionOutputTokens int
// CompactionSummaryPercent is the share of MaxContextTokens a summary
// gets, up to CompactionOutputTokens. Zero takes the package default.
CompactionSummaryPercent int
// ToolLimits bounds every host tool result. Zero fields take the package
// defaults.
ToolLimits tools.Limits
// CommandEnvironment is the base environment of every command the agent
// runs, as KEY=VALUE entries. Nil means the process environment. A worker
// passes its own environment without the controller's secrets.
CommandEnvironment []string
// 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 call of any tool except runCommand and waitJob,
// hooks included. Those two are bounded by the wait they ask for.
ToolTimeout time.Duration
// MaxToolResultTokens bounds one tool result before it enters context.
MaxToolResultTokens int
// MaxTurnTokens fails a turn, or a child agent's run, before a model
// round once its rounds have billed this many tokens. Zero sets no limit.
MaxTurnTokens int64
// HookCommandTimeout bounds an executable hook action that sets no timeout
// of its own. Zero takes the 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
// HookStateRoot is a writable runtime-owned root for session hook state. A
// worker supplies its private socket mount because the config mount is
// read-only.
HookStateRoot string
// MaxEventWakesPerHour bounds how often events may start turns for one
// session. Zero or negative disables the bound.
MaxEventWakesPerHour int
// AskTimeout bounds how long the ask tool waits for an answer. The model
// cannot change it. Zero waits up to the messaging tools' cap.
AskTimeout time.Duration
// 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 launchAgent: 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.
func RuntimeOptionsFromConfig ¶ added in v0.8.0
func RuntimeOptionsFromConfig( deployment config.Config, models ModelResolver, metricRegistry *metrics.Metrics, ) RuntimeOptions
RuntimeOptionsFromConfig maps a deployment's configuration onto the runtime.
Both the control plane and a session worker build a runtime from the same configuration, so this mapping lives here rather than in either of them. Two copies is how a setting gets wired in one place and forgotten in the other.
Store and Resolver are left zero. The control plane fills them from its own SQLite handle, and a worker fills them with the protocol-backed store and its own resolver, because a worker never opens the controller's database.
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)
// ListSessionFeed returns raw store items rather than an API page, so the
// HTTP layer can render each one with the same function a live frame
// uses. The second return is the resolved limit, defaulted when the
// caller sent none, since session.FeedPage carries no limit of its own.
ListSessionFeed(
ctx context.Context,
params api.ListSessionFeedParams,
) (*session.FeedPage, int32, 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 launchAgent invocation about to run.
type TurnOrigin ¶
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 {
ExpectedStopRevision *int64
SessionID *uuid.UUID
RequestID uuid.UUID
Message string
// Images follow Message in the turn's first user message.
Images []MessageImage
Workspace string
Model string
// ReasoningEffort is the reasoning level for this turn's model calls.
// Empty leaves the provider default. Elelem drops the level for a model
// that cannot take one.
ReasoningEffort elelem.ReasoningEffort
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.
type WakeRunner ¶ added in v0.15.1
WakeRunner runs a turn a session event started. A controller sets one that sends the turn to the session's worker, so a woken turn runs under the session's agent space and streams to clients like any other turn.
Source Files
¶
- agentinbox.go
- agentmessages.go
- agentrun.go
- agentruncompaction.go
- agentrunsapi.go
- agentruntranscriptapi.go
- agentschemas.go
- api.go
- assemble.go
- assemblesession.go
- autoevolve.go
- childbootstrap.go
- childcallbackfinish.go
- childcallbackphases.go
- childcallbacks.go
- childcallbackscope.go
- childcompaction.go
- childconversation.go
- childfactory.go
- childfinish.go
- childinbox.go
- childmodel.go
- childmodelprojection.go
- childphasebuffer.go
- childphaseevents.go
- childphaseparent.go
- childphaseprojection.go
- childpreparation.go
- childrecovery.go
- childrecoveryinbox.go
- childrecoveryprompt.go
- childrecoverytools.go
- childregistry.go
- childrestoration.go
- childresumetools.go
- childsubmission.go
- childtool.go
- childtoolphase.go
- childworkflowinbox.go
- childworkflowpreparation.go
- childworkflowquestion.go
- compaction.go
- compactionhookcallbacks.go
- compactionprompt.go
- converters.go
- deferredevents.go
- deferredroot.go
- directorycontinuation.go
- directorygate.go
- directoryharness.go
- directoryphase.go
- directoryreplay.go
- directorytools.go
- directoryworkflow.go
- durablejobobserver.go
- durablereadsapi.go
- errors.go
- eventsapi.go
- executioncontroltools.go
- executionresolutiontools.go
- executiontools.go
- filesystem.go
- idlewake.go
- imageinput.go
- imageread.go
- inboxprojection.go
- injectedtags.go
- jobsapi.go
- jobschemas.go
- launchagent.go
- lifecycle.go
- mcp.go
- messageimages.go
- metrics.go
- metricstool.go
- modelaudit.go
- nativechildmessages.go
- openingnotices.go
- promptbudget.go
- providers.go
- reasoning.go
- reconstruction.go
- rootbootstrap.go
- rootcallbackfinish.go
- rootcallbackgate.go
- rootcallbackpause.go
- rootcallbacks.go
- rootcallbackscope.go
- rootcompaction.go
- rootconversation.go
- rootfactory.go
- rootfinalprojection.go
- rootinbox.go
- rootmodelprojection.go
- rootmodelrequest.go
- rootmodelstream.go
- rootopening.go
- rootphasebuffer.go
- rootphaseprojection.go
- rootpreparation.go
- rootrestoration.go
- rootstream.go
- rootstreamtools.go
- rootsubmission.go
- rootsubmissionfailure.go
- rootterminalhooks.go
- roottoolactivity.go
- roottoolphase.go
- rootworkflowquestion.go
- runtime.go
- runtimeconfig.go
- scopedrules.go
- sessionevents.go
- skillactivation.go
- skillmessages.go
- skills.go
- skillschemas.go
- stopadmission.go
- streamoffset.go
- systemprompt.go
- toolhooks.go
- toolnames.go
- tooloutput.go
- tools.go
- toolschemas.go
- turnendnotices.go
- turnstream.go
- types.go
- userqueue.go
- userqueueadmission.go
- wake.go
- workflow.go
- workflowactivities.go
- workflowclient.go
- workflowcompactingmodel.go
- workflowcompaction.go
- workflowcompactionhooks.go
- workflowcompactionprefix.go
- workflowcompactionrestore.go
- workflowcompactionstate.go
- workflowcontinuation.go
- workflowcontrol.go
- workflowdeferred.go
- workflowdelivery.go
- workflowdispatch.go
- workflowfailedhooks.go
- workflowfinish.go
- workflowhandoff.go
- workflowhookstate.go
- workflowinboxacceptance.go
- workflowinboxqueue.go
- workflowmodel.go
- workflowmodeldelivery.go
- workflowmodelprojection.go
- workflownativestop.go
- workflownotification.go
- workflowopening.go
- workflowpassivewait.go
- workflowphased.go
- workflowphasedelivery.go
- workflowphaseexecution.go
- workflowphasehooks.go
- workflowphasestream.go
- workflowphasevalidation.go
- workflowpreparation.go
- workflowquestiondelivery.go
- workflowquestionwake.go
- workflowresume.go
- workflowrunner.go
- workflowskillmerge.go
- workflowskills.go
- workflowstate.go
- workflowsubmission.go
- workflowterminal.go
- workflowtool.go
- workflowtoollimits.go
- workflowtoolphases.go
- workflowturncompaction.go
- workflowtypes.go
- workflowworker.go