peen

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2026 License: MIT Imports: 17 Imported by: 0

README

peen

pkg/peen is Peen's stable, supported programmatic entry point. It embeds the same durable agent runtime the HTTP service exposes, without starting Servicepack or an HTTP listener.

New binds the process working directory to one durable session. Every Message and Stream call uses that session, including after a restart with the same state directory and working directory.

When Message or Stream reaches a local active turn, MessageResult.Queued is true and Message is empty. The existing turn owns the eventual provider response. Queued input cannot override model or system-prompt settings, and it is not replayed automatically after a restart.

Embedding example

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/psyb0t/elelem"
	"github.com/psyb0t/elelem/drivers/openai"
	"github.com/psyb0t/peen/pkg/peen"
)

func main() {
	driver, err := openai.NewDriver(openai.WithAPIKey("your-token-here"))
	if err != nil {
		log.Fatal(err)
	}

	const modelReference = "openai/gpt-4o-mini"

	runtime, err := peen.New(peen.Options{
		ConfigDirectory: "/var/lib/peen", // must already exist
		RootAgent:       "default",
		Models: map[string]peen.ModelClient{
			modelReference: {
				Client: elelem.New(driver),
				Model:  elelem.Model{ID: "gpt-4o-mini"},
			},
		},
		DefaultModel:     modelReference,
		MaxContextTokens: 32768,
	})
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()

	result, err := runtime.Message(ctx, peen.MessageRequest{
		Message: "list the files in the current directory",
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.Message)

	// Stream the next turn from the same startup workspace session.
	_, err = runtime.Stream(ctx, peen.MessageRequest{
		Message: "now summarize what you found",
	}, func(event peen.Event) error {
		fmt.Printf("%s: %s\n", event.Type, event.Payload)

		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}

What this package does not expose

pkg/peen never leaks transcript storage internals, generated HTTP types, concrete tool implementations, Servicepack services, or provider credentials. Its exported method set is deliberately small: Message, Stream, ListMessages, Session, and Cancel.

Documentation

Overview

Package peen is Peen's stable, supported programmatic entry point.

It embeds the same durable agent runtime the HTTP service exposes, without starting Servicepack or an HTTP listener. A caller builds Options (a config directory holding the durable SQLite store plus optional SYSTEM.md, APPEND_SYSTEM.md, and COMPACTION.md overrides, a default workspace, a root agent, a named Elelem upstream registry, and qualified main and compaction model references), constructs one Runtime with New, and then:

  • collects a final answer for one turn with Message;
  • does the same while observing events as they happen with Stream;
  • reads the workspace's stored transcript with ListMessages;
  • reads the workspace's metadata with Details;
  • requests cancellation of the active turn with Cancel.

No call takes or returns a session identifier. A Runtime is one workspace and owns its durable session privately. Session IDs exist so a controller can route between many workspaces, which a direct caller never has to do.

New never reads environment variables, starts Servicepack, opens an HTTP listener, or touches global state; every dependency arrives through Options. This package does not expose transcript storage internals, generated HTTP types, concrete tool implementations, Servicepack services, or provider credentials. See README.md for a runnable embedding example.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CancelResult

type CancelResult struct {
	CancelRequested bool
}

CancelResult reports whether a cancel request was accepted.

type CompactionMode

type CompactionMode string

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

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

type Event

type Event struct {
	Type    string
	Payload json.RawMessage
}

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

type EventSink

type EventSink func(Event) error

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

type ListMessagesRequest

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

ListMessagesRequest describes one bounded transcript page request.

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

type ListMessagesResult

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

ListMessagesResult is one complete limit-offset transcript page.

type Message

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

Message is one durable transcript record.

type MessageOrder

type MessageOrder string

MessageOrder controls transcript pagination direction.

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

type MessageRequest

type MessageRequest struct {
	// Message is the user's text. It must not be empty or whitespace-only.
	Message string
	// SystemPrompt overrides or extends the base system prompt for only this
	// message.
	SystemPrompt *SystemPrompt
}

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

type MessageResult

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

MessageResult carries the final assistant message.

It names no session on purpose. This runtime is one workspace, and it owns its durable session identity privately. Session IDs are a control-plane concept: they exist so a controller can route between many workspaces, which is not a problem a direct caller has.

type MessageRole

type MessageRole string

MessageRole classifies who or what produced a transcript message.

const (
	MessageRoleUser      MessageRole = "user"
	MessageRoleAssistant MessageRole = "assistant"
	MessageRoleTool      MessageRole = "tool"
)

type MessageToolCall

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

MessageToolCall is one tool call an assistant message requested.

type ModelClient

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

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

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

type Options

type Options struct {
	// ConfigDirectory must already exist. It holds the durable SQLite store
	// plus the optional SYSTEM.md, APPEND_SYSTEM.md, and COMPACTION.md files.
	ConfigDirectory string
	// RootAgent names the base agent definition every session starts from.
	RootAgent string

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

	// MaxContextTokens bounds one turn's request budget. Zero takes the
	// package default.
	MaxContextTokens int
	// TurnTimeout bounds one turn's provider call. Zero takes the package
	// default.
	TurnTimeout time.Duration
	// MaxConcurrentTurns bounds turns running at once across every session.
	// Zero takes the internal default; negative disables the bound.
	MaxConcurrentTurns int
	// MaxMessageBytes bounds one caller-supplied message. Zero takes the
	// internal default.
	MaxMessageBytes int
	// MaxQueuedUserMessages bounds messages accepted while a session's turn is
	// active. Zero takes the internal default.
	MaxQueuedUserMessages int
	// MaxSystemPromptBytes bounds one caller-supplied system prompt. Zero
	// takes the internal default.
	MaxSystemPromptBytes int
	// MaxStoredMessageBytes bounds one durable transcript row. Zero takes the
	// internal default.
	MaxStoredMessageBytes int

	// CompactionMode selects what happens over budget. Empty takes
	// CompactionModeDropOldest.
	CompactionMode CompactionMode
	// CompactionPrompt overrides the summarizer instructions. Empty reads
	// COMPACTION.md from ConfigDirectory and otherwise takes the embedded
	// default.
	CompactionPrompt string
	// CompactionOutputTokens reserves bounded space for the summary. Zero
	// takes the internal default.
	CompactionOutputTokens int
	// CompactionTimeout bounds the separate summarization call. Zero takes
	// the internal default.
	CompactionTimeout time.Duration

	// MaxToolRounds bounds how many tool rounds one turn may run. Zero takes
	// the internal default.
	MaxToolRounds int
	// MaxConcurrentTools bounds parallel tool execution inside one round.
	// Zero takes the internal default.
	MaxConcurrentTools int
	// ToolTimeout bounds one tool call, hooks included. Zero takes the
	// internal default.
	ToolTimeout time.Duration
	// MaxToolResultTokens bounds one tool result before it enters context.
	// Zero takes the internal default.
	MaxToolResultTokens int
	// EnableWorkspaceHooks opts into executable hook actions from workspace
	// .agents/hooks.yaml files. Config-directory hooks always run.
	EnableWorkspaceHooks bool
	// HookCommandTimeout bounds one executable hook action. Zero takes the
	// internal default.
	HookCommandTimeout time.Duration
	// MaxHookCommandOutput bounds stdout or stderr from an executable hook
	// action. Zero takes the internal default.
	MaxHookCommandOutput int

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

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

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

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

type PromptMode

type PromptMode string

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

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

type Runtime

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

Runtime is Peen's embedding surface over the internal agent runtime.

The public package sketch calls for a type alias to the internal runtime, but agent.Runtime's exported method set includes RunMessage, ListSessionJobs, CancelSessionAgentRun, ShutdownJobs, and more: aliasing it would expose all of that, the opposite of the deliberately small surface this package promises. Wrapping the internal runtime behind an unexported field is how that narrow surface is actually delivered.

func New

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

New builds one Runtime from explicit, validated dependencies.

func (*Runtime) Cancel

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

Cancel requests cancellation of this workspace's active turn. It is idempotent: cancelling with no active turn reports CancelRequested false rather than failing.

func (*Runtime) Details added in v0.8.0

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

Details reads this workspace's read-only metadata.

func (*Runtime) ListMessages

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

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

func (*Runtime) Message

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

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

func (*Runtime) Stream

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

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

type SessionDetails

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

SessionDetails is this workspace's read-only metadata.

It carries no identifier on purpose. This runtime is one workspace and owns its durable session privately, so there is nothing for a caller to address. Session IDs are a control-plane concept: they exist so a controller can route between many workspaces, which is not a problem a direct caller has.

type SystemPrompt

type SystemPrompt struct {
	Content string
	Mode    PromptMode
}

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

Jump to

Keyboard shortcuts

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