chat

package
v0.1.0-alpha.68 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: GPL-3.0 Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package chat orchestrates local LLM turns into app-level semantic actions.

Index

Constants

View Source
const (
	// MotionActionNone leaves motion unchanged.
	MotionActionNone = "none"
	// MotionActionStart starts motion through the motion engine.
	MotionActionStart = "start"
	// MotionActionTarget retargets already running motion through the motion engine.
	MotionActionTarget = "target"
	// MotionActionUpdate retargets active dynamic geometry through the motion engine.
	MotionActionUpdate = "update"
	// MotionActionStop stops motion through the motion engine.
	MotionActionStop = "stop"
)
View Source
const (
	// DynamicSpanProfileSteady holds one stroke length.
	DynamicSpanProfileSteady = "steady"
	// DynamicSpanProfileBreathe produces a slow coherent swell.
	DynamicSpanProfileBreathe = "breathe"
	// DynamicSpanProfileWander produces smooth correlated range changes.
	DynamicSpanProfileWander = "wander"
	// DynamicSpanProfileContrast groups tight, medium, and broad strokes.
	DynamicSpanProfileContrast = "contrast"
)
View Source
const (
	AreaZoneTip   = "tip"
	AreaZoneShaft = "shaft"
	AreaZoneBase  = "base"
	AreaZoneFull  = "full"
)

Named area-focus zones the model may request. "full" explicitly clears an active focus.

View Source
const (
	MessageRoleUser      = "user"
	MessageRoleAssistant = "assistant"
)

Message roles accepted by the visible chat log.

View Source
const (
	MessagePageMaxBytes = 256 << 10
	MessagePreviewBytes = 16 << 10
)

MessagePageMaxBytes includes the HTTP envelope. Preview limits apply only to history reads; canonical content and model prompt policies remain unchanged.

View Source
const (
	ModelCheckPass = "pass"
	ModelCheckWarn = "warn"
	ModelCheckFail = "fail"
	ModelCheckSkip = "skip"
)

Model check verdicts.

View Source
const (
	ModelCheckReasoning = "reasoning"
	ModelCheckContract  = "contract"
	ModelCheckTruncated = "truncation"
	ModelCheckSpeed     = "speed"
	ModelCheckVerbosity = "verbosity"
	ModelCheckRefusals  = "refusals"
)

Model check item IDs the scripted turns decide.

View Source
const (
	// DefaultPromptSetID is the bundled behavior profile used when the selected
	// set is missing.
	DefaultPromptSetID = "magichandy_motion_v1"

	// PromptSetIDSpanish is the built-in Spanish behavior profile.
	PromptSetIDSpanish = "magichandy_motion_v1_es"
	// PromptSetIDPortugueseBrazil is the built-in Brazilian Portuguese behavior profile.
	PromptSetIDPortugueseBrazil = "magichandy_motion_v1_pt_br"
	// PromptSetIDSimplifiedChinese is the built-in Simplified Chinese behavior profile.
	PromptSetIDSimplifiedChinese = "magichandy_motion_v1_zh_hans"
	// PromptSetIDJapanese is the built-in Japanese behavior profile.
	PromptSetIDJapanese = "magichandy_motion_v1_ja"
)
View Source
const (
	LabMethodStrokeEnds = "stroke_ends"
	LabMethodGroove     = "groove"
	LabMethodPlainWords = "plain_words"
)

The stroke Lab modes test three model-facing vocabularies over one stroke score (motion.StrokeSpec): numeric turn points, a groove with accents, and plain words. They share the engine and differ only in what the model writes, so live results compare vocabularies rather than generators.

View Source
const (
	ChatCursorCap = appstore.ChatCursorLimit
)

Cursor retention bounds bookkeeping independently from the message window. Eviction loses only a read marker; it cannot delete messages or grant access.

View Source
const ContractInstructions = contractBase + "\n" + contractPatternSection + "\n" + contractAreaSection

ContractInstructions is the full-capability response contract appended to every system prompt by code. User-editable prompt sets can change persona and tone, but never this contract (IMPLEMENTATION_PLAN.md Phase 10 rule). Capability gates compose reduced variants via contractInstructions.

View Source
const FailureRetention = 24

FailureRetention bounds all sessions together; failed attempts are never conversation messages and cannot reach model history, mood or speech.

View Source
const MessageContentChunkBytes = 64 << 10

MessageContentChunkBytes bounds each materialized download chunk. No database connection or read transaction is retained while its bytes reach a client.

View Source
const MessageLogCap = 200

MessageLogCap bounds a display page; retaining longer conversations must not enlarge browser pages or the local model's prompt.

View Source
const MessageRetentionCap = 1000

MessageRetentionCap bounds persisted messages per session, independently of display pages and the selected model's input window.

View Source
const MotionLabPrompt = `` /* 1263-byte string literal not displayed */

MotionLabPrompt is a deliberately isolated experimental contract. It cannot emit a motion action and is never appended to the production chat prompt.

View Source
const PromptHistoryLimit = 64

PromptHistoryLimit retains up to 32 exchanges from the canonical session. A separate byte bound keeps verbose sessions from consuming the context.

Variables

View Source
var (
	ErrPromptSetNotFound  = errors.New("prompt set not found")
	ErrPromptSetProtected = errors.New("built-in prompt sets are read-only; duplicate one to edit it")
	ErrPromptSetInvalid   = errors.New("invalid prompt set")
	ErrPromptSetLimit     = errors.New("prompt set limit reached")
)

Library errors distinguish protection from absence for API status codes.

View Source
var (
	ErrChatSessionNotFound    = errors.New("chat session not found")
	ErrActiveSessionDelete    = errors.New("the active chat session cannot be deleted")
	ErrUnsavedSessionConflict = errors.New("the active unsaved chat must be saved or discarded first")
)

Session lifecycle errors returned by MessageLog mutations.

View Source
var ErrChatMessageNotFound = errors.New("chat message is no longer available; reload the conversation")

ErrChatMessageNotFound covers missing, pending and superseded message identities.

Functions

func ApplyLayeredEdit

func ApplyLayeredEdit(edit LayeredEdit, current motion.FlowSpec, limits config.MotionSettings) (motion.FlowSpec, error)

ApplyLayeredEdit merges an edit transactionally. A rejected edit never mutates the original score, including its layer backing array.

func AreaZones

func AreaZones() []string

AreaZones lists the accepted area values in prompt order.

func AutopilotDecisionMessage

func AutopilotDecisionMessage(context AutopilotContext) string

AutopilotDecisionMessage remains as a compatibility alias for callers that only need the motion prompt.

func AutopilotMotionMessage

func AutopilotMotionMessage(context AutopilotContext) string

AutopilotMotionMessage renders one motion-planning turn. Its strict model contract has no reply field; the independent speech clock owns spoken lines.

func AutopilotSpeechMessage

func AutopilotSpeechMessage(context AutopilotContext, authority ...Capabilities) string

AutopilotSpeechMessage renders the independent autonomous speech turn.

func ComposeSystem

func ComposeSystem(set PromptSet, memories []string) string

ComposeSystem builds the full system prompt: behavior text from the set, then the code-owned contract, then enabled memories when present.

func ComposeSystemForTest

func ComposeSystemForTest(set PromptSet, memories []string, capabilities Capabilities, context *ConversationContext) string

ComposeSystemForTest exposes the full composition path, including the conversation context, so a caller in another package can assert what the model actually receives. Production code reaches this through the service.

func ComposeSystemWithCapabilities

func ComposeSystemWithCapabilities(set PromptSet, memories []string, patterns []PatternChoice, capabilities Capabilities) string

ComposeSystemWithCapabilities composes the system prompt for the enabled capability set: disabled control methods are never described to the model.

func ComposeSystemWithMotionContext

func ComposeSystemWithMotionContext(set PromptSet, memories []string, patterns []PatternChoice, capabilities Capabilities, context MotionContext) string

ComposeSystemWithMotionContext adds the authoritative semantic motion state for one interactive turn. The state is code-owned data, not chat history.

func ComposeSystemWithPatterns

func ComposeSystemWithPatterns(set PromptSet, memories []string, patterns []PatternChoice) string

ComposeSystemWithPatterns appends enabled catalog data after the immutable contract with every capability enabled. Pattern labels are untrusted data; only IDs are selectable.

func CreativeV2CharacterUnchanged

func CreativeV2CharacterUnchanged(before, after motion.FlowSpec) bool

CreativeV2CharacterUnchanged is shared by scheduled Lab and production turns. Realization seeds are intentionally excluded from this semantic comparison.

func CreativeV2ContinuationMessage

func CreativeV2ContinuationMessage() string

CreativeV2ContinuationMessage is the Creative v2 Autopilot planning policy shared by production and the Lab. The model judges which recent human words still shape the motion.

