ask

package
v0.7.39 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 32 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 ask answers the questions the addon queues with /ask (schema 1, see docs/ask.md). It reads WoWCompanionDB.asks from the addon's SavedVariables file, runs a headless agent CLI once per unanswered question, and writes the WoWCompanion_Answers slot addon's Answers.lua.

The agent gets the question and the character key, never the capture: it reads facts through the advisor's MCP tools.

Index

Constants

View Source
const (
	MaxAnswer        = 1500
	MaxOutput        = 64 << 10
	DefaultTimeout   = 2 * time.Minute
	DefaultMaxPerRun = 5
)

Limits. MaxAnswer is in characters. MaxOutput bounds what is read from the agent at all.

View Source
const (
	SourceFlag   = "flag"   // --agent
	SourceConfig = "config" // "agent" in the config file
	SourceAuto   = "auto"   // found on this machine
	SourceNone   = "none"   // no agent configured and none found
)

Where an agent came from, as the companion's handshake reports it.

View Source
const (
	// FactsBudget is the most characters of pre-fetched facts in a prompt (about 1.5k tokens).
	FactsBudget = 6000
	// FactsSteps is how many next steps are pre-fetched.
	FactsSteps = 5
	// FactsPlanSteps is how many route plan stops are pre-fetched (the plan's count covers the rest).
	FactsPlanSteps = 8
)

Pre-fetched facts: the character's brief and next steps are put in the prompt, so most questions need no tool call (each tool round trip resends the whole context). The tools stay available.

View Source
const (
	LengthBrief    = "brief"
	LengthStandard = "standard" // the default
	LengthDetailed = "detailed"
)

Answer length, applied in the system prompt the same way for every client.

View Source
const (
	TierEfficient = "efficient"
	TierBalanced  = "balanced"
	TierBest      = "best"
	TierCustom    = "custom" // Options.Custom, a model name the player typed
)

Model tiers. Efficient is the default: the client's small, fast tier.

View Source
const AgyRule = "mcp(" + ServerName + "/*)"

AgyRule is the permission rule that lets agy run the advisor's MCP tools without asking (https://antigravity.google/docs/permissions?tab=cli: mcp(server/*) matches every tool of one server).

View Source
const AutoAgent = "auto"

AutoAgent is the --agent (or config) value that asks for detection even when the config file names an agent.

View Source
const GroundingRules = "How to answer: answer from these facts first. Look anything up by id (quest id, NPC id, item id), " +
	"never by name alone. A lookup that finds nothing is not an answer: never tell the player there was \"no match\" or that " +
	"you cannot tell what this is. When the facts are thin, say plainly what they do show (who gives it, where, the level, " +
	"whether it is a class quest, why it is listed) and what it usually means. Never invent specifics such as a reward, " +
	"an ability name or a location that is not in the facts."

GroundingRules tell the agent how to use a subject's facts: they are the answer's first source, ids are the key for lookups (a quest or item can be missing from the dataset by name), and a miss is never reported to the player as "no match".

View Source
const JustReadRule = "" /* 140-byte string literal not displayed */

JustReadRule is added whenever a question arrives with a ref: the player clicked the entry and has read its card, so the answer is only what the card does not say, in the short answer shape.

View Source
const MaxTurns = 10

MaxTurns caps the agent's turns per ask where the CLI has a flag for it (Claude Code only).

View Source
const NeedsPlayStyle = "play_style"

NeedsPlayStyle is the Needs value of a question that cannot be answered before the character has a play style.

View Source
const NeedsSpec = "spec"

NeedsSpec is the Needs value of a talent question for a character that has a role and focus but no spec: the card has one button per talent tree and nothing else.

View Source
const NoDataFacts = "Game data not downloaded yet; see Setup. Tell the player this, in those words, rather than guessing quests, zones or gear."

NoDataFacts stands in for the next steps when no game dataset has downloaded.

View Source
const ProbeTimeout = 60 * time.Second

ProbeTimeout bounds one Probe.

View Source
const Schema = 1

Schema is the Answers.lua format version this package writes.

View Source
const ServerName = "wowc-advisor"

ServerName is the advisor's name in the generated MCP config and in each CLI's own settings.

View Source
const ShortAnswerRules = "Answer the question asked in your first sentence. Then add at most 3 short bullets (lines starting with \"- \"), only what matters for that question. " +
	"Never restate or re-list the plan, and add no unrelated steps. One optional last line starting \"Heads-up:\" is allowed for something urgent and nearby (such as a quest ready to turn in on the way). " +
	"The plan in the facts is shared context: if your answer would change what it says, say so in one plain sentence (for example \"Your plan has her later, after Unwelcome Spirits\") rather than contradicting it silently." + WordingRules

