chatsessionmodes

package
v0.10.2 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package chatsessionmodes routes each chat turn: resolves which chain to run, injects context, executes steps, and persists the result.

Index

Constants

This section is empty.

Variables

View Source
var DefaultChainByMode = map[string]string{
	"chat":   "default-chain.json",
	"prompt": "default-chain.json",
	"plan":   "default-chain.json",
}

DefaultChainByMode maps product mode ids to VFS chain references when ?chainId is omitted. chat: conversational default; prompt: same file until a dedicated prompt chain ships; plan: same (plan tools via plan_manager in chain JSON).

View Source
var (

	// ErrMissingModelProvider is returned when default-model / default-provider are unset and query overrides are empty.
	ErrMissingModelProvider = errors.New("missing model or provider for task chain")
)

Functions

func BuildInjectedSystemMessages

func BuildInjectedSystemMessages(ctxPayload *ContextPayload, now time.Time) ([]taskengine.Message, error)

BuildInjectedSystemMessages turns structured context into system messages.

For every artifact it:

  1. validates the kind against [artifactKindPattern];
  2. enforces the per-kind byte cap (or the global [maxArtifactPayloadBytes]);
  3. dispatches to the typed renderer from the kind registry when the kind is known, or falls back to the flat `<raw-json>` body for unknown kinds so older clients keep working;
  4. prepends the uniform `[Context kind=<kind>]` header so the LLM always sees a consistent delimiter.

The cumulative body size across all emitted messages is capped at [maxContextInjectionBytes] to prevent a pathological turn from blowing the prompt budget.

func FormatChainResultForChat

func FormatChainResultForChat(result any) string

FormatChainResultForChat turns arbitrary chain outputs into a single assistant message string.

func MergeChatHistoryPreservingInjections

func MergeChatHistoryPreservingInjections(injected []taskengine.Message, out []taskengine.Message) []taskengine.Message

MergeChatHistoryPreservingInjections ensures injected system messages appear in the persisted thread when the chain output dropped them.

func PrependInjectionsBeforeLastUser

func PrependInjectionsBeforeLastUser(thread []taskengine.Message, injected []taskengine.Message) ([]taskengine.Message, error)

PrependInjectionsBeforeLastUser splices injected system messages immediately before the last message (the new user turn).

Types

type ActivePlanInjector

type ActivePlanInjector struct {
	Plans planservice.Service
}

ActivePlanInjector injects a snapshot of the active execution plan (if any) for plan mode.

func (*ActivePlanInjector) Inject

Inject implements Injector. When there is no active plan, returns nil, nil.

type ArtifactKind

type ArtifactKind string

ArtifactKind is a typed discriminator for ContextArtifact.

The set of first-party kinds below forms the vocabulary that Beam's canvas can round-trip into the LLM context. Each has a dedicated renderer (see [renderersByKind]) that produces an LLM-friendly system-message body. Any kind that is NOT in this registry still passes the generic regex check in BuildInjectedSystemMessages and falls back to the flat format so older clients keep working.

const (
	// ArtifactKindFileExcerpt is the original UI-contributed kind: a byte-bounded
	// slice of a file selected in the Beam workspace. Payload: [FileExcerptPayload].
	ArtifactKindFileExcerpt ArtifactKind = "file_excerpt"

	// ArtifactKindTerminalOutput captures a recent block of terminal output that
	// the user chose to attach. The LLM is told this may be stale.
	// Payload: [TerminalOutputPayload].
	ArtifactKindTerminalOutput ArtifactKind = "terminal_output"

	// ArtifactKindOpenFile carries the full (still byte-bounded) content of the
	// file currently open or selected in Beam's files tree / editor.
	// Payload: [OpenFilePayload].
	ArtifactKindOpenFile ArtifactKind = "open_file"

	// ArtifactKindPlanStep carries a structured slice of plan state — one step,
	// its status, its summary handover, its optional failure class. Used when
	// the user or agent wants the agent to reason about a specific plan step.
	// Payload: [PlanStepPayload].
	ArtifactKindPlanStep ArtifactKind = "plan_step"

	// ArtifactKindCommandOutput is for structured tool-execution output (as
	// distinct from terminal chatter): typically `{command, output, exit_code}`.
	// Payload: [CommandOutputPayload].
	ArtifactKindCommandOutput ArtifactKind = "command_output"

	// ArtifactKindRuntimeState carries a named unit of taskengine runtime state
	// (from the captured-state sidebar). Payload: [RuntimeStatePayload].
	ArtifactKindRuntimeState ArtifactKind = "runtime_state"
)