func CreativeV2ResponseSchema

func CreativeV2ResponseSchema(limits config.MotionSettings, mood bool) json.RawMessage

CreativeV2ResponseSchema is identical in production and the prompt Lab.

func DefaultLayeredScore

func DefaultLayeredScore(speed int) motion.FlowSpec

DefaultLayeredScore varies reach, location and pace on independent time scales.

func DynamicAnchorNames

func DynamicAnchorNames() []string

DynamicAnchorNames lists the compact anchor vocabulary in travel order.

func DynamicAnchorPosition

func DynamicAnchorPosition(name string) (int, bool)

DynamicAnchorPosition resolves one model-facing anchor to semantic position.

func DynamicSpanProfiles

func DynamicSpanProfiles() []string

DynamicSpanProfiles lists the compact range-envelope vocabulary exposed to local models. It is duplicated at the chat boundary to keep chat independent of the motion package.

func FreshCreativeV2Score

func FreshCreativeV2Score(speed int) motion.FlowSpec

FreshCreativeV2Score selects a new replayable realization. The model edits the semantic grammar, never the random seed or generated point sequence.

func FreshLayeredScore

func FreshLayeredScore(speed int) motion.FlowSpec

FreshLayeredScore gives a new conversation its own irregular realization. The chosen seed is retained with the score for faithful plots and replay.

func FreshStrokeLabScore

func FreshStrokeLabScore(limits config.MotionSettings) motion.FlowSpec

FreshStrokeLabScore is the stroke modes' starting score with a fresh seed: long strokes around the middle that breathe at a medium pace. Every vocabulary can state it exactly, so the model reads back clean values.

func InteractiveResponseSchema

func InteractiveResponseSchema(patterns []PatternChoice, capabilities Capabilities, state *MotionContext) json.RawMessage

InteractiveResponseSchema is shared by production and prompt inspection.

func IsStrokeLabMethod

func IsStrokeLabMethod(method string) bool

IsStrokeLabMethod reports whether a Lab method edits a stroke score.

func LLMLabPrompts

func LLMLabPrompts() map[string]string

LLMLabPrompts isolates experimental control interfaces from production prompting.

func LLMLabPromptsFor

func LLMLabPromptsFor(schemaUnenforced bool) map[string]string

LLMLabPromptsFor returns the Lab prompts that match production for a provider, omitting the reach guide where the response schema may be ignored.

func LLMLabSchema

func LLMLabSchema(method string, limits config.MotionSettings) json.RawMessage

LLMLabSchema constrains syntax, field names and numeric ranges, not intent. The same strict semantic parser still runs for schema-guided and plain JSON.

func LayeredContinuationMessage

func LayeredContinuationMessage() string

LayeredContinuationMessage is the Layered Autopilot planning policy shared by production and the Lab.

func LayeredResponseSchema

func LayeredResponseSchema(limits config.MotionSettings, mood bool) json.RawMessage

LayeredResponseSchema shares one compact contract between live chat and Labs.

func ModelCheckMaxAverageWords

func ModelCheckMaxAverageWords(length ReplyLength) int

ModelCheckMaxAverageWords is the reply length a model should keep to for each length setting before the check suggests a shorter one.

func ParseLLMLab

func ParseLLMLab(raw, method string, current motion.FlowSpec, limits config.MotionSettings) (string, motion.FlowSpec, []string, error)

ParseLLMLab merges only explicit valid changes into the authoritative score.

func ParseStrokeLab

func ParseStrokeLab(raw, method string, current motion.FlowSpec, limits config.MotionSettings) (string, motion.FlowSpec, []string, error)

ParseStrokeLab merges one reply's explicit edits into the stroke score. An invalid value rejects the whole reply; nothing is repaired or inferred.

func PatternResponseSchema

func PatternResponseSchema(patterns []PatternChoice, capabilities Capabilities, state *MotionContext) json.RawMessage

PatternResponseSchema constrains chat-only replies or the compact library action vocabulary, according to this turn's capabilities. Intent, lifecycle authority and actual motion still pass normal validation. It never supplies a missing action or selects a pattern.

func PlanningHistory

func PlanningHistory(history []llm.Message, at []time.Time, now time.Time) []llm.Message

PlanningHistory marks each human line in a continuous planning turn's history with how long ago it was said. Planning replies are never dialogue, so the person's last line stays the latest user turn for minutes. Without the age the model read an old "that's too much" as a new reaction to the pace it had chosen since, and cut the pace again. Only human lines are marked, and a planning reply is never published, so the mark is not spoken. When any time is unknown, the history is returned unchanged.

func RepairPrompt

func RepairPrompt(prompt PromptSet, parseError string) string

RepairPrompt asks the same model to replace malformed output with the contract.

func SelectRecentUserRequests

func SelectRecentUserRequests(lines []string) []string

SelectRecentUserRequests returns the latest non-blank human lines, oldest first. Every kind of message counts: whether a line is a motion direction, a standing wish or small talk is for the model to judge in context, not for a word list to decide before it sees them.

func StrokeLabContinuationMessage

func StrokeLabContinuationMessage(method string) string

StrokeLabContinuationMessage is the Lab Autopilot policy for a stroke mode. It reuses the production continuous judgment: recent requests shape the motion, and the model develops what they leave open.

func StrokeLabSchema

func StrokeLabSchema(method string, limits config.MotionSettings) json.RawMessage

StrokeLabSchema constrains syntax, names and ranges, not intent. The strict parser still runs on schema-guided and plain output alike.

func TechnicalAutopilotSchema

func TechnicalAutopilotSchema(patterns []PatternChoice, capabilities Capabilities, state *MotionContext) json.RawMessage

TechnicalAutopilotSchema shares the existing semantic vocabulary without composing a persona, memories, or conversation into the cloud request.

func UserRequestTimeline

func UserRequestTimeline(lines []RecentUserRequest, now time.Time) ([]string, []int)

UserRequestTimeline splits recent lines into the texts and ages a motion context carries. Ages are omitted unless every line has a time, so a model is never shown a guessed age.

func ValidateUserMessage

func ValidateUserMessage(message string) (string, error)

ValidateUserMessage normalizes one user turn before either persistence or model generation so both paths enforce the same byte limit.

func WithoutCreativeV2ReachGuide

func WithoutCreativeV2ReachGuide(prompt string) string

WithoutCreativeV2ReachGuide returns a Creative v2 prompt as it was before the shared reach guide, so evaluation tools can reproduce that baseline.

Types

type AssistantResponse

type AssistantResponse struct {
	Reply   string         `json:"reply"`
	NewMood *Mood          `json:"new_mood,omitempty"`
	Motion  *MotionCommand `json:"motion,omitempty"`
	// StayUnchanged is a live continuous-chat turn's reading of a standing
	// wish while Autopilot composes: true when the human wants the motion to
	// stay exactly as it is from now on, false otherwise. The model interprets
	// the conversation; the host only remembers the answer and holds Autopilot
	// motion while it stands. Autopilot's own turns never set it.
	StayUnchanged *bool `json:"stay_unchanged,omitempty"`
	// contains filtered or unexported fields
}

AssistantResponse is the only model output shape accepted by MagicHandy.

func ParseAssistantResponse

func ParseAssistantResponse(raw string) (AssistantResponse, error)

ParseAssistantResponse validates one strict JSON response from the model.

func ParseAssistantResponseWithPatterns

func ParseAssistantResponseWithPatterns(raw string, patterns []PatternChoice) (AssistantResponse, error)

ParseAssistantResponseWithPatterns accepts only the supplied enabled IDs.

func ParseCreativeV2Reply

func ParseCreativeV2Reply(raw string, current motion.FlowSpec, limits config.MotionSettings) (AssistantResponse, motion.FlowSpec, []string, error)

ParseCreativeV2Reply merges an explicit partial edit transactionally. The complete score is kept behind the same internal continuous-motion handoff as Layered; the two model vocabularies remain disjoint.

func ParseLayeredReply

func ParseLayeredReply(raw string, current motion.FlowSpec, limits config.MotionSettings) (AssistantResponse, motion.FlowSpec, []string, error)

ParseLayeredReply is the shared Lab/production contract. It keeps the raw rejected proposal intact for callers; no inferred repair or preset is applied.

type AutopilotContext