ShortAnswerRules shape every answer, whatever its length setting: the question first, little after it, and the plan left alone. The length setting is an upper bound on top of them.

View Source
const SlotAddon = "WoWCompanion_Answers"

SlotAddon is the data-only addon the answers are written into.

View Source
const SpecNote = "Saved for this character. Change it any time in Settings → Play Style."

SpecNote is the line under the spec buttons.

View Source
const ToolsUnavailable = "The advisor's tools weren't available to the AI client (setup problem)."

ToolsUnavailable is the answer when the AI client would not run the advisor's tools.

View Source
const UsageTip = "" /* 139-byte string literal not displayed */

UsageTip is the tooltip of the usage line.

View Source
const WordingRules = " Wording: lead with the answer. Never mention the advisor, data, \"general game knowledge\", tools, sources or what is missing; " +
	"when a fact is unknown, give the best practical step plainly (\"Any Blacksmithing trainer can teach it.\"), but for who trains, sells or teaches a recipe call where_to_learn and name the place it gives. " +
	"A requirement already met by far is an ability (\"You can make these now.\"), never \"you have 35, it needs 1\". " +
	"Never say something was saved unless the save tool succeeded in this answer."

WordingRules are the one wording rule for every answer, on both the CLI and the API path.

Variables

View Source
var (
	Lengths = []string{LengthStandard, LengthBrief, LengthDetailed}
	Tiers   = []string{TierEfficient, TierBalanced, TierBest, TierCustom}
	// Reasonings are the reasoning levels, lowest first.
	Reasonings = []string{"low", "medium", "high"}
)

Lengths and Tiers list the valid values, default first.

View Source
var DetectOrder = []string{"claude", "codex", "agy", "gemini"}

DetectOrder is the order the AI CLIs are looked for in; the first one found is used. Gemini CLI is legacy (API keys only since 2026-06-18), so it is chosen only when nothing else is installed.

View Source
var Presets = map[string][]string{

	"claude": {"claude", "-p", "{prompt}", "--mcp-config", "{mcp_config}", "--strict-mcp-config",
		"--tools", "", "--setting-sources", "", "--disable-slash-commands", "--no-session-persistence",
		"--exclude-dynamic-system-prompt-sections", "--allowedTools", "mcp__" + ServerName},

	"codex": {"codex", "exec", "--skip-git-repo-check", "--ephemeral", "-s", "read-only", "-c", "mcp_servers." + ServerName + "={mcp_codex}", "{prompt}"},

	"agy": {"agy", "-p", "{prompt}"},

	"gemini": {"gemini", "--allowed-mcp-server-names", ServerName, "--policy", "{mcp_policy}", "-p", "{prompt}"},
}

Presets are the documented agent commands (docs/ask.md lists what each passes). {prompt} is the question text, {mcp_config} the path of a generated MCP config file, {mcp_codex} the advisor server as a Codex inline config table, {mcp_policy} the path of a generated Gemini policy file; a command without {prompt} gets the prompt as its last argument.

Each preset pre-allows the advisor's tools and nothing else, because a headless run refuses what it cannot ask about.

View Source
var StreamArgs = []string{"--output-format", "stream-json", "--verbose", "--include-partial-messages"}

StreamArgs are appended to a Claude command to make it print stream-json with partial messages.

View Source
var Tools = []string{"character_brief", "get_character_profile", "list_characters", "quest_plan", "server_info", "set_character_profile", "stat_check", "talent_tree", "update_digest", "upgrade_finder", "upgrade_paths", "whats_next"}

Tools are the advisor tool names; an answer that names one gets it in its sources line.

Functions

func AgyWorkspace added in v0.4.0

func AgyWorkspace(mcpConfig string) string