func FirstPartyArtifactKinds

func FirstPartyArtifactKinds() []ArtifactKind

FirstPartyArtifactKinds returns every kind this package knows how to render natively. Useful for UI-side validation.

type ArtifactRenderer

type ArtifactRenderer func(payload json.RawMessage) (body string, err error)

ArtifactRenderer turns a raw payload into the body of a single system message. The returned string MUST NOT include the `[Context kind=…]` header — BuildInjectedSystemMessages prepends it uniformly so the LLM always sees a consistent delimiter.

type ChainResolver

type ChainResolver interface {
	Resolve(explicitChainID, mode string) (chainRef string, err error)
}

ChainResolver resolves which chain ref to load given explicit query and mode.

type ClientArtifactInjector

type ClientArtifactInjector struct{}

ClientArtifactInjector turns request context.artifacts into system messages.

func (ClientArtifactInjector) Inject

Inject implements Injector.

type CommandOutputPayload

type CommandOutputPayload struct {
	Command  string `json:"command"`
	Output   string `json:"output"`
	ExitCode *int   `json:"exit_code,omitempty"`
}

CommandOutputPayload is the structured output of a command or tool run.

type ContextArtifact

type ContextArtifact struct {
	Kind    string          `json:"kind"`
	Payload json.RawMessage `json:"payload,omitempty"`
}

ContextArtifact is one structured block merged into the thread before the user turn.

type ContextPayload

type ContextPayload struct {
	Artifacts []ContextArtifact `json:"artifacts,omitempty"`
}

ContextPayload mirrors the HTTP body; client artifacts become system messages.

type Deps

type Deps struct {
	DB                 libdbexec.DBManager
	TaskService        execservice.TasksEnvService
	ChainService       taskchainservice.Service
	PlanService        planservice.Service
	WorkspaceID        string
	ModeToDefaultChain map[string]string
}

type FileExcerptPayload

type FileExcerptPayload struct {
	Path      string `json:"path"`
	Text      string `json:"text"`
	Truncated bool   `json:"truncated,omitempty"`
}

type HTTPChat

type HTTPChat interface {
	CreateChatSession(ctx context.Context, identity string) (chatID string, startedAt time.Time, err error)
	ListChatMessages(ctx context.Context, sessionID string) ([]taskengine.Message, error)
	ListChatSessions(ctx context.Context, identity string) ([]ListedChatSession, error)
	SendTurn(ctx context.Context, in TurnInput) (*TurnResult, error)
}

HTTPChat is the method set used by internalchatapi (supports activity decoration).

func WithHTTPChatActivityTracker

func WithHTTPChatActivityTracker(svc HTTPChat, tracker libtracker.ActivityTracker) HTTPChat

WithHTTPChatActivityTracker wraps an HTTPChat with activity logging.

type InjectInput

type InjectInput struct {
	SessionID string
	Now       time.Time
	Turn      TurnInput
}

InjectInput is passed to each Injector for one turn.

type Injector

type Injector interface {
	Inject(ctx context.Context, in InjectInput) ([]taskengine.Message, error)
}

Injector adds zero or more system messages before the new user message.

type KindSpec

type KindSpec struct {
	Kind     ArtifactKind
	MaxBytes int // 0 → use maxArtifactPayloadBytes
	Render   ArtifactRenderer
}

KindSpec binds a kind to its renderer and optional per-kind limits.

type ListedChatMessage

type ListedChatMessage struct {
	ID      string
	Role    string
	Content string
	SentAt  time.Time
	IsUser  bool
}

ListedChatMessage is one row for HTTP list/history responses.

type ListedChatSession