type AutopilotContext struct {
	// Hosted selects guidance for API models. It is resolved from the provider,
	// never from the person's words; local prompt bytes stay unchanged.
	Hosted bool
	// Technical marks a planning turn that is shown motion state only: no
	// conversation, persona or memory. It replaces guidance that depends on the
	// person's words with what the motion history alone can say.
	Technical bool
	// LastHumanSecondsAgo, when known, is how long ago the person last spoke.
	// Continuous planning uses it to judge how long a slow stretch has lasted.
	LastHumanSecondsAgo *int
	// RecentSpeeds lists recent stretch speeds and how long ago each began,
	// oldest first.
	RecentSpeeds         []SpeedStep
	Style                string
	SegmentIndex         int
	RecentPatternIDs     []string
	SpeedMinPercent      int
	SpeedMaxPercent      int
	LastSay              string
	CurrentPatternID     string
	CurrentSpeed         int
	CurrentArea          string
	AreaFocusEnabled     bool
	MotionMode           MotionMode
	CurrentCenter        int
	CurrentSpan          int
	CurrentSpanMin       int
	CurrentSpanProfile   string
	CurrentAnchors       []string
	CurrentVariation     int
	CurrentSegment       int
	CurrentSectionCount  int
	CurrentFlow          *motion.FlowSpec
	CommandedMeanTravel  int
	CommandedPeakSpeed   int
	CommandedPositionMin int
	CommandedPositionMax int
	MeanStrokeLength     int
	LocalStrokeCV        int
	LocalStrokeRange     int
	RecentPositionBands  []PositionBand
	MotionFeedback       string
	MotionMinSeconds     int
	MotionMaxSeconds     int
	MotionChangeLevel    int
	// AutoTiming asks a hosted planner for next_check_seconds in place of the
	// soon/normal/later category. RecentCheckSeconds lists its recent choices,
	// oldest first, as observations.
	AutoTiming         bool
	RecentCheckSeconds []int
	// SessionTracking gates the session facts below. When false they are
	// omitted from the prompt entirely rather than rendered as zeros, so the model
	// cannot reason from a number that means "unknown".
	SessionTracking          bool
	SessionSeconds           int
	SecondsAtCurrentSpeed    int
	SecondsAtCurrentPhrase   int
	DecisionsAtCurrentPhrase int
	ConsecutiveHolds         int
	SpeedTrend               string
	// ArcEnabled gates the visible session buildup. Disabled means the buildup is
	// never described, so the model cannot act on progress the user was not shown.
	ArcEnabled bool
	ArcPercent int
}

AutopilotContext is bounded semantic context for an autonomous model turn. It contains no transport or engine details.

type AutopilotKind

type AutopilotKind string

AutopilotKind selects one of the two independent autonomous model contracts.

const (
	// AutopilotKindMotion selects the motion-only planning contract.
	AutopilotKindMotion AutopilotKind = "motion"
	// AutopilotKindSpeech selects the independent spoken-check-in contract.
	AutopilotKindSpeech AutopilotKind = "speech"
)

type AutopilotResponse

type AutopilotResponse struct {
	Reply string
	// Intent is a short planning handle for motion-only turns. Asking the model
	// to name a concept before numbers reduces copy-the-current-target behavior;
	// it is diagnostic context, not executable motion.
	Intent string
	Motion *MotionCommand
	Next   AutopilotTiming
	// Variability is how much the target should wander before the next boundary.
	// Motion turns require the model to choose it explicitly so a scheduler hold
	// cannot acquire backend-invented movement after the model answered.
	Variability string
	// NextCheckSeconds is an auto-timing planner's own horizon; zero means the
	// scheduler samples its window. The scheduler varies and bounds it.
	NextCheckSeconds int
}

AutopilotResponse is a validated motion-plan or speech-check-in response.

func ParseTechnicalAutopilot

func ParseTechnicalAutopilot(raw string, patterns []PatternChoice, capabilities Capabilities, state *MotionContext) (AutopilotResponse, error)

ParseTechnicalAutopilot uses production validation, without repair/fallback.

type AutopilotService

type AutopilotService struct {
	Provider              llm.Provider
	Prompt                PromptSet
	Model                 string
	MaxTokens             int
	ReasoningMode         string
	ReasoningBudgetTokens int
	PromptBudget          PromptBudgetSettings
	// Temperature lets the motion-change preference widen or narrow model
	// exploration without turning qualitative geometry into fixed presets.
	// Zero preserves the ordinary chat-tuned default.
	Temperature         float64
	Memories            []string
	Patterns            []PatternChoice
	MotionContext       *MotionContext
	ConversationContext *ConversationContext
	Capabilities        Capabilities
}

AutopilotService runs the dedicated autonomous contracts through the same provider, personalization, history and semantic motion validation used by interactive chat. Hosted output is held on failure; local output may repair.

func (AutopilotService) Complete

func (s AutopilotService) Complete(ctx context.Context, kind AutopilotKind, request Request) (AutopilotResponse, error)

Complete runs one autonomous decision, with one repair for local output.

type AutopilotTiming

type AutopilotTiming string

AutopilotTiming is a semantic timing preference. Deterministic scheduler code maps it into the user's bounded cadence window; the model never emits seconds.

const (
	// AutopilotTimingSoon asks the scheduler to sample from the early window.
	AutopilotTimingSoon AutopilotTiming = "soon"
	// AutopilotTimingNormal asks the scheduler to sample from the middle window.
	AutopilotTimingNormal AutopilotTiming = "normal"
	// AutopilotTimingLater asks the scheduler to sample from the late window.
	AutopilotTimingLater AutopilotTiming = "later"
)

type Capabilities

type Capabilities struct {
	// HostedMotion selects hosted planning guidance and the exclusive Layered
	// set/adjust contract. It changes representation, never motion authority.
	// Local runtimes retain their compact prompts and controls/change_by edits.
	HostedMotion bool
	// SchemaUnenforced marks a provider that may ignore the response schema,
	// such as an external OpenAI-compatible server. Its Creative v2 contract
	// omits the reach guide: without the schema, local Gemma 12B wrote
	// malformed edits with the guide (31/42 against 40/42 valid).
	SchemaUnenforced bool
	// PreserveConversationText keeps included canonical messages verbatim for
	// an explicitly selected hosted full-conversation role.
	PreserveConversationText bool
	// Hosted history budgets are resolved per connection. Local composition
	// ignores these fields and retains its existing prompt and runtime cost.
	HistoryMessages      int
	HistoryBytes         int
	Motion               bool
	MotionMode           MotionMode
	Patterns             bool
	AreaFocus            bool
	ExperimentalPatterns bool
	Voice                VoiceLevel
	// Style is the active persona's reaction style, or StyleNeutral. It sits
	// beside Voice because it is the same kind of thing: a reply-shaping axis
	// with no motion authority.
	Style ReactionStyle
	// MoodTracking permits inert reply-register metadata for interactive,
	// non-utility chat. It never grants a motion capability.
	MoodTracking bool
	// MotionHolder says what owns the device when a turn is chat-only for a
	// reason other than Settings, so the reply can say who drives.
	MotionHolder MotionHolder
	// ReplyLength steers the reply's length; the zero value composes nothing.
	ReplyLength ReplyLength
	// AutoTiming asks an Autopilot motion turn for next_check_seconds, its own
	// reconsideration horizon. Only hosted planning routes set it: small local
	// models settle on one value, so their cadence stays backend-sampled.
	AutoTiming bool
}

Capabilities mirrors the user's prompt-composition settings: the checkbox gates for post-parse enforcement plus the selected reply voice. The zero value is chat-only in the utility voice; callers resolve defaults from settings.

func FullCapabilities

func FullCapabilities() Capabilities

FullCapabilities matches the historical always-on behavior plus area focus.

type ConversationContext

type ConversationContext struct {
	PersonaDescription     string
	PersonaName            string
	PersonaLore            []string
	UserAnatomy            string
	CustomAnatomy          string
	CurrentMood            Mood
	RecentAssistantReplies []string
}

ConversationContext is backend-owned continuity and bounded profile data for one turn. It stays separate from MotionContext so reply metadata cannot enter semantic motion validation.

type DisplayMessage

type DisplayMessage struct {
	Seq       int64  `json:"seq"`
	Role      string `json:"role"`
	Content   string `json:"content"`
	Truncated bool   `json:"truncated"`
}

DisplayMessage contains only user-visible conversation text, never prompts, diagnostics, speech IDs or browser attribution.

type DynamicSectionCommand

type DynamicSectionCommand struct {
	CenterPercent    *int     `json:"center_percent,omitempty"`
	SpanPercent      *int     `json:"span_percent,omitempty"`
	SpanMinPercent   *int     `json:"span_min_percent,omitempty"`
	SpanProfile      string   `json:"span_profile,omitempty"`
	Anchors          []string `json:"anchors,omitempty"`
	VariationPercent *int     `json:"variation_percent,omitempty"`
	Cycles           int      `json:"cycles"`
}

DynamicSectionCommand is one semantic movement idea in a compact Creative phrase. It intentionally duplicates the small geometry vocabulary at the chat boundary so the chat package remains independent of the motion engine.

type EarlierScore

type EarlierScore struct {
	Flow              motion.FlowSpec
	StartedSecondsAgo int
	PlayedSeconds     int
}