AgyWorkspace is the folder an Antigravity run starts in: it holds .agents/mcp_config.json, the workspace MCP config agy reads (https://antigravity.google/docs/mcp/), beside the generated config.

func Argv

func Argv(tmpl []string, prompt, mcpConfig string) []string

Argv fills the placeholders in the command template; with no {prompt}, the prompt is appended. An argument that needs the MCP config is dropped, with the flag before it, when there is none.

func Clean

func Clean(s string) string

Clean trims the agent's output and cuts it to MaxAnswer characters, at a rune boundary.

func CleanTo added in v0.3.0

func CleanTo(s string, max int) string

CleanTo is Clean with a limit of max characters.

func ClientName added in v0.3.0

func ClientName(command []string) string

ClientName is the preset name (claude, codex, agy, gemini) of an agent command, or "" for any other.

func Command

func Command(ctx context.Context, argv []string) *exec.Cmd

Command is exec.CommandContext for the agent argv. On Windows a .cmd or .bat shim (npm's) runs through cmd.exe and a .ps1 script through PowerShell; anything else runs directly.

func Detect

func Detect(pathEnv string, extra []string) (name, path string, ok bool)

Detect finds the first of DetectOrder in the PATH list, else in the extra directories, and the full path to it.

func DetectedPath

func DetectedPath(source string, command []string) string

DetectedPath is the executable a detected agent runs ("" for any other source).

func DisplayName added in v0.4.0

func DisplayName(id string) string

DisplayName is the name people know a client by (Claude Code, Codex, Antigravity, Gemini CLI); any other id comes back as given. The overlay keeps the same table in app.js.

func ExtraDirs

func ExtraDirs(getenv func(string) string) []string

ExtraDirs are the places the AI CLIs' installers put them that a desktop app's PATH may lack. getenv supplies USERPROFILE, APPDATA, LOCALAPPDATA and ProgramFiles (Windows) or HOME.

On Windows:

%USERPROFILE%\.local\bin                       Claude Code's native installer (claude.exe)
%USERPROFILE%\.claude\local                    Claude Code's local install
%LOCALAPPDATA%\agy\bin                        Antigravity CLI's installer (agy.exe; install.ps1, https://antigravity.google/docs/getting-started)
%APPDATA%\npm                                  npm install -g shims (claude.cmd, codex.cmd, gemini.cmd)
%LOCALAPPDATA%\Microsoft\WinGet\Links          WinGet's command links
%LOCALAPPDATA%\Programs\claude
%USERPROFILE%\scoop\shims                      Scoop shims
%ProgramFiles%\nodejs                          a system-wide npm prefix

func Facts added in v0.4.0

func Facts(cfg Config, q Question) string

Facts is the pre-fetched facts block for q's character, or "" when the character cannot be chosen or the capture cannot be read (the agent then uses its tools, as before). The block is cut at FactsBudget characters.

func GeminiPolicy

func GeminiPolicy() []byte

GeminiPolicy is the Gemini CLI policy file: the advisor's tools run without asking, and shell, file writes and web access are denied outright (a headless run cannot ask).

func Launch added in v0.3.0

func Launch(ctx context.Context, argv []string, extraEnv ...string) (*exec.Cmd, error)

Launch builds the command for an agent argv: argv[0] is resolved to an absolute path, scripts are wrapped (see Command) and the environment carries a fresh PATH. The error is fit to show.

func LookPath added in v0.3.0

func LookPath(name string) (string, error)

LookPath resolves an agent command to an absolute file, by the rules detection uses: PATH from freshPath, PATHEXT, then the known install folders. A name with a directory is used as given (with an extension added on Windows). A .ps1 script is swapped for a sibling .cmd or .exe.

func MCPConfig

func MCPConfig(exe string, env map[string]string) []byte

MCPConfig renders the MCP config JSON handed to the agent: it starts this binary as a stdio server on the capture. The agent reads facts through it and is never given the file itself.

func ModelArgs added in v0.3.0

func ModelArgs(command []string, o Options) (args []string, at int)

ModelArgs are the arguments that select the model (and cap the turns) for the command's client, and the index in the argv they go at: right after the program, or after Codex's exec subcommand. A command that is not a known client gets none.

func ModelUsed added in v0.3.0

func ModelUsed(command []string, o Options) string

ModelUsed names the model an ask with these options runs, as far as the command line says: the alias or custom name, or "default model" when the client picks its own.

func OrderSpecs added in v0.7.35

func OrderSpecs(specs []string, role string) []string

OrderSpecs puts the trees that fit the role first: tank trees for a tank, healing trees for a healer, the rest for damage. Every tree is still offered; the order is otherwise kept.

func PathStepsRule added in v0.7.16

func PathStepsRule(kind string) string

PathStepsRule is added when the player asks an upgrade's first question, the one that follows the path the card suggests: they want the steps, not the card's one line again. It keeps the short answer shape (one answer line, then at most 3 steps) and takes its facts from upgrade_paths.

func PolicyPath

func PolicyPath(mcpConfig string) string

PolicyPath is where the Gemini policy file sits: next to the generated MCP config.

func Probe added in v0.3.0

func Probe(ctx context.Context, command []string, prompt string) (string, error)

Probe sends one tiny prompt through the agent and returns its first output line. A failure is an error whose text is the first line the agent printed to stderr (for example "not signed in"), else a short reason. It reads nothing from the game and hands the agent no MCP config.

func Prompt

func Prompt(q Question) string

Prompt is PromptFor at the default (Standard) length.

func PromptFor added in v0.3.0

func PromptFor(q Question, length string) string

PromptFor is what the agent is asked: the question and the character key, where the facts are, what to say if the tools are missing, and how long the answer should be. It is kept short on purpose, as it is sent with every ask.

func PromptWithFacts added in v0.4.0

func PromptWithFacts(q Question, length, facts string) string

PromptWithFacts is PromptFor plus the pre-fetched facts, when there are any.

func ResolveAgent

func ResolveAgent(flagValue, configPath string) ([]string, error)

ResolveAgent turns the --agent value, or else the config file's "agent" field, into an argv. A preset name (claude, codex, agy, gemini) expands to its command; anything else is split on spaces.

func ResolveRef added in v0.7.7

func ResolveRef(cfg Config, q Question) string

ResolveRef is q's ref: the one it carries, else that of the current suggested question of the character that the text matches exactly (case and punctuation aside); "" when neither.

func Respond

func Respond(ctx context.Context, cfg Config, q Question, prompt string, stream bool, onText func(string)) (text string, streamed bool, err error)

Respond runs the agent for q with prompt (see Prompt) and returns the answer. With stream set the command is Claude's: its text deltas are passed to onText as they arrive and streamed is true when any did. Otherwise the output is read whole, cut like ask does, and streamed is false.

func SavedNote added in v0.7.35

func SavedNote(text string) string

SavedNote is the saved_note field of a set_character_profile result, "" when it is not there.

func Sources

func Sources(s string) []string

Sources lists the advisor tools the output names, in Tools order.

func Stamp

func Stamp(path string) string

Stamp identifies a file's content cheaply enough to poll.

func StatQuestion added in v0.7.12

func StatQuestion(q Question) bool

StatQuestion reports whether a question is about the character's stats (the stat check's subject).

func TalentQuestion added in v0.7.0

func TalentQuestion(text string) bool

TalentQuestion reports whether a question is about talents.

func WithModel added in v0.3.0

func WithModel(argv []string, command []string, o Options) []string

WithModel returns argv with ModelArgs spliced in.

func WithSaved added in v0.7.35

func WithSaved(answer, note string) string

WithSaved ends the answer with the saved note, once; the note comes from the tool, not the model.

func WriteAgyWorkspace added in v0.4.0

func WriteAgyWorkspace(mcpConfig string, data []byte) error

WriteAgyWorkspace writes mcpConfig's contents to AgyWorkspace's .agents/mcp_config.json.

Types

type API added in v0.7.26

type API struct {
	Name    string           // short name for messages, e.g. "Anthropic (Claude)"
	Adapter provider.Adapter // sends the calls; holds the key
	Model   string           // the model id to ask
	NeedKey bool
	HasKey  bool
	// MaxTurns, Timeout and MaxResult override the loop's defaults (zero: MaxTurns, Config.Timeout, the loop's).
	MaxResult int
}

API is a model provider API client (client kind "api"): the loop runs in this process, and the advisor's tools are served to it over an in-memory MCP session, the same server a CLI starts.

func APIFor added in v0.7.26

func APIFor(ref provider.ClientRef, opts Options, keys provider.KeyStore, hc *http.Client) (*API, error)

APIFor builds the API client for ref; keys supplies its key (nil: none). opts is the overlay's answer setting, which picks the tier when ref names none.

type Agent

type Agent struct {
	Command []string
	Name    string
	Source  string
}

Agent is a resolved agent: its argv, its short name and where it came from. A Source of SourceNone has no Command.

func ResolveAuto

func ResolveAuto(flagValue, configPath string) (Agent, error)

ResolveAuto is ResolveAgent for callers that can run without an agent: with nothing configured, or the value "auto", it looks for the first of DetectOrder installed. Nothing found is no error.

type Choice added in v0.3.0

type Choice struct {
	Tier  string `json:"tier"`  // the Options.Tier it selects
	Label string `json:"label"` // "Haiku (small)"
}

Choice is one entry of a client's model dropdown.

type Choices added in v0.3.0

type Choices struct {
	Models        []Choice `json:"models"`                   // empty: the client's model is not ours to set
	ModelNote     string   `json:"model_note"`               // the model dropdown's tooltip
	Reasoning     []string `json:"reasoning"`                // empty: the client has no reasoning option
	ReasoningNote string   `json:"reasoning_note,omitempty"` // the reasoning dropdown's tooltip
}

Choices is what the settings dropdowns offer for a client.

func ChoicesFor added in v0.3.0

func ChoicesFor(client string) Choices

ChoicesFor lists the model and reasoning options for a client name; a client that is not a known preset gets none, and the notes say why.

type Config

type Config struct {
	SavedVariables string             // the addon's WoWCompanion.lua
	Command        []string           // the agent argv, see Presets; empty when no agent is set up (the companion only)
	Name, Source   string             // the agent's short name and where it came from (see Agent); may be empty
	Dataset        string             // dataset directory for the pre-fetched next steps (empty: none)
	MCPConfig      string             // path of the MCP config file handed to the agent; may be empty
	Options        Options            // answer length, model tier and reasoning, see Options
	API            *API               // set: ask this model provider API instead of running Command
	Server         func() *mcp.Server // builds the advisor's tools for an API client (nil: none)
	Fallback       []Config           // tried in order when this client cannot start (see RespondUsage)
	Notice         func(string)       // told a one-line notice, e.g. that the CLI rejected a flag (may be nil)
	Timeout        time.Duration
	MaxPerRun      int
	Now            func() time.Time
}

Config is one pass's settings.

func (Config) Prompt added in v0.4.0

func (c Config) Prompt(q Question) string

Prompt is what the agent is asked for q under cfg: PromptFor with the pre-fetched facts.

func (Config) Usable added in v0.7.26

func (c Config) Usable() bool

Usable reports whether the config can ask anything: an agent command or an API client.

func (Config) WithClients added in v0.7.26

func (c Config) WithClients(st provider.Settings, keys provider.KeyStore, hc *http.Client) Config

WithClients applies a saved client list to c: the first client answers, the rest follow in order when it cannot start. An empty list returns c unchanged (the CLI-only setup).

type Entity added in v0.7.30

type Entity struct {
	Kind string `json:"kind"`
	ID   int64  `json:"id,omitempty"`
	Name string `json:"name"`
}

Entity is something an answer's tools touched: a quest, NPC, item, zone or recipe, with its display name.

func AnswerEntities added in v0.7.35

func AnswerEntities(cfg Config, char, answer string, touched []Entity) []Entity

AnswerEntities is what the answer is about: the touched, character and dataset entities named in the answer text, first mention first.

func DatasetEntities added in v0.7.35

func DatasetEntities(ds store.DataStore, answer string) []Entity

DatasetEntities are the dataset's items, recipes, NPCs and instances named in the answer: every run of up to six words that starts with a capital is looked up by exact name.

func EntitiesIn added in v0.7.30

func EntitiesIn(tool, text string) []Entity

EntitiesIn finds the entities in one tool result: JSON objects with a display name and an id (or a tool that names its kind), and a "zone" name. At most maxPerResult, in the order they appear.

func KnownEntities added in v0.7.35

func KnownEntities(cfg Config, char string) []Entity

KnownEntities are the names the character's own data can put on a card: its quest log, gear, bags, NPCs, zone and the entries of its digest.

func Subjects added in v0.7.35

func Subjects(answer string, known []Entity) []Entity

Subjects are the known entities whose names appear in the answer text, in the order they first appear, so the answer's lead subject comes first. A name inside a longer matched name is not a separate subject. Each entity counts once.

type Needs added in v0.7.7

type Needs struct {
	Needs      string   `json:"needs"` // NeedsPlayStyle
	Character  string   `json:"character"`
	Question   string   `json:"question"` // the original question, as asked
	Ref        string   `json:"ref,omitempty"`
	Hook       string   `json:"hook,omitempty"` // for a stat question: "Choose a play style for a stat check"
	Roles      []Option `json:"roles"`
	Activities []Option `json:"activities"`
	Specs      []string `json:"specs,omitempty"` // the class's trees, optional
	Note       string   `json:"note,omitempty"`  // NeedsSpec: the line under the buttons
	Role       string   `json:"role,omitempty"`  // NeedsSpec: the saved role and focus the choice is saved with
	Focus      string   `json:"focus,omitempty"`
}

Needs is the structured response to a question that needs a play style the character does not have. No AI call is made for it: the overlay shows the options as buttons, saves the choice with the profile store (POST /api/profile), and the question is then asked again once, automatically.

func NeedsFor added in v0.7.7

func NeedsFor(c character.Character, q Question) Needs

NeedsFor builds the choices for c.

func PlayStyleNeeded added in v0.7.7

func PlayStyleNeeded(cfg Config, q Question) (Needs, bool)

PlayStyleNeeded is the choices to put to the player instead of an AI call, when q needs a play style the character has not saved; ok is false when it does not, or the character cannot be read (the agent then works as before).

type Option added in v0.7.7

type Option struct {
	Value string `json:"value"`
	Label string `json:"label"`
}

Option is one button: the value saved and the words shown.

type Options added in v0.3.0

type Options struct {
	Length string // brief, standard (default) or detailed
	Tier   string // efficient (default), balanced, best or custom
	Custom string // the model name for TierCustom
	// Reasoning is the reasoning level (low, medium or high); low is the default. It is passed only
	// to a client that has a flag for it, see reasoningFor.
	Reasoning string
	// contains filtered or unexported fields
}

Options are the per-ask settings the player controls. The zero value is Standard and Efficient.

func (Options) AnswerLimit added in v0.3.0

func (o Options) AnswerLimit() int

AnswerLimit is the most characters an answer of this length is kept to.

func (Options) Normalize added in v0.3.0

func (o Options) Normalize() Options

Normalize replaces an unknown value by its default; a custom tier without a usable model name (it is passed as a flag value, so it must look like a model name) falls back to Efficient.

type Question

type Question struct {
	ID        string
	Character string
	Text      string
	AskedAt   int64
	Answered  bool
	// Ref is the subject the question is about (a digest entry's ref, see docs/digest.md); empty for a
	// free-typed question. The advisor expands it into the entry's facts.
	Ref string
}

Question is one queued question.

type Registry added in v0.3.0

type Registry interface {
	// Paths are the user's and the system's PATH values, %VAR% references already expanded.
	Paths(getenv func(string) string) []string
}

Registry reads the PATH the machine's settings hold, as opposed to the one this process was started with. A fake stands in for it in tests so they run on any OS.

type Trace added in v0.7.30

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

Trace collects the entities seen in one ask's tool calls and results, oldest first.

func (*Trace) Add added in v0.7.30

func (t *Trace) Add(tool, text string)

Add records the text a named tool returned.

func (*Trace) Entities added in v0.7.30

func (t *Trace) Entities() []Entity

Entities is what was seen, oldest first.

func (*Trace) Result added in v0.7.30

func (t *Trace) Result(id, text string)

Result records the text a tool returned for the call id.

func (*Trace) Saved added in v0.7.35

func (t *Trace) Saved() string

Saved is the line a successful set_character_profile call returned in this ask ("" when none did).

func (*Trace) Use added in v0.7.30

func (t *Trace) Use(id, tool string)

Use records a tool call (stream-json "tool_use") so its result can be matched to the tool.

type Usage added in v0.3.0

type Usage struct {
	Tokens   int      // input, output and cache tokens together
	In       int      // fresh input: new input plus tokens written to the cache
	Out      int      // output
	Cached   int      // tokens read from the cache
	CostUSD  float64  // total_cost_usd, when reported
	Model    string   // the model that ran: reported by Claude, else the one the command line selected
	Notice   string   // a one-line notice for the player, e.g. a rejected flag that was dropped
	Saved    string   // the line a successful set_character_profile returned, for the end of the answer
	Entities []Entity // what the answer's tools touched, oldest first (empty when the client shows no tool trace)
}

Usage is what the CLI reported for one ask. Tokens is zero when it reported nothing.

func RespondUsage added in v0.3.0

func RespondUsage(ctx context.Context, cfg Config, q Question, prompt string, stream bool, onText func(string)) (text string, streamed bool, usage Usage, err error)

RespondUsage is Respond that also returns the token usage Claude's stream-json result reports.

With cfg.Fallback set, a client that cannot start (no key, not reachable, key refused, no such program) hands over to the next one, and the usage notice says so.

func (Usage) Line added in v0.3.0

func (u Usage) Line() string

Line is the small muted text shown under an answer ("≈4k in · 0.6k out · 52k cached · haiku"; only the total when the CLI gave no split), empty with neither tokens nor a model.

Jump to

Keyboard shortcuts

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