type ListedChatSession struct {
	ID          string
	StartedAt   time.Time
	LastMessage *ListedChatMessage
}

ListedChatSession is one session row for GET /chats (list).

type MapChainResolver

type MapChainResolver struct {
	ModeToChain map[string]string
}

MapChainResolver uses DefaultChainByMode (or a copy passed at construction).

func (*MapChainResolver) Resolve

func (m *MapChainResolver) Resolve(explicitChainID, mode string) (string, error)

Resolve implements ChainResolver.

type ModeRegistry

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

ModeRegistry lists injectors to run in order for a given mode id (lowercased).

func NewDefaultModeRegistry

func NewDefaultModeRegistry(planSvc planservice.Service) *ModeRegistry

NewDefaultModeRegistry wires standard injectors: plan mode prepends ActivePlanInjector when planSvc is non-nil.

func (*ModeRegistry) Injectors

func (r *ModeRegistry) Injectors(mode string) []Injector

Injectors returns injectors for mode, defaulting to chat when unknown.

type OpenFilePayload

type OpenFilePayload struct {
	Path     string `json:"path"`
	Text     string `json:"text"`
	LineFrom int    `json:"line_from,omitempty"`
	LineTo   int    `json:"line_to,omitempty"`
}

OpenFilePayload is for the current file open/selected in Beam's files tree.

type PlanStepPayload

type PlanStepPayload struct {
	PlanID       string `json:"plan_id"`
	Ordinal      int    `json:"ordinal"`
	Description  string `json:"description"`
	Status       string `json:"status"`
	Summary      string `json:"summary,omitempty"`
	FailureClass string `json:"failure_class,omitempty"`
	LastFailure  string `json:"last_failure,omitempty"`
}

PlanStepPayload is a slice of plan state the user or agent wants to reason about.

type RuntimeStatePayload

type RuntimeStatePayload struct {
	Name string          `json:"name"`
	Data json.RawMessage `json:"data,omitempty"`
}

RuntimeStatePayload is one captured state unit pulled from the sidebar.

type Service

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

func New

func New(deps Deps) *Service

func (*Service) CreateChatSession

func (s *Service) CreateChatSession(ctx context.Context, identity string) (chatID string, startedAt time.Time, err error)

CreateChatSession allocates a new chat session index for the given identity.

func (*Service) ListChatMessages

func (s *Service) ListChatMessages(ctx context.Context, sessionID string) ([]taskengine.Message, error)

ListChatMessages returns all messages for a session (chronological).

func (*Service) ListChatSessions

func (s *Service) ListChatSessions(ctx context.Context, identity string) ([]ListedChatSession, error)

ListChatSessions returns sessions for an identity with optional last-message preview.

func (*Service) SendTurn

func (s *Service) SendTurn(ctx context.Context, in TurnInput) (*TurnResult, error)

SendTurn runs load history → inject → execute → persist.

type TerminalOutputPayload

type TerminalOutputPayload struct {
	SessionID  string `json:"session_id,omitempty"`
	Command    string `json:"command,omitempty"`
	Output     string `json:"output"`
	CapturedAt string `json:"captured_at,omitempty"`
	Truncated  bool   `json:"truncated,omitempty"`
}

TerminalOutputPayload captures a user-attached block of terminal output.

type TurnInput

type TurnInput struct {
	SessionID string
	Message   string
	// ExplicitChainRef is the chainId query param when set (wins over Mode).
	ExplicitChainRef string
	// SummarizerChainRef is required for build-mode turns (they compile a plan DAG
	// whose per-step terminals feed a summarizer subgraph). Ignored by other modes.
	SummarizerChainRef string
	Mode               string
	Context            *ContextPayload
	Model              string
	Provider           string
	RequestID          string
}

TurnInput is everything needed to run one user message through the chain engine.

type TurnResult

type TurnResult struct {
	Response         string
	State            []taskengine.CapturedStateUnit
	InputTokenCount  int
	OutputTokenCount int
}

TurnResult is the successful chat turn outcome (errors are returned as Go errors from SendTurn).

Jump to

Keyboard shortcuts

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