askq

package
v0.177.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 20 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 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

View Source
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.

View Source
const (
	ByMuster   = "muster"
	ByTerminal = "terminal"
)

Who answered (Entry.By).

View Source
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.

View Source
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).

View Source
const MultiJoin = ", "

MultiJoin is how a multi-select answer joins its parts.

View Source
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.

View Source
const SweepEvery = time.Minute

SweepEvery is RunSweep's period.

View Source
const ToolName = "AskUserQuestion"

ToolName is the tool this package answers.

Variables

View Source
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")
)
View Source
var ErrInvalid = errors.New("askq")

ErrInvalid wraps every refusal of a question set or of answers.

Functions

func AnswersOf

func AnswersOf(qs []Question, choices []Choice) map[string]string

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

func CheckAnswers(qs []Question, answers map[string]string) error

CheckAnswers verifies answers against qs: exactly one non-empty answer per question, keyed by its text, each within MaxAnswer and free of control characters.

func NewID

func NewID() string

NewID is a fresh entry id.

func ValidID

func ValidID(id string) bool

ValidID reports whether id is an entry id.

Types

type Choice

type Choice struct {
	Picks []int  `json:"picks,omitempty"`
	Other string `json:"other,omitempty"`
}

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

func FromForm(qs []Question, form url.Values) ([]Choice, map[string]string, error)

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
	// 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
}

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.

func (Hook) Run

func (h Hook) Run(ctx context.Context, payload []byte) bool

Run registers payload's call with muster. It returns whether muster took it; either way the hook prints nothing.

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

type Key struct {
	Owner     int64
	Source    string
	Scope     string
	Session   string
	ToolUseID string
}

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"`
}

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

func (q Question) Previews() bool

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"
)

func (State) Open

func (s State) Open() bool

Open reports whether a question in state s is still unanswered.

type Store

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

Store is the question store. The zero value is not usable; New.

func New

func New() *Store

New returns an empty store.

func (*Store) BeginTyping

func (s *Store) BeginTyping(key Key, answers map[string]string) (e Entry, again bool, err error)

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

func (s *Store) Dismissing(key Key) (Entry, error)

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) Find

func (s *Store) Find(key Key) (Entry, bool)

Find is key's newest entry, if the store has one.

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) Get

func (s *Store) Get(id string) (Entry, bool)

Get is entry id, if the store has it.

func (*Store) Gone

func (s *Store) Gone(owner int64, source, scope, session, why string) int

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) OnChange

func (s *Store) OnChange(fn func(Entry))

OnChange installs the change callback: a question was opened or changed.

func (*Store) Open

func (s *Store) Open(key Key, qs []Question, id string) (Entry, error)

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

func (s *Store) OpenIn(owner int64, source, scope, session string) []Entry

OpenIn is the open questions of (owner, source, scope, session), oldest first: what a watcher of that session waits on.

func (*Store) Pending

func (s *Store) Pending(owner int64) []Entry

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

func (s *Store) Restore(key Key, qs []Question) (e Entry, changed bool, err error)

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) RunSweep

func (s *Store) RunSweep(ctx context.Context, interval time.Duration)

RunSweep runs Sweep every interval until ctx ends.

func (*Store) Seen added in v0.151.0

func (s *Store) Seen(owner int64, source, scope, session string)

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) SetNow

func (s *Store) SetNow(now func() time.Time)

SetNow replaces the clock (tests).

func (*Store) Sweep

func (s *Store) Sweep()

Sweep runs the expiry rules now, firing OnChange for every question it expires.

func (*Store) TypingDone

func (s *Store) TypingDone(key Key)

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

func (s *Store) TypingFailed(key Key, f Failure) (Entry, error)

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).

func (*Store) Watched

func (s *Store) Watched(owner int64, source, scope, session string) []Entry

Watched is the questions of (owner, source, scope, session) whose result can still be recorded: the open ones, and the superseded or expired ones still retained (Retain) — what a watcher of that session keeps reading the transcript for.

Jump to

Keyboard shortcuts

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