EarlierScore is a distinct score that played earlier in this Autopilot session, newest first in a MotionContext.

type FailureContent

type FailureContent struct {
	Raw       string `json:"raw_response"`
	RepairRaw string `json:"repair_response,omitempty"`
	Prompt    string `json:"system_prompt"`
	Schema    string `json:"response_schema"`
	Truncated bool   `json:"truncated"`
}

FailureContent is redacted before storage and omitted from default reports.

type LLMLabTrial

type LLMLabTrial struct {
	Autopilot     bool                  `json:"autopilot,omitempty"`
	MotionApplied bool                  `json:"motion_applied,omitempty"`
	MotionError   string                `json:"motion_error,omitempty"`
	Message       string                `json:"message"`
	Reply         string                `json:"reply"`
	Raw           string                `json:"raw"`
	Error         string                `json:"error,omitempty"`
	Valid         bool                  `json:"valid"`
	Changed       []string              `json:"changed"`
	Model         string                `json:"model"`
	Method        string                `json:"method"`
	Prompt        string                `json:"prompt"`
	ElapsedMillis int64                 `json:"elapsed_ms"`
	ProviderCalls int                   `json:"provider_calls"`
	SchemaGuided  bool                  `json:"schema_guided"`
	RecipeName    string                `json:"recipe_name,omitempty"`
	Before        motion.FlowSpec       `json:"before"`
	After         motion.FlowSpec       `json:"after"`
	Limits        config.MotionSettings `json:"limits"`
}

LLMLabTrial retains raw failures as evidence, without repair or fallback.

func RunLLMLab

func RunLLMLab(ctx context.Context, provider llm.Provider, model, method, prompt, message string, current motion.FlowSpec, limits config.MotionSettings, history []llm.Message, schemaGuided bool) LLMLabTrial

RunLLMLab uses one inference request and a strict semantic parser. It has no engine or transport access and never writes the production conversation.

type LayeredEdit

type LayeredEdit struct {
	Geometry     string                     `json:"geometry,omitempty"`
	StrokeWidth  *LayeredStrokeWidth        `json:"stroke_width,omitempty"`
	Controls     map[string]json.RawMessage `json:"controls,omitempty"`
	ChangeBy     map[string]json.RawMessage `json:"change_by,omitempty"`
	Layers       []LayeredLayerEdit         `json:"layers,omitempty"`
	RemoveLayers []string                   `json:"remove_layers,omitempty"`
	Evolve       bool                       `json:"evolve,omitempty"`
}

LayeredEdit describes changes to a persistent continuous score. It contains no device commands, playback clock, ordered sections or turnaround shaping.

type LayeredFollow

type LayeredFollow struct {
	Axis     string `json:"axis"`
	Relation string `json:"relation"`
}

LayeredFollow materializes an explicit timing relationship into the score. It interprets only a model-selected operation, never conversation text.

type LayeredLayerEdit

type LayeredLayerEdit struct {
	Axis               string         `json:"axis"`
	AmountPercent      *int           `json:"amount_percent,omitempty"`
	PeriodCycles       *int           `json:"period_cycles,omitempty"`
	PeriodChangeCycles *int           `json:"period_change_cycles,omitempty"`
	PhasePercent       *int           `json:"phase_percent,omitempty"`
	Shape              *string        `json:"shape,omitempty"`
	LowRatePercent     *int           `json:"low_rate_percent,omitempty"`
	Inverted           *bool          `json:"inverted,omitempty"`
	Follow             *LayeredFollow `json:"follow,omitempty"`
}

LayeredLayerEdit updates only supplied attributes of one modulation axis.

type LayeredStrokeWidth

type LayeredStrokeWidth struct {
	MinPercent int `json:"min_percent"`
	MaxPercent int `json:"max_percent"`
}

LayeredStrokeWidth pairs the shortest and widest requested stroke.

type LogMessage

type LogMessage struct {
	Seq                int64               `json:"seq"`
	Revision           int64               `json:"revision,omitempty"`
	Role               string              `json:"role"`
	Content            string              `json:"content"`
	ClientID           string              `json:"client_id,omitempty"`
	CreatedAt          string              `json:"created_at"`
	Diagnostics        *MessageDiagnostics `json:"diagnostics,omitempty"`
	SpeechRequestID    string              `json:"speech_request_id,omitempty"`
	ContentBytes       int64               `json:"content_bytes,omitempty"`
	ContentTruncated   bool                `json:"content_truncated,omitempty"`
	DiagnosticsOmitted bool                `json:"diagnostics_omitted,omitempty"`
}

LogMessage is one visible row in a chat session.

type MessageContentChunk

type MessageContentChunk struct {
	Data       []byte
	TotalBytes int64
}

MessageContentChunk contains at most one bounded slice of canonical UTF-8 bytes.

type MessageDiagnostics

type MessageDiagnostics struct {
	Source                string `json:"source,omitempty"`
	Provider              string `json:"provider,omitempty"`
	Model                 string `json:"model,omitempty"`
	PromptSet             string `json:"prompt_set,omitempty"`
	RefusalFallbackFrom   string `json:"refusal_fallback_from,omitempty"`
	RefusalFallbackModel  string `json:"refusal_fallback_model,omitempty"`
	DeclinedRequestMillis int64  `json:"declined_request_ms,omitempty"`
	// PersonaID and PersonaName record who the reply came from. Storing the name
	// alongside the id is what lets the transcript stay readable after a persona
	// is renamed or deleted, and it is what a mid-conversation persona divider is
	// derived from — no new message role required.
	PersonaID              string `json:"persona_id,omitempty"`
	PersonaName            string `json:"persona_name,omitempty"`
	RequestMillis          int64  `json:"request_ms,omitempty"`
	PreparationMillis      int64  `json:"preparation_ms,omitempty"`
	SchedulerWaitMillis    int64  `json:"scheduler_wait_ms,omitempty"`
	FirstTokenMillis       int64  `json:"first_token_ms,omitempty"`
	FirstActivityMillis    int64  `json:"first_activity_ms,omitempty"`
	ModelLoadMillis        int64  `json:"model_load_ms,omitempty"`
	PromptEvalMillis       int64  `json:"prompt_eval_ms,omitempty"`
	PromptTokens           int    `json:"prompt_tokens,omitempty"`
	CachedPromptTokens     int    `json:"cached_prompt_tokens,omitempty"`
	GeneratedTokens        int    `json:"generated_tokens,omitempty"`
	GenerationMillis       int64  `json:"generation_ms,omitempty"`
	RepairMillis           int64  `json:"repair_ms,omitempty"`
	ProviderCalls          int    `json:"provider_calls,omitempty"`
	PromptBytes            int    `json:"prompt_bytes,omitempty"`
	PromptLimitBytes       int    `json:"prompt_limit_bytes,omitempty"`
	HistoryMessagesDropped int    `json:"history_messages_dropped,omitempty"`
	Repaired               bool   `json:"repaired,omitempty"`
	SemanticFallback       bool   `json:"semantic_fallback,omitempty"`
	InitialMalformed       bool   `json:"initial_malformed,omitempty"`
	MotionAction           string `json:"motion_action,omitempty"`
	Mood                   Mood   `json:"mood,omitempty"`
	MoodChanged            bool   `json:"mood_changed,omitempty"`
}

MessageDiagnostics is the non-secret provenance retained with one visible assistant reply. Prompts, memories, request bodies, and credentials never enter this payload.

type MessageLog

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

MessageLog owns chat sessions, their bounded messages, and per-client, per-session cursors in the process datastore.

func OpenMessageLog

func OpenMessageLog(dataDir string) (*MessageLog, error)

OpenMessageLog opens a chat log that owns its datastore connection.

func OpenMessageLogWithDatabase

func OpenMessageLogWithDatabase(database *dbstore.DB) (*MessageLog, error)

OpenMessageLogWithDatabase opens a chat log over the process datastore.

func (*MessageLog) ActivateSession

func (l *MessageLog) ActivateSession(id string, discardCurrentUnsaved bool) (Session, error)

ActivateSession selects one tab and optionally discards the prior unsaved tab.

func (*MessageLog) ActiveSessionID

func (l *MessageLog) ActiveSessionID() (string, error)

ActiveSessionID returns the singleton workspace's selected session.

func (*MessageLog) ActiveSessionIDContext

func (l *MessageLog) ActiveSessionIDContext(ctx context.Context) (string, error)

ActiveSessionIDContext is the request-cancellable form of ActiveSessionID.

func (*MessageLog) AdvanceCursor

func (l *MessageLog) AdvanceCursor(clientID string, seq int64) (int64, error)

AdvanceCursor moves a client's active-session cursor monotonically forward.

func (*MessageLog) AdvanceCursorSession

func (l *MessageLog) AdvanceCursorSession(clientID, sessionID string, seq int64) (int64, error)

