Documentation
¶
Index ¶
- Constants
- Variables
- func AcceptTrim(estimateBefore, tokensRemoved, contextWindow int, settings CompactionSettings) bool
- func AcquireFileLock(path string) (io.Closer, error)
- func AddProjectAllowPattern(workspaceRoot, pattern string) error
- func AgentIDFromContext(ctx context.Context) string
- func AllowedModelAliases(allowedIDs []string) []string
- func AllowedOAuthCode(code string) string
- func BuildSTTPrompt(vocabulary []string) string
- func BuiltinOnlyToolName(name string) bool
- func CacheDebug() bool
- func CacheTTLDuration(cfg MoaConfig) time.Duration
- func CanonicalModelID(id string) string
- func CanonicalOrRaw(path string) string
- func CanonicalizePath(path string) (string, error)
- func CloneArgs(m map[string]any) map[string]any
- func CodebaseKey(dir string) string
- func CompactModelFallbackNotice(reason CompactModelFallback, spec string, used Model) string
- func CompactModelUnavailableNotice(configured, used Model, reason string) string
- func ConfigDir() string
- func ConfigSubdir(parts ...string) string
- func CorrectImageMime(b64, declared string) string
- func DaybreakPromptCacheKey(key, program string) string
- func DaybreakSpec(spec string) bool
- func EffectiveThinkingLevel(model Model, level string) (string, error)
- func EstimateOutputTokens(m Message) int
- func EstimateTokens(m Message) int
- func ExtractAssistantText(msg AgentMessage) string
- func ExtractFinalAssistantText(msgs []AgentMessage) string
- func FastCostMultiplier(model Model) float64
- func FastNote(modelID string) string
- func GetCacheTTL(cfg MoaConfig) string
- func GetCompactAt(cfg MoaConfig) int
- func GetCompactModel(cfg MoaConfig) string
- func GetCompactStrategy(cfg MoaConfig) string
- func GetMaxRunDuration(cfg MoaConfig) time.Duration
- func GetSTTLanguage(cfg MoaConfig) string
- func GetSTTModel(cfg MoaConfig) string
- func GetSubagentMaxRunDuration(cfg MoaConfig) time.Duration
- func GetTrimDisabled(cfg MoaConfig) bool
- func HumanSessionMentionsCustom(ids []string) map[string]any
- func ImageDimensions(data []byte) (width, height int)
- func ImageExceedsMaxDimension(b64 string) (width, height int, exceeds bool)
- func ImageMimeFromBytes(data []byte) string
- func ImportLegacyProjectVeto(cwd string) error
- func IsAskUserAsync(cfg MoaConfig, def bool) bool
- func IsAutoVerifyEnabled(cfg MoaConfig) bool
- func IsForYouSnapshot(m AgentMessage) bool
- func IsMCPPathTrusted(cfg MoaConfig, path string) bool
- func IsMemoryEnabled(cfg MoaConfig) bool
- func IsModelAllowed(model Model, allowedIDs []string) bool
- func IsModelAllowedFor(model Model, daybreak bool, allowedIDs []string) bool
- func IsPersistentShellEnabled(cfg MoaConfig) bool
- func IsProjectPathTrusted(cfg MoaConfig, path string) bool
- func IsUpdateCheckEnabled(cfg MoaConfig) bool
- func IsValidThinkingLevel(level string) bool
- func LoadMCPFile(path string) (map[string]MCPServer, error)
- func MergeMCPServers(maps ...map[string]MCPServer) map[string]MCPServer
- func ModelAliases() []string
- func NativeDocBytes(content []Content) int64
- func NewMsgID() string
- func NewSteerID() string
- func ProjectHash(workspaceRoot string) string
- func ProjectStateDir(workspaceRoot string) string
- func PromptCacheKey(sessionID string) string
- func ProviderSupportsDeferredTools(p Provider, modelID string) bool
- func ProviderSupportsDocuments(p Provider) bool
- func ReactiveRefreshError(provider string, err error) error
- func ReasoningEffortsForModel(model Model) []string
- func RegisterOrLog(reg *Registry, t Tool)
- func RepoCodebaseKey(dir string) (string, bool)
- func ReservedToolName(name string) bool
- func ResolveCompactAt(sessionCompactAt, globalCompactAt int) int
- func ResolveCompactModel(spec string, sessionModel Model, available AuxiliaryModelAvailable) (Model, CompactModelFallback)
- func ResolveMaxOutputTokens(model Model, requested *int) int
- func ResolvePathScope(pathScope string, disableSandbox bool, permMode string) string
- func SameModelIdentity(requested, effective string) bool
- func SameResponseOrigin(requested, effective string) bool
- func SaveGlobalConfig(update func(*MoaConfig)) error
- func SaveProjectConfig(cwd string, update func(*MoaConfig)) error
- func SetConfigPathGuardForTests(guard func(path string))
- func SetMCPServerDisabled(cfg *MoaConfig, name string, disabled bool)
- func SetProjectMCPServerDisabled(workspaceRoot, server string, disabled bool) error
- func ShouldCompact(contextTokens, contextWindow int, settings CompactionSettings) bool
- func ShouldWarnBeforeCompact(contextTokens, contextWindow int, settings CompactionSettings) (warn bool, remaining int)
- func SkillInvocation(custom map[string]any) (command string, ok bool)
- func SubagentPromptCacheKey(parentKey string) string
- func SuggestAliasFrom(spec string, aliases []string) string
- func SuggestModelAlias(spec string) string
- func SupportsFast(modelID string) bool
- func ThinkingAlwaysOn(model Model) bool
- func ThinkingLevelOptions() string
- func ThinkingPosition(model Model, effort string) string
- func ToolCallIDFromContext(ctx context.Context) string
- func ToolCallMessageIDFromContext(ctx context.Context) string
- func TrimMinGain(contextWindow int, settings CompactionSettings) int
- func UpdatePinnedModels(models []string, id string, pinned bool) []string
- func UpdateProjectState(workspaceRoot string, update func(*ProjectState)) error
- func ValidateAuxiliaryModelConfig(cfg MoaConfig) error
- func ValidateAuxiliaryModelSpec(spec string) error
- func ValidateEventSourceName(name string) error
- func ValidateMCPServers(servers map[string]MCPServer) error
- func ValidateModelSpec(spec string) error
- func WithAgentID(ctx context.Context, id string) context.Context
- func WithToolCallID(ctx context.Context, id string) context.Context
- func WithToolCallMessageID(ctx context.Context, id string) context.Context
- type AgentEvent
- type AgentMessage
- type AnthropicThinking
- type AppliedOutputCap
- type AssistantEvent
- type AuxiliaryModelAvailable
- type BackgroundCompactionState
- type CacheKeepAliveConfig
- type CacheMiss
- type CachePrewarmer
- type CacheUsageAccumulator
- type CacheUsageSummary
- type CompactModelFallback
- type CompactionCommit
- type CompactionNotSavedError
- type CompactionPayload
- type CompactionSettings
- type CompactionSummarizer
- type Content
- func CloneContent(in []Content) []Content
- func DocumentContent(data, mime, filename string) Content
- func ImageContent(data, mime string) Content
- func TextContent(text string) Content
- func ThinkingContent(text string) Content
- func ToolCallContent(id, name string, args map[string]any) Content
- func ToolReferenceContent(name string) Content
- type ContextEstimate
- type DaybreakAvailability
- type DeferredToolsProvider
- type DocumentCapableProvider
- type EmptyResponseError
- type EventCreateConfig
- type EventSourceConfig
- func (s EventSourceConfig) AutorunEnabled() bool
- func (s EventSourceConfig) RateOrDefault() int
- func (s EventSourceConfig) TargetKind() string
- func (s EventSourceConfig) Validate(name string) error
- func (s EventSourceConfig) WhenManyOrDefault() string
- func (s EventSourceConfig) WhenNoneOrDefault() string
- type EventTarget
- type EventsConfig
- type ExecuteFunc
- type FallbackTranscriber
- type FreshPayload
- type KeepAliveHorizons
- type KeepAlivePolicy
- type KeepAliveRolePolicy
- type LoadedMoaConfig
- type LockKeyFunc
- type MCPDisablePolicy
- type MCPDisableResolution
- type MCPDisableScope
- type MCPDisableSources
- type MCPServer
- type Message
- type MoaConfig
- type Model
- type ModelEntry
- type NoFallbackError
- type PermissionsConfig
- type PreviewConfig
- type Pricing
- type PricingTier
- type ProjectState
- type Provider
- type ProviderAuthError
- type ProviderCredentialError
- type ProviderDispatch
- type ProviderErrorDetail
- type ProviderExecution
- type ProviderRetryReady
- type ProviderRetryWait
- type ProviderSource
- type ProviderUnwrapper
- type ProviderWait
- type QuotaExceededError
- type RateLimit
- type Registry
- func (r *Registry) All() []Tool
- func (r *Registry) Count() int
- func (r *Registry) Get(name string) (Tool, bool)
- func (r *Registry) Register(t Tool) error
- func (r *Registry) Specs() []ToolSpec
- func (r *Registry) Unregister(name string)
- func (r *Registry) WithInternalTools(internal ...Tool) (*Registry, error)
- type Request
- type RequestBreakpoint
- type RequestFingerprint
- type RequestFingerprintFunc
- type RequestPrefixHash
- type Result
- type SteerItem
- type StreamOptions
- type Tool
- type ToolCallDecision
- type ToolEffect
- type ToolSpec
- type TranscribeOptions
- type Transcriber
- type TrimPayload
- type TrimPlan
- type TrimSpan
- type Usage
- type VoiceCallHours
- type VoiceCallsConfig
- type VoiceConfig
Constants ¶
const ( // CacheMissExpired: the gap since the previous request outlasted the // provider's cache window. CacheMissExpired = "expired" // CacheMissModelChanged: another provider or model served the request, and // a cache is per model. CacheMissModelChanged = "model_changed" // CacheMissCompaction: the history was rewritten by a compaction. CacheMissCompaction = "compaction" // CacheMissContextCut: the context shrank (start fresh or trimmed tool // results), so the prefix no longer matches. CacheMissContextCut = "context_cut" // CacheMissUnknown: nothing the transcript records explains it. A gap // inside the window lands here on purpose: a cause is only named when it // is demonstrated. CacheMissUnknown = "unknown" )
Why a turn read less cache than the previous one had left behind.
const ( // SummarizerCapNone: the request carried no output cap. SummarizerCapNone = "none" // SummarizerCapApplied: the request carried MaxOutputTokens. SummarizerCapApplied = "applied" // SummarizerCapUnknown: the provider did not report what it sent. SummarizerCapUnknown = "unknown" )
Output cap states of a summarizer call.
const ( MinQuestionCallMinutes = 5 MaxQuestionCallMinutes = 240 )
Bounds of a question's wait before a call, in minutes (call_after_minutes and QuestionCallMinutes alike).
const ( // CompactPlain summarizes with no warning. What the agent was holding // survives only insofar as the summarizer captured it. CompactPlain = "plain" // CompactNotify tells the agent the threshold is near and to persist // anything that exists only in the conversation. Costs no extra request: // the notice rides on the next message. CompactNotify = "notify" // CompactPrepare gives the agent a full turn to prepare before compacting // (the /prepare-compact path). More thorough — it can use the ephemeral // checkpoint — but costs a request and may write files. CompactPrepare = "prepare" )
Compaction strategies: what the agent gets before its context is summarized.
An automatic compaction arrives mid-task with no warning, so anything the agent had worked out but not yet written down is replaced by a summary.
const ( // DaybreakAccessProgram is the wire value of access_programs.cyber. DaybreakAccessProgram = "daybreak_blue" // DaybreakModelID is the model the "daybreak" spec resolves to. DaybreakModelID = "gpt-6-sol" // LegacyDaybreakModelID is the retired alias sessions used before the mode // existed. It stays in the registry for the cost and identity of history, // but asking for it now means DaybreakModelID with the program. LegacyDaybreakModelID = "gpt-daybreak-blue-latest" )
Daybreak is a per-session request mode, not a model: the request carries an access program next to an ordinary model, the way the official Codex client sends it ({"access_programs":{"cyber":"daybreak_blue"}}).
const ( AgentEventProviderExecution = "provider_execution" AgentEventStart = "agent_start" AgentEventEnd = "agent_end" AgentEventError = "agent_error" AgentEventTurnStart = "turn_start" AgentEventTurnEnd = "turn_end" AgentEventMessageStart = "message_start" AgentEventMessageUpdate = "message_update" AgentEventMessageEnd = "message_end" AgentEventToolExecStart = "tool_execution_start" AgentEventToolExecUpdate = "tool_execution_update" AgentEventToolExecEnd = "tool_execution_end" AgentEventSteer = "steer" // a steering message was injected mid-run // AgentEventUserMessage reports a user prompt that just entered the // conversation as the first message of a new run, emitted at the append // point (under the state lock) so the fact is already true in history when // subscribers see it. Mid-run injections keep using AgentEventSteer. AgentEventUserMessage = "user_message" // AgentEventSteersCanceled reports queued steers dropped after a failed run. AgentEventSteersCanceled = "steers_canceled" AgentEventCompactionStart = "compaction_start" AgentEventCompactionEnd = "compaction_end" // AgentEventContextTrimmed reports that old tool results were replaced by // placeholders in the model's context INSTEAD of compacting. No summarizer // call, no information destroyed: the tree keeps the originals. AgentEventContextTrimmed = "context_trimmed" // AgentEventBackgroundCompaction reports a transition of the background // compaction state. Session-level: never part of a run's accounting. AgentEventBackgroundCompaction = "background_compaction" // AgentEventCompactionUsage reports the known usage of one background // summary call, once, whether or not its result is kept. Origin is the // invocation that started the job. AgentEventCompactionUsage = "compaction_usage" // rejected premium-speed request and disabled it for the session. AgentEventFastUnavailable = "fast_unavailable" )
Agent event type constants.
const ( EventTargetInbox = "inbox" EventTargetProject = "project" EventTargetSession = "session" EventTargetOwner = "owner" EventWhenInbox = "inbox" EventWhenCreate = "create" EventWhenLatest = "latest" // DefaultEventRatePerHour caps auto-deliveries and session creations per // source when `rate` is omitted. DefaultEventRatePerHour = 10 )
Event source routing defaults. An omitted field means the same as these.
const ( KeepAliveRoleOwner = "owner" KeepAliveRoleSession = "session" KeepAliveRoleSubagent = "subagent" )
Keep-alive roles: who the agent is decides how long its cache is worth keeping warm.
const ( KeepAliveIdle = "idle" // nothing pending KeepAliveAskUser = "ask_user" // blocked on a question to the user KeepAliveWaiting = "waiting" // blocked on a tool, or idle with background work (bash job, async subagent) )
Keep-alive states: what an agent that is not calling the model is waiting for.
const ( ProviderEventStart = "start" ProviderEventTextStart = "text_start" ProviderEventTextDelta = "text_delta" ProviderEventTextEnd = "text_end" ProviderEventThinkingStart = "thinking_start" ProviderEventThinkingDelta = "thinking_delta" ProviderEventThinkingEnd = "thinking_end" ProviderEventToolCallStart = "toolcall_start" ProviderEventToolCallDelta = "toolcall_delta" ProviderEventToolCallEnd = "toolcall_end" ProviderEventRateLimit = "ratelimit" ProviderEventDone = "done" ProviderEventError = "error" )
Provider event type constants.
const ( CredentialMissing = "missing" CredentialReconnect = "reconnect" CredentialKeyRejected = "key_rejected" CredentialTemporary = "temporary" CredentialChanged = "credentials_changed" CredentialPersistenceFailed = "persistence_failed" CredentialSaveConflict = "save_conflict" CredentialQuota = "quota" CredentialPermissions = "permissions" )
Credential error classes. They describe what the user can do about a provider credential failure, not what the upstream said.
const ( CredentialSourceEnv = "env" CredentialSourceStore = "store" )
Credential sources.
const ( // ToolCallDecisionKindPermission marks user-facing permission denials. ToolCallDecisionKindPermission = "permission" // ToolCallDecisionKindPolicy marks non-permission policy/plan blocks. ToolCallDecisionKindPolicy = "policy" )
const CacheOff = "off"
CacheOff is the CacheRetention value for a request whose prefix will never be reused. A cache write is billed at a premium over plain input, so paying it for an entry no later request can hit is pure cost: conversation turns share a prefix and benefit, one-shot requests built from a different system prompt and a flattened transcript do not.
const CompactModelSession = "session"
CompactModelSession is the CompactModel value meaning "summarize with the model the session is already using", which is how compaction behaved before this setting existed.
const CustomDurableAdmission = "durable_admission"
CustomDurableAdmission is the Custom key of a message whose admission to the conversation must be on disk before the model reads it: the loop saves the session, acknowledged, before the next request that would carry it. A failed save ends the run without inferring, so a receipt (the message in the saved transcript) always precedes the work that message causes.
const CustomKeyHumanSessionMentions = "human_session_mentions"
CustomKeyHumanSessionMentions is the Custom key under which the serve layer records the sessions a human explicitly selected (@) in a message. It is a receipt minted only by the human /send path; read_session authorizes against it, never against the message text.
const CustomKeyPatchFiles = "patch_files"
CustomKeyPatchFiles is the Result.Custom key under which apply_patch records the per-file diffs of what it wrote. The frontend renders them; the model never receives them.
const CustomSnapshotEpoch = "snapshot_epoch"
CustomSnapshotEpoch is the Custom key of a For you snapshot holding the compaction epoch it was added under, so a context rebuilt after a compaction (even across a restart) knows it still owes a fresh one.
const DefaultCallRingSeconds = 45
DefaultCallRingSeconds is how long an owner's call request rings (D6).
const DefaultMaxOutputTokens = 32_000
DefaultMaxOutputTokens bounds a single model response when the caller has not selected a smaller cap. It leaves room for reasoning without allowing one request to consume a model's entire output allowance.
const DefaultQuestionCallMinutes = 15
DefaultQuestionCallMinutes is how long an owner's tap-only question waits before it escalates to a call, unless Settings say otherwise.
const DefaultSTTModel = "gpt-transcribe"
DefaultSTTModel is the speech-to-text model used when none is configured.
gpt-transcribe replaced whisper-1 as the default: on our own Spanish dictation it was faster, 25% cheaper per minute, and noticeably better at technical names (whisper turned "MCP" into "MSP" and "goreleaser" into "Gore Leaser").
const DefaultVoiceBackendModel = "gpt-6.1-sol"
DefaultVoiceBackendModel serves the tools of a voice call when no model is configured.
const MaxImageBase64Bytes = 10 * 1024 * 1024
MaxImageBase64Bytes is Anthropic's maximum image payload size after base64 encoding. The limit is applied where images enter history so a block that would be rejected cannot poison every later replay of the conversation.
const MaxImageDimension = 8000
MaxImageDimension is the largest side, in pixels, accepted for an inline image. It is Anthropic's limit: it rejects anything above 8000 px per side with a hard 400, and because history is replayed on every turn a single oversized image makes the whole conversation unsendable until the block is removed.
OpenAI has no equivalent hard limit — it caps the request payload (512 MB) and the image count (1500), and oversized images are resized server-side to a patch/pixel budget rather than rejected. The one exception is GPT-5.6 with detail "original"/"auto" (what convertUserContent sends), which preserves the input dimensions and bills every patch: a 395x8239 screenshot is not an error there, just expensive. So the limit is enforced where images enter history (the read tool and attachments), which keeps a session portable across providers — a history built under OpenAI must not become unsendable the moment the user switches to Anthropic mid-session.
const SourceForYouSnapshot = "foryou_snapshot"
SourceForYouSnapshot is the Custom "source" of a user-role message that carries the session's For you state as moa observed it (its open questions and recent News). The loop appends one when that state changes, and never edits or moves an earlier one: the latest in the context governs, the earlier ones are history. It is moa talking to the model, not the user.
const ToolSearchName = "tool_search"
ToolSearchName is the tool the agent adds to a request whose deferrable tools the provider loads on demand. It is never registered: the agent provides it only while deferral is on, so no other source may claim it.
const ( // TrimProjectionVersion is the version of the elision algorithm below. It // is persisted with every trim so a later change to the placeholder format // or the eligibility rule cannot retroactively rewrite regions elided by an // older build: each region is replayed with the rules that produced it, // which is what keeps a restored context identical to the one the provider // saw — and its prefix cache warm. TrimProjectionVersion = 1 )
Variables ¶
var DefaultCacheKeepAlive = KeepAlivePolicy{ LargeContextTokens: 200_000, PingEvery1h: 55 * time.Minute, PingEvery5m: 4*time.Minute + 30*time.Second, Roles: map[string]KeepAliveRolePolicy{ KeepAliveRoleOwner: { MinContextTokens: 100_000, Idle: 3 * time.Hour, IdleLarge: 16 * time.Hour, AskUser: 12 * time.Hour, AskUserLarge: 24 * time.Hour, Waiting: 3 * time.Hour, WaitingLarge: 3 * time.Hour, }, KeepAliveRoleSession: { MinContextTokens: 100_000, Idle: time.Hour, IdleLarge: 3 * time.Hour, AskUser: 6 * time.Hour, AskUserLarge: 6 * time.Hour, Waiting: 3 * time.Hour, WaitingLarge: 3 * time.Hour, }, KeepAliveRoleSubagent: { AskUser: time.Hour, AskUserLarge: time.Hour, Waiting: time.Hour, WaitingLarge: time.Hour, }, }, }
DefaultCacheKeepAlive is the preset: the per-case policy of 18/10/2026 (warm while the chance of a wake in the next hour pays for the ping).
var DefaultCompactionSettings = CompactionSettings{ Enabled: true, ReserveTokens: 16384, KeepRecent: 20000, }
DefaultCompactionSettings provides sensible defaults.
var ErrAPIBackupUncertain = errors.New("API backup request outcome is uncertain; continue explicitly to retry")
var ErrAnthropicLowCredit = errors.New("anthropic API credit balance too low")
ErrAnthropicLowCredit identifies an explicit HTTP 400 API credit refusal, not a generic API failure or a plan quota limit.
var ErrCompactionObsolete = errors.New("compaction source is no longer current")
ErrCompactionObsolete reports a background compaction whose source changed or was invalidated before its cut was accepted. Nothing was saved, and it is not a storage failure.
var ErrEmptyResponse = &EmptyResponseError{}
ErrEmptyResponse is a sentinel for errors.Is(err, core.ErrEmptyResponse).
var ErrPrewarmUnsupported = errors.New("cache prewarm not supported for this request")
ErrPrewarmUnsupported is returned, before anything is sent, by a prewarm the provider cannot serve for this request or credential.
var ErrProviderReconfigured = errors.New("provider request configuration changed")
var ErrProviderWaitNotSaved = errors.New("provider wait could not be saved; stop and continue explicitly")
var ErrQuotaExceeded = &QuotaExceededError{}
ErrQuotaExceeded is a sentinel for errors.Is(err, core.ErrQuotaExceeded).
var ErrWaitInterruptedBySteer = errors.New("wait interrupted by user steer")
ErrWaitInterruptedBySteer marks a wait tool whose parent agent received a user steer. The job being observed continues in the background; only the parent's blocking wait is interrupted so it can process the new message.
var IsReservedSlashName = func(string) bool { return false }
IsReservedSlashName reports whether a bare /name belongs to a built-in command, which wins over a skill of the same name. The command registry lives in the serve layer, which sets this once at start-up; until then nothing is reserved.
var ThinkingLevels = []string{"off", "low", "medium", "high", "xhigh"}
ThinkingLevels is the canonical list of valid thinking levels. All validation and UI should reference this slice — not hardcoded strings.
Functions ¶
func AcceptTrim ¶ added in v0.41.0
func AcceptTrim(estimateBefore, tokensRemoved, contextWindow int, settings CompactionSettings) bool
AcceptTrim reports whether a planned trim should be applied instead of compacting.
Winning minGain is not enough on its own. The threshold check only says the context is ABOVE T, not by how much: a single huge result can take it far past T in one step, and a trim that wins minGain from there can still leave the request over the threshold — sent, because the loop evaluates compaction once per iteration and then proceeds. Requiring the projected size to land at least minGain BELOW T is what makes the low-water mark real, and with it the guarantee that at least minGain of new tokens must arrive before the next event.
func AcquireFileLock ¶ added in v0.25.0
AcquireFileLock takes an exclusive advisory lock on path, creating it if needed, and blocks until it is free. Close releases it.
It is the same lock the project state uses for its read-modify-write, hoisted so other packages can serialize their own multi-process critical sections instead of inventing a second locking scheme. The memory migration is one: two sessions starting at once in two worktrees of a repository would otherwise both try to fold the old per-path stores into the shared one.
func AddProjectAllowPattern ¶ added in v0.24.0
AddProjectAllowPattern records an "always allow" approval for a workspace.
func AgentIDFromContext ¶
AgentIDFromContext returns the agent id set by WithAgentID, or "" if none.
func AllowedModelAliases ¶ added in v0.30.0
AllowedModelAliases returns the aliases of the models whose IDs appear in allowedIDs, in the same curated order as ModelAliases.
An empty (or nil) allowedIDs means "no restriction" and yields every alias: the allowlist is opt-in, so an unset one must never shrink what callers may offer. IDs matching no known model are skipped rather than reported — the registry changes over time and a stale saved entry must not invalidate the rest of the list.
func AllowedOAuthCode ¶ added in v0.46.0
AllowedOAuthCode maps an upstream OAuth error code onto the allowlist so an arbitrary upstream string never reaches an output surface.
func BuildSTTPrompt ¶
BuildSTTPrompt turns a configured vocabulary into the provider's prompt hint.
The prompt is a hint, not a substitution: it biases spelling toward these words without forcing them. We send it as a plain comma-separated list, the shape OpenAI documents for "a list of correct spellings".
It deliberately uses "prompt" rather than the newer "keywords" field: whisper-1 rejects keywords outright, and the model is user-configurable, so a vocabulary that only works on some models would be a trap. Both produce the same result in practice.
Terms are trimmed, blank ones dropped, and duplicates removed case-insensitively (keeping the first spelling, which is the one the user cared to write).
func BuiltinOnlyToolName ¶ added in v0.46.0
BuiltinOnlyToolName reports whether name belongs to a builtin that the permission gate trusts by name: the secret-action tools show the owner their own card instead of a permission prompt. Scripts and extensions must never supply these names, even where the builtin is not registered (CLI, headless), or their tool would run without either prompt. MCP tools cannot collide: their names always carry the mcp__ prefix.
func CacheDebug ¶ added in v0.48.0
func CacheDebug() bool
CacheDebug reports whether prompt-cache diagnostics are on (MOA_DEBUG_CACHE=1): the per-request shape and body-fingerprint logs and the provider's response request-id. They carry hashes, sizes and positions only — never message content, tokens or secrets — but are one line or more per request, so they are opt-in. Failure logs do not depend on it.
func CacheTTLDuration ¶
CacheTTLDuration maps the configured cache retention to a concrete window. Anthropic's default ephemeral cache lives 5 minutes; the extended window ("1h") lives an hour. Each request refreshes the timer, so the cache stays warm until the last run + this duration.
func CanonicalModelID ¶ added in v0.33.0
CanonicalModelID maps a model id to the registry's spelling for it, so a provider naming the same model differently per backend does not fragment cost attribution or identity checks. Unknown ids pass through unchanged: a custom model must reach its provider verbatim.
func CanonicalOrRaw ¶
CanonicalOrRaw is the exported form of canonicalOrRaw: a clean, absolute, symlink-resolved path, falling back to the input on failure. Used to compare session working directories when fanning out project-scoped preferences.
func CanonicalizePath ¶
CanonicalizePath returns a clean, absolute, symlink-resolved path. Falls back to Abs+Clean if EvalSymlinks fails (e.g., broken symlinks).
func CloneArgs ¶ added in v0.23.0
CloneArgs deep-copies a tool call's JSON-shaped arguments. Exported for callers outside core that hold on to an args map the agent keeps mutating (pkg/bus's live-tool registry), where a shallow copy would still share the nested maps and slices.
func CodebaseKey ¶ added in v0.25.0
CodebaseKey identifies the repository a directory belongs to, so that every git worktree of the same repo answers with the same key.
ProjectHash cannot do this: it hashes the canonical path, and a worktree is by definition a different path. Anything scoped by ProjectHash is therefore scoped per worktree, and deleting a worktree orphans whatever was stored under it — with a dozen worktrees on one repo, that is a dozen unrelated islands and a permanent leak every time one is removed.
A directory inside a submodule keys on the submodule, not on the superproject: a submodule is a repository with its own history and its own remote, usually maintained by other people, and what is learned about it belongs to it rather than to whoever vendored it. The corollary is that the same submodule checked out under two worktrees of the superproject gets two keys, because git gives each one its own git dir (super/.git/modules/... vs super/.git/worktrees/<wt>/...) and nothing ties them back together without resolving the superproject, which would defeat the decision above.
Outside a repository, or when git cannot answer, the key is the hash of the canonical path: the current behaviour. It never fails and never returns "".
func CompactModelFallbackNotice ¶ added in v0.37.0
func CompactModelFallbackNotice(reason CompactModelFallback, spec string, used Model) string
CompactModelFallbackNotice renders the fallback for the conversation. It returns "" when nothing was overridden, so callers can emit unconditionally.
The ordinary compaction says nothing: the compaction card already tells that story. This line exists only for the case the transcript could not otherwise explain — the configured summarizer was not the one that wrote the summary. It leads with what happened, and gives the reason second.
func CompactModelUnavailableNotice ¶ added in v0.46.0
CompactModelUnavailableNotice renders the runtime fallback: the configured summarizer failed with a temporary provider error and the session's model wrote the summary instead. Same shape as CompactModelFallbackNotice.
func ConfigDir ¶ added in v0.24.0
func ConfigDir() string
ConfigDir returns the directory holding moa's own state: config.json, credentials, sessions, skills, memory and attachments.
MOA_CONFIG_DIR overrides it. That knob existed before this function but was only honored by some of the call sites, so setting it produced a half-moved instance: credentials in the new directory, config and history still in the home one. Everything that resolves moa state must go through here, so the override either moves all of it or none of it.
It deliberately does not cover paths that merely happen to live under the home directory, such as expanding "~" in a path the user typed.
func ConfigSubdir ¶ added in v0.24.0
ConfigSubdir returns a path inside ConfigDir, or "" if it cannot be resolved — callers already treat an empty path as "this feature is unavailable" rather than writing to a relative directory.
func CorrectImageMime ¶ added in v0.22.0
CorrectImageMime returns the media type to declare for a base64 image payload: the one the bytes actually are, falling back to the declared one when the format isn't recognized.
A mislabeled image (e.g. a GIF saved as .png, which the read tool types from the extension) is rejected by Anthropic with a hard 400 naming the mismatch. History is replayed every turn, so one such block makes the whole conversation unsendable — hence the correction sits at the provider edge too, where it also un-poisons sessions that already recorded the wrong type.
func DaybreakPromptCacheKey ¶ added in v0.47.0
DaybreakPromptCacheKey derives the cache key of a request sent with program, so a Daybreak conversation never shares the standard one's cache routing. Deterministic: the same session and program always yield the same key.
func DaybreakSpec ¶ added in v0.47.0
DaybreakSpec reports whether spec names the Daybreak mode: "daybreak" or the retired alias, optionally prefixed with "openai/".
func EffectiveThinkingLevel ¶ added in v0.26.0
EffectiveThinkingLevel resolves a persisted level for a model. xAI requires reasoning and only accepts low/medium/high. Meta also requires it; "off" becomes "low" so a session never persists a level the selector can't show, while internal callers may ask for "minimal" explicitly. GPT-6 Astra maps Moa's five selector positions onto its five supported efforts. Anthropic models whose thinking cannot be turned off promote "off" to their API default effort, and models without "xhigh" cap it at "high". Other providers keep the value.
func EstimateOutputTokens ¶
EstimateOutputTokens estimates the logical output generated by an assistant message. It intentionally excludes thinking and counts only text and tool calls, which are the content returned to the user or sent to tools.
func EstimateTokens ¶
EstimateTokens estimates the token count of a single message using a chars/4 heuristic. Conservative (overestimates slightly).
func ExtractAssistantText ¶ added in v0.30.0
func ExtractAssistantText(msg AgentMessage) string
ExtractAssistantText returns the concatenated non-empty text blocks of an assistant message. Keeping this rule separate lets streaming transcript readers reuse the exact outcome extraction semantics without materializing every preceding message.
func ExtractFinalAssistantText ¶
func ExtractFinalAssistantText(msgs []AgentMessage) string
ExtractFinalAssistantText returns the concatenated text content of the last assistant message in the conversation. Returns "" if none found.
func FastCostMultiplier ¶ added in v0.36.0
FastCostMultiplier returns the premium-tier token-price multiplier for a model, or 1 when the model has no fast tier. Anthropic's fast-mode documentation table lists Opus 5 / 4.8 at $10 input / $50 output versus $5 / $25 standard; Fable 5.2 is $16 / $80 versus $8 / $40, also 2x, and the cache multipliers stack on top.
func FastNote ¶ added in v0.35.0
FastNote describes what fast mode costs on a given model, for the UI to show at the moment of turning it on. The wording is per-provider because the trade-off genuinely differs: OpenAI bills it against the plan's credits, while Anthropic charges usage credits that sit outside the subscription.
func GetCacheTTL ¶
GetCacheTTL returns the prompt-cache TTL for the interactive agent. The default is "1h": interactive sessions routinely sit idle for more than five minutes, and a lapsed cache forces a full-price prefix rebuild that costs far more than the 2x (vs 1.25x) write premium of the extended window. An explicit "5m" opts back into the provider's short-lived cache; anything else (including a typo) also gets the 1h default. Subagents and one-shot calls never use this — their runs are short-lived, so the 5m cache fits them.
func GetCompactAt ¶ added in v0.34.0
GetCompactAt returns the default soft compaction threshold in tokens, applied to sessions — and to the subagents they spawn — that carry no threshold of their own. 0 means automatic: compaction waits for the model's window, which is the behaviour of every session before this setting existed.
A negative value reads as unset rather than as an error: a hand-edited config must not be able to hand the engine a threshold it would have to defend against later. Values below CompactionSettings.MinCompactAt are deliberately NOT clamped here — EffectiveWindow already raises them, and the floor depends on reserve/keep values that belong to a session that may not exist yet.
func GetCompactModel ¶ added in v0.37.0
GetCompactModel returns the model spec that should write compaction summaries, or "" to use the session's own model.
Compaction is extraction, not reasoning: the summarizer re-reads a flattened transcript under its own system prompt, so the session's model is not required to be the one doing it, and the strongest (most expensive) model is rarely the right tool for it.
An unset value and the explicit "session" both mean the session's model. The spec is not validated here — a hand-edited config must not stop a session from loading — so callers resolve it and fall back when it names a model they cannot reach.
func GetCompactStrategy ¶ added in v0.35.0
GetCompactStrategy returns the configured pre-compaction strategy.
Defaults to notify: it is free, and measured against the real API an agent holding unsaved findings persisted them in 6 of 6 runs, while one with nothing pending wrote nothing — the notice alone (without telling it what to do) changed nothing in 6 of 6.
func GetMaxRunDuration ¶
GetMaxRunDuration parses MaxRunDurationStr into a time.Duration. Returns 0 (unlimited) if empty or invalid.
func GetSTTLanguage ¶
GetSTTLanguage returns the ISO-639-1 language hint for speech-to-text. Default is "en" (English) when unset — a safe international default that also avoids Whisper mis-detecting short/ambiguous clips. Set "stt_language" in config (e.g. "es") to override; "auto" (any case) yields "" so the model auto-detects.
The value is normalized to a lowercase two-letter code. Anything that isn't a plausible ISO-639-1 code (wrong length, non-letters) falls back to "en" so a typo can't turn every transcription into an HTTP 400 from the provider.
func GetSTTModel ¶
GetSTTModel returns the speech-to-text model id to send to the provider.
Set "stt_model" in config to try another one (e.g. "whisper-1" to go back, or "gpt-4o-mini-transcribe" for half the price) without needing a new build: these models appear and change price faster than moa releases.
func GetSubagentMaxRunDuration ¶
GetSubagentMaxRunDuration parses SubagentMaxRunDuration into a time.Duration. Returns 0 (use package default) if empty or invalid.
func GetTrimDisabled ¶ added in v0.41.0
GetTrimDisabled reports whether the pre-compaction tool-result elision is turned off. Absent means on: the trim is the cheaper of the two ways to make room, and a session that never edits its config should get it.
It exists so the one feature that rewrites context on the critical path of every session can be switched off by editing a file, without a rebuild — the first thing anyone wants when a context change misbehaves.
func HumanSessionMentionsCustom ¶ added in v0.47.0
HumanSessionMentionsCustom builds the Custom of a human message that selected the given sessions. The IDs are stored as []any so a deep clone (and the JSON round trip of persistence) never shares or changes their shape.
func ImageDimensions ¶
ImageDimensions reports the pixel size from an image header. Returns 0,0 when the format is unsupported or the header is unreadable — an unknown size is never treated as oversized, so callers fall through to normal handling.
func ImageExceedsMaxDimension ¶
ImageExceedsMaxDimension reports whether a base64 image payload has a side above MaxImageDimension. Only the header is decoded, so the cost is bounded regardless of image size.
func ImageMimeFromBytes ¶ added in v0.22.0
ImageMimeFromBytes reports the media type implied by an image's magic bytes, or "" when the format isn't one providers accept inline. Only the formats in that set are recognized, so an unknown payload is left for the caller to handle rather than guessed at.
func ImportLegacyProjectVeto ¶ added in v0.24.0
ImportLegacyProjectVeto carries vetoes an older moa wrote into a trusted project's own config over to this user's state, once.
Merging them on every read instead would leave the MCP panel in a state the user cannot get out of: the veto would show under the project scope, but switching the server back on writes to the state, and the next session would read the project file again and turn it off. Importing makes the toggle mean what it says, and the flag stops the import from undoing that later.
func IsAskUserAsync ¶ added in v0.47.0
IsAskUserAsync reports whether ask_user is asynchronous for a session built with cfg. nil means "no opinion": the caller supplies its default.
func IsAutoVerifyEnabled ¶
IsAutoVerifyEnabled returns whether auto-verify is enabled. Default is false when AutoVerify is nil (not configured).
func IsForYouSnapshot ¶ added in v0.48.0
func IsForYouSnapshot(m AgentMessage) bool
IsForYouSnapshot reports whether m is a For you snapshot.
func IsMCPPathTrusted ¶
IsMCPPathTrusted reports whether path is in the config's trusted MCP paths.
func IsMemoryEnabled ¶
IsMemoryEnabled returns whether cross-session memory is enabled. Default is true when MemoryEnabled is nil (not configured).
func IsModelAllowed ¶ added in v0.30.0
IsModelAllowed reports whether model may be used under allowedIDs. An empty list means unrestricted, so existing installs keep working untouched.
func IsModelAllowedFor ¶ added in v0.47.0
IsModelAllowedFor is IsModelAllowed for a request that may carry Daybreak. The "daybreak" spec and the retired alias authorize DaybreakModelID with the program, never the model on its own.
func IsPersistentShellEnabled ¶
IsPersistentShellEnabled returns whether the bash tool persists cwd and exported env across calls. Default is true when PersistentShell is nil.
func IsProjectPathTrusted ¶
IsProjectPathTrusted reports whether path is trusted to auto-load its repo-local .moa/config.json and .moa/tools/*. Repo-local config can escalate permissions and register shell-executing tools, so — like .mcp.json — it is only honored for directories the user has explicitly trusted.
Paths are compared after canonicalization (abs + symlink-resolved) so a dir trusted via one spelling still matches when a caller later canonicalizes cwd (e.g. the serve path resolves /var → /private/var on macOS).
func IsUpdateCheckEnabled ¶
IsUpdateCheckEnabled returns whether release update checks are enabled. They are enabled by default; MOA_NO_UPDATE_CHECK=1 is handled by pkg/release.
func IsValidThinkingLevel ¶
IsValidThinkingLevel reports whether level is a recognized thinking level.
func LoadMCPFile ¶
LoadMCPFile reads a .mcp.json file. Returns nil map if file doesn't exist. Returns error for parse failures — and for entries that don't describe exactly one valid transport — so callers can warn the user instead of silently starting a half-defined server.
func MergeMCPServers ¶
MergeMCPServers merges server maps. Later maps override earlier ones by name (full replacement, not field-level merge).
func ModelAliases ¶ added in v0.30.0
func ModelAliases() []string
ModelAliases returns every alias that resolves to a known model, in the curated display order. Callers that need to *tell* a model which names are valid must derive the list from here rather than writing one by hand: a hand-kept copy silently drifts from modelAliases as models come and go.
func NativeDocBytes ¶
NativeDocBytes sums the decoded size of the native document/image blocks in content — the base64 payloads that count against a session's native-content budget. Text/thinking/tool blocks contribute nothing.
func NewMsgID ¶
func NewMsgID() string
NewMsgID mints a stable message identifier, using the same mechanism as Message.EnsureMsgID. Used when a caller needs a message's ID before the message is built (e.g. to correlate a later event with it).
func NewSteerID ¶
func NewSteerID() string
NewSteerID mints a random identifier for a steer item, using the same crypto/rand mechanism as Message.EnsureMsgID.
func ProjectHash ¶ added in v0.24.0
ProjectHash identifies a workspace by its canonical path. Memory already scopes per project this way; sharing the function keeps a project from hashing to two different directories depending on who asks.
func ProjectStateDir ¶ added in v0.24.0
ProjectStateDir returns where this user's state for a workspace lives, or "" when the config directory cannot be resolved.
func PromptCacheKey ¶ added in v0.33.0
PromptCacheKey builds the conversation identifier sent to the Responses providers (OpenAI, xAI) so requests sharing a prefix reach the machine holding their cache. Cache entries are per-machine, and traffic above a provider's per-machine limit overflows elsewhere and misses; a stable key per conversation is what keeps a session pinned to its own cache.
The key only influences routing — a read still requires the prefix to match — so it is never a correctness concern, and an empty sessionID yields an empty key that callers omit from the request.
It deliberately excludes the model: routing is already per-model, so adding it would only churn the key on every model switch. The session id is a random token, not derived from user content.
func ProviderSupportsDeferredTools ¶ added in v0.48.0
ProviderSupportsDeferredTools reports whether p, following decorators, loads deferred tools on demand for modelID. Unknown providers report false: they get every definition, as before.
func ProviderSupportsDocuments ¶
ProviderSupportsDocuments reports whether p accepts native document blocks. Conservative: an unknown provider (not implementing DocumentCapableProvider) returns false, so callers fall back to disk rather than silently dropping a PDF the provider can't handle.
func ReactiveRefreshError ¶ added in v0.46.0
ReactiveRefreshError is what a transport returns when the refresh of a rejected token failed: the classified failure when there is one, otherwise the rejection itself. The refresh error's own text is never kept.
func ReasoningEffortsForModel ¶ added in v0.37.0
ReasoningEffortsForModel returns the validated reasoning efforts a model accepts. A nil result preserves the Responses API's existing behavior for models without an explicit capability declaration.
func RegisterOrLog ¶
RegisterOrLog registers a tool and logs a warning on failure. Use for dynamic tool sources (MCP, extensions) where a registration error shouldn't abort the caller.
func RepoCodebaseKey ¶ added in v0.25.0
RepoCodebaseKey is CodebaseKey restricted to directories git recognizes as part of a repository: it reports no key at all instead of falling back to the path hash.
The distinction matters to anything that uses a directory as *evidence* about who owns something rather than as the workspace it was asked about. The fallback is the right answer for "which key does this workspace use" — it always answers, and unrelated paths get unrelated keys — but as evidence it is worthless: it would name an owner for every path on the filesystem, including ones no workspace will ever open.
func ReservedToolName ¶
ReservedToolName reports whether name is reserved for an internal tool which must never be supplied by scripts, extensions, or MCP servers.
func ResolveCompactAt ¶ added in v0.34.0
ResolveCompactAt picks the threshold to apply when the session value and the global default come from different places — the parent agent and the config file, as when spawning a subagent. Session value wins, then the global one, then 0 meaning "compact at the model window".
func ResolveCompactModel ¶ added in v0.37.0
func ResolveCompactModel(spec string, sessionModel Model, available AuxiliaryModelAvailable) (Model, CompactModelFallback)
ResolveCompactModel picks the model that writes compaction summaries.
It returns the session's own model unchanged when no summarizer is configured, and never fails: a compaction that refuses to run leaves the session growing until it hits the window, which is a worse outcome than summarizing with a more expensive model. When the configured choice cannot be honoured the session's model is returned together with the reason, so the caller can say so in the conversation rather than swallow it.
func ResolveMaxOutputTokens ¶
ResolveMaxOutputTokens returns the effective output cap for a request. An explicit caller value wins, subject to the model's advertised capability; otherwise the shared operational default is used.
func ResolvePathScope ¶
ResolvePathScope determines the effective path scope from config values.
permMode is expected to be already resolved by the caller: bootstrap defaults an unset permission mode to "yolo" (moa's out-of-the-box posture for a single-user local tool) BEFORE calling this, so in normal operation the empty-mode branch below is never hit and the effective default scope is "unrestricted". The empty-mode → "workspace" branch is only a conservative fallback for direct callers that pass an unresolved mode; it does NOT reflect the CLI default.
Priority:
- Explicit pathScope ("workspace" or "unrestricted") — use as-is
- Legacy disableSandbox: true → "unrestricted"
- Derive from permission mode: - "yolo" or "ask" → "unrestricted" - "auto" → "workspace" - "" (unresolved) → "workspace" (conservative fallback; see note above)
func SameModelIdentity ¶ added in v0.29.0
SameModelIdentity compares model IDs after resolving known aliases. Unknown provider-returned IDs remain comparable without pretending they are aliases.
func SameResponseOrigin ¶ added in v0.37.4
SameResponseOrigin reports whether state recorded under the effective model id belongs to the model now being requested. It is SameModelIdentity plus the alias relation the registry declares: an alias is answered under its target's id, so its own history comes back spelled as the target.
The relation is deliberately one-way. A request for the alias accepts the target's state, because that state was produced by serving this alias. A request for the target does NOT accept the alias's state: the two are different products (Daybreak carries its own safeguards) and only the alias knows it is being redirected. Treating them as one identity would also hide a genuine provider fallback.
Verified live on /codex/responses: encrypted reasoning recorded under gpt-5.6-sol during a gpt-daybreak-blue-latest session is accepted when replayed under the alias.
func SaveGlobalConfig ¶
SaveGlobalConfig reads the current global config, applies update, and writes it back atomically. Creates ~/.config/moa/ if it doesn't exist.
func SaveProjectConfig ¶
SaveProjectConfig reads the current project config, applies update, and writes it back atomically. Creates <cwd>/.moa/ if it doesn't exist.
func SetConfigPathGuardForTests ¶ added in v0.46.0
func SetConfigPathGuardForTests(guard func(path string))
SetConfigPathGuardForTests installs (or, with nil, removes) a hook called with every path ConfigDir and ConfigSubdir are about to return. Only test harnesses should use it.
func SetMCPServerDisabled ¶
SetMCPServerDisabled adds or removes a server name from a config's disabled list, keeping it sorted and deduplicated. Removing the last entry sets the slice to nil so omitempty drops the field. It is the read-modify-write body callers pass to SaveGlobalConfig / SaveProjectConfig.
func SetProjectMCPServerDisabled ¶ added in v0.24.0
SetProjectMCPServerDisabled records this user's veto for a workspace.
func ShouldCompact ¶
func ShouldCompact(contextTokens, contextWindow int, settings CompactionSettings) bool
ShouldCompact returns true if context tokens exceed the safe threshold. Returns false for disabled settings, zero/negative context windows, or degenerate settings where reserve >= window.
func ShouldWarnBeforeCompact ¶ added in v0.35.0
func ShouldWarnBeforeCompact(contextTokens, contextWindow int, settings CompactionSettings) (warn bool, remaining int)
ShouldWarnBeforeCompact reports whether the agent is close enough to the compaction threshold to be told about it, and how many tokens remain.
An automatic compaction arrives with no warning mid-task, so whatever the agent had worked out but not written down is replaced by a summary. This is what gives it the chance to persist it first.
func SkillInvocation ¶ added in v0.47.0
SkillInvocation reports whether a message's Custom marks it as the user invoking an inline skill with /<name>, and what the user typed to do it.
Messages written before skills started a run carry only custom.skill, with no source; they are the same event. A forked skill's anchor has its own source and is not an invocation of this kind.
func SubagentPromptCacheKey ¶ added in v0.33.0
SubagentPromptCacheKey derives a child's cache key from its parent session. Children of one session share the key: GPT-5.6 still reads a matching instructions+tools prefix on a sibling's first request (measured on disk: terra subagents ~49% first-request hits without a key, via prefix-hash routing). A per-job suffix would pin each child to its own machine and throw that away. The parent stays on a different key because its tool set (subagent, ask_user, …) is not the child's.
func SuggestAliasFrom ¶ added in v0.30.0
SuggestAliasFrom is SuggestModelAlias over an explicit alias set, so a caller that may only offer some models (a subagent allowlist) never teaches a name it would then refuse.
func SuggestModelAlias ¶ added in v0.30.0
SuggestModelAlias returns the alias a misspelled spec most likely meant, or "" when nothing is close enough. It exists so an unknown-model error can teach the correct name instead of only rejecting the wrong one: agents write these names from memory and a near miss ("sonet", "grok/4") is far more common than an unknown model.
Only unambiguous matches are offered: a suggestion that is wrong is worse than none, because it invites a second failed attempt.
func SupportsFast ¶ added in v0.35.0
SupportsFast reports whether a model can be served in fast mode.
Fast mode is the same model at a premium speed and price, and each provider gates it differently:
- Anthropic serves it on Opus and Fable 5.2 (fast-mode page); every other model, Fable 5.1 included, rejects the `speed` field outright ("does not support the `speed` parameter").
- OpenAI offers it per model; see openAIFastMultipliers.
- xAI accepts the priority tier across its catalogue.
An unknown model is reported as unsupported: offering a switch that the API will reject is worse than not offering it.
func ThinkingAlwaysOn ¶ added in v0.35.0
ThinkingAlwaysOn reports whether a model thinks on every turn. Off is not a real setting there: the API still thinks, at its default effort.
func ThinkingLevelOptions ¶
func ThinkingLevelOptions() string
ThinkingLevelOptions returns a human-readable list for error messages.
func ThinkingPosition ¶ added in v0.46.0
ThinkingPosition is the inverse of EffectiveThinkingLevel for the models that shift selector positions onto other efforts (GPT-6 Astra, GPT-6.1 Sol, GPT-6.1 Terra): it turns a persisted or running effort back into the selector position that produced it. Re-feeding an effort as a position would raise it one notch on every pass (high -> xhigh -> max). Other models use the same words for both.
func ToolCallIDFromContext ¶
ToolCallIDFromContext returns the tool call id set by WithToolCallID, or "" if the context does not represent a tool call.
func ToolCallMessageIDFromContext ¶ added in v0.47.0
ToolCallMessageIDFromContext returns the id set by WithToolCallMessageID, or "" if the context does not represent a tool call.
func TrimMinGain ¶ added in v0.41.0
func TrimMinGain(contextWindow int, settings CompactionSettings) int
TrimMinGain is the smallest saving that justifies a trim for these settings. It reuses minWarnBandTokens as a floor, the same "below this a band is not worth acting on" precedent the warning band uses.
func UpdatePinnedModels ¶ added in v0.26.0
UpdatePinnedModels returns models with id added or removed. Adding preserves the existing order and appends new IDs; removing preserves the order of IDs that remain.
func UpdateProjectState ¶ added in v0.24.0
func UpdateProjectState(workspaceRoot string, update func(*ProjectState)) error
UpdateProjectState applies update to the stored state and writes it back.
update must not call back into UpdateProjectState or the lock deadlocks, and it should not read the state either: it receives the current one, and a LoadProjectState from inside would return the version before its own edits.
The whole read-modify-write is under an advisory lock, and the write goes through a uniquely named temporary file. Both matter: the project config writer this replaces used a fixed temp name and no lock, so two moa processes could clobber each other — reachable with one user running two sessions in the same project, which would silently drop an approval or re-enable a server they had switched off.
func ValidateAuxiliaryModelConfig ¶ added in v0.27.0
ValidateAuxiliaryModelConfig validates the two background-model settings without requiring credentials. Credential availability is intentionally a startup concern: a valid config remains valid when a user logs out.
func ValidateAuxiliaryModelSpec ¶ added in v0.27.0
ValidateAuxiliaryModelSpec validates a config value without requiring credentials. It accepts auto, off, and every normal model spec.
func ValidateEventSourceName ¶ added in v0.37.0
ValidateEventSourceName restricts names to a URL path segment so /hooks/<source>/<secret> cannot be ambiguous.
func ValidateMCPServers ¶ added in v0.20.0
ValidateMCPServers checks every entry of a server map, reporting the first offending name (in name order, so the message is stable) so the user can fix the file.
func ValidateModelSpec ¶
ValidateModelSpec reports whether spec can possibly be used to build a provider, without needing pricing/context metadata for it. It rejects two cases ResolveModel alone can't distinguish by its return value:
- a bare (no "provider/" prefix) spec that isn't a known alias, model ID, or display name
- a "provider/model" spec whose model portion IS a known model but registered under a *different* provider (almost certainly a typo, e.g. "openai/sonnet" — sonnet is an Anthropic model)
A "provider/model" spec whose model portion is simply absent from the registry is accepted (nil error): it's treated as a legitimate custom model, just without pricing/context-window metadata.
func WithAgentID ¶
WithAgentID tags ctx with an agent identifier used to isolate per-agent shell state (see pkg/tool.BashState). The root/parent agent uses "" (no tag).
func WithToolCallID ¶
WithToolCallID tags ctx with the identifier of the tool call being executed.
func WithToolCallMessageID ¶ added in v0.47.0
WithToolCallMessageID tags ctx with the MsgID of the assistant message that carried the tool call being executed. Together with the tool call ID it names the invocation, which a tool that must be idempotent across a crash keys its effect on.
Types ¶
type AgentEvent ¶
type AgentEvent struct {
Type string
ProviderExecution *ProviderExecution
// Populated per type:
Message AgentMessage // message_start, message_end, user_message
AssistantEvent *AssistantEvent // message_update (streaming deltas)
Text string // steer, user_message (plain-text prompt)
SteerID string // steer
MsgID string // steer, user_message (MsgID of the user message, for client dedup)
AttachmentIDs []string // steers_canceled
SteerIDs []string // steers_canceled: IDs of the discarded user steers
ToolCallID string // tool_execution_*
ToolName string // tool_execution_*
Args map[string]any // tool_execution_start
Result *Result // tool_execution_end/update
IsError bool // tool_execution_end
Rejected bool // tool_execution_end (true for human permission denial, incl. tool-raised prompts)
Messages []AgentMessage // agent_end (full conversation)
Compaction *CompactionPayload // compaction_end
Trim *TrimPayload // context_trimmed
// TrimOriginals carries the conversation as it stood BEFORE a trim, so the
// session tree can persist the untrimmed originals of the current run
// before the trim marker is appended. Internal plumbing, never payload: it
// must not be serialized onto the wire, where it would turn every trim into
// a frame carrying the whole conversation.
TrimOriginals []AgentMessage // context_trimmed
Error error // agent_error, compaction_end (non-fatal)
// Pricing is the rate card of the model that served a message_end's
// request. The session's model can change while a run is in flight, so its
// current pricing is not necessarily this response's.
Pricing *Pricing // message_end, compaction_usage
// BackgroundJobID identifies the background compaction a compaction_end,
// compaction_usage or background_compaction event belongs to. Zero for
// foreground (manual or preparation) compactions.
BackgroundJobID uint64
// BackgroundCompaction is the session-level state (background_compaction).
BackgroundCompaction *BackgroundCompactionState
// Usage is what a background summary call cost (compaction_usage).
Usage *Usage
// Origin is the context of the agent invocation that produced the event,
// stamped at emission; nil outside a run. A consumer that lags behind can
// tell an event of a finished run from one of the run now in flight.
// Internal plumbing, never serialized.
Origin context.Context `json:"-"`
}
AgentEvent is emitted by the agent loop for UI/extension consumption.
type AgentMessage ¶
AgentMessage wraps Message with extension-custom data. Custom messages (role not user/assistant/tool_result) are filtered before LLM calls.
func ApplyTrims ¶ added in v0.41.0
func ApplyTrims(msgs []AgentMessage, spans []TrimSpan) []AgentMessage
ApplyTrims replays persisted trims over a reconstructed conversation. Spans are applied in chronological order, each over its own interval, so a region elided by an older build keeps that build's placeholders.
A span whose watermark is no longer present was dropped by a later compaction: everything the compaction retained is newer than that watermark, so the span has nothing left to elide. A span that would move the boundary backwards is ignored rather than trusted — persisted state cannot be assumed well-ordered, and re-eliding an older region would silently diverge from the context the provider actually saw.
func WrapMessage ¶
func WrapMessage(m Message) AgentMessage
WrapMessage converts a Message to an AgentMessage.
func (AgentMessage) IsLLMMessage ¶
func (m AgentMessage) IsLLMMessage() bool
IsLLMMessage returns true if this message should be sent to the LLM.
type AnthropicThinking ¶ added in v0.41.0
type AnthropicThinking struct {
// Adaptive models take output_config.effort; the rest take budget_tokens.
Adaptive bool
// AlwaysOn models reject thinking disabled: off is not a real setting.
AlwaysOn bool
// OnByDefault models think when the request omits thinking, so off must
// send thinking disabled explicitly.
OnByDefault bool
// OffType is the thinking type off sends on an OnByDefault model. Empty
// means "disabled". Sonnet 5.5 rejects disabled; its lowest setting is
// "between_tools" (no up-front thinking), accepted at high effort or below,
// so off sends it without an effort and the API applies its default, high.
OffType string
// DefaultEffort is the effort the API applies when the request omits it.
DefaultEffort string
// XHigh reports whether effort "xhigh" exists for the model.
XHigh bool
}
AnthropicThinking describes how an Anthropic model thinks, per https://platform.claude.com/docs/en/build-with-claude/effort (levels, defaults) and https://platform.claude.com/docs/en/build-with-claude/thinking-troubleshooting#thinking-support-defaults-and-rejected-configurations (which thinking types each model accepts). Moa does not expose "max".
model thinking levels (moa) API default effort Fable 5.2 adaptive, always on low medium high xhigh high Fable 5.1 adaptive, always on low medium high xhigh high Fable 5 adaptive, always on low medium high xhigh high Opus 5.5 adaptive, always on low medium high xhigh medium Sonnet 5.5 adaptive, on off low … xhigh high (off = between_tools) Opus 5 adaptive, on off low … xhigh high Opus 4.8 adaptive, off off low … xhigh high Sonnet 5 adaptive, on off low … xhigh high Haiku 4.5 extended (budget) off low medium high — (no effort)
func AnthropicThinkingFor ¶ added in v0.41.0
func AnthropicThinkingFor(model Model) (AnthropicThinking, bool)
AnthropicThinkingFor returns the thinking spec of a known Anthropic model. Aliases resolve first, so "opus" and "fable" work.
type AppliedOutputCap ¶ added in v0.48.0
AppliedOutputCap reports the output cap of a built request. Reported is false until a provider has built the request; Tokens is 0 when the request carries no cap (e.g. the ChatGPT OAuth backend rejects max_output_tokens).
func (*AppliedOutputCap) Report ¶ added in v0.48.0
func (c *AppliedOutputCap) Report(tokens int)
Report records the cap of a built request. Safe on a nil receiver.
type AssistantEvent ¶
type AssistantEvent struct {
Type string `json:"type"`
ContentIndex int `json:"content_index,omitempty"`
Delta string `json:"delta,omitempty"`
Partial *Message `json:"partial,omitempty"`
Message *Message `json:"message,omitempty"`
Error error `json:"-"`
// Tool call metadata — populated for toolcall_start, toolcall_delta, toolcall_end events.
ToolCallID string `json:"tool_call_id,omitempty"`
ToolName string `json:"tool_name,omitempty"`
PartialArgs map[string]any `json:"partial_args,omitempty"`
// RateLimit — populated for the "ratelimit" event, emitted once at stream
// start from the response headers (independent of message success).
RateLimit *RateLimit `json:"rate_limit,omitempty"`
// Provider identifies which provider produced this event (e.g. "openai",
// "anthropic"). Populated alongside RateLimit so consumers can attribute
// each reading to the provider that actually served this request, instead
// of relying on the session's provider at some other point in time — the
// two can differ when the model changes mid-run.
Provider string `json:"provider,omitempty"`
}
AssistantEvent is emitted by providers during streaming.
Terminal events: "done" (success) or "error" (failure). Every stream ends with exactly one terminal event, then channel close.
func (AssistantEvent) IsTerminal ¶
func (e AssistantEvent) IsTerminal() bool
IsTerminal returns true for "done" or "error" events.
type AuxiliaryModelAvailable ¶ added in v0.27.0
AuxiliaryModelAvailable reports whether normal completion credentials are available for a provider. Transcription-only credentials must not satisfy it.
type BackgroundCompactionState ¶ added in v0.46.0
type BackgroundCompactionState struct {
JobID uint64 `json:"job_id"`
Revision uint64 `json:"revision"`
Active bool `json:"active"`
// Waiting is true while the run waits for the summary because its next
// request would exceed the model window minus the reserve.
Waiting bool `json:"waiting"`
}
BackgroundCompactionState is the session-level state of the automatic compaction computed off the run's critical path. Revision increases at each transition, so a late update can never replace a newer one.
type CacheKeepAliveConfig ¶ added in v0.47.0
type CacheKeepAliveConfig struct {
// LargeContextTokens splits the "_large" horizons from the others.
LargeContextTokens int `json:"large_context_tokens,omitempty"`
// PingEvery1h and PingEvery5m are the ping periods for each cache TTL,
// as Go durations: how long after a request the next ping goes.
PingEvery1h string `json:"ping_every_1h,omitempty"`
PingEvery5m string `json:"ping_every_5m,omitempty"`
Owner *KeepAliveHorizons `json:"owner,omitempty"`
Session *KeepAliveHorizons `json:"session,omitempty"`
Subagent *KeepAliveHorizons `json:"subagent,omitempty"`
}
CacheKeepAliveConfig is the "cache_keepalive" setting. Each role is switched on on its own ("owner": {"enabled": true}); absent, every role is off and no ping is ever sent. A segment inside an enabled role is switched off with a "0" horizon. Every other field is optional and falls back to the preset (DefaultCacheKeepAlive).
type CacheMiss ¶ added in v0.46.0
type CacheMiss struct {
Cause string
GapSeconds int64 // since the previous request; 0 when a timestamp is missing
Tokens int // prefix tokens that had to be processed again
CostUSD float64 // extra cost over reading them from cache; 0 for an unpriced model
At int64 // Unix seconds of the missing turn
Provider string
Model string
}
CacheMiss is one turn that missed the prompt cache.
type CachePrewarmer ¶ added in v0.47.0
CachePrewarmer is optionally implemented by providers that can refresh a prompt cache without generating output: Prewarm resends req as a zero-output request and returns its usage. It never retries.
func ProviderPrewarmer ¶ added in v0.47.0
func ProviderPrewarmer(p Provider) (CachePrewarmer, bool)
ProviderPrewarmer returns p's prewarm capability, following decorators.
type CacheUsageAccumulator ¶ added in v0.44.1
type CacheUsageAccumulator struct {
// contains filtered or unexported fields
}
CacheUsageAccumulator is SummarizeCacheUsage fed one message at a time, so a caller can aggregate a transcript it does not want to materialise.
func (*CacheUsageAccumulator) Add ¶ added in v0.44.1
func (a *CacheUsageAccumulator) Add(message *AgentMessage)
Add folds one message, in transcript order, into the summary.
func (*CacheUsageAccumulator) Summary ¶ added in v0.44.1
func (a *CacheUsageAccumulator) Summary() CacheUsageSummary
Summary returns the aggregate of everything added so far.
type CacheUsageSummary ¶ added in v0.41.0
type CacheUsageSummary struct {
Available bool
Ratio float64
Read int
Written int
Streak int
Alert bool
// Misses counts turns whose cache read fell short of what the previous
// turn had cached; MissCostUSD is what re-caching those tokens cost over
// reading them. LastMiss is the most recent one, nil when there is none.
Misses int
MissCostUSD float64
LastMiss *CacheMiss
}
CacheUsageSummary describes cache activity across a session's completed assistant turns.
func SummarizeCacheUsage ¶ added in v0.41.0
func SummarizeCacheUsage(messages []AgentMessage) CacheUsageSummary
SummarizeCacheUsage returns cache usage aggregated from valid assistant turns. Error turns are ignored. Available is false when no turn reported input or cache tokens, so Ratio is not a synthetic percentage. Streak and Alert describe only the current trailing sequence of writes without reads.
type CompactModelFallback ¶ added in v0.37.0
type CompactModelFallback string
CompactModelFallback says why compaction is not using the configured summarizer. It exists so the reason can be shown in the conversation instead of silently billing the session's (usually pricier) model.
const ( // CompactModelFallbackNone: the configured model is being used, or none is // configured and the session's model is the intended one. CompactModelFallbackNone CompactModelFallback = "" // CompactModelFallbackUnknown: the spec names no model in the catalog, // typically a hand-edited config or a model dropped from a release. CompactModelFallbackUnknown CompactModelFallback = "unknown_model" // CompactModelFallbackNoCredential: the model exists but its provider has // no usable credential right now — an expired OAuth token, a deleted key. CompactModelFallbackNoCredential CompactModelFallback = "no_credential" )
type CompactionCommit ¶ added in v0.46.0
type CompactionCommit struct {
Originals []AgentMessage
Payload *CompactionPayload
// Trims is how many context trims the agent had emitted to its owner
// before this compaction, counted since the commit was installed. Their
// events carry the untrimmed originals, so the owner records them before
// staging Originals, which hold the placeholders.
Trims uint64
// Accept, when set, is the producer's cut transaction: the owner calls it
// before staging, under the locks that order this save with every other
// one. It validates that the source is still current and returns adopt,
// which the owner calls once the save succeeded and the tree adopted the
// boundary, and release, which the owner calls when the commit is settled
// (after recording a storage failure). An error from Accept means nothing
// was saved; ErrCompactionObsolete is not a storage failure. Nil keeps the
// original contract: the producer adopts after the commit returns.
Accept func() (adopt func(), release func(), err error)
// CheckpointGeneration is the generation of the session checkpoint the
// summary embeds; nil when it embeds none. The snapshot that makes the
// boundary durable records the slot as pending only if it has moved past
// that generation, so a crash before the next save cannot resurrect a
// checkpoint the summary already carries. Transient, never persisted.
CheckpointGeneration *uint64
}
CompactionCommit is what a compaction hands its owner to make durable before the agent adopts it: the conversation the summary replaces, exactly as it stood (the originals the transcript must keep), and the result.
type CompactionNotSavedError ¶ added in v0.46.0
type CompactionNotSavedError struct {
Payload *CompactionPayload
Err error
}
CompactionNotSavedError reports a compaction whose summary was produced (and paid for) but could not be made durable, so the agent kept its previous conversation. Payload carries the usage to charge.
func (*CompactionNotSavedError) Error ¶ added in v0.46.0
func (e *CompactionNotSavedError) Error() string
func (*CompactionNotSavedError) Unwrap ¶ added in v0.46.0
func (e *CompactionNotSavedError) Unwrap() error
type CompactionPayload ¶
type CompactionPayload struct {
Summary string `json:"summary"`
TokensBefore int `json:"tokens_before"`
TokensAfter int `json:"tokens_after"`
ReadFiles []string `json:"read_files,omitempty"`
ModifiedFiles []string `json:"modified_files,omitempty"`
SummaryMsgID string `json:"summary_msg_id,omitempty"`
FirstKeptMsgID string `json:"first_kept_msg_id,omitempty"`
// SummarizerNotice explains, for the reader, that the summary above was
// NOT written by the configured summarizer — an expired credential, a
// model no longer in the catalog. Empty in the ordinary case, including
// when a configured model was honoured: the compaction card is the whole
// story there, and a line on every compaction would be noise.
//
// It is part of the payload because it has to outlive the run that
// produced it: the reader usually comes back hours later, and a summary
// whose provenance is not what they configured is exactly what they need
// to know when judging it.
SummarizerNotice string `json:"summarizer_notice,omitempty"`
Usage *Usage `json:"usage,omitempty"`
// Summarizer is the telemetry of the call that wrote the summary: which
// model, what it spent and why it stopped. Optional: old payloads and
// producers that do not know it leave it nil.
Summarizer *CompactionSummarizer `json:"summarizer,omitempty"`
// Pricing is the rate card of the model that wrote the summary, for
// charging Usage. Not persisted: cost is settled when the event is seen.
Pricing *Pricing `json:"-"`
// Ephemeral marks a compaction of the discarded preparation conversation.
// The producer fixes its origin before asynchronous delivery: a generation
// stamped by a later consumer may belong to a different run. This only
// routes persistence; it is not part of the saved or client-facing payload.
Ephemeral bool `json:"-"`
// BoundaryID is the identity of the durable compaction boundary, minted by
// the producer so the commit, the live marker and the saved entry are one
// row. Empty for producers that predate the commit (a new one is minted).
BoundaryID string `json:"-"`
}
CompactionPayload is the typed result of a compaction event.
type CompactionSettings ¶
type CompactionSettings struct {
Enabled bool `json:"enabled"`
ReserveTokens int `json:"reserve_tokens"` // keep free for model output + thinking
KeepRecent int `json:"keep_recent"` // tokens of recent context to keep verbatim
CompactAt int `json:"compact_at,omitempty"` // soft threshold in tokens; 0 = use the model window
// DefaultCompactAt is the fallback threshold (the global config setting)
// used when this session has no CompactAt of its own. Kept as a separate
// field rather than folded into CompactAt because only CompactAt is the
// session's OWN choice and only CompactAt is persisted as session metadata:
// merging them would freeze today's global value into every session, so a
// later change to the global setting would never reach them.
DefaultCompactAt int `json:"default_compact_at,omitempty"`
// TrimDisabled turns off the deterministic tool-result elision that runs
// before compaction. Phrased as a negative so the zero value keeps it on:
// settings are built explicitly in many places (tests, subagents, the CLI),
// and a positive TrimEnabled would have silently disabled the feature in
// every one of them that was written before it existed.
TrimDisabled bool `json:"trim_disabled,omitempty"`
}
CompactionSettings controls automatic context compaction.
func CompactionFromConfig ¶ added in v0.41.0
func CompactionFromConfig(globalCompactAt int, trimDisabled bool) *CompactionSettings
CompactionFromConfig is CompactionWithDefault plus the trim switch, so the one setting that can turn off a feature on the critical path of every session is read in the same place as the threshold it guards — and can be flipped by editing the config rather than by rebuilding the binary.
func CompactionWithDefault ¶ added in v0.34.0
func CompactionWithDefault(globalCompactAt int) *CompactionSettings
CompactionWithDefault returns the standard settings carrying globalCompactAt as the fallback threshold. Callers build agents this way instead of assigning DefaultCompactAt by hand so the global setting cannot be wired into one agent construction site and forgotten in another.
func (CompactionSettings) EffectiveWindow ¶
func (s CompactionSettings) EffectiveWindow(maxInput int) int
EffectiveWindow returns the context window to use for compaction decisions. When a threshold is set (>0) it caps the model's real window so compaction fires earlier; it is clamped to maxInput, so an over-large value harmlessly degrades to plain overflow protection rather than disabling compaction. It is also floored so a too-low threshold can't cause per-turn compaction thrash. The threshold is the session's own CompactAt, falling back to the global DefaultCompactAt: session → global → model window, resolved in one place so the floor and the clamp apply identically whichever level set the value.
func (CompactionSettings) MinCompactAt ¶
func (s CompactionSettings) MinCompactAt() int
MinCompactAt is the lowest CompactAt that still behaves as asked: below it EffectiveWindow silently raises the threshold to avoid per-turn thrash. A UI offering a threshold has to read this rather than assume, since it moves with ReserveTokens and KeepRecent — a control that let you pick below it would be promising a compaction point the engine will not honor.
type CompactionSummarizer ¶ added in v0.48.0
type CompactionSummarizer struct {
Provider string `json:"provider,omitempty"`
Model string `json:"model"`
Usage *Usage `json:"usage,omitempty"`
// StopReason is the provider's finish reason ("max_tokens" when the cap
// cut the summary), empty when the provider reported none.
StopReason string `json:"stop_reason,omitempty"`
// OutputCap is one of the SummarizerCap* constants; MaxOutputTokens is
// the cap sent, only when OutputCap is "applied".
OutputCap string `json:"output_cap,omitempty"`
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
}
CompactionSummarizer records which model wrote a summary, what the call spent and why it ended, so a summary cut short by a cap can be told apart from one that finished. It is observation only: it never drives behavior.
func (*CompactionSummarizer) Clone ¶ added in v0.48.0
func (s *CompactionSummarizer) Clone() *CompactionSummarizer
Clone returns a deep copy; nil stays nil.
type Content ¶
type Content struct {
Type string `json:"type"`
// text
Text string `json:"text,omitempty"`
// TextSignature carries provider round-trip metadata for a text/message
// block so the exact item can be replayed on the next request. For the
// OpenAI Responses API this is a small JSON blob {id, phase} — the model's
// output message id and its phase ("commentary"/"final_answer"). OpenAI
// warns that dropping the phase when replaying manually causes "early
// stopping and other misbehavior", which manifests as empty/stalled turns.
// Opaque to everything except the provider/model pair that produced it.
// Replay adapters must discard it when Message.Provider or Message.Model
// differs from their target.
TextSignature string `json:"text_signature,omitempty"`
// thinking
Thinking string `json:"thinking,omitempty"`
ThinkingSignature string `json:"thinking_signature,omitempty"`
Redacted bool `json:"redacted,omitempty"`
// image/document
Data string `json:"data,omitempty"`
MimeType string `json:"mime_type,omitempty"`
Filename string `json:"filename,omitempty"`
// attachment reference (image/document stored out-of-line in the blob store).
// When AttachmentID is set, Data is empty in persisted/in-memory history and is
// rehydrated only at request time by the materializer. Size is the decoded byte
// size, kept so budgeting/sizing works without reading the blob.
AttachmentID string `json:"attachment_id,omitempty"`
AttachmentSize int64 `json:"attachment_size,omitempty"`
// tool_call
ToolCallID string `json:"tool_call_id,omitempty"`
ToolName string `json:"tool_name,omitempty"`
Arguments map[string]any `json:"arguments,omitempty"`
// ToolCallItemID is the provider's output-item id for a tool_call (OpenAI
// Responses: the "fc_..." id, distinct from ToolCallID which is the
// "call_id" that pairs the call with its function_call_output). Preserved
// so the function_call item can be replayed with its original id, matching
// how the reasoning item that preceded it was paired. Empty for providers
// that don't use a separate item id.
ToolCallItemID string `json:"tool_call_item_id,omitempty"`
}
Content is a tagged union. Type determines which fields are populated.
"text" → Text "thinking" → Thinking, ThinkingSignature, Redacted "image" → Data, MimeType "document" → Data, MimeType, Filename "tool_call" → ToolCallID, ToolName, Arguments "tool_reference" → ToolName (a deferred tool a tool_search result loads)
func CloneContent ¶
CloneContent returns a deep copy of a content slice (see Content.Clone). A nil input yields a nil output.
func DocumentContent ¶
func ImageContent ¶
func ThinkingContent ¶
func ToolReferenceContent ¶ added in v0.48.0
ToolReferenceContent points a tool result at a deferred tool, which the provider then loads into the model's context. Codecs that do not defer tools ignore it; the result also carries text for them.
func (Content) Clone ¶
Clone returns a deep copy of the content: every field is copied by value except Arguments (a map[string]any), which is cloned so the copy shares no mutable backing state with the original. Nested values inside Arguments are copied via cloneAny (maps and slices are rebuilt recursively). Used at ownership boundaries (e.g. when the agent takes a caller-supplied content block into its own state) so a later mutation by the caller can't change the stored message or race a concurrent reader.
type ContextEstimate ¶
type ContextEstimate struct {
Tokens int // total estimated context tokens
UsageTokens int // from provider-reported usage (0 if none valid)
TrailingTokens int // estimated tokens for messages after last valid usage
OverheadTokens int // system prompt + tool specs
}
ContextEstimate holds the result of a context size estimation.
func EstimateContextTokens ¶
func EstimateContextTokens(msgs []AgentMessage, systemPrompt string, toolSpecs []ToolSpec, compactionEpoch int) ContextEstimate
EstimateContextTokens estimates total context size including system prompt and tool spec overhead. Uses provider-reported Usage from the last assistant message whose compaction epoch matches the current one. Stale usage from pre-compaction messages is ignored.
type DaybreakAvailability ¶ added in v0.47.0
type DaybreakAvailability struct {
// Transport is whether the selected OpenAI credential is the plan's OAuth,
// the only transport that carries the program.
Transport bool
// Known is whether the catalog was ever read. Until then nothing is
// rejected: the request is sent and the provider answers.
Known bool
// Models maps a catalog model id to whether it accepts Daybreak.
Models map[string]bool
}
DaybreakAvailability is a snapshot of what the account's model catalog says about Daybreak.
func (DaybreakAvailability) Any ¶ added in v0.47.0
func (a DaybreakAvailability) Any() bool
Any reports whether the switch is worth offering: the plan transport is selected and the catalog advertises some selectable Daybreak model.
func (DaybreakAvailability) Rejects ¶ added in v0.47.0
func (a DaybreakAvailability) Rejects(m Model) bool
Rejects reports whether the catalog rules m out for Daybreak. Only a known catalog rejects, and only OpenAI models: another provider simply does not apply the program.
func (DaybreakAvailability) Sendable ¶ added in v0.47.0
func (a DaybreakAvailability) Sendable(m Model) bool
Sendable reports whether a Daybreak request for m would carry the program.
type DeferredToolsProvider ¶ added in v0.48.0
DeferredToolsProvider is optionally implemented by a provider that, for modelID, accepts deferred tool definitions (ToolSpec.Deferred) and expands the tool_reference blocks of a tool_search result into them.
type DocumentCapableProvider ¶
type DocumentCapableProvider interface {
SupportsDocuments() bool
}
DocumentCapableProvider is an optional interface a Provider may implement to declare whether it accepts native "document" content blocks (e.g. PDFs). Providers that don't implement it are treated as NOT document-capable.
type EmptyResponseError ¶
type EmptyResponseError struct {
// Provider is the provider name (e.g. "openai").
Provider string
// Usage carries the token usage the provider reported for the empty
// response, if any. An empty completed response can still bill input
// tokens; the loop must account for this before retrying so a stall can't
// silently bypass the budget. nil when the provider reported no usage.
Usage *Usage
}
EmptyResponseError is returned by a provider when a turn completed with no substantive content (no text and no tool call) and the backend gave no signal that it intends to continue. It is a distinct, typed condition so the agent loop can re-sample the same request once (a transient empty turn during polling often self-corrects) before surfacing it as a visible error, rather than ending the run in silence or failing on the first occurrence.
func (*EmptyResponseError) Error ¶
func (e *EmptyResponseError) Error() string
func (*EmptyResponseError) Is ¶
func (e *EmptyResponseError) Is(target error) bool
Is enables errors.Is(err, core.ErrEmptyResponse).
type EventCreateConfig ¶ added in v0.37.0
type EventCreateConfig struct {
Model string `json:"model,omitempty"`
Thinking string `json:"thinking,omitempty"`
Yolo bool `json:"yolo,omitempty"`
Title string `json:"title,omitempty"` // may contain "{title}"
}
EventCreateConfig is used when a project target has no live session and when_none is "create".
type EventSourceConfig ¶ added in v0.37.0
type EventSourceConfig struct {
Secret string `json:"secret"`
Target EventTarget `json:"target"`
WhenNone string `json:"when_none,omitempty"` // "inbox" | "create" (project target)
WhenMany string `json:"when_many,omitempty"` // "inbox" | "latest" (project target)
Create EventCreateConfig `json:"create,omitempty"`
// Autorun: true starts a turn on delivery to an idle session. Absent or
// false records the event in the transcript without starting a turn.
Autorun *bool `json:"autorun,omitempty"`
// Rate is auto-deliveries and session creations allowed per source per
// rolling hour. 0 / omitted = DefaultEventRatePerHour.
Rate int `json:"rate,omitempty"`
}
EventSourceConfig is one inbound hook.
func (EventSourceConfig) AutorunEnabled ¶ added in v0.37.0
func (s EventSourceConfig) AutorunEnabled() bool
AutorunEnabled reports whether a delivered event may start a turn. Absent means no — starting a turn is an explicit opt-in.
func (EventSourceConfig) RateOrDefault ¶ added in v0.37.0
func (s EventSourceConfig) RateOrDefault() int
func (EventSourceConfig) TargetKind ¶ added in v0.37.0
func (s EventSourceConfig) TargetKind() string
func (EventSourceConfig) Validate ¶ added in v0.37.0
func (s EventSourceConfig) Validate(name string) error
Validate reports the first problem with this source. name is the map key.
func (EventSourceConfig) WhenManyOrDefault ¶ added in v0.37.0
func (s EventSourceConfig) WhenManyOrDefault() string
func (EventSourceConfig) WhenNoneOrDefault ¶ added in v0.37.0
func (s EventSourceConfig) WhenNoneOrDefault() string
type EventTarget ¶ added in v0.37.0
type EventTarget struct {
Kind string `json:"-"` // inbox | project | session
Project string `json:"-"`
Session string `json:"-"`
Owner string `json:"-"`
}
EventTarget is "inbox", {project: dir}, {session: id}, or {owner: id|name}.
func (EventTarget) MarshalJSON ¶ added in v0.37.0
func (t EventTarget) MarshalJSON() ([]byte, error)
func (*EventTarget) UnmarshalJSON ¶ added in v0.37.0
func (t *EventTarget) UnmarshalJSON(data []byte) error
type EventsConfig ¶ added in v0.37.0
type EventsConfig struct {
Sources map[string]EventSourceConfig `json:"sources,omitempty"`
}
EventsConfig is the global wake-on-event setting: named webhook sources, each with its own secret and routing rule. It lives in ~/.config/moa/config.json (secrets must not be in a repository).
func (*EventsConfig) DropInvalid ¶ added in v0.37.0
func (c *EventsConfig) DropInvalid() []string
DropInvalid removes sources that fail Validate and returns their names.
func (*EventsConfig) Source ¶ added in v0.37.0
func (c *EventsConfig) Source(name string) (EventSourceConfig, bool)
Source returns a configured source by name.
func (*EventsConfig) WarnShortSecrets ¶ added in v0.37.0
func (c *EventsConfig) WarnShortSecrets()
WarnShortSecrets logs sources whose secret is shorter than 24 bytes. They remain configured; the warning is so a truncated secret is visible.
type ExecuteFunc ¶
type ExecuteFunc func(ctx context.Context, params map[string]any, onUpdate func(Result)) (Result, error)
ExecuteFunc runs a tool. onUpdate streams partial results (e.g., bash stdout lines).
type FallbackTranscriber ¶ added in v0.47.0
type FallbackTranscriber struct {
Primary Transcriber
Fallback Transcriber
}
FallbackTranscriber tries Primary and, only if it fails, Fallback. It exists so dictation can ride the subscription and fall back to a billed API key. Either side may be nil.
func (*FallbackTranscriber) Transcribe ¶ added in v0.47.0
func (f *FallbackTranscriber) Transcribe(ctx context.Context, audio io.Reader, filename string, opts TranscribeOptions) (string, error)
type FreshPayload ¶ added in v0.42.0
type FreshPayload struct {
FirstKeptMsgID string `json:"first_kept_msg_id"`
TokensBefore int `json:"tokens_before"`
TokensAfter int `json:"tokens_after"`
}
FreshPayload is the result of starting fresh: the conversation was cut at the same point a compaction would keep from, and nothing replaced what came before it — no summary, no model call.
type KeepAliveHorizons ¶ added in v0.47.0
type KeepAliveHorizons struct {
Enabled bool `json:"enabled"`
MinContextTokens *int `json:"min_context_tokens,omitempty"`
Idle string `json:"idle,omitempty"`
IdleLarge string `json:"idle_large,omitempty"`
AskUser string `json:"ask_user,omitempty"`
AskUserLarge string `json:"ask_user_large,omitempty"`
Waiting string `json:"waiting,omitempty"`
WaitingLarge string `json:"waiting_large,omitempty"`
}
KeepAliveHorizons is how long after its last request an agent of one role is kept warm, per state, as Go durations ("0" = never). Agents whose last request was smaller than MinContextTokens are never kept warm.
type KeepAlivePolicy ¶ added in v0.47.0
type KeepAlivePolicy struct {
LargeContextTokens int
PingEvery1h time.Duration
PingEvery5m time.Duration
Roles map[string]KeepAliveRolePolicy
}
KeepAlivePolicy is a resolved cache_keepalive setting.
func GetCacheKeepAlive ¶ added in v0.47.0
func GetCacheKeepAlive(cfg MoaConfig) (KeepAlivePolicy, bool)
GetCacheKeepAlive resolves the setting. ok is false when no role is enabled, which is the default. A malformed duration keeps the preset value: a hand-edited config must not stop sessions from loading.
func (KeepAlivePolicy) Horizon ¶ added in v0.47.0
func (p KeepAlivePolicy) Horizon(role, state string, contextTokens int) time.Duration
Horizon is how long after its last request an agent of role, in state, whose last request carried contextTokens, is kept warm. 0 = not at all.
func (KeepAlivePolicy) PingEvery ¶ added in v0.47.0
func (p KeepAlivePolicy) PingEvery(ttl time.Duration) time.Duration
PingEvery is the ping period for a cache that lives ttl, or 0 when the TTL has no period (no cache).
func (KeepAlivePolicy) RoleEnabled ¶ added in v0.47.0
func (p KeepAlivePolicy) RoleEnabled(role string) bool
RoleEnabled reports whether agents of role are kept warm at all.
type KeepAliveRolePolicy ¶ added in v0.47.0
type KeepAliveRolePolicy struct {
Enabled bool
MinContextTokens int
Idle, AskUser, Waiting time.Duration
IdleLarge, AskUserLarge, WaitingLarge time.Duration
}
KeepAliveRolePolicy is the resolved horizons of one role.
type LoadedMoaConfig ¶
type LoadedMoaConfig struct {
Config MoaConfig
MCPDisabled MCPDisableSources
}
LoadedMoaConfig is the merged config plus the disabled-server provenance the merge discards. LoadMoaConfig remains the simple entry point (returns .Config); scope-aware callers use LoadMoaConfigResolved.
func LoadMoaConfigResolved ¶
func LoadMoaConfigResolved(cwd string) LoadedMoaConfig
LoadMoaConfigResolved loads and merges config exactly like LoadMoaConfig, but also returns the disabled-server preference split by scope. The project list is included only when cwd is a trusted project path — matching the trust gate that governs whether the project config is merged at all.
type LockKeyFunc ¶
LockKeyFunc returns a canonical path used as a lock key for scheduling. Returns empty string on failure, which causes fallback to shell scheduling.
type MCPDisablePolicy ¶
type MCPDisablePolicy struct {
Global map[string]struct{}
Project map[string]struct{}
Session map[string]struct{}
}
MCPDisablePolicy is the resolved veto sets for one session, across all three scopes. The session set is process-lifetime and never persisted.
func NewMCPDisablePolicy ¶
func NewMCPDisablePolicy(sources MCPDisableSources) MCPDisablePolicy
NewMCPDisablePolicy builds a policy from loaded config sources. The session set starts empty; callers add to it at runtime.
func (MCPDisablePolicy) DisabledSet ¶
func (p MCPDisablePolicy) DisabledSet() map[string]bool
DisabledSet returns the names disabled for a session across all scopes, ready to hand to Manager.Start as initiallyDisabled.
type MCPDisableResolution ¶
type MCPDisableResolution struct {
// Disabled is true if any scope vetoes the server.
Disabled bool
// Scopes lists every scope that vetoes it, in stable order (global,
// project, session). Empty when the server is enabled.
Scopes []MCPDisableScope
}
MCPDisableResolution is the outcome of resolving one server against a policy.
func ResolveMCPDisabled ¶
func ResolveMCPDisabled(name string, p MCPDisablePolicy) MCPDisableResolution
ResolveMCPDisabled resolves whether a server is disabled for a session. Vetoes accumulate: disabled = global OR project OR session. No scope can re-enable a veto from another scope, so the result reports every applicable scope, which lets the UI explain why a server stays disabled after one scope is cleared.
type MCPDisableScope ¶
type MCPDisableScope string
MCPDisableScope identifies the configuration level that vetoes an MCP server. The three scopes are the only values ever produced; this is a closed set, not an open enum persisted to disk (the persisted form is just a list of names per config level).
const ( // MCPScopeGlobal is the user's global moa config (~/.config/moa/config.json). MCPScopeGlobal MCPDisableScope = "global" // MCPScopeProject is the repo-local moa config (<cwd>/.moa/config.json), // honored only for trusted project paths. MCPScopeProject MCPDisableScope = "project" // MCPScopeSession is a temporary, in-memory veto for one conversation. It is // never persisted. MCPScopeSession MCPDisableScope = "session" )
type MCPDisableSources ¶
type MCPDisableSources struct {
// Global lists names vetoed by the global config.
Global []string
// Project lists names this user vetoed for this workspace. It comes from
// their own project state, not from <cwd>/.moa/config.json: switching a
// server off is a preference, while the project file declares which servers
// exist and is meant to be committed.
Project []string
// ProjectTrusted reports whether <cwd>/.moa/config.json is trusted, i.e.
// whether the project's own MCP definitions are loaded at all.
ProjectTrusted bool
}
MCPDisableSources is the disabled-server preference split by provenance, which the merged MoaConfig loses. Loaded once so startup, the controller, and the UI all agree on which scope vetoes a server.
type MCPServer ¶
type MCPServer struct {
Command string `json:"command"`
Args []string `json:"args"`
Env map[string]string `json:"env"`
// Lazy delays the connection until a tool is called, using previously
// discovered tool metadata to advertise tools in the meantime.
Lazy bool `json:"lazy,omitempty"`
// IdleTimeout closes an unused connection after a Go duration (e.g. "15m").
// Empty means the connection stays open until the session ends.
IdleTimeout string `json:"idle_timeout,omitempty"`
// URL is the streamable-HTTP endpoint of a remote MCP server. Only http and
// https are accepted. It is an outbound connection to an endpoint the
// operator configured, so it carries the same trust as the rest of the file.
URL string `json:"url"`
// Headers are extra HTTP headers sent on every request to URL (typically
// Authorization). Ignored for command-based servers.
Headers map[string]string `json:"headers"`
}
MCPServer defines an MCP tool server connection. A server is EITHER command-based (stdio: a local subprocess) OR url-based (streamable HTTP: a remote endpoint). Setting both, or neither, is a configuration error.
type Message ¶
type Message struct {
MsgID string `json:"msg_id,omitempty"`
Role string `json:"role"`
Content []Content `json:"content"`
Timestamp int64 `json:"timestamp"`
// assistant-only
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
// RequestedModel is the normalized model selected for this response; Model
// is the effective model reported by the provider.
RequestedModel string `json:"requested_model,omitempty"`
// AccessProgram is the access program requested for this response (see
// StreamOptions.AccessProgram). Empty means standard, which is also what
// every response written before it was recorded asked for.
AccessProgram string `json:"access_program,omitempty"`
ProviderSource *ProviderSource `json:"provider_source,omitempty"`
Usage *Usage `json:"usage,omitempty"`
// RateLimit is the plan-quota state the provider reported on the response
// that produced this message (percent used and reset per window, no
// content). Absent when the provider sent none.
RateLimit *RateLimit `json:"rate_limit,omitempty"`
StopReason string `json:"stop_reason,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
// tool_result-only
ToolCallID string `json:"tool_call_id,omitempty"`
ToolName string `json:"tool_name,omitempty"`
IsError bool `json:"is_error,omitempty"`
}
Message is a tagged union. Role determines which fields are relevant.
"user" → Content "assistant" → Content, Provider, Model, Usage, StopReason "tool_result" → ToolCallID, ToolName, Content, IsError
func DropUnansweredToolCalls ¶ added in v0.46.0
DropUnansweredToolCalls returns msgs without the assistant tool_calls that have no tool_result in the run of tool_result messages right after them, and without any later tool_result for a call it removed (a restored session appends such a late synthetic result at the end). Providers reject both halves for good (Anthropic: "tool_use ids were found without tool_result blocks immediately after", "unexpected tool_use_id"), so a session that once persisted an unanswered call would never recover. It only shapes a request: the input slice and the persisted history are left untouched, and when there is nothing to drop msgs is returned as-is.
func NewToolResultMessage ¶
NewToolResultMessage creates a tool_result message.
func NewUserMessage ¶
NewUserMessage creates a user message with text content.
func NewUserMessageWithContent ¶
NewUserMessageWithContent creates a user message with arbitrary content blocks.
func (*Message) EnsureMsgID ¶
func (m *Message) EnsureMsgID()
EnsureMsgID assigns a stable identifier when the message does not have one.
type MoaConfig ¶
type MoaConfig struct {
DisableSandbox bool `json:"disable_sandbox"` // Deprecated: use PathScope. YOLO mode: allow any file path
AllowedPaths []string `json:"allowed_paths"` // Additional directories accessible outside workspace
PathScope string `json:"path_scope"` // "workspace", "unrestricted", or "" (derive from permission mode)
Permissions PermissionsConfig `json:"permissions"` // Tool execution permission policy
PinnedModels []string `json:"pinned_models"` // Model IDs pinned for Ctrl+P cycling
BraveAPIKey string `json:"brave_api_key"` // Brave Search API key for web_search tool
MCPServers map[string]MCPServer `json:"mcp_servers"` // MCP tool server connections
DisabledMCPServers []string `json:"disabled_mcp_servers,omitempty"` // MCP server names vetoed at this config level (server stays configured but is not started)
TrustedMCPPaths []string `json:"trusted_mcp_paths"` // Project paths trusted for .mcp.json auto-load
TrustedProjectPaths []string `json:"trusted_project_paths"` // Project paths trusted for .moa/config.json + .moa/tools/* auto-load
AutoTitleModel string `json:"auto_title_model,omitempty"` // "auto", "off", or model spec for automatic session titles
SessionBriefModel string `json:"session_brief_model,omitempty"` // "auto", "off", or model spec for web/Pulse session briefs
MaxBudget float64 `json:"max_budget"` // Max USD per agent run. 0 = unlimited.
MaxTurns int `json:"max_turns,omitempty"` // Max agent turns per run. 0 = unlimited.
MaxToolCallsPerTurn int `json:"max_tool_calls_per_turn,omitempty"` // Max tool calls per turn. 0 = unlimited.
MaxRunDurationStr string `json:"max_run_duration,omitempty"` // Max run duration as Go duration string (e.g. "30m"). Empty = unlimited.
MemoryEnabled *bool `json:"memory_enabled,omitempty"` // nil = true (enabled by default)
AutoVerify *bool `json:"auto_verify,omitempty"` // nil = false (disabled by default)
PersistentShell *bool `json:"persistent_shell,omitempty"` // nil = true (enabled by default)
UpdateCheck *bool `json:"update_check,omitempty"` // nil = true (check stable releases at most every 6h)
AskUserAsync *bool `json:"ask_user_async,omitempty"` // Pilot: ask_user posts a durable question and returns at once; the answer arrives later as an event. nil = the build's default (on); false turns it off.
PushSummaries string `json:"push_summaries,omitempty"` // How owner digests and event notifications are announced: "passive" (default: no sound, one per project replacing the last), "active" or "off".
PushRelayURL string `json:"push_relay_url,omitempty"` // Origin of the native push relay (default https://moa-push-relay.ealeixandre.workers.dev, provisional until push.letmoa.run exists). Only for an app built with its own APNs key and relay. Global config only.
CacheTTL string `json:"cache_ttl,omitempty"` // Interactive prompt-cache TTL: "1h" (default) or "5m". Only "5m" changes behavior.
CacheKeepAlive *CacheKeepAliveConfig `json:"cache_keepalive,omitempty"` // Keep idle Anthropic prompt caches warm with zero-output pings (global-only; off by default; see CacheKeepAliveConfig).
STTLanguage string `json:"stt_language,omitempty"` // Speech-to-text language as ISO-639-1 (e.g. "es", "en"). Empty = "en"; "auto" lets the model detect.
STTModel string `json:"stt_model,omitempty"` // Speech-to-text model id. Empty = "gpt-transcribe".
STTVocabulary []string `json:"stt_vocabulary,omitempty"` // Words the transcriber tends to get wrong (names, jargon). Keep it short: long lists hurt accuracy.
SubagentMaxTurns int `json:"subagent_max_turns,omitempty"` // Max turns per subagent run. 0 = use package default.
SubagentMaxRunDuration string `json:"subagent_max_run_duration,omitempty"` // Max subagent run duration as Go duration string. Empty = use package default.
SubagentMaxConcurrent int `json:"subagent_max_concurrent_async,omitempty"` // Max concurrent async subagents. 0 = use package default.
SubagentAllowedModels []string `json:"subagent_allowed_models,omitempty"` // Model IDs a subagent may run under. Empty/absent = no restriction (opt-in).
CompactAt int `json:"compact_at,omitempty"` // Default soft compaction threshold in tokens for sessions with none of their own. 0 = compact at the model window.
CompactModel string `json:"compact_model,omitempty"` // Model that writes compaction summaries. Empty/"session" = the session's own model. See GetCompactModel.
CompactStrategy string `json:"compact_strategy,omitempty"` // What happens before an automatic compaction: "plain", "notify" (default) or "prepare". See GetCompactStrategy.
TrimDisabled *bool `json:"trim_disabled,omitempty"` // Turn off the tool-result elision that runs before compaction. Absent/false = on. A pointer so an explicit false is distinguishable from "unset" when configs merge.
Events *EventsConfig `json:"events,omitempty"` // wake-on-event: inbound webhook sources (global-only; see EventsConfig).
Preview *PreviewConfig `json:"preview,omitempty"` // Live Preview proxy address, remembered so the web UI does not ask again (global-only).
Voice *VoiceConfig `json:"voice,omitempty"` // Voice calls: plan provider, paid alternative and backend model (global-only; see VoiceConfig).
}
MoaConfig holds sandbox, path, and permission settings. Loaded from config files at three levels: global (~/.config/moa/config.json), project (<cwd>/.moa/config.json), and session (flags). Merged with OR for booleans, concatenation for slices.
func LoadGlobalConfig ¶
func LoadGlobalConfig() MoaConfig
LoadGlobalConfig loads only the user's global moa config (~/.config/moa/config.json), without merging any project config. Callers that need the trusted-project allowlist or global-only settings use this.
func LoadMoaConfig ¶
LoadMoaConfig reads and merges config from global and project levels. Global: ~/.config/moa/config.json. Project: <cwd>/.moa/config.json. Project values override/extend global values. Also loads global .mcp.json (always). Project .mcp.json is handled separately in main.go behind a trust gate.
type Model ¶
type Model struct {
ID string `json:"id"`
Provider string `json:"provider"`
API string `json:"api"`
Name string `json:"name"`
MaxInput int `json:"max_input"`
MaxOutput int `json:"max_output"`
Pricing *Pricing `json:"pricing,omitempty"`
// AliasOf names the model this alias currently resolves to, when the
// provider answers under that other id. Responses record the effective
// id, so without this an alias's own history looks like a different
// model's on replay and its encrypted reasoning is discarded every turn.
// Empty for ordinary models, whose responses come back under the
// requested id.
AliasOf string `json:"alias_of,omitempty"`
}
Model identifies an LLM model.
func ResolveAuxiliaryModel ¶ added in v0.27.0
func ResolveAuxiliaryModel(spec string, available AuxiliaryModelAvailable) (Model, bool, error)
ResolveAuxiliaryModel resolves an auto-title or session-brief model setting. Empty is equivalent to "auto". Auto deliberately considers only the two inexpensive completion models: Luna first, then Haiku. It never selects Grok merely because xAI credentials happen to be present.
func ResolveModel ¶
ResolveModel resolves a model specifier to a fully-populated Model.
Accepted formats:
- "sonnet" → alias lookup
- "claude-sonnet-4-6" → direct registry lookup
- "anthropic/claude-sonnet-4" → provider prefix (strips prefix, looks up rest)
- "openai/gpt-5.3-codex" → provider prefix
For unknown models, returns a Model with MaxInput=0 and ok=false.
When a "provider/model" spec resolves to a known model whose registered Provider differs from the requested prefix (e.g. "openai/sonnet", where "sonnet" is an Anthropic model), ok is false — a provider/model mismatch on a *known* model name is treated as caller error, not as an intentional custom model. A provider/model pair that resolves to no known model at all is still accepted as a legitimate custom model spec (ok=false, but Provider/ID are populated verbatim so callers can still use it — pricing and context-window metadata will simply be absent). Use ValidateModelSpec to distinguish these two ok=false cases when that matters (e.g. to decide whether to fail fast at config-parse time).
type ModelEntry ¶
ListModels returns all unique known models, deduplicated by ID, sorted by provider then name. Each model also carries its shortest alias.
func ListModels ¶
func ListModels() []ModelEntry
type NoFallbackError ¶ added in v0.47.0
NoFallbackError marks a Primary failure that the Fallback must not retry, e.g. the service rejected the audio itself, so a paid retry would fail too.
type PermissionsConfig ¶
type PermissionsConfig struct {
Mode string `json:"mode"` // "yolo", "ask", or "auto" (default: "yolo")
Allow []string `json:"allow"` // Glob patterns auto-approved in ask mode: "Bash(npm:*)", "edit"
Deny []string `json:"deny"` // Glob patterns always denied (checked before allow)
Model string `json:"model"` // Model for auto mode evaluator (e.g. "haiku")
Rules []string `json:"rules"` // Natural language rules for auto mode
}
PermissionsConfig controls tool execution approval.
type PreviewConfig ¶ added in v0.37.0
type PreviewConfig struct {
PublicURL string `json:"public_url,omitempty"` // URL through which the browser reaches the proxy listener
Port int `json:"port,omitempty"` // Local port the listener binds on 127.0.0.1
}
PreviewConfig remembers how the browser reaches the Live Preview proxy. Only the address is stored: whether the proxy is running is decided per use, in memory, so Moa never reopens a port on startup because of a saved flag.
type Pricing ¶
type Pricing struct {
Input float64 `json:"input"` // $/M input tokens
Output float64 `json:"output"` // $/M output tokens
CacheRead float64 `json:"cache_read"` // $/M cached input tokens
CacheWrite float64 `json:"cache_write"` // $/M cache write tokens (5-minute window)
// FastMultiplier is the premium-tier price multiplier. Zero means this
// model does not support a premium tier.
FastMultiplier float64 `json:"fast_multiplier,omitempty"`
// CacheWrite1h is the $/M rate for writes into the extended 1-hour cache
// (Anthropic bills these at 2x input, versus 1.25x for the 5-minute
// window). Zero means the model has no extended window, and Usage's
// CacheWrite1h tokens — which will also be zero — fall back to CacheWrite.
CacheWrite1h float64 `json:"cache_write_1h,omitempty"`
// Tiers holds additional pricing tiers keyed by a context-length
// threshold, for providers that charge more once the prompt exceeds a
// given size. Must be sorted ascending by Threshold.
Tiers []PricingTier `json:"tiers,omitempty"`
}
Pricing holds per-token costs in USD per million tokens.
Some providers (e.g. OpenAI's long-context GPT models) charge a different flat rate once the prompt exceeds a context-length threshold. Tiers lists those higher-context rates in ascending Threshold order; the base Input/Output/CacheRead/CacheWrite fields are the tier that applies below the first threshold ("short context"). Cost picks the tier by the request's total input context (Input+CacheRead+CacheWrite tokens count toward the prompt length the provider bills against) and applies it to the *whole* request, matching how these providers actually bill — not a blended rate.
func (*Pricing) Cost ¶
Cost calculates the USD cost for a given Usage, selecting the pricing tier based on the request's total context (Input+CacheRead+CacheWrite tokens) and applying that tier's rates to the entire request.
Cache writes are split: Usage.CacheWrite1h is the portion written into the extended 1-hour window and is billed at the higher CacheWrite1h rate; the remainder is billed at the 5-minute CacheWrite rate. When either the usage split or the extended rate is absent, the whole write falls back to CacheWrite, which is the pre-split behavior.
type PricingTier ¶
type PricingTier struct {
Threshold int `json:"threshold"` // tier applies when Input+CacheRead+CacheWrite >= this
Input float64 `json:"input"` // $/M input tokens
Output float64 `json:"output"` // $/M output tokens
CacheRead float64 `json:"cache_read"` // $/M cached input tokens
CacheWrite float64 `json:"cache_write"` // $/M cache write tokens (5-minute window)
CacheWrite1h float64 `json:"cache_write_1h,omitempty"` // $/M extended-window cache write tokens
}
PricingTier is a pricing tier that applies once the request's context (input + cache-read + cache-write tokens) reaches Threshold tokens.
type ProjectState ¶ added in v0.24.0
type ProjectState struct {
// PermissionAllow holds patterns approved with "always allow".
PermissionAllow []string `json:"permission_allow,omitempty"`
// DisabledMCPServers holds servers this user switched off for this project.
DisabledMCPServers []string `json:"disabled_mcp_servers,omitempty"`
// Config is settings you want in this project but not in the repository —
// a turn limit you prefer here, a review model, your own budget. It is
// hand-edited: moa never writes it. Merged after the project's own config
// and before session flags, and subject to the same rules, so it can
// tighten a limit the project set but never relax one.
Config *MoaConfig `json:"config,omitempty"`
// LegacyVetoImported records that vetoes an older moa wrote into the
// project's own config were carried over. It has to be remembered: without
// it the import would run again after the user switches a server back on,
// and the toggle would appear to do nothing.
LegacyVetoImported bool `json:"legacy_veto_imported,omitempty"`
}
ProjectState is what moa decides on its own while the user works in a project: approvals they granted, MCP servers they switched off.
It is deliberately not a MoaConfig. <project>/.moa/config.json describes the project — which MCP servers it uses, what its limits are — and is meant to be committed and shared. What one person clicked is not that: it followed the user's machine into the repository, showed up as a diff nobody wanted, and on a shared checkout the first writer's private permissions locked everyone else out of the directory. So it lives with the user instead.
func LoadProjectState ¶ added in v0.24.0
func LoadProjectState(workspaceRoot string) (ProjectState, error)
LoadProjectState reads this user's state for a workspace. A missing file is an empty state; anything else is an error, because silently treating an unreadable file as "no approvals" would re-prompt for everything with no indication why.
type Provider ¶
type Provider interface {
Stream(ctx context.Context, req Request) (<-chan AssistantEvent, error)
}
Provider streams LLM responses. Each provider (Anthropic, OpenAI, etc.) implements this interface, emitting normalized AssistantEvents.
Error contract:
- Returns error immediately for pre-stream failures (auth, invalid model, network).
- If channel is returned, it ALWAYS receives exactly one terminal event ("done" or "error") before being closed.
- The caller must drain the channel to avoid goroutine leaks.
- Context cancellation causes an "error" event with ctx.Err().
type ProviderAuthError ¶ added in v0.46.0
ProviderAuthError is an inference request the provider refused with 401 or 403. It knows only the status: which credential was rejected, and so what the user can do about it, is decided by the caller that chose it.
func (*ProviderAuthError) Error ¶ added in v0.46.0
func (e *ProviderAuthError) Error() string
type ProviderCredentialError ¶ added in v0.46.0
type ProviderCredentialError struct {
Provider string
Source string // CredentialSourceEnv or CredentialSourceStore
Operation string // e.g. "resolve", "refresh", "save", "login"
Class string // one of the Credential* classes
Action string // suggested next step, derived from Class and Source
Generation string // opaque login generation, when known
Status int // upstream HTTP status, when one was received
OAuthCode string // allowlisted OAuth error code, "other" or ""
}
ProviderCredentialError is a classified provider credential failure that is safe to show, log and send to clients. It deliberately carries only allowlisted metadata: no upstream bodies, URLs, tokens or wrapped causes, so no wrapper can leak a secret through Error() or errors.Unwrap.
func AsProviderCredentialError ¶ added in v0.46.0
func AsProviderCredentialError(err error) (*ProviderCredentialError, bool)
AsProviderCredentialError extracts a *ProviderCredentialError from an error chain, if present.
func NewProviderCredentialError ¶ added in v0.46.0
func NewProviderCredentialError(provider, source, operation, class string) *ProviderCredentialError
NewProviderCredentialError builds an error with the action implied by the class and source.
func (*ProviderCredentialError) Error ¶ added in v0.46.0
func (e *ProviderCredentialError) Error() string
type ProviderDispatch ¶ added in v0.46.0
type ProviderDispatch func(context.Context, ProviderSource) error
type ProviderErrorDetail ¶ added in v0.46.0
type ProviderErrorDetail struct {
Provider string `json:"provider"`
Source string `json:"source,omitempty"`
CredentialGeneration string `json:"credential_generation,omitempty"`
Class string `json:"class"`
Action string `json:"action"`
}
ProviderErrorDetail is the client-facing form of a credential failure: the structured counterpart of a session's error text. It carries no secret.
func CredentialErrorDetail ¶ added in v0.46.0
func CredentialErrorDetail(err error) *ProviderErrorDetail
CredentialErrorDetail returns the detail of the credential failure in err's chain, or nil when err is not one.
type ProviderExecution ¶ added in v0.46.0
type ProviderExecution struct {
Source *ProviderSource `json:"source,omitempty"`
Generation uint64 `json:"generation"`
Epoch uint64 `json:"epoch"`
Phase string `json:"phase"`
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
Bound bool `json:"bound,omitempty"`
Wait *ProviderWait `json:"wait,omitempty"`
Saved bool `json:"saved,omitempty"`
SaveError string `json:"save_error,omitempty"`
}
type ProviderRetryReady ¶ added in v0.46.0
type ProviderRetryReady struct {
Source *ProviderSource
Attempt int
Wait *ProviderWait
}
ProviderRetryReady is internal control flow: the closed HTTP attempt can be rebuilt with fresh configuration and credentials, without another turn.
func (*ProviderRetryReady) Error ¶ added in v0.46.0
func (e *ProviderRetryReady) Error() string
type ProviderRetryWait ¶ added in v0.46.0
type ProviderRetryWait func(context.Context, ProviderWait) error
type ProviderSource ¶ added in v0.46.0
type ProviderSource struct {
Kind string `json:"kind"`
PrimaryGeneration string `json:"primary_generation,omitempty"`
BackupGeneration string `json:"backup_generation,omitempty"`
WireProfile string `json:"wire_profile,omitempty"`
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
OAuthNotBefore *time.Time `json:"oauth_not_before,omitempty"`
OAuthQuotaObservedAt *time.Time `json:"oauth_quota_observed_at,omitempty"`
EstimatedCost *float64 `json:"estimated_cost,omitempty"`
UsageComplete bool `json:"usage_complete,omitempty"`
InputTransformations []string `json:"input_transformations,omitempty"`
}
ProviderSource records provenance, never tokens or reusable authorization. A continuation binding is checked against the Store again at dispatch.
type ProviderUnwrapper ¶
type ProviderUnwrapper interface {
Unwrap() Provider
}
ProviderUnwrapper is optionally implemented by Provider decorators to expose the provider they wrap. Capability helpers follow this chain so decorators do not hide optional provider interfaces.
Unwrap must return nil when there is no wrapped provider.
type ProviderWait ¶ added in v0.46.0
type ProviderWait struct {
Kind string `json:"kind"`
Scope string `json:"scope,omitempty"`
ResetSource string `json:"reset_source,omitempty"`
RetrySource string `json:"retry_source,omitempty"`
ObservedAt time.Time `json:"observed_at"`
ResetAt *time.Time `json:"reset_at,omitempty"`
RetryAfterAt *time.Time `json:"retry_after_at,omitempty"`
NextAttemptAt time.Time `json:"next_attempt_at"`
Attempt int `json:"attempt"`
Status int `json:"status,omitempty"`
}
ProviderWait contains only evidence from a closed rejection, never credentials or permission to dispatch after a process restart.
type QuotaExceededError ¶
type QuotaExceededError struct {
// Provider is the provider name (e.g. "openai", "anthropic").
Provider string
// Message is the human-readable message from the provider, if any.
Message string
// PlanType is the subscription plan reported by the provider (may be empty).
PlanType string
// ResetsIn is the time until the exhausted window resets (0 if unknown).
ResetsIn time.Duration
// ResetsAt is the wall-clock reset time (zero if unknown).
ResetsAt time.Time
// Window labels which limit was hit ("5h", "weekly", or "" if unknown).
Window string
// Wait is populated only for a proven, automatically waitable rejection.
Wait *ProviderWait
}
QuotaExceededError is returned by a provider when the account's usage limit has been reached (e.g. a ChatGPT/Codex subscription 5-hour or weekly window), as opposed to a transient rate limit that a retry would clear. It is NOT a user cancellation: callers must surface it as an actionable "limit reached, resets in X" message rather than a generic error or an interruption marker.
func AsQuotaExceeded ¶
func AsQuotaExceeded(err error) (*QuotaExceededError, bool)
AsQuotaExceeded extracts a *QuotaExceededError from an error chain, if present.
func (*QuotaExceededError) Error ¶
func (e *QuotaExceededError) Error() string
func (*QuotaExceededError) Is ¶
func (e *QuotaExceededError) Is(target error) bool
Is reports whether target is a *QuotaExceededError, enabling errors.Is checks against the ErrQuotaExceeded sentinel.
type RateLimit ¶
type RateLimit struct {
Status string `json:"status,omitempty"` // allowed / allowed_warning / rejected
RepresentativeClaim string `json:"representative_claim,omitempty"` // window that currently binds: five_hour / seven_day / overage / ...
FiveHourUtil float64 `json:"five_hour_util"` // [0,1], or -1 if unknown
SevenDayUtil float64 `json:"seven_day_util"` // [0,1], or -1 if unknown
OverageStatus string `json:"overage_status,omitempty"`
OverageUtil float64 `json:"overage_util"` // [0,1], or -1 if unknown
// FiveHourResetAt and SevenDayResetAt are when each window resets, in Unix
// seconds; 0 when the provider did not say.
FiveHourResetAt int64 `json:"five_hour_reset_at,omitempty"`
SevenDayResetAt int64 `json:"seven_day_reset_at,omitempty"`
}
RateLimit captures the unified rate-limit state a provider reports on each response (Anthropic's anthropic-ratelimit-unified-* headers).
Utilization fields are fractions in [0,1], or -1 when the corresponding header was absent/invalid — callers must treat -1 as "unknown" and NOT overwrite a known value with it (the endpoint is reverse-engineered and may change shape).
It lets callers see, per request, how much of each plan window is used and whether the request was served from pay-as-you-go "extra usage" — instantly, without polling the account-global usage endpoint.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds registered tools. Thread-safe.
func (*Registry) All ¶
All returns all registered tools (snapshot), sorted by name for deterministic order.
func (*Registry) Register ¶
Register adds or replaces a tool. Returns error if a WritePath tool is missing its LockKey function.
func (*Registry) Specs ¶
Specs returns ToolSpecs for all registered tools (for sending to LLM), sorted by name.
func (*Registry) WithInternalTools ¶
WithInternalTools returns a new, isolated registry containing this registry's current tools plus internal tools. It never mutates the receiver, including when an internal tool uses a reserved name. Creating an overlay only changes tool visibility; it does not grant permissions to execute any tool in the overlay.
type Request ¶
type Request struct {
Model Model
System string // System prompt
Messages []Message // Conversation history (user, assistant, tool_result)
Tools []ToolSpec // Available tools for tool_use
Options StreamOptions
}
Request contains everything needed for an LLM call.
type RequestBreakpoint ¶ added in v0.46.0
type RequestBreakpoint struct {
Section string `json:"section"`
Message int `json:"message"`
Block int `json:"block"`
TTL string `json:"ttl"`
TTLExplicit bool `json:"ttl_explicit,omitempty"`
}
RequestBreakpoint is one cache_control marker: where it sits and its TTL ("5m" by default, or "1h"). TTLExplicit tells whether the request spelled the TTL out or relied on the provider default.
type RequestFingerprint ¶ added in v0.46.0
type RequestFingerprint struct {
BuiltAt time.Time `json:"built_at"`
BodySHA256 string `json:"body_sha256"`
ToolsSHA256 string `json:"tools_sha256,omitempty"`
SystemSHA256 string `json:"system_sha256,omitempty"`
OptionsSHA256 string `json:"options_sha256"`
Prefixes []RequestPrefixHash `json:"prefixes,omitempty"`
Breakpoints []RequestBreakpoint `json:"breakpoints,omitempty"`
}
RequestFingerprint describes one final provider request without carrying any of its content: only SHA-256 digests and the positions of cache markers, so it is safe to persist. Equal Prefixes mean the converted request content matches up to that point; they do not guarantee a cache hit, which also depends on the model, options, TTL and the provider's cache backend. Markers are recorded apart from content so moving one does not change any content hash.
type RequestFingerprintFunc ¶ added in v0.46.0
type RequestFingerprintFunc func() (RequestFingerprint, error)
RequestFingerprintFunc computes the fingerprint of one final request body on demand. It holds only that immutable body, so retaining it keeps one request alive; the cost of hashing is paid only when it is called.
type RequestPrefixHash ¶ added in v0.46.0
type RequestPrefixHash struct {
Section string `json:"section"`
Message int `json:"message"`
Block int `json:"block"`
SHA256 string `json:"sha256"`
}
RequestPrefixHash is the rolling hash of the request up to and including one block. Section is "tools", "system" or "messages"; Message is the message index (-1 outside messages) and Block the block index within its section or message.
type Result ¶
type Result struct {
Content []Content `json:"content"`
IsError bool `json:"is_error,omitempty"`
// Custom annotates the recorded tool result with facts the UI needs but the
// model does not — it is merged into the tool_result message's own Custom
// map and never reaches the provider. The subagent tool uses it to record
// which job a call spawned, a link that is otherwise lost on restart.
Custom map[string]any `json:"custom,omitempty"`
}
Result is what a tool returns to the LLM. Uses the same Content type as messages — no duplication.
func ErrorResult ¶
ErrorResult creates a Result representing an error message. Sets IsError=true so the agent loop can detect tool-level errors even when the tool returns (Result, nil) instead of (Result, error).
func RejectedResult ¶ added in v0.46.0
RejectedResult is an ErrorResult for a call the human refused at a prompt the tool itself raised. The marker lets the loop tell a refusal, which is the user's answer, from a failure the model should change course on.
func TextResult ¶
TextResult creates a Result with a single text content block.
type SteerItem ¶
type SteerItem struct {
ID string `json:"id"`
Text string `json:"text"`
// Custom is persisted with the eventual conversation message. It lets
// internal ingress retain its rendering/source metadata when it has to wait
// on the queue rail instead of starting a direct run.
Custom map[string]any `json:"-"`
// Content, when non-nil, is the full payload of a steer (text plus image or
// other content blocks). It is injected with NewUserMessageWithContent. A
// nil Content means a plain-text steer carried in Text.
Content []Content `json:"content,omitempty"`
// Command, when non-empty, marks this item as a queued command (a BARRIER):
// it holds the raw normalized command line (e.g. "/compact", "/model sonnet").
// A barrier item is never injected as a conversation message — it stops the
// queue drain, and is executed at the next idle point (RunEnded) by the bus.
// Invariant: a barrier carries no Content, and an Internal item is never a
// barrier.
Command string `json:"command,omitempty"`
// Internal marks a system-generated steer (e.g. a subagent/bash completion
// injected into the parent run) as opposed to a user-typed message. Internal
// steers are delivered to the agent but excluded from the authoritative
// queue snapshot, since their delivery event is suppressed and they must not
// surface as user-visible "queued" chips.
Internal bool `json:"-"`
}
SteerItem is a queued item in the agent's unified queue rail. It is either a steering message (text, optionally with image/content blocks) injected into a run, or a queued command that acts as a turn barrier (see Command). Items are consumed in strict FIFO order, so a command queued between two messages runs exactly in that position.
type StreamOptions ¶
type StreamOptions struct {
OnProviderDispatch ProviderDispatch `json:"-"`
OnProviderPrepare ProviderDispatch `json:"-"`
ProviderBinding *ProviderSource `json:"-"`
AnthropicWireProfile string `json:"-"`
OnProviderRetry ProviderRetryWait `json:"-"`
ProviderRetryAttempt int `json:"-"`
Temperature *float64 `json:"temperature,omitempty"`
MaxTokens *int `json:"max_tokens,omitempty"`
// AppliedCap, when set, is filled by the provider with the output cap the
// wire request really carries. It is telemetry for the caller (the
// compaction record) and never part of a provider payload.
AppliedCap *AppliedOutputCap `json:"-"`
APIKey string `json:"-"`
ThinkingLevel string `json:"thinking_level,omitempty"`
// CacheRetention selects the prompt-cache TTL: "" is the provider default
// (5 minutes), "1h" opts into the long TTL, and CacheOff suppresses cache
// writes entirely.
CacheRetention string `json:"cache_retention,omitempty"`
// PromptCacheKey identifies the conversation this request belongs to, so
// requests sharing a prefix are routed to the machine holding its cache.
// Consumed by the Responses providers (OpenAI, xAI); Anthropic has no
// equivalent and ignores it.
PromptCacheKey string `json:"prompt_cache_key,omitempty"`
// Fast asks the provider to serve this request at a premium speed and
// price. Each provider spells it differently — Anthropic takes a beta
// header plus `speed`, the Responses providers a `service_tier` — and a
// provider that has no such notion, or a model that doesn't support it,
// ignores the flag rather than failing.
Fast bool `json:"fast,omitempty"`
// because the account cannot use the premium tier. It is process-local
// state coordination, never part of a provider payload.
OnFastUnavailable func() `json:"-"`
// AccessProgram is the access program this request asks for (Daybreak's
// DaybreakAccessProgram), "" for standard. Only a transport that supports
// it sends it; everyone else ignores it.
AccessProgram string `json:"access_program,omitempty"`
// OnRequestFingerprint, when set, receives a lazy thunk for the final
// provider request body, once per logical request, before it is sent.
// Providers that do not fingerprint requests ignore it. The consumer
// decides when to evaluate it: subagents hash the first request here and
// retain only the latest thunk for evaluation when the job ends.
OnRequestFingerprint func(RequestFingerprintFunc) `json:"-"`
}
StreamOptions configures an LLM request.
type Tool ¶
type Tool struct {
Name string `json:"name"`
Label string `json:"label"`
Description string `json:"description"`
Parameters json.RawMessage `json:"parameters"`
SpecFunc func() ToolSpec `json:"-"` // Lets schemas that reflect live policy be refreshed for each provider request.
Execute ExecuteFunc `json:"-"`
Effect ToolEffect `json:"-"` // scheduling hint for conflict-aware execution
LockKey LockKeyFunc `json:"-"` // required when Effect is EffectWritePath
// Deferrable marks a tool the provider may load on demand, through
// tool_search, instead of with every request. Only MCP tools set it.
Deferrable bool `json:"-"`
}
Tool is a callable function with JSON Schema parameters.
type ToolCallDecision ¶
type ToolCallDecision struct {
Block bool
Reason string
Kind string // optional classification (e.g. permission, policy)
}
ToolCallDecision is returned by tool-call hooks to optionally block execution.
type ToolEffect ¶
type ToolEffect int
ToolEffect classifies a tool's side effects for the conflict-aware scheduler. The zero value (EffectUnknown) is treated as a barrier — safe by default.
const ( EffectUnknown ToolEffect = iota // zero value — serialized (conservative) EffectReadOnly // no side effects — safe to parallelize EffectWritePath // writes to a specific path via LockKey EffectShell // may write anywhere — acts as barrier EffectInteractive // blocks on a human response (e.g. ask_user) — acts as a total barrier )
type ToolSpec ¶
type ToolSpec struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters json.RawMessage `json:"parameters"`
// Deferred asks the provider to keep the definition out of the model's
// context until a tool_search result references it. Set only by the agent,
// and only for a provider that reports SupportsDeferredTools.
Deferred bool `json:"deferred,omitempty"`
}
ToolSpec is a tool definition sent to the LLM (name + description + JSON schema). Separate from the executable Tool to keep the provider layer dependency-free.
type TranscribeOptions ¶
type TranscribeOptions struct {
// Language is an ISO-639-1 hint (e.g. "es", "en"). Empty lets the provider
// auto-detect. Setting it avoids mis-detection on short/ambiguous audio.
Language string
// Prompt biases the decoder toward specific vocabulary/spelling. Optional.
Prompt string
// Model is the provider's model id. Empty lets the provider pick its own
// default, so callers that do not care keep working.
Model string
}
TranscribeOptions tunes a speech-to-text request.
type Transcriber ¶
type Transcriber interface {
Transcribe(ctx context.Context, audio io.Reader, filename string, opts TranscribeOptions) (string, error)
}
Transcriber converts audio to text. Providers that support speech-to-text (e.g. OpenAI) implement this interface.
type TrimPayload ¶ added in v0.41.0
type TrimPayload struct {
WatermarkMsgID string `json:"watermark_msg_id"`
Version int `json:"version"`
TokensBefore int `json:"tokens_before"`
TokensAfter int `json:"tokens_after"`
Results int `json:"results"`
}
TrimPayload is the typed result of a trim event.
type TrimPlan ¶ added in v0.41.0
type TrimPlan struct {
WatermarkMsgID string
Version int
Results int
TokensRemoved int
Messages []AgentMessage
}
TrimPlan is the outcome of PlanTrim: the projected conversation plus what it would cost and save. Messages is nil when nothing was eligible.
func PlanTrim ¶ added in v0.41.0
func PlanTrim(msgs []AgentMessage, keepRecent int, prevWatermarkMsgID string) (TrimPlan, bool)
PlanTrim computes the next trim over msgs: protect a recent tail of about keepRecent estimated tokens, then elide every eligible message between prevWatermarkMsgID (exclusive of nothing — it is where the last trim stopped) and the start of that tail.
The watermark is snapped BACKWARD to the assistant that owns a group of tool results, never forward: forward is what compaction's FindCutPoint does, because there the boundary decides what gets summarized, and pushing a whole tool group to the summarized side is the safe direction. Here the boundary decides what is PROTECTED, so the safe direction is the opposite one — snapping forward would elide a large, very recent result that the promise of a protected tail says it must keep.
Returns ok=false when nothing could be elided (including a watermark that would not advance past the previous one: trims must move forward, or an older region would be re-elided under newer rules).
type TrimSpan ¶ added in v0.41.0
TrimSpan is one applied trim: everything eligible from the previous span's watermark up to (not including) WatermarkMsgID was elided under Version.
type Usage ¶
type Usage struct {
Input int `json:"input"`
Output int `json:"output"`
CacheRead int `json:"cache_read"`
CacheWrite int `json:"cache_write"`
// Fast reports that the provider actually served this request at its
// premium tier, rather than merely that it was requested.
Fast bool `json:"fast,omitempty"`
// CacheWrite1h is the subset of CacheWrite billed at the extended
// (1-hour) cache-write rate rather than the 5-minute one. Anthropic
// reports the split in cache_creation; providers without an extended
// window leave it zero, which prices the whole write at the base rate.
CacheWrite1h int `json:"cache_write_1h,omitempty"`
TotalTokens int `json:"total_tokens"`
}
Usage tracks token consumption for a single LLM call.
type VoiceCallHours ¶ added in v0.47.0
type VoiceCallHours struct {
From string `json:"from"` // "HH:MM"
Until string `json:"until"` // "HH:MM"
TZ string `json:"tz"` // IANA zone of the device that set it
}
VoiceCallHours is a daily window [From, Until) in TZ; Until before From crosses midnight.
type VoiceCallsConfig ¶ added in v0.47.0
type VoiceCallsConfig struct {
RingSeconds int `json:"ring_seconds,omitempty"` // how long one request rings before it is missed. 0 = DefaultCallRingSeconds.
PausedUntil string `json:"paused_until,omitempty"` // RFC 3339; no owner call is announced before it.
Hours *VoiceCallHours `json:"hours,omitempty"` // when owners may call; nil = any time.
// QuestionCallMinutes is how long an owner's tap-only question waits
// unanswered before the owner calls about it. 0 = DefaultQuestionCallMinutes.
QuestionCallMinutes int `json:"question_call_minutes,omitempty"`
}
VoiceCallsConfig bounds the calls owners start. Additive: absent fields keep the defaults (45 s of ringing, no pause, any hour).
type VoiceConfig ¶ added in v0.47.0
type VoiceConfig struct {
Provider string `json:"provider,omitempty"` // plan used by default: "chatgpt-plan" or "grok-plan". Empty = ChatGPT, then Grok.
PaidProvider string `json:"paid_provider,omitempty"` // paid alternative offered when the plan fails: "xai-api" or "openai-live-api". Empty = the plan's own provider.
BackendModel string `json:"backend_model,omitempty"` // model behind ChatGPT-plan handoffs and Live delegation. Empty = DefaultVoiceBackendModel.
Calls VoiceCallsConfig `json:"calls,omitzero"` // calls owners start (request_call): ring time, pause and allowed hours.
}
VoiceConfig chooses how voice calls are made. Every field is optional and additive: an absent value keeps the default. None of them is consent to pay: a paid provider is only used when the user picks it for a call.
func GetVoiceConfig ¶ added in v0.47.0
func GetVoiceConfig(cfg MoaConfig) VoiceConfig
GetVoiceConfig returns the voice settings with defaults filled in.
Source Files
¶
- agentctx.go
- auxiliary_model.go
- cache_miss.go
- cache_usage.go
- codebase.go
- compact_model.go
- compaction.go
- config.go
- config_lock_unix.go
- configdir.go
- daybreak.go
- errors.go
- event.go
- events_config.go
- fastmode.go
- filelock.go
- image.go
- keepalive.go
- mcp_policy.go
- message.go
- model_identity.go
- models.go
- orphan_tool_calls.go
- project_state.go
- provider.go
- provider_credential_error.go
- provider_source.go
- provider_wait.go
- skill_invocation.go
- state_lock_unix.go
- tool.go
- transcribe.go
- trim.go