Documentation
¶
Overview ¶
Package askq is Claude Code's AskUserQuestion tool as muster shows it: the question set's shape and bounds, the answers a person may give to it in muster, and the store of the questions sessions are asking.
It is SURFACE-NEUTRAL. Nothing here knows about mirrored hosts or dispatched agents: a question is keyed by (owner, source, scope, Claude session, tool_use id) — Key — and the mirror plugin's hook (`muster-mirror ask`) is only the first source.
A question is shown IN BOTH PLACES AT ONCE (an operator decision): the terminal draws its own picker the moment the call is made, and muster draws the same question. Whichever is answered first wins. An answer given in muster is TYPED into the terminal's picker by the host (internal/askdrive), never handed to the CLI any other way; the CLI's own record of the call's result (the transcript's toolUseResult) is what says which answer won.
Index ¶
- Constants
- Variables
- func AnswersOf(qs []Question, choices []Choice) map[string]string
- func CheckAnswers(qs []Question, answers map[string]string) error
- func NewID() string
- func ValidID(id string) bool
- type Choice
- type Entry
- type Failure
- type Hook
- type HookPayload
- type Key
- type Option
- type Progress
- type Question
- type Result
- type State
- type Store
- func (s *Store) BeginMessage(key Key, offered func(Entry) bool) (Entry, error)
- func (s *Store) BeginTyping(key Key, answers map[string]string) (e Entry, again bool, err error)
- func (s *Store) Dismissing(key Key) (Entry, error)
- func (s *Store) EndMessage(key Key, note string) Entry
- func (s *Store) Find(key Key) (Entry, bool)
- func (s *Store) ForSession(owner int64, source, scope, session string, shownFor time.Duration) []Entry
- func (s *Store) Get(id string) (Entry, bool)
- func (s *Store) Gone(owner int64, source, scope, session, why string) int
- func (s *Store) OnChange(fn func(Entry))
- func (s *Store) Open(key Key, qs []Question, id string) (Entry, error)
- func (s *Store) OpenIn(owner int64, source, scope, session string) []Entry
- func (s *Store) Pending(owner int64) []Entry
- func (s *Store) Resolve(owner int64, source, scope, session, toolUseID string, ...) (Entry, bool)
- func (s *Store) Restore(key Key, qs []Question) (e Entry, changed bool, err error)
- func (s *Store) RunSweep(ctx context.Context, interval time.Duration)
- func (s *Store) Seen(owner int64, source, scope, session string)
- func (s *Store) SetNow(now func() time.Time)
- func (s *Store) Sweep()
- func (s *Store) TypingDone(key Key)
- func (s *Store) TypingFailed(key Key, f Failure) (Entry, error)
- func (s *Store) Watched(owner int64, source, scope, session string) []Entry
Constants ¶
const ( MaxQuestions = 4 MaxOptions = 6 MaxHeader = 128 MaxQuestion = 2048 MaxLabel = 256 MaxDescription = 2048 // MaxPreview bounds an option's preview (Option.Preview). MaxPreview = 4096 // MaxAnswer bounds one question's answer (labels joined, or typed text). MaxAnswer = 4096 // MaxFreeText bounds what a person types as their own answer. MaxFreeText = 2048 )
The bounds of a question set muster will show. The CLI's own schema asks for 1-4 questions of 2-4 options; a little slack is allowed on the options, and anything past these is refused — the hook then leaves the question to the terminal, which shows it whatever its size.
const ( ByMuster = "muster" ByTerminal = "terminal" )
Who answered (Entry.By).
const ( // MaxOpen is how long an open question stays open while its session is NOT // SEEN listed (Store.Seen; from Created until it first is). A question // whose session is listed never reaches it: the watcher marks it seen. It // bounds what a host that went away for good leaves open. MaxOpen = 6 * time.Hour // Retain is how long a resolved question is kept, so a page that loads // after it still shows how it went. Retain = 15 * time.Minute // MaxPendingPerOwner bounds one owner's open questions, // MaxEntriesPerOwner all of one owner's entries (open and resolved), and // MaxEntries the store's whole size. MaxPendingPerOwner = 32 MaxEntriesPerOwner = 256 MaxEntries = 4096 )
The store's bounds and clocks.
const MaxDrive = 90 * time.Second
MaxDrive bounds how long a host can be typing one answer: longer than the hub waits for the host's outcome (60 s) and the host's own bound (50 s).
const MultiJoin = ", "
MultiJoin is how a multi-select answer joins its parts.
const OtherValue = "__other__"
OtherValue is the form value of a question's "Other" choice: the person's own text (field o<i>) is the answer, or part of it.
const SweepEvery = time.Minute
SweepEvery is RunSweep's period.
const ToolName = "AskUserQuestion"
ToolName is the tool this package answers.
Variables ¶
var ( // ErrNotFound: no such question this caller may see. ErrNotFound = errors.New("askq: no such question") // ErrClosed: the question was answered (or dismissed) already. ErrClosed = errors.New("askq: this question was already answered") // ErrBusy: an answer is being typed in for it already. ErrBusy = errors.New("askq: an answer is already being typed in for this question") // ErrFull: too many questions are open. ErrFull = errors.New("askq: too many questions are waiting") // ErrIDTaken: the id a hook chose names another question. ErrIDTaken = errors.New("askq: that question id is taken") )
var ErrInvalid = errors.New("askq")
ErrInvalid wraps every refusal of a question set or of answers.
Functions ¶
func AnswersOf ¶
AnswersOf is the answers choices give, keyed by question text, as the CLI records them — the review screen's lines and the transcript's toolUseResult: a multi-select answer's options in the question's order, then the text, all joined by MultiJoin.
func CheckAnswers ¶
CheckAnswers verifies answers against qs: exactly one non-empty answer per question, keyed by its text, each within MaxAnswer and free of control characters.
Types ¶
type Choice ¶
Choice is one question's answer as the picker takes it: the options chosen (0-based indexes into its Options) and the person's own text ("" for none).
func FromForm ¶
FromForm builds the answers to qs from a submitted form: for question i (from 0), the values a<i> are the chosen option labels — or OtherValue, whose text is o<i> — and o<i> is the person's own answer. It returns them both as the picker takes them (choices) and as the CLI records them (answers, keyed by question text).
Every question must be answered. A single-select question takes exactly one choice; a multi-select one at least one, its answer being the chosen labels in the question's own order, joined by MultiJoin, then the person's own text. A field naming a question qs does not have, a label that is not one of the question's options, a repeated choice, OtherValue with no text, text past MaxFreeText, and text with a line break or a tab (the terminal's picker takes one line, and the answer is typed into it) are refused.
type Entry ¶
type Entry struct {
ID string
Key Key
Questions []Question
State State
// Answers is the recorded answers (Answered); Typed the answers muster is
// typing or typed (Typing, and kept after); By who answered (Answered).
Answers map[string]string
Typed map[string]string
By string
// Note is why typing failed (Failed).
Note string
// Retry (Failed) says the failure leaves the question answerable from
// muster again: typing can be tried again (Failure.Retry).
Retry bool
// Reason (Failed) is the failure's reason code (Failure.Reason,
// internal/askattempt's Reasons): what the card offers to recover with.
Reason string
// Sending (Failed) says a "Send as a message" holds the question
// (BeginMessage): the card offers nothing until it ends.
Sending bool
// Left is what muster's typing is KNOWN to have left in the terminal's
// picker: the choices it was typing and how many keys of their plan it
// sent (nil: nothing known to be there). A drive that stopped part way
// leaves it; the next drive is handed it (BeginTyping) so it can tell
// muster's own partial answer from someone else's and continue it.
Left *Progress
Created time.Time
Resolved time.Time
// Seen is when the question's session was last seen listed by its host
// (Store.Seen); zero until then — Created counts instead.
Seen time.Time
}
Entry is one question set and where it is.
type Failure ¶
type Failure struct {
// Note is what the card says (Entry.Note).
Note string
// Settled says the host reported its outcome (it is not typing).
Settled bool
// Left is what the drive is known to have left in the picker (Entry.Left).
// It is recorded only when Settled; nil (no key of this drive reached the
// picker) keeps what the last drive left.
Left *Progress
// Retry says the question can be answered from muster again (Entry.Retry).
Retry bool
// Reason is the failure's reason code (Entry.Reason).
Reason string
}
Failure is how a drive that did not type the answer in ended.
type Hook ¶
type Hook struct {
// Base is muster's base URL; Path the registration route ("/mirror/ask").
Base, Path string
// Auth sets the request's credential.
Auth func(*http.Request)
// Client makes the one request; its Timeout bounds the hook (the picker
// is drawn once the hook returns).
Client *http.Client
Logf func(format string, a ...any)
}
Hook is one hook run's configuration.
type HookPayload ¶
type HookPayload struct {
HookEventName string `json:"hook_event_name"`
ToolName string `json:"tool_name"`
ToolInput json.RawMessage `json:"tool_input"`
SessionID string `json:"session_id"`
ToolUseID string `json:"tool_use_id"`
}
HookPayload is the subset of Claude Code's PreToolUse hook payload read here.
type Key ¶
Key names one question set: whose it is, which surface asked (Source: "mirror"), within what (Scope: the mirror host's name), and the Claude Code call (Session: the Claude session id; ToolUseID: the call's tool_use id).
type Option ¶
type Option struct {
Label string `json:"label"`
Description string `json:"description,omitempty"`
// Preview is the option's preview text, when the call gave one: the CLI
// draws it in a box beside the options of a single-select question
// (Question.Previews).
Preview string `json:"preview,omitempty"`
}
Option is one choice of a question.
type Progress ¶
type Progress struct {
Choices []Choice `json:"choices"`
Keys int `json:"keys"`
// Reset asks the drive, when the picker is neither untouched nor exactly
// as Keys of Choices left it, to put it back to the first option of its
// first question before typing (internal/askdrive's DriveFrom) — a card's
// Try again after a recoverable failure (internal/askattempt's
// RecoverRetry). The drive re-reads the screen first, and resets only a
// picker on its first question with no answer of one's own typed in.
// 🔴 BACKWARD-COMPATIBLE BOTH WAYS: an older host ignores it (and refuses
// a touched picker as before); an older muster never sets it.
Reset bool `json:"reset,omitempty"`
}
Progress is how far muster's typing of an answer got into the terminal's picker: the choices it was typing, and how many keys of their plan (internal/askdrive's Plan) it sent.
type Question ¶
type Question struct {
Question string `json:"question"`
Header string `json:"header,omitempty"`
Options []Option `json:"options"`
MultiSelect bool `json:"multiSelect,omitempty"`
}
Question is one question of an AskUserQuestion call.
func ParseInput ¶
func ParseInput(input json.RawMessage) ([]Question, error)
ParseInput reads an AskUserQuestion call's whole input (the hook's tool_input) and returns its questions.
func ParseQuestions ¶
func ParseQuestions(raw json.RawMessage) ([]Question, error)
ParseQuestions reads an AskUserQuestion call's `questions` and checks them against the bounds: 1..MaxQuestions questions, each with a non-empty text unique in the set, a header, and 1..MaxOptions options whose labels are non-empty and unique in their question. A question of any kind but a choice is refused (there is nothing to pick from).
func (Question) Previews ¶
Previews reports whether the terminal draws q as a PREVIEW picker: a single-select question any of whose options has a preview. Measured (Claude Code 2.1.289): the options are drawn in a column with the cursor's preview boxed beside them, there is NO "Type something" row (so no answer of one's own), a digit only moves the cursor to its row, and Enter takes the option under the cursor. A multi-select question is drawn as usual.
type Result ¶
type Result struct {
Questions []Question `json:"questions"`
Answers map[string]string `json:"answers"`
}
Result is a call's outcome as the transcript records it (the user record's toolUseResult): the questions and the answers given.
func ParseResult ¶
func ParseResult(raw json.RawMessage) (Result, bool)
ParseResult reads a transcript record's toolUseResult as an AskUserQuestion outcome: ok only when it has a valid question set and an answers object. Answers are capped, not refused — this is drawing history, not accepting input — and answers to questions the set does not have are dropped.
type State ¶
type State string
State is where a question is.
const ( // Pending: the picker is on screen; nobody has answered. Pending State = "pending" // Typing: muster is typing a person's answer into the picker; the CLI has // not recorded a result yet. Typing State = "typing" // Failed: muster could not type the answer in (Note says why); the picker // is still the terminal's to answer. Failed State = "failed" // Answered: the CLI recorded answers (By says whose they were). Answered State = "answered" // Declined: the CLI recorded the call ended with no answers (the picker // was dismissed in the terminal). Declined State = "declined" // Expired: the session went away (Gone; Note says so), or the question was // not seen in a listed session for MaxOpen. Read open again in its // transcript, it is reopened (Restore). Expired State = "expired" // Superseded: a newer question was asked in the same Claude session, so // this one's picker is no longer on screen; it is never typed into. Superseded State = "superseded" )
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the question store. The zero value is not usable; New.
func (*Store) BeginMessage ¶ added in v0.198.0
BeginMessage CLAIMS a Failed question for internal/api's "Send as a message", under the store's lock: offered(e) says the card offers it (its reason, an answer muster was typing). 🔴 ONE CLAIM AT A TIME: a second request while one holds it is ErrBusy (and so is a question a host may still be typing into), so two concurrent requests never both dismiss and queue. While claimed (Entry.Sending) the card offers no recovery, no typing begins (BeginTyping's ErrBusy) and nothing else dismisses it. ErrNotFound for a question not there; ErrClosed for one not Failed, or whose card does not offer it. EndMessage releases the claim.
func (*Store) BeginTyping ¶
BeginTyping marks the question at key (key.Owner is the request's own owner; another owner's entry is ErrNotFound) as being answered from muster with answers, which must fit its questions. Only a Pending question — or one whose last typing Failed — may begin: a question already being typed is ErrBusy, one the CLI has resolved ErrClosed.
🔴 REPLAY-SAFE: beginning again with the SAME answers while they are being typed, or once the CLI took them, returns the entry and no error and `again` true — the caller must then NOT type them a second time.
func (*Store) Dismissing ¶
Dismissing reports whether the question at key (key.Owner is the request's own owner; another owner's is ErrNotFound) may be dismissed from muster: an open question no answer is being typed into (ErrBusy for one that is, and for one whose last typing's outcome is not known yet — a host may still be typing it), and not resolved (ErrClosed).
func (*Store) EndMessage ¶ added in v0.198.0
EndMessage releases BeginMessage's claim on key. note "" puts the card back as it was (the attempt failed before anything was done, so it still offers what it did); otherwise note is what the card says from now on and it offers no recovery any more (no Retry, no Reason) — the answer was sent, or muster cannot send it — until the CLI's record of the call resolves it.
func (*Store) ForSession ¶
func (s *Store) ForSession(owner int64, source, scope, session string, shownFor time.Duration) []Entry
ForSession is owner's questions in (source, scope, session) that are open, or were resolved within the last shownFor — oldest first: what a view of that session shows.
func (*Store) Gone ¶
Gone expires every open question of (owner, source, scope, session) — the session is no longer running anywhere its host lists — with why as the Note. It returns how many it expired.
func (*Store) Open ¶
Open registers qs for key under id — the hook's own choice, so a retried registration names the same entry; "" lets the store choose.
Opening an id that already names key's entry returns it, whatever its state; an id naming another key is ErrIDTaken. Opening a key that is already OPEN under another id returns that entry; opening one that was resolved starts a new entry (the same call asked again).
func (*Store) OpenIn ¶
OpenIn is the open questions of (owner, source, scope, session), oldest first: what a watcher of that session waits on.
func (*Store) Pending ¶
Pending is owner's open questions, oldest first: what an attention view lists as "waiting on you".
func (*Store) Resolve ¶
func (s *Store) Resolve(owner int64, source, scope, session, toolUseID string, answers map[string]string) (Entry, bool)
Resolve records the call's result as the CLI recorded it: answers (nil when it ended with none — dismissed). An answered question is By muster when muster typed exactly these answers, else By the terminal. Resolving a resolved question changes nothing — except a Superseded or Expired one, whose result can still arrive (a session that came back, a late record) and is recorded. ok is false when the store has no open, superseded or expired question for the call.
func (*Store) Restore ¶ added in v0.151.0
Restore registers qs for key because the session's TRANSCRIPT shows the call open now — the session waiting, the call the newest unanswered one with no result (cctranscript.OpenAskOf; internal/api's open-question scan) — IDEMPOTENTLY, whatever was registered before:
- no entry for key (a restarted muster, a hook that never reached it): a new Pending one, as Open would make;
- an OPEN entry: left exactly as it is — never a second card, and an answer being typed is not disturbed;
- an EXPIRED one (its session looked gone, or it was not seen for MaxOpen): REOPENED, Pending, under the same id — the transcript says its picker is there;
- an ANSWERED, DECLINED or SUPERSEDED one: left as it is. The CLI's record (or a newer question) ended it; a late or stale read never reopens it.
🔴 A READ NEVER REPLACES A NEWER QUESTION: when key is missing or Expired and its session already has ANOTHER open question, Restore does nothing (key's entry as it is, or a zero Entry; unchanged). The read began before Restore runs, and whatever is open by then was registered during it — by the hook, from the picker on screen now — so it is the newer call; opening key would supersede it, and key's card (same text) would type into ITS picker.
changed reports whether it opened or reopened the question.
func (*Store) Seen ¶ added in v0.151.0
Seen records that the session (owner, source, scope, session) is listed by its host now: its open questions do not age towards MaxOpen.
func (*Store) Sweep ¶
func (s *Store) Sweep()
Sweep runs the expiry rules now, firing OnChange for every question it expires.
func (*Store) TypingDone ¶
TypingDone records that the host reported it typed the answer in: the CLI's record will resolve the question; no drive is running, and nothing of muster's is left half-typed.
func (*Store) TypingFailed ¶
TypingFailed records that muster could not type the answer in (f): a Typing question becomes Failed, still the terminal's to answer. A question the CLI resolved meanwhile is left as it is. Unsettled, no new typing may begin until MaxDrive after the last began (BeginTyping's ErrBusy), and what the picker holds is not known (no Left).