AdvanceCursorSession moves a client's selected-session cursor forward.

func (*MessageLog) AdvanceCursorSessionContext

func (l *MessageLog) AdvanceCursorSessionContext(ctx context.Context, clientID, sessionID string, seq int64) (int64, error)

AdvanceCursorSessionContext is the cancelable legacy sequence-only update.

func (*MessageLog) AdvanceReadCursorContext

func (l *MessageLog) AdvanceReadCursorContext(ctx context.Context, clientID, sessionID string, seq int64, revision *int64) (ReadCursor, error)

AdvanceReadCursorContext cancels while waiting for the writer and clamps both read markers to current committed bounds. Passive retries of an unchanged marker avoid rewriting it or renewing its retention timestamp.

func (*MessageLog) After

func (l *MessageLog) After(after int64, limit int) ([]LogMessage, error)

After returns active-session messages after a sequence number.

func (*MessageLog) AfterSession

func (l *MessageLog) AfterSession(sessionID string, after int64, limit int) ([]LogMessage, error)

AfterSession returns selected-session messages after a sequence number.

func (*MessageLog) AfterSessionContext

func (l *MessageLog) AfterSessionContext(ctx context.Context, sessionID string, after int64, limit int) ([]LogMessage, error)

AfterSessionContext is the request-cancellable form of AfterSession.

func (*MessageLog) Append

func (l *MessageLog) Append(role string, content string, clientID string) (int64, error)

Append adds to the active session. New code that binds a streaming request to a session should use AppendTo so a tab switch cannot redirect its reply.

func (*MessageLog) AppendPendingAssistantContext

func (l *MessageLog) AppendPendingAssistantContext(ctx context.Context, sessionID, content string, diagnostics *MessageDiagnostics) (int64, error)

AppendPendingAssistantContext allows autonomous publication to leave a busy writer queue when its run is canceled. Interactive durable commits retain their existing background-context contract.

func (*MessageLog) AppendPendingAssistantTo

func (l *MessageLog) AppendPendingAssistantTo(sessionID, content string, diagnostics *MessageDiagnostics) (int64, error)

AppendPendingAssistantTo stages one generated reply. Reads and cap pruning ignore it until CommitPending makes the row visible.

func (*MessageLog) AppendTo

func (l *MessageLog) AppendTo(sessionID, role, content, clientID string, diagnostics *MessageDiagnostics) (int64, error)

AppendTo adds one visible message to the selected session.

func (*MessageLog) Clear

func (l *MessageLog) Clear() error

Clear resets every chat session and cursor. It is test support; settings reset intentionally does not erase conversations.

func (*MessageLog) Close

func (l *MessageLog) Close() error

Close releases the datastore only when the log opened it.

func (*MessageLog) CommitPending

func (l *MessageLog) CommitPending(seq int64) error

CommitPending atomically exposes one staged assistant reply and applies the per-session cap. A Stop that wins the caller's commit barrier deletes the staged row instead, so a canceled reply cannot evict visible history.

func (*MessageLog) CommitPendingContext

func (l *MessageLog) CommitPendingContext(ctx context.Context, seq int64) error

CommitPendingContext is the cancelable autonomous counterpart to CommitPending.

func (*MessageLog) ConversationHeadContext

func (l *MessageLog) ConversationHeadContext(ctx context.Context, sessionID string) (seq, revision int64, err error)

ConversationHeadContext reads display and recovery heads in one snapshot.

func (*MessageLog) CreateSession

func (l *MessageLog) CreateSession(discardCurrentUnsaved bool) (Session, error)

CreateSession selects a new unsaved conversation. discardCurrentUnsaved is used only after explicit UI confirmation; saved sessions are never deleted.

func (*MessageLog) Cursor

func (l *MessageLog) Cursor(clientID string) (int64, error)

Cursor returns a client's read position for the active session.

func (*MessageLog) CursorSession

func (l *MessageLog) CursorSession(clientID, sessionID string) (int64, error)

CursorSession returns a client's read position for one session.

func (*MessageLog) CursorSessionContext

func (l *MessageLog) CursorSessionContext(ctx context.Context, clientID, sessionID string) (int64, error)

CursorSessionContext is the request-cancellable form of CursorSession.

func (*MessageLog) Delete

func (l *MessageLog) Delete(seq int64) error

Delete removes one message by its process-wide sequence number.

func (*MessageLog) DeleteSession

func (l *MessageLog) DeleteSession(id string) error

DeleteSession removes an inactive retained tab and its dependent rows.

func (*MessageLog) Failure

func (l *MessageLog) Failure(ctx context.Context, sessionID string, id int64, includeContent bool) (RequestFailure, error)

Failure fetches private model content only when explicitly requested.

func (*MessageLog) Failures

func (l *MessageLog) Failures(ctx context.Context, sessionID string) ([]RequestFailure, error)

Failures reads a bounded metadata list for one conversation, newest first.

func (*MessageLog) FailuresForExport

func (l *MessageLog) FailuresForExport(ctx context.Context, includeContent bool) ([]SessionFailure, error)

FailuresForExport reads the retained failure ring across the shared workspace. Callers enforce host-administrator access and explicitly select private content.

func (*MessageLog) LatestSeq

func (l *MessageLog) LatestSeq() (int64, error)

LatestSeq returns the active session's newest sequence number.

func (*MessageLog) LatestSeqSession

func (l *MessageLog) LatestSeqSession(sessionID string) (int64, error)

LatestSeqSession returns one session's newest sequence number.

func (*MessageLog) LatestSeqSessionContext

func (l *MessageLog) LatestSeqSessionContext(ctx context.Context, sessionID string) (int64, error)

LatestSeqSessionContext is the request-cancellable form of LatestSeqSession.

func (*MessageLog) PromptContext

func (l *MessageLog) PromptContext(sessionID string) (SessionPromptContext, error)

PromptContext returns the effective mood and latest assistant lines for one session. Values are projected and bounded for prompts; stored replies remain unchanged.

func (*MessageLog) ReadMessageContentChunkContext

func (l *MessageLog) ReadMessageContentChunkContext(ctx context.Context, sessionID string, seq, revision, offset int64) (MessageContentChunk, error)

ReadMessageContentChunkContext releases the database before returning the chunk.

func (*MessageLog) ReadMessagePageContext

func (l *MessageLog) ReadMessagePageContext(ctx context.Context, request MessagePageRequest) (MessagePage, error)

ReadMessagePageContext bounds materialized rows and encoded message bytes without taking the application's write gate. Bounds, rows and cursor share a read transaction, which ends before any HTTP response write.

func (*MessageLog) ReadPromptContext

func (l *MessageLog) ReadPromptContext(ctx context.Context, sessionID string) (SessionPromptContext, error)

ReadPromptContext is the request-cancellable form of PromptContext.

func (*MessageLog) Recent

func (l *MessageLog) Recent(limit int) ([]LogMessage, error)

Recent returns the active session's newest messages in chronological order.

func (*MessageLog) RecentDisplayMessages

func (l *MessageLog) RecentDisplayMessages(ctx context.Context, sessionID string) ([]DisplayMessage, error)

RecentDisplayMessages reads a bounded tail of committed messages. Both row count and content are bounded in SQLite before Go allocates the result.

func (*MessageLog) RecentPromptHistoryContext

func (l *MessageLog) RecentPromptHistoryContext(ctx context.Context, sessionID string, messageLimit, byteLimit int) ([]LogMessage, int, error)

RecentPromptHistoryContext bounds materialized text as well as rows before building a hosted request. Large old imports must not allocate hundreds of megabytes merely because a provider can see more messages. A one-byte probe distinguishes a full message from an oversized one; partial text is never returned to the model. Visible history uses its independent paged reader.

func (*MessageLog) RecentSession

func (l *MessageLog) RecentSession(sessionID string, limit int) ([]LogMessage, error)

RecentSession returns one session's newest messages in chronological order.

func (*MessageLog) RecentSessionContext

func (l *MessageLog) RecentSessionContext(ctx context.Context, sessionID string, limit int) ([]LogMessage, error)

RecentSessionContext is the request-cancellable form of RecentSession.

func (*MessageLog) RecentUserRequestTimelineContext

func (l *MessageLog) RecentUserRequestTimelineContext(ctx context.Context, sessionID string) ([]RecentUserRequest, error)

RecentUserRequestTimelineContext reads bounded human intent, with when each line was said, within the caller's lifetime.

func (*MessageLog) RecentUserRequests

func (l *MessageLog) RecentUserRequests(sessionID string) ([]string, error)

RecentUserRequests keeps bounded human intent available independently of automated assistant check-ins. The session's normal message retention applies.

func (*MessageLog) ReconcileShutdown

func (l *MessageLog) ReconcileShutdown(keepUnsaved bool) error

ReconcileShutdown removes an unsaved working conversation during a clean shutdown unless the user explicitly chose to retain it. Startup performs the same reconciliation because a killed process cannot run this hook.

func (*MessageLog) ReconcileStartup

func (l *MessageLog) ReconcileStartup(startupBehavior string, keepUnsaved bool) (Session, error)

ReconcileStartup applies the configured restart policy once when the server opens its persistent domains. Saved sessions are never removed.

func (*MessageLog) SaveFailure

func (l *MessageLog) SaveFailure(ctx context.Context, sessionID string, failure RequestFailure) (int64, error)

SaveFailure retains only a bounded diagnostic record; it publishes no reply.

func (*MessageLog) SaveSession

func (l *MessageLog) SaveSession(id string) (Session, error)

SaveSession marks one tab for retention across process starts.

func (*MessageLog) Session

func (l *MessageLog) Session(id string) (Session, error)

Session returns one retained tab and its current summary.

func (*MessageLog) SessionContext

func (l *MessageLog) SessionContext(ctx context.Context, id string) (Session, error)

SessionContext is the request-cancellable form of Session.

func (*MessageLog) SessionPersona

func (l *MessageLog) SessionPersona(sessionID string) (string, error)

SessionPersona returns the persona bound to one session, or empty.

func (*MessageLog) SessionPersonaContext

func (l *MessageLog) SessionPersonaContext(ctx context.Context, sessionID string) (string, error)

SessionPersonaContext reads a session's binding with the caller's lifetime.

func (*MessageLog) Sessions

func (l *MessageLog) Sessions() ([]Session, error)

Sessions lists retained tabs in stable creation order.

func (*MessageLog) SessionsContext

func (l *MessageLog) SessionsContext(ctx context.Context) ([]Session, error)

SessionsContext is the request-cancellable form of Sessions.

func (*MessageLog) SetSessionPersona

func (l *MessageLog) SetSessionPersona(sessionID, personaID string) (Session, error)

SetSessionPersona records which persona a conversation is held with. An empty id clears the binding back to the global axis values.

It deliberately does not touch updated_at: that column orders the tab strip, and changing who you are talking to is not the same event as the conversation gaining a message.

type MessagePage

type MessagePage struct {
	SessionID      string           `json:"session_id"`
	Messages       []LogMessage     `json:"messages"`
	LatestSeq      int64            `json:"latest_seq"`
	FirstSeq       int64            `json:"first_seq"`
	Revision       int64            `json:"revision"`
	NextRevision   int64            `json:"next_revision"`
	Snapshot       *MessageSnapshot `json:"snapshot,omitempty"`
	HasMore        bool             `json:"has_more"`
	Reset          bool             `json:"reset"`
	HistoryGap     bool             `json:"history_gap"`
	HistoryLimit   int              `json:"history_limit"`
	Cursor         int64            `json:"cursor"`
	CursorRevision int64            `json:"cursor_revision"`
}

MessagePage describes one short database snapshot. NextRevision covers only delivered changes. Snapshot, when present, must accompany the next request so a partial reset below a deletion marker does not restart the same first page.

type MessagePageRequest

type MessagePageRequest struct {
	SessionID     string
	ClientID      string
	AfterSequence int64
	AfterRevision *int64
	Snapshot      *MessageSnapshot
	Limit         int
	RecentOnly    bool
}

MessagePageRequest chooses legacy display order or committed recovery order.

type MessageSnapshot

type MessageSnapshot struct {
	Revision       int64 `json:"revision"`
	PrunedRevision int64 `json:"pruned_revision"`
	FirstSeq       int64 `json:"first_seq"`
}

MessageSnapshot is a stateless continuation, not an access credential. Its pruning marker detects removal even when the removed row predates the head.

type ModelCheckItem

type ModelCheckItem struct {
	ID     string `json:"id"`
	Status string `json:"status"`
}

ModelCheckItem is one verdict the model check reports.

func JudgeModelCheckTurns

func JudgeModelCheckTurns(summary ModelCheckSummary, judgement ModelCheckJudgement) []ModelCheckItem

JudgeModelCheckTurns turns the summary into verdicts, in display order.

type ModelCheckJudgement

type ModelCheckJudgement struct {
	// MaxAverageWords flags replies that run longer than the chosen length.
	MaxAverageWords int
	// AdultVoice enables the refusal check; a utility voice never asks for
	// adult content, so refusals there are not a model problem.
	AdultVoice bool
}

ModelCheckJudgement tunes how the turns are judged for the saved settings.

type ModelCheckSummary

type ModelCheckSummary struct {
	Turns                   int     `json:"turns"`
	FirstTry                int     `json:"first_try"`
	Repaired                int     `json:"repaired"`
	Failed                  int     `json:"failed"`
	Truncated               int     `json:"truncated"`
	Refused                 int     `json:"refused"`
	ReasoningChars          int     `json:"reasoning_chars"`
	ThinkingMarkup          int     `json:"thinking_markup"`
	AverageMillis           int64   `json:"average_millis"`
	AverageFirstTokenMillis int64   `json:"average_first_token_millis"`
	AverageWords            int     `json:"average_words"`
	TokensPerSecond         float64 `json:"tokens_per_second"`
}

ModelCheckSummary totals the scripted turns.

func SummarizeModelCheckTurns

func SummarizeModelCheckTurns(turns []ModelCheckTurn) ModelCheckSummary

SummarizeModelCheckTurns totals the turns.

type ModelCheckTurn

type ModelCheckTurn struct {
	Message          string `json:"message"`
	Reply            string `json:"reply,omitempty"`
	Motion           string `json:"motion,omitempty"`
	Millis           int64  `json:"millis"`
	FirstTokenMillis int64  `json:"first_token_millis"`
	ValidJSON        bool   `json:"valid_json"`
	FirstTry         bool   `json:"first_try"`
	Repaired         bool   `json:"repaired"`
	Failed           bool   `json:"failed"`
	Truncated        bool   `json:"truncated"`
	Refused          bool   `json:"refused"`
	ReasoningChars   int    `json:"reasoning_chars"`
	ThinkingMarkup   bool   `json:"thinking_markup"`
	Words            int    `json:"words"`
	DecodeTokens     int    `json:"decode_tokens"`
	DecodeMillis     int64  `json:"decode_millis"`
	Error            string `json:"error,omitempty"`
}

ModelCheckTurn is one scripted turn's outcome. The reply is kept so the user can judge the voice; hidden reasoning is only ever counted.

func RunModelCheckTurns

func RunModelCheckTurns(ctx context.Context, service Service, onTurn func(ModelCheckTurn)) ([]ModelCheckTurn, error)

RunModelCheckTurns sends the scripted conversation through service, which the caller configures exactly like a chat turn. Motion in the replies is summarized and never applied: nothing here reaches the motion engine.

type Mood

type Mood string

Mood is model-reported reply-register state. It is inert metadata and never enters MotionCommand, MotionContext, or transport dispatch.

const (
	MoodCurious      Mood = "Curious"
	MoodTeasing      Mood = "Teasing"
	MoodPlayful      Mood = "Playful"
	MoodLoving       Mood = "Loving"
	MoodExcited      Mood = "Excited"
	MoodPassionate   Mood = "Passionate"
	MoodSeductive    Mood = "Seductive"
	MoodAnticipatory Mood = "Anticipatory"
	MoodBreathless   Mood = "Breathless"
	MoodDominant     Mood = "Dominant"
	MoodSubmissive   Mood = "Submissive"
	MoodVulnerable   Mood = "Vulnerable"
	MoodConfident    Mood = "Confident"
	MoodIntimate     Mood = "Intimate"
	MoodNeedy        Mood = "Needy"
	MoodOverwhelmed  Mood = "Overwhelmed"
	MoodAfterglow    Mood = "Afterglow"
)

Moods match the reviewed STGPT-RV register and remain stable JSON protocol values even when surrounding prompt prose is localized.

func Moods

func Moods() []Mood

Moods returns the accepted mood values in prompt order.

type MotionCommand

