Documentation
¶
Overview ¶
Package suggest is SUGGESTED REPLIES: up to three short drafts the operator can tap into a mirrored session's composer when the agent has handed control back ("Which do you prefer?", "Should I open the PR?").
🔴 A SUGGESTION IS NEVER SENT BY MUSTER. A tap only fills the composer (and appends below a draft that is already there); the operator edits it and presses Send, which keeps its own step-up gate. Nothing in this package can reach a pane: it produces text. The one exception is an ask's suggestion on a paired phone's notification, sent as the ask's answer only by a signed action the person confirmed with the phone's step-up key (internal/api device_actions.go) — the confirmation is the send.
The pieces, in the order a suggestion passes through them:
- HandsBack: the cheap deterministic pre-gate. A final reply that does not ask a question, offer options or say "should I" gets no model call.
- Build: the model's input, exactly three parts — the operator's own messages (numbered A<n> from the prompt index, newest first), the session's focus history (labelled untrusted), and the transcript tail (the final reply R, its END kept, and the few entries before it). Every field goes through redact.Secrets first; a tool call is its name and file path only; tool output and thinking never enter it.
- Generator (OpenRouter): one chat call, strict JSON out.
- Filter: the deterministic post-filter. A suggestion survives only when its citations exist, its quote is verbatim in a cited source, and it passes the shape rules (no leading / or !, one line, no URL, no code fence, no secret). Zero survivors means no chips, which is a correct outcome.
- Engine: the cache (by input fingerprint: a new turn regenerates, the same input never calls again), the rate cap, the kill switch and the per-user toggle.
🔴 A SESSION'S SUGGESTION TEXT IS NEVER STORED. It lives in the Engine's in-memory cache for at most CacheTTL and is then dropped (Engine.Sweep); only the input's fingerprint outlives it, so an unchanged session is not paid for twice. The ONE exception is an attention ask's set (internal/api attention_suggest.go): its notification is re-pushed carrying it and its page draws it on any replica, so it is stored on the ask (migration 0057), beside the question it was made from, and only while the ask is open.
Index ¶
- Constants
- Variables
- func Filter(raw []Raw, b Built) ([]Suggestion, []Dropped)
- func FinalReply(tail []Entry) (string, int, bool)
- func Fingerprint(prompt string) string
- func HandsBack(reply string) bool
- func Reason(err error) string
- func ValidKind(k string) bool
- type Built
- type Drop
- type Dropped
- type Engine
- func (e *Engine) Enabled(ctx context.Context, owner int64) Outcome
- func (e *Engine) Forget(owner int64)
- func (e *Engine) Latest(owner int64, subject string) (Set, bool)
- func (e *Engine) OffForEveryone() bool
- func (e *Engine) Record(ctx context.Context, owner int64, subject, fp, ev string, dist int) bool
- func (e *Engine) Resume(ctx context.Context, owner int64)
- func (e *Engine) Run(ctx context.Context)
- func (e *Engine) Stats(ctx context.Context, owner int64) (Tally, error)
- func (e *Engine) Suggest(ctx context.Context, owner int64, subject string, b Built, turn int64) (Set, Outcome, error)
- func (e *Engine) Sweep() int
- type Entry
- type Expect
- type Fixture
- type FixtureEntry
- type FocusEntry
- type Generation
- type Generator
- type HTTPError
- type Input
- type KeyChecker
- type OpenRouter
- type Outcome
- type PGPrefs
- type PGUsage
- func (p *PGUsage) Add(ctx context.Context, owner int64, shown, filled, sent, edit int64) (Tally, error)
- func (p *PGUsage) Get(ctx context.Context, owner int64) (Tally, error)
- func (p *PGUsage) Reset(ctx context.Context, owner int64) error
- func (p *PGUsage) SetPaused(ctx context.Context, owner int64, paused bool) error
- type Prefs
- type Raw
- type Result
- type Set
- type Suggestion
- type Tally
- type Usage
- type UsageStore
Constants ¶
const ( // AutoPauseMinShown is how many sets must have been shown before the rate // is judged. AutoPauseMinShown = 200 // AutoPauseRatePercent: below this percentage of shown sets filled, the // user is paused. AutoPauseRatePercent = 5 )
The auto-pause's bounds.
const ( EventShown = "shown" EventFilled = "filled" EventSent = "sent" )
The events the composer reports.
const ( // PerOwnerPerHour is the operator's own cap for suggestions (separate from // focus's, so suggestions never starve it). PerOwnerPerHour = 120 // GlobalPerHour bounds every owner together. GlobalPerHour = 1000 // MaxConcurrent bounds calls in flight across every owner. MaxConcurrent = 2 // CacheTTL is how long a set's text is kept in memory. CacheTTL = time.Hour // SweepInterval is how often expired text is dropped. SweepInterval = time.Minute // MaxCached bounds the subjects the cache holds; the least recently // generated is evicted past it. MaxCached = 2000 )
The engine's bounds.
const ( // MaxAskBytes bounds one operator message. MaxAskBytes = 500 // MaxAsksBytes bounds the operator's messages together; the newest are // kept. MaxAsksBytes = 6 << 10 // MaxFocusEntries is how many focus-history entries the input carries // (the newest). MaxFocusEntries = 10 // MaxFocusEntryBytes bounds one focus entry (title and description). MaxFocusEntryBytes = 1 << 10 // MaxReplyBytes bounds the final reply R, cut from the FRONT: the options // and the question sit at the end of a reply. MaxReplyBytes = 4 << 10 // MaxTailEntries is how many entries before R the input carries. MaxTailEntries = 3 // MaxTailEntryBytes bounds each of them. MaxTailEntryBytes = 1 << 10 )
The input's bounds.
const ( RoleUser = "user" RoleAssistant = "assistant" RoleTool = "tool" )
Roles an Entry may carry. Anything else is dropped by Build.
const ( // DefaultModel is the operator's choice, spelled exactly as OpenRouter's // model list (GET /api/v1/models) names it; that list priced it at $0.10 // in / $0.50 out per Mtok when this was written. MUSTER_SUGGEST_MODEL // overrides it. DefaultModel = "openai/gpt-6-luna" // DefaultReasoningEffort keeps a reasoning model's thinking short: the // chips must land within seconds of the turn ending. DefaultReasoningEffort = "low" // MaxTokens bounds the answer (reasoning included, for a reasoning model). MaxTokens = 2000 )
The defaults.
const ( // KindPick chooses one of the options the agent offered (or combines them). KindPick = "pick" // KindGap points at an operator ask the reply did not address. KindGap = "gap" // KindVerify asks for a check the agent skipped or deferred. KindVerify = "verify" // KindDecide approves or declines a proposed action, WITH its reason or // condition. KindDecide = "decide" // KindRedirect narrows the work or stops it. KindRedirect = "redirect" )
The five kinds a suggestion can be. The model is told what each means (Instructions) and the filter refuses any other.
const ( // MaxSuggestions is how many chips a set holds at most. MaxSuggestions = 3 // MaxTextRunes bounds one suggestion's text. MaxTextRunes = 140 // MinQuoteBytes is the shortest quote that counts as grounding (a shorter // one matches almost anything), unless it is the whole cited source. MinQuoteBytes = 6 )
The bounds of what is generated and what is kept.
const ( ReasonNoKey = "no OpenRouter key" ReasonKeyLookup = "the OpenRouter key could not be read" ReasonRateLimited = "rate-limited" ReasonUnusable = "the suggester's answer was unusable" ReasonUnreachable = "the suggester could not be reached" ReasonFailed = "the suggestion failed" )
The fixed reasons a failed or skipped generation records (Reason). Short, and carrying nothing from the transcript, the key or the provider's body, in focus's vocabulary (internal/focus Reason*).
const DefaultDisabled = true
DefaultDisabled is a user's toggle when they have never saved one: OFF (operator decision — suggestions spend the user's OpenRouter key and send their conversation to it, so each user opts in, in Account → Suggested replies). It holds in the no-database mode too (operator decision), where nobody can save a choice and Engine.On (MUSTER_SUGGEST=on) is the server's opt-in for everyone.
🔴 THE ONE PLACE THE DEFAULT IS DECIDED: Engine.userOff applies it to every owner with no saved choice, and nothing else spells it. It is a semantics of the absence of a row, so changing it rewrites no one's saved choice: a saved ON (disabled=false) stays on and a saved OFF stays off.
const DefaultRecheckTimeout = 5 * time.Second
DefaultRecheckTimeout bounds the toggle re-check after a paid call.
const HandsBackWindow = 400
HandsBackWindow is how much of the reply's end the pre-gate reads: the proposal's measurement ("a ? in the last 400 chars") used the same window.
const Instructions = `` /* 2536-byte string literal not displayed */
Instructions is the system message.
const PromptVersion = "suggest-v2"
PromptVersion is mixed into the fingerprint: a change to the instructions or the input's shape makes every cached set stale.
const ReplyID = "R"
ReplyID is the final reply's citation id.
Variables ¶
var ( ErrNoKey = errors.New("suggest: no OpenRouter key for this owner") ErrKeyLookup = errors.New("suggest: the owner's OpenRouter key could not be read") ErrRateLimited = errors.New("suggest: the provider is rate-limiting (429)") ErrMalformed = errors.New("suggest: the model's answer is not the JSON asked for") ErrOversized = errors.New("suggest: the model's answer is larger than a suggestion set can be") ErrUnreachable = errors.New("suggest: the provider could not be reached") // ErrCapped is a generation the rate cap refused: nothing was called. ErrCapped = errors.New("suggest: the suggestion rate cap is reached; try again later") )
The errors a generation can end in. Each maps to a short fixed Reason.
var ErrNotOwner = errors.New("suggest: the toggle is read only as its owner")
ErrNotOwner refuses a toggle read whose ctx does not act as the owner.
var Kinds = []string{KindPick, KindGap, KindVerify, KindDecide, KindRedirect}
Kinds is every kind, in the order the instructions list them.
Functions ¶
func Filter ¶
func Filter(raw []Raw, b Built) ([]Suggestion, []Dropped)
Filter keeps the suggestions in raw that pass every rule, at most MaxSuggestions, in the model's order (a gap whose ask R already seems to cover moves to the end: a ranking heuristic, never a drop). b is the input the model was given.
func FinalReply ¶
FinalReply is the conversation's final reply: the assistant segments after the last prompt or tool call, joined, and whether the conversation ENDS in one. A conversation whose newest entry is a prompt or a tool call has no final reply: the agent has not handed control back.
func Fingerprint ¶
Fingerprint is the cache key of a rendered input.
Types ¶
type Built ¶
type Built struct {
// Prompt is the user message sent to the model.
Prompt string
// Fingerprint is the hex sha256 of PromptVersion and the input without
// its relative times.
Fingerprint string
// Reply is R, the final reply, as the input carries it.
Reply string
// Sources maps each citable id ("R", "A<n>") to its text as the input
// carries it: a quote must be verbatim in one of these.
Sources map[string]string
}
Built is the rendered input and what the filter checks against.
type Drop ¶
type Drop string
Drop is why Filter dropped a suggestion.
const ( DropKind Drop = "kind" DropEmpty Drop = "empty" DropTooLong Drop = "too-long" DropSlashBang Drop = "slash-or-bang" DropMultiline Drop = "multiline" DropURL Drop = "url" DropFence Drop = "code-fence" DropSecret Drop = "secret" DropCite Drop = "cite" DropQuote Drop = "quote" DropPickNotR Drop = "pick-not-r" DropDecideNotR Drop = "decide-not-r" DropGapNoAsk Drop = "gap-no-ask" DropActNotR Drop = "act-not-r" DropStock Drop = "stock-phrase" DropUnknownTerm Drop = "unknown-term" DropDuplicate Drop = "duplicate" DropOverflow Drop = "overflow" )
type Dropped ¶
Dropped is one suggestion Filter refused, and why (for tests and the eval; never logged with its text).
type Engine ¶
type Engine struct {
Gen Generator
// Off is the kill switch (MUSTER_SUGGEST=off): nothing is generated or
// served.
Off bool
// On is MUSTER_SUGGEST=on: in the no-database mode (Prefs nil, so no user
// can save a choice), it turns suggestions on for everyone. With a
// database it changes nothing: a user's own saved choice, or
// DefaultDisabled, governs (userOff).
On bool
Prefs Prefs
// Usage keeps each user's counts and pause (autopause.go); nil keeps them
// in memory.
Usage UsageStore
Now func() time.Time
// RecheckTimeout bounds the toggle re-check after a paid call (0 =
// DefaultRecheckTimeout).
RecheckTimeout time.Duration
// PerOwner and Global override the hourly caps (0 = the constants).
PerOwner, Global int
Logger *log.Logger
// Calls counts model calls made (a test reads it).
Calls int
// contains filtered or unexported fields
}
Engine generates and caches suggestion sets.
func (*Engine) Enabled ¶
Enabled is "" when owner may get suggestions now, or the Outcome that says why not (Off, UserOff, Paused). A Prefs read error fails CLOSED (UserOff).
func (*Engine) Forget ¶
Forget drops owner's cached sets (the toggle turned off: nothing of theirs stays in memory).
func (*Engine) Latest ¶
Latest is (owner, subject)'s newest set while its text is within CacheTTL, and whether there is one. It never calls.
func (*Engine) OffForEveryone ¶ added in v0.182.0
OffForEveryone is true when no user can have suggestions: the kill switch, or no database (no per-user switch) with the default off and no MUSTER_SUGGEST=on. The Features page reads it, so it says what the engine does.
func (*Engine) Record ¶
Record counts one composer event for owner: ev is EventShown, EventFilled or EventSent, fp the set's fingerprint, subject the conversation it was served for, dist the edit distance (EventSent only). It reports whether the event counted (a repeat, an unknown event or fingerprint does not).
func (*Engine) Resume ¶
Resume un-pauses owner, starting their counts over; a user who was not paused keeps them.
func (*Engine) Suggest ¶
func (e *Engine) Suggest(ctx context.Context, owner int64, subject string, b Built, turn int64) (Set, Outcome, error)
Suggest is the set for (owner, subject) built from b: the cached one when its fingerprint is b's, otherwise a new one (a model call). turn is the caller's turn token, kept with the set (Set.Turn).
type Entry ¶
Entry is one line of the conversation: a prompt (RoleUser), a reply segment (RoleAssistant) or a tool call already reduced to its name and file path (RoleTool).
type Expect ¶
type Expect struct {
// MinKept: at least this many survivors.
MinKept int `yaml:"min_kept"`
// AnyKind: at least one survivor is one of these kinds.
AnyKind []string `yaml:"any_kind"`
// AnyContains: at least one survivor contains one of these (any case).
AnyContains []string `yaml:"any_contains"`
// CitesAsk: at least one survivor cites this ask id ("A3").
CitesAsk string `yaml:"cites_ask"`
// Forbid: no survivor contains any of these (any case) — the injected
// action, the option the operator ruled out.
Forbid []string `yaml:"forbid"`
}
Expect is what a fixture's surviving set must satisfy.
type Fixture ¶
type Fixture struct {
Name string `yaml:"name"`
// FocusHistory is the session's focus over time, oldest first, each
// written AgoMinutes before the fixture's fixed now.
FocusHistory []struct {
Title string `yaml:"title"`
Description string `yaml:"description"`
AgoMinutes int `yaml:"ago_minutes"`
} `yaml:"focus_history"`
Asks []string `yaml:"asks"`
Tail []FixtureEntry `yaml:"tail"`
// HandsBack is the pre-gate's expected verdict on the final reply; a
// fixture that does not hand back is never sent to the model.
HandsBack bool `yaml:"hands_back"`
Expect Expect `yaml:"expect"`
// Canned is a synthetic model answer for the offline layer, and
// CannedKept how many of its items must survive Filter.
Canned []Raw `yaml:"canned"`
CannedKept int `yaml:"canned_kept"`
}
Fixture is one synthetic conversation and what a good set for it must do.
func LoadFixtures ¶
LoadFixtures reads a fixtures file.
type FixtureEntry ¶
type FixtureEntry struct {
Role string `yaml:"role"`
Text string `yaml:"text"`
Tool string `yaml:"tool"`
Input string `yaml:"input"`
Output string `yaml:"output"`
}
FixtureEntry is one line of a fixture's conversation. A tool call names Tool and Input (the call's argument JSON); Output is its result, which the input must NEVER carry (it is there to prove that).
type FocusEntry ¶
FocusEntry is one focus the session had, and when it was written.
type Generation ¶
Generation is one call's outcome: the raw suggestions and what it cost.
func ParseCompletion ¶
func ParseCompletion(raw []byte) (Generation, error)
ParseCompletion reads a chat completion into a Generation.
type Generator ¶
type Generator interface {
Generate(ctx context.Context, owner int64, prompt string) (Generation, error)
}
Generator turns a built input into the model's raw suggestions. owner is whose session it is: the credential spent is that owner's.
type HTTPError ¶
HTTPError is a non-2xx answer. Body is the provider's error text, cut; never the key, which went in a header.
type Input ¶
type Input struct {
// Asks are the operator's messages, oldest first, as the prompt index
// carries them (cctranscript.PromptRef.Text). AskBase is the number of
// messages before Asks[0] (the index's dropped count), so the ids stay the
// message's position in the WHOLE conversation.
Asks []string
AskBase int
// Focus is the session's focus history, oldest first.
Focus []FocusEntry
// Now is what the focus entries' "ago" is measured from (zero: no times).
Now time.Time
// Tail is the conversation, newest last; Build reads only its end.
Tail []Entry
}
Input is what Build assembles the model's input from.
type KeyChecker ¶
KeyChecker is a Generator that can say, without a call, that it cannot serve owner (no OpenRouter key).
type OpenRouter ¶
type OpenRouter struct {
Key focus.KeyFunc
// Missing reports whether a Key error means "this owner has no key"
// (credentials.IsNoCredential); any other error is a lookup failure.
Missing func(error) bool
// Model is the model slug ("" = DefaultModel).
Model string
// ReasoningEffort ("" = DefaultReasoningEffort; "none" sends none).
ReasoningEffort string
URL string // "" = focus.OpenRouterChatURL
Client *http.Client
}
OpenRouter is the Generator on OpenRouter's chat completions.
func (*OpenRouter) CanGenerate ¶
func (o *OpenRouter) CanGenerate(ctx context.Context, owner int64) error
CanGenerate is nil when owner has a key (no call is made).
func (*OpenRouter) Generate ¶
func (o *OpenRouter) Generate(ctx context.Context, owner int64, prompt string) (Generation, error)
Generate implements Generator.
func (*OpenRouter) RequestBody ¶
func (o *OpenRouter) RequestBody(prompt string) []byte
RequestBody is the JSON body Generate posts (exported for the tests and the eval harness, which must send exactly what production sends).
type Outcome ¶
type Outcome string
Outcome is what one Suggest did.
const ( OutcomeGenerated Outcome = "generated" OutcomeCached Outcome = "cached" // the fingerprint skip: no call OutcomeExpired Outcome = "expired" // the fingerprint skip, text gone: no call OutcomeOff Outcome = "off" // MUSTER_SUGGEST=off OutcomeUserOff Outcome = "user-off" OutcomeFailed Outcome = "failed" )
const OutcomePaused Outcome = "paused"
OutcomePaused is Enabled's answer for a user the auto-pause paused.
type PGPrefs ¶
type PGPrefs struct {
// contains filtered or unexported fields
}
PGPrefs is Prefs on suggest_preferences (migration 0048), under row-level security: ctx must act as the owner it names (a request's, or the rendered view socket's, principal), and a row of another owner's is invisible.
func (*PGPrefs) Choice ¶ added in v0.182.0
Choice implements Prefs: a row is the user's saved choice, on or off; no row is saved=false (the engine gives it DefaultDisabled).
🔴 FAILS CLOSED WITHOUT THE OWNER'S PRINCIPAL. Row-level security hides a row from any other principal, and a hidden row would read as "no row" — the default, whatever the user saved. So a ctx that does not act as owner is an error, which the engine reads as off.
type PGUsage ¶
type PGUsage struct {
// contains filtered or unexported fields
}
PGUsage is UsageStore on suggest_usage (migration 0049), under row-level security: ctx must act as the owner it names (a request's, or the rendered view socket's, principal), and another owner's row is invisible. Numbers only: nothing it writes can hold text.
func (*PGUsage) Add ¶
func (p *PGUsage) Add(ctx context.Context, owner int64, shown, filled, sent, edit int64) (Tally, error)
Add implements UsageStore: one statement, so two adds never lose a count.
type Prefs ¶
type Prefs interface {
Choice(ctx context.Context, owner int64) (disabled, saved bool, err error)
SetDisabled(ctx context.Context, owner int64, disabled bool) error
}
Prefs is the per-user toggle store. Choice is owner's SAVED choice: saved=false when they never chose, and then disabled means nothing — a Prefs never decides the default; Engine.userOff does (DefaultDisabled). A nil Prefs is the no-database mode: nobody has a saved choice.
type Raw ¶
type Raw struct {
Text string `json:"text"`
Kind string `json:"kind"`
Cites []string `json:"cites"`
Quote string `json:"quote"`
}
Raw is one suggestion as the model wrote it, before Filter.
func ParseSuggestions ¶
ParseSuggestions reads the model's JSON content. A fenced block ("```json … ```") is unwrapped first; anything that is not the asked-for object is ErrMalformed. More than MaxSuggestions items are cut, not refused.
type Result ¶
type Result struct {
Fixture string
// Properties maps each property checked to whether it held.
Properties map[string]bool
// Kept is how many survived; Raw how many the model wrote; Drops the
// reasons of the ones dropped.
Kept, Raw int
Drops []Drop
}
Result is one fixture scored.
type Set ¶
type Set struct {
Fingerprint string
Suggestions []Suggestion
// Turn is the caller's token for the turn the set answers (the window's
// StatusSince): Latest's reader serves it only while the turn is the same.
Turn int64
At time.Time
// Problem is why the set is empty when a call failed (Reason), "" else.
Problem string
}
Set is one cached suggestion set.
type Suggestion ¶
Suggestion is one chip: what a tap fills, and its kind. It is what the endpoint serves; the citation and quote it was checked against stay here.
type Tally ¶
type Tally struct {
Shown, Filled, Sent int64
// EditSum is the sum of the edit distances reported with Sent.
EditSum int64
Paused bool
}
Tally is one user's counts.
func (Tally) FillPercent ¶
FillPercent is the percentage of shown sets that were filled (0 with none).
type Usage ¶
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
Cost float64 `json:"cost"`
}
Usage is what OpenRouter reports a call cost (usage accounting); zero when it reports none.
type UsageStore ¶
type UsageStore interface {
// Get is owner's counts (zero with none).
Get(ctx context.Context, owner int64) (Tally, error)
// Add adds to owner's counts and returns them after.
Add(ctx context.Context, owner int64, shown, filled, sent, edit int64) (Tally, error)
// SetPaused records the pause.
SetPaused(ctx context.Context, owner int64, paused bool) error
// Reset starts owner's counts over, un-paused.
Reset(ctx context.Context, owner int64) error
}
UsageStore keeps each user's counts (PGUsage: suggest_usage, migration 0049). ctx acts as the owner it names (row-level security).