Documentation
¶
Overview ¶
Package chat orchestrates local LLM turns into app-level semantic actions.
Index ¶
- Constants
- Variables
- func ApplyLayeredEdit(edit LayeredEdit, current motion.FlowSpec, limits config.MotionSettings) (motion.FlowSpec, error)
- func AreaZones() []string
- func AutopilotDecisionMessage(context AutopilotContext) string
- func AutopilotMotionMessage(context AutopilotContext) string
- func AutopilotSpeechMessage(context AutopilotContext) string
- func ComposeSystem(set PromptSet, memories []string) string
- func ComposeSystemForTest(set PromptSet, memories []string, capabilities Capabilities, ...) string
- func ComposeSystemWithCapabilities(set PromptSet, memories []string, patterns []PatternChoice, ...) string
- func ComposeSystemWithMotionContext(set PromptSet, memories []string, patterns []PatternChoice, ...) string
- func ComposeSystemWithPatterns(set PromptSet, memories []string, patterns []PatternChoice) string
- func CreativeV2CharacterUnchanged(before, after motion.FlowSpec) bool
- func CreativeV2ContinuationMessage(requests []string) string
- func CreativeV2ResponseSchema(limits config.MotionSettings, mood bool) json.RawMessage
- func DefaultLayeredScore(speed int) motion.FlowSpec
- func DynamicAnchorNames() []string
- func DynamicAnchorPosition(name string) (int, bool)
- func DynamicSpanProfiles() []string
- func FreshCreativeV2Score(speed int) motion.FlowSpec
- func FreshLayeredScore(speed int) motion.FlowSpec
- func HasMotionDirection(requests []string) bool
- func LLMLabPrompts() map[string]string
- func LLMLabSchema(method string, limits config.MotionSettings) json.RawMessage
- func LayeredAutopilotMessage() string
- func LayeredContinuationMessage(requests []string) string
- func LayeredExactHoldRequested(requests []string) bool
- func LayeredResponseSchema(limits config.MotionSettings, mood bool) json.RawMessage
- func ParseLLMLab(raw, method string, current motion.FlowSpec, limits config.MotionSettings) (string, motion.FlowSpec, []string, error)
- func PatternResponseSchema(patterns []PatternChoice, capabilities Capabilities, state *MotionContext) json.RawMessage
- func RepairPrompt(prompt PromptSet, parseError string) string
- func ValidateUserMessage(message string) (string, error)
- type AssistantResponse
- func ParseAssistantResponse(raw string) (AssistantResponse, error)
- func ParseAssistantResponseWithPatterns(raw string, patterns []PatternChoice) (AssistantResponse, error)
- func ParseCreativeV2Reply(raw string, current motion.FlowSpec, limits config.MotionSettings) (AssistantResponse, motion.FlowSpec, []string, error)
- func ParseLayeredReply(raw string, current motion.FlowSpec, limits config.MotionSettings) (AssistantResponse, motion.FlowSpec, []string, error)
- type AutopilotContext
- type AutopilotKind
- type AutopilotResponse
- type AutopilotService
- type AutopilotTiming
- type Capabilities
- type ConversationContext
- type DynamicSectionCommand
- type LLMLabTrial
- type LayeredEdit
- type LayeredLayerEdit
- type LayeredStrokeWidth
- type LogMessage
- type MessageDiagnostics
- type MessageLog
- func (l *MessageLog) ActivateSession(id string, discardCurrentUnsaved bool) (Session, error)
- func (l *MessageLog) ActiveSessionID() (string, error)
- func (l *MessageLog) AdvanceCursor(clientID string, seq int64) (int64, error)
- func (l *MessageLog) AdvanceCursorSession(clientID, sessionID string, seq int64) (int64, error)
- func (l *MessageLog) After(after int64, limit int) ([]LogMessage, error)
- func (l *MessageLog) AfterSession(sessionID string, after int64, limit int) ([]LogMessage, error)
- func (l *MessageLog) Append(role string, content string, clientID string) (int64, error)
- func (l *MessageLog) AppendPendingAssistantTo(sessionID, content string, diagnostics *MessageDiagnostics) (int64, error)
- func (l *MessageLog) AppendTo(sessionID, role, content, clientID string, diagnostics *MessageDiagnostics) (int64, error)
- func (l *MessageLog) Clear() error
- func (l *MessageLog) Close() error
- func (l *MessageLog) CommitPending(seq int64) error
- func (l *MessageLog) CreateSession(discardCurrentUnsaved bool) (Session, error)
- func (l *MessageLog) Cursor(clientID string) (int64, error)
- func (l *MessageLog) CursorSession(clientID, sessionID string) (int64, error)
- func (l *MessageLog) Delete(seq int64) error
- func (l *MessageLog) DeleteSession(id string) error
- func (l *MessageLog) LatestSeq() (int64, error)
- func (l *MessageLog) LatestSeqSession(sessionID string) (int64, error)
- func (l *MessageLog) PromptContext(sessionID string) (SessionPromptContext, error)
- func (l *MessageLog) Recent(limit int) ([]LogMessage, error)
- func (l *MessageLog) RecentSession(sessionID string, limit int) ([]LogMessage, error)
- func (l *MessageLog) RecentUserRequests(sessionID string) ([]string, error)
- func (l *MessageLog) ReconcileShutdown(keepUnsaved bool) error
- func (l *MessageLog) ReconcileStartup(startupBehavior string, keepUnsaved bool) (Session, error)
- func (l *MessageLog) SaveSession(id string) (Session, error)
- func (l *MessageLog) Session(id string) (Session, error)
- func (l *MessageLog) SessionPersona(sessionID string) (string, error)
- func (l *MessageLog) Sessions() ([]Session, error)
- func (l *MessageLog) SetSessionPersona(sessionID, personaID string) (Session, error)
- type Mood
- type MotionCommand
- type MotionContext
- type MotionLabProposal
- type MotionMode
- type PatternChoice
- type PositionBand
- type PromptComposition
- type PromptLibrary
- func (l *PromptLibrary) Close() error
- func (l *PromptLibrary) Create(name string, system string) (PromptSet, error)
- func (l *PromptLibrary) Delete(id string) error
- func (l *PromptLibrary) List() ([]PromptSet, error)
- func (l *PromptLibrary) Recovered() bool
- func (l *PromptLibrary) Resolve(id string) (set PromptSet, found bool, err error)
- func (l *PromptLibrary) Update(id string, name string, system string) (PromptSet, error)
- type PromptSection
- type PromptSet
- type ReactionStyle
- type Request
- type Result
- type Service
- type Session
- type SessionPromptContext
- type StreamEvent
- type VoiceLevel
Constants ¶
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" )
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" )
const ( AreaZoneTip = "tip" AreaZoneShaft = "shaft" AreaZoneBase = "base" AreaZoneFull = "full" )
Named area-focus zones the model may request. "full" explicitly clears an active focus.
const ( MessageRoleUser = "user" MessageRoleAssistant = "assistant" )
Message roles accepted by the visible chat log.
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" )
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.
const MessageLogCap = 200
MessageLogCap bounds each chat session independently.
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.
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 ¶
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.
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.
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) string
AutopilotSpeechMessage renders the independent autonomous speech turn.
func ComposeSystem ¶
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 ¶
CreativeV2CharacterUnchanged is shared by scheduled Lab and production turns. Realization seeds are intentionally excluded from this semantic comparison.
func CreativeV2ContinuationMessage ¶
CreativeV2ContinuationMessage preserves the human's geometry and pacing.
func CreativeV2ResponseSchema ¶
func CreativeV2ResponseSchema(limits config.MotionSettings, mood bool) json.RawMessage
CreativeV2ResponseSchema is identical in production and the prompt Lab.
func DefaultLayeredScore ¶
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 ¶
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 ¶
FreshCreativeV2Score selects a new replayable realization. The model edits the semantic grammar, never the random seed or generated point sequence.
func FreshLayeredScore ¶
FreshLayeredScore gives a new conversation its own irregular realization. The chosen seed is retained with the score for faithful plots and replay.
func HasMotionDirection ¶
HasMotionDirection distinguishes a human-authored character from an empty Autopilot session. Questions and social conversation do not lock a default score forever, and they cannot erase earlier motion directions.
func LLMLabPrompts ¶
LLMLabPrompts isolates experimental control interfaces from production prompting.
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 LayeredAutopilotMessage ¶
func LayeredAutopilotMessage() string
LayeredAutopilotMessage gives Labs and production the same continuation intent.
func LayeredContinuationMessage ¶
LayeredContinuationMessage makes explicit user preservation authoritative in the autonomous request, rather than competing with an evolution instruction.
func LayeredExactHoldRequested ¶
LayeredExactHoldRequested recognizes explicit continuing preservation, not a one-turn question or a scoped instruction to keep only speed unchanged.
func LayeredResponseSchema ¶
func LayeredResponseSchema(limits config.MotionSettings, mood bool) json.RawMessage
LayeredResponseSchema shares one compact contract between live chat and Labs.
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 PatternResponseSchema ¶
func PatternResponseSchema(patterns []PatternChoice, capabilities Capabilities, state *MotionContext) json.RawMessage
PatternResponseSchema constrains the compact library action vocabulary. Intent, lifecycle authority and actual motion still pass normal validation. It never supplies a missing action or selects a pattern.
func RepairPrompt ¶
RepairPrompt asks the same model to replace malformed output with the contract.
func ValidateUserMessage ¶
ValidateUserMessage normalizes one user turn before either persistence or model generation so both paths enforce the same byte limit.
Types ¶
type AssistantResponse ¶
type AssistantResponse struct {
Reply string `json:"reply"`
NewMood *Mood `json:"new_mood,omitempty"`
Motion *MotionCommand `json:"motion,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 {
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
// 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
}
AutopilotResponse is a validated motion-plan or speech-check-in response.
type AutopilotService ¶
type AutopilotService struct {
Provider llm.Provider
Prompt PromptSet
Model string
MaxTokens int
ReasoningMode string
ReasoningBudgetTokens int
// 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, semantic motion validation, and one-shot repair policy used by interactive chat.
func (AutopilotService) Complete ¶
func (s AutopilotService) Complete(ctx context.Context, kind AutopilotKind, request Request) (AutopilotResponse, error)
Complete runs one autonomous decision and repairs malformed output once.
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 {
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
}
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 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 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 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"`
}
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"`
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"`
}
LogMessage is one visible row in a chat session.
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"`
// 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"`
GenerationMillis int64 `json:"generation_ms,omitempty"`
RepairMillis int64 `json:"repair_ms,omitempty"`
ProviderCalls int `json:"provider_calls,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) 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) 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) Append ¶
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) 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) 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) 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) 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) 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) Recent ¶
func (l *MessageLog) Recent(limit int) ([]LogMessage, error)
Recent returns the active session's newest messages in chronological order.
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) 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) 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) SessionPersona ¶
func (l *MessageLog) SessionPersona(sessionID string) (string, error)
SessionPersona returns the persona bound to one session, or empty.
func (*MessageLog) Sessions ¶
func (l *MessageLog) Sessions() ([]Session, error)
Sessions lists retained tabs in stable creation order.
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 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.
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
}
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 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 PatternChoice ¶
PatternChoice is one enabled library entry exposed to the model as data.
type PositionBand ¶
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 PromptComposition ¶
type PromptComposition struct {
Prompt string `json:"prompt"`
Sections []PromptSection `json:"sections"`
Characters int `json:"characters"`
Bytes int `json:"bytes"`
}
PromptComposition is the exact prompt sent to the provider plus a section index over those same bytes.
func ComposePrompt ¶
func ComposePrompt(set PromptSet, memories []string, patterns []PatternChoice, capabilities Capabilities, motionContext *MotionContext, conversationContext *ConversationContext) 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.
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 ¶
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 Result ¶
type Result struct {
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
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
}
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).
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 SessionPromptContext ¶
SessionPromptContext is the backend-owned per-session continuity snapshot supplied to one model turn.
type StreamEvent ¶
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" )
Source Files
¶
- autopilot.go
- autopilot_catalog.go
- autopilot_dynamic_prompt.go
- autopilot_motion_facts.go
- autopilot_service.go
- autopilot_speech_facts.go
- continuous_action.go
- continuous_history.go
- contract.go
- creative_v2.go
- creative_v2_prompt.go
- dynamic_intent.go
- layered.go
- layered_context.go
- layered_continuation.go
- layered_geometry.go
- layered_history.go
- layered_prompt.go
- layered_schema.go
- layered_service.go
- layered_variation.go
- library.go
- library_lab.go
- llm_lab.go
- llm_lab_edits.go
- llm_lab_schema.go
- log.go
- motion_context.go
- motion_lab.go
- pattern_authorization.go
- pattern_schema.go
- prompt_localization.go
- prompt_motion_contract.go
- prompts.go
- service.go