type MotionCommand struct {
	Action    string `json:"action"`
	PatternID string `json:"pattern_id,omitempty"`
	// Intensity is accepted only to decode responses produced by older prompts.
	// normalizePacing removes it before validation and dispatch.
	Intensity    *int `json:"intensity,omitempty"`
	SpeedPercent *int `json:"speed_percent,omitempty"`
	// Area optionally focuses motion on a named zone. Named zones localize to
	// bounded relative windows in deterministic code (the STGPT-RV area-focus
	// lesson: zones, never raw model-authored depth numbers).
	Area string `json:"area,omitempty"`
	// Dynamic geometry is available only in Dynamic generation mode. Pointer
	// fields preserve omitted running values without conflating zero with absent.
	CenterPercent    *int                    `json:"center_percent,omitempty"`
	SpanPercent      *int                    `json:"span_percent,omitempty"`
	SpanMinPercent   *int                    `json:"span_min_percent,omitempty"`
	SpanProfile      string                  `json:"span_profile,omitempty"`
	Anchors          []string                `json:"anchors,omitempty"`
	VariationPercent *int                    `json:"variation_percent,omitempty"`
	SegmentSeconds   *int                    `json:"segment_seconds,omitempty"`
	Sections         []DynamicSectionCommand `json:"sections,omitempty"`
	// Layered contains a complete continuous score resolved by the Layered or
	// Creative v2 contract. Gesture distinguishes v2 at admission. The original
	// geometry/library contracts cannot populate this internal handoff field.
	Layered *motion.FlowSpec `json:"layered,omitempty"`
}

MotionCommand is semantic motion intent, not a transport command.

type MotionContext

type MotionContext struct {
	UserRequests     []string
	Running          bool
	Paused           bool
	PatternID        string
	ProgramID        string
	RecentPatternIDs []string
	SpeedPercent     int
	Area             string
	SpeedMinPercent  int
	SpeedMaxPercent  int
	MotionMode       MotionMode
	CenterPercent    int
	SpanPercent      int
	SpanMinPercent   int
	SpanProfile      string
	Anchors          []string
	VariationPercent int
	SegmentSeconds   int
	SectionCount     int
	Layered          *motion.FlowSpec
	Envelope         motion.PlanningEnvelope
	// Autopilot reports that continuous Autopilot composes the motion between
	// chat turns, and StandingHold that it is holding it because the human
	// asked. Only then can live chat declare or release that wish.
	Autopilot    bool
	StandingHold bool
	// UserRequestSecondsAgo, when known, says how long ago each line in
	// UserRequests was said, in the same order. Planning uses it to judge how
	// long a requested slow stretch has lasted before rebuilding.
	UserRequestSecondsAgo []int
	// EarlierScores are distinct scores that played earlier in this Autopilot
	// session, newest first, so a person can ask for one again.
	EarlierScores []EarlierScore
}

MotionContext is the transport-neutral motion state supplied to one model turn. It contains only semantic state and the user's configured speed band; the model never receives device or transport details.

type MotionHolder

type MotionHolder string

MotionHolder names what owns the device during a chat-only turn.

const (
	// MotionHolderSettings is the zero value: the user switched LLM motion off.
	MotionHolderSettings MotionHolder = ""
	// MotionHolderVideoScript means an open video's paired script drives the device.
	MotionHolderVideoScript MotionHolder = "video_script"
	// MotionHolderVideoOff means the viewer chose no motion for the open video.
	MotionHolderVideoOff MotionHolder = "video_off"
)

type MotionLabProposal

type MotionLabProposal struct {
	Method              string `json:"method"`
	RangeAnchorPercent  *int   `json:"range_anchor_percent"`
	OutboundTimePercent *int   `json:"outbound_time_percent"`
	Explanation         string `json:"explanation"`
}

MotionLabProposal has no authority to dispatch motion or change settings.

func ProposeMotionLab

func ProposeMotionLab(ctx context.Context, provider llm.Provider, model, message, reference string) (MotionLabProposal, error)

ProposeMotionLab makes one real provider request. Failures remain visible; there is no repair, invented fallback, chat persistence or engine access.

type MotionMode

type MotionMode string

MotionMode selects the one model-facing motion vocabulary composed for a turn. The zero value preserves the legacy pattern/speed contract in tests.

const (
	// MotionModeDynamic exposes bounded model-authored geometry.
	MotionModeDynamic MotionMode = "dynamic"
	// MotionModePattern exposes enabled library pattern curation.
	MotionModePattern MotionMode = "pattern"
	// MotionModeLayered edits one persistent score with independent modulation layers.
	MotionModeLayered MotionMode = "layered"
	// MotionModeCreativeV2 generates strokes with asymmetric travel and rebounds.
	MotionModeCreativeV2 MotionMode = "creative_v2"
	// MotionModeOff keeps the model chat-only.
	MotionModeOff MotionMode = "off"
)

type MotionReview

type MotionReview struct {
	Verdict    string          `json:"verdict"`
	Confidence string          `json:"confidence"`
	Reason     string          `json:"reason"`
	Feedback   string          `json:"feedback"`
	Correction json.RawMessage `json:"correction"`
	Motion     *MotionCommand  `json:"-"`
}

MotionReview is a second opinion, not dispatch authority. The caller must still admit it against the exact live target and all current user controls.

type MotionReviewInput

type MotionReviewInput struct {
	Source         string
	Request        string
	RecentRequests []string
	Before         motion.MotionTarget
	After          motion.MotionTarget
	Limits         config.MotionSettings
	Context        MotionContext
	Autopilot      *AutopilotContext
}

MotionReviewInput describes an already accepted local choice. Reviewers see motion evidence and explicitly shared requests, never persona or memory data.

type MotionReviewService

type MotionReviewService struct {
	Provider     llm.Provider
	Model        string
	Capabilities Capabilities
	Patterns     []PatternChoice
}

MotionReviewService uses one provider call and the existing motion grammar. It cannot repair a refusal, inject conversation, or access an engine.

func (MotionReviewService) Complete

Complete scores one accepted choice without owning or dispatching motion.

type PatternChoice

type PatternChoice struct {
	ID          string
	Name        string
	Description string
	Tags        []string
	Weight      float64
}

PatternChoice is one enabled library entry exposed to the model as data.

type PositionBand

type PositionBand struct {
	Minimum int
	Maximum int
}

PositionBand is one previously compiled outer position envelope. Hidden autonomous decisions are not part of chat history, so this compact bounded memory lets the model see whether its recent range choices really differed.

type PromptBudgetSettings

type PromptBudgetSettings struct {
	ContextSize           int
	MaxOutputTokens       int
	ReasoningBudgetTokens int
}

PromptBudgetSettings lets composition reserve the smallest supported input budget before selecting memories. The final provider guard also accounts for actual schema bytes and removes old history if necessary.

type PromptComposition

type PromptComposition struct {
	Prompt           string          `json:"prompt"`
	Sections         []PromptSection `json:"sections"`
	Characters       int             `json:"characters"`
	Bytes            int             `json:"bytes"`
	MemoryCandidates int             `json:"memory_candidates"`
	MemoriesIncluded int             `json:"memories_included"`
	MemoryLimitBytes int             `json:"memory_limit_bytes"`
}

PromptComposition is the exact prompt sent to the provider plus a section index over those same bytes.

func ComposeInteractivePrompt

func ComposeInteractivePrompt(set PromptSet, memories []string, patterns []PatternChoice, capabilities Capabilities, state *MotionContext, conversation *ConversationContext, budget ...PromptBudgetSettings) PromptComposition

ComposeInteractivePrompt includes the lifecycle contract used by live chat. Autonomous planning and experimental Lab prompts intentionally use their own authority; they must not acquire interactive start permission from this path.

func ComposePrompt

func ComposePrompt(set PromptSet, memories []string, patterns []PatternChoice, capabilities Capabilities, motionContext *MotionContext, conversationContext *ConversationContext, budget ...PromptBudgetSettings) PromptComposition

ComposePrompt exposes the production composition path for inspectability. Callers receive the exact prompt and counts from the same code Service uses.

type PromptLibrary

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

PromptLibrary owns user-created prompt sets in the datastore. Built-in sets are code-defined templates and never enter the DB.

func OpenPromptLibrary

func OpenPromptLibrary(dataDir string) (*PromptLibrary, error)

OpenPromptLibrary loads user prompt sets from dataDir, recovering to an empty library if the file is unreadable or corrupt (defaults stay usable).

func OpenPromptLibraryWithDatabase

func OpenPromptLibraryWithDatabase(database *dbstore.DB) (*PromptLibrary, error)

OpenPromptLibraryWithDatabase borrows the process-owned datastore.

func (*PromptLibrary) Close

func (l *PromptLibrary) Close() error

Close releases the prompt library database handle.

func (*PromptLibrary) Create

func (l *PromptLibrary) Create(name string, system string) (PromptSet, error)

Create validates and persists a new user prompt set.

func (*PromptLibrary) Delete

func (l *PromptLibrary) Delete(id string) error

Delete removes a user prompt set. Built-in sets are protected.

func (*PromptLibrary) List

func (l *PromptLibrary) List() ([]PromptSet, error)

List returns built-in sets first, then user sets sorted by name.

func (*PromptLibrary) Recovered

func (l *PromptLibrary) Recovered() bool

Recovered reports whether an unreadable file was replaced by an empty library.

func (*PromptLibrary) Resolve

func (l *PromptLibrary) Resolve(id string) (set PromptSet, found bool, err error)

Resolve returns a built-in or user prompt set by identifier. A missing set is reported as found=false; storage failures are returned separately.

func (*PromptLibrary) ResolveContext

func (l *PromptLibrary) ResolveContext(ctx context.Context, id string) (set PromptSet, found bool, err error)

ResolveContext reads a prompt set with the caller's lifetime.

func (*PromptLibrary) Update

func (l *PromptLibrary) Update(id string, name string, system string) (PromptSet, error)

Update edits a user prompt set. Built-in sets are protected.

type PromptSection

type PromptSection struct {
	ID         string `json:"id"`
	Title      string `json:"title"`
	Text       string `json:"text"`
	Characters int    `json:"characters"`
	Bytes      int    `json:"bytes"`
}

PromptSection is one backend-composed part of the exact system prompt. The diagnostics inspector renders these values instead of reconstructing prompt state in the browser.

type PromptSet

type PromptSet struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	System  string `json:"system"`
	Builtin bool   `json:"builtin"`
}

PromptSet contains the behavior instructions for one chat profile. The machine JSON contract is never part of a set: ComposeSystem appends it in code so prompt edits cannot weaken or change it.

func BuiltinPromptSetByID

func BuiltinPromptSetByID(id string) (PromptSet, bool)

BuiltinPromptSetByID returns a bundled prompt set by identifier.

func BuiltinPromptSets

func BuiltinPromptSets() []PromptSet

BuiltinPromptSets returns the read-only bundled prompt sets.

type ReactionStyle

type ReactionStyle string

ReactionStyle selects how the assistant carries itself: who leads, whether it teases, how much it defers. It is orthogonal to VoiceLevel, which selects only how explicit the language may be — a submissive persona can be explicit and a dominant one can be chaste.

Like VoiceLevel it shapes the reply text and nothing else. No style block mentions motion, speed, patterns, zones, the device, or JSON, so a "dominant" style can never read as authority over the actuator.

const (
	// StyleNeutral composes no block at all. This is what keeps the axis inert
	// by default: a persona left on neutral produces the same prompt bytes as
	// having no persona, which is asserted by test.
	StyleNeutral ReactionStyle = "neutral"
	// StylePlayful teases lightly and initiates.
	StylePlayful ReactionStyle = "playful"
	// StyleTender is attentive, reassuring, unhurried.
	StyleTender ReactionStyle = "tender"
	// StyleDominant leads and says what happens next.
	StyleDominant ReactionStyle = "dominant"
	// StyleSubmissive follows, asks, and defers.
	StyleSubmissive ReactionStyle = "submissive"
	// StyleTeasing withholds and draws things out.
	StyleTeasing ReactionStyle = "teasing"
)

type ReadCursor

type ReadCursor struct {
	Sequence int64
	Revision int64
}

ReadCursor keeps display position distinct from committed recovery order.

type RecentUserRequest

type RecentUserRequest struct {
	Text string
	At   time.Time
}

RecentUserRequest is one recent human line and when it was committed.

func SelectRecentUserRequestTimeline

func SelectRecentUserRequestTimeline(lines []RecentUserRequest) []RecentUserRequest

SelectRecentUserRequestTimeline is SelectRecentUserRequests for lines that carry when they were said.

type ReplyLength

type ReplyLength string

ReplyLength steers how long the "reply" field runs. It shapes prose only: the motion contract and every motion gate are identical at every length.

const (
	// ReplyLengthBalanced is the zero value and composes nothing, so the
	// prompts keep the pacing they were tuned with.
	ReplyLengthBalanced ReplyLength = ""
	// ReplyLengthShort asks for one or two short sentences.
	ReplyLengthShort ReplyLength = "short"
	// ReplyLengthDetailed allows three to five sentences when the moment
	// calls for it.
	ReplyLengthDetailed ReplyLength = "detailed"
)

type Request

type Request struct {
	Message                string
	History                []llm.Message
	HistoryMessagesDropped int
}

Request is one local chat turn.

type RequestFailure

type RequestFailure struct {
	ID            int64              `json:"id"`
	CreatedAt     string             `json:"created_at"`
	Error         string             `json:"error"`
	Kind          string             `json:"kind,omitempty"`
	MotionMode    string             `json:"motion_mode"`
	ReasoningMode string             `json:"reasoning_mode"`
	MaxTokens     int                `json:"max_tokens"`
	Version       string             `json:"app_version"`
	Commit        string             `json:"app_commit"`
	Diagnostics   MessageDiagnostics `json:"diagnostics"`
	Details       *FailureContent    `json:"content,omitempty"`
}

RequestFailure contains non-secret provenance. Content is fetched explicitly.

type Result

type Result struct {
	Input            *llm.ChatRequest `json:"-"`
	Response         AssistantResponse
	Raw              string
	RepairRaw        string
	InitialMalformed bool
	Malformed        bool
	MalformedError   string
	Repaired         bool
	SemanticFallback bool
}

Result is the validated chat turn outcome.

type Service

type Service struct {
	Provider              llm.Provider
	Prompt                PromptSet
	Model                 string
	MaxTokens             int
	ReasoningMode         string
	ReasoningBudgetTokens int
	PromptBudget          PromptBudgetSettings
	Memories              []string
	Patterns              []PatternChoice
	// MotionContext is the authoritative semantic snapshot for this turn.
	// Nil is retained for non-interactive callers such as legacy tests.
	MotionContext *MotionContext
	// ConversationContext is backend-derived profile and continuity data. It
	// remains separate from request text and semantic motion validation.
	ConversationContext *ConversationContext
	// Capabilities gates which control methods the prompt advertises and the
	// result may carry. Nil preserves the historical full-capability behavior.
	Capabilities *Capabilities
	// TrustedMotionInput is reserved for backend-generated Autopilot decision
	// messages. Interactive user chat must leave this false.
	TrustedMotionInput bool
	// AutonomousTemperature is supplied only by the backend scheduler. Ordinary
	// chat keeps its reviewed sampling controls.
	AutonomousTemperature float64
	// SingleAttempt disables local repair/salvage for an explicitly bounded retry.
	SingleAttempt bool
}

Service runs chat prompts, strict validation, and repair over an LLM provider. Prompt is the resolved behavior profile; Memories are the enabled memory texts (empty when the memory switch is off; chat must work without them).

func (Service) Complete

func (s Service) Complete(ctx context.Context, request Request, emit func(StreamEvent) error) (Result, error)

Complete streams a model response, repairs malformed JSON once, and returns a validated result.

type Session

type Session struct {
	ID    string `json:"id"`
	Title string `json:"title"`
	Saved bool   `json:"saved"`
	// PersonaID is which persona this conversation is being held with, or empty
	// for the global axis values from Settings. It can name a deleted persona:
	// a past conversation should still read as the conversation it was, so
	// callers resolve a dangling id rather than the log rewriting history.
	PersonaID    string `json:"persona_id,omitempty"`
	Active       bool   `json:"active"`
	MessageCount int    `json:"message_count"`
	LatestSeq    int64  `json:"latest_seq"`
	CreatedAt    string `json:"created_at"`
	UpdatedAt    string `json:"updated_at"`
}

Session is one retained or process-local conversation tab. Exactly one row is active through the chat_workspace singleton.

type SessionFailure

type SessionFailure struct {
	SessionID string `json:"session_id"`
	RequestFailure
}

SessionFailure keeps failures associated with their conversation without reading successful messages or conversation titles into a diagnostic export.

type SessionPromptContext

type SessionPromptContext struct {
	CurrentMood            Mood
	RecentAssistantReplies []string
}

SessionPromptContext is the backend-owned per-session continuity snapshot supplied to one model turn.

type SpeedStep

type SpeedStep struct {
	SpeedPercent int
	SecondsAgo   int
	Interactive  bool
}

SpeedStep is one recent stretch's speed and how long ago it began. Interactive marks a speed the person set through chat.

type StreamEvent

type StreamEvent struct {
	Type  string
	Phase string
	Text  string
	Error string
}

StreamEvent describes chat orchestration progress.

type VoiceLevel

type VoiceLevel string

VoiceLevel selects how sexual the model's reply register may be. It shapes only the user-facing reply text: the motion contract, capability enforcement, speed limits, and Stop behavior are identical at every level.

const (
	// VoiceUtility is the original neutral motion-assistant register.
	VoiceUtility VoiceLevel = "utility"
	// VoiceWarm is a flirtatious companion: suggestive at most, never explicit.
	VoiceWarm VoiceLevel = "warm"
	// VoiceIntimate is a first-person partner voice with sensual language.
	VoiceIntimate VoiceLevel = "intimate"
	// VoiceExplicit permits direct erotic language, matching STGPT-RV's
	// partner prompts; the user opts in from Settings.
	VoiceExplicit VoiceLevel = "explicit"
)

Jump to

Keyboard shortcuts

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