store

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package store manages global application UI state for the REPL using kites.

Index

Constants

View Source
const (
	// DefaultHint is the standard shortcut hint shown on the status line.
	DefaultHint = "Shift+Tab mode · /help"
	// CtrlCHint is the exit confirmation hint shown when Ctrl+C is first pressed.
	CtrlCHint = "Press Ctrl+C again to exit"
)
View Source
const ThinkingProviderDefault = "provider default"

Variables

Functions

func ActiveModelSupports

func ActiveModelSupports(mod string) (modelID string, supported bool)

ActiveModelSupports reports whether the active (or draft) session model supports the requested input modality ("image", "pdf", "audio"), returning the model ID for notices when explicitly unsupported. Models with unknown modalities (nil InputModalities) report supported=true.

func AppendCommandOutput

func AppendCommandOutput(cmd, out string)

AppendCommandOutput appends the output of a local slash command to the transcript scrollback.

func AppendContextUsage

func AppendContextUsage(d ContextUsageData)

AppendContextUsage appends a /context usage view to the transcript scrollback.

func AppendError

func AppendError(title, msg string)

AppendError appends a local or turn error message to the transcript scrollback.

func AppendHeader

func AppendHeader(d HeaderData)

AppendHeader appends a header item to the transcript scrollback.

func AppendMessage

func AppendMessage(msg Message)

AppendMessage appends a finalized message to the transcript scrollback.

func AppendNotice

func AppendNotice(text string)

AppendNotice appends a local informational notice to the transcript scrollback.

func AppendOutput

func AppendOutput(out string)

func AppendSkippedPresetAliasNotices

func AppendSkippedPresetAliasNotices(skipped []api.SkippedPresetAlias)

func AppendTimelineEntry

func AppendTimelineEntry(e api.TimelineEntry)

AppendTimelineEntry appends an API timeline entry to the transcript scrollback.

func AppendTranscript

func AppendTranscript(items ...TranscriptItem)

AppendTranscript appends items to the transcript. It allocates a new slice copy so Items gets a new pointer for kites.Use. If an incoming item has an ID != "" that already exists in Items, it is skipped to avoid duplicates within the current epoch. In frozen mode, if the transcript is currently empty and the first item being appended is not a Header, a snapshot HeaderItem is prepended. In draft mode (!Frozen), items are simply appended without a Header item.

func AppendWarning

func AppendWarning(text string)

func ApplyEvent

func ApplyEvent(event api.Event)

ApplyEvent applies an API SSE event to the active conversation stream.

func ApplyStatusLine

func ApplyStatusLine(cfg StatusLineConfig) ([]string, error)

func ApplyThinkingChange

func ApplyThinkingChange(setting *api.ThinkingSetting)

func ApprovePermissionAndAcceptEdits

func ApprovePermissionAndAcceptEdits(req api.PermissionRequest)

func Cancel

func Cancel()

Cancel aborts the active turn if streaming.

func CancelTurn

func CancelTurn()

CancelTurn resets the active turn stream state to idle and discards drafts.

func ClearScreen

func ClearScreen()

ClearScreen clears the transcript screen. In draft mode (!Frozen), it simply clears draft items without incrementing Epoch. In frozen mode, it clears terminal scrollback and repaints only the header banner.

func ClearSlot

func ClearSlot()

ClearSlot resets SlotState to empty.

func ClearTranscript

func ClearTranscript()

ClearTranscript resets TranscriptState to Epoch 0, Frozen false, and nil Items.

func Client

func Client() *client.Client

Client returns the currently active daemon client, if any.

func CloseOnboarding

func CloseOnboarding()

CloseOnboarding closes the wizard without writing.

func CurrentThinkingModel

func CurrentThinkingModel(ctx context.Context) (*api.Model, error)

func CycleMode

func CycleMode() api.PermissionMode

CycleMode atomically advances to the next permission mode in sequence and returns the new mode.

func DecidePermission

func DecidePermission(req api.PermissionRequest, dec api.PermissionDecision)

DecidePermission submits a user decision on a pending permission request.

func DecideSubagentPermission

func DecideSubagentPermission(subagentID string, req api.PermissionRequest, dec api.PermissionDecision)

DecideSubagentPermission submits a user decision on a pending permission request for a child subagent.

func DefaultAgent

func DefaultAgent() string

DefaultAgent returns the default agent configured at startup.

func DefaultModel

func DefaultModel() string

DefaultModel returns the default model configured at startup.

func DequeueSlot

func DequeueSlot()

DequeueSlot removes the front item from the slot queue if non-empty.

func EnqueueSlot

func EnqueueSlot(item SlotItem)

EnqueueSlot enqueues an item into the slot queue. If item.ID is empty, a unique non-empty ID is automatically assigned. If an item with the same ID already exists, it is updated in place to prevent duplicates.

func FinishOnboarding

func FinishOnboarding(ctx context.Context, c *client.Client) error

FinishOnboarding calls client.InitWorkspace with the draft configuration and marks completed.

func ForceRefreshWorkspaceTools

func ForceRefreshWorkspaceTools(ctx context.Context) (int, error)

ForceRefreshWorkspaceTools refetches tools for the effective agent and replaces the AppState cache even when it already looks fresh. Use it after a daemon-side mutation (such as enabling or disabling a tool) whose response is not agent-classified.

func ForceSetModel

func ForceSetModel(modelID string)

ForceSetModel updates the model for the session, omitting any unsupported historical media descriptors on future turns when switching drops modalities.

func ForkSession

func ForkSession(sessionID, title string)

ForkSession branches the given session (or the active session when sessionID is empty) into a new top-level session that starts from the same conversation, then switches to it. An empty title derives one from the source session's title.

func FreezeTranscript

func FreezeTranscript()

FreezeTranscript transitions the transcript from live draft mode to frozen static scrollback. If items does not already start with a Header item, one is prepended with CurrentHeaderData().

func GetContext

func GetContext() api.ContextState

GetContext returns the current ContextState snapshot.

func GetQuota

func GetQuota() *api.ModelQuota

GetQuota returns the active model's latest quota reading, or nil.

func GetRunningDelegatedSubagents

func GetRunningDelegatedSubagents() []api.Session

GetRunningDelegatedSubagents returns running delegated slash-command subagents (excluding autonomous invoke_agent background subagents).

func GetRunningSubagents

func GetRunningSubagents() []api.Session

GetRunningSubagents returns a snapshot of running subagents for the active session.

func GetRunningTasks

func GetRunningTasks() []api.Task

GetRunningTasks returns a snapshot of active running and pending tasks for the active session.

func GetStatusLineDropped

func GetStatusLineDropped() []string

func GetSubagents

func GetSubagents() []api.Session

GetSubagents returns a snapshot of child subagents for the active session.

func GetTasks

func GetTasks() []api.Task

GetTasks returns a snapshot of background tasks for the active session.

func GetUsage

func GetUsage() api.SessionUsage

GetUsage returns the active session's usage snapshot.

func GetWaitingSubagents

func GetWaitingSubagents() []api.Session

GetWaitingSubagents returns a snapshot of subagents waiting for permission or a question.

func GoBack

func GoBack() bool

GoBack pops the previous step from History, or cancels if history is empty.

func GoToStep

func GoToStep(targetStep OnboardingStep)

GoToStep transitions directly to targetStep while recording current step in history. The user scope has no repository, so nothing a tool-selection step chooses could be written deterministically; it is skipped there.

func InitSession

func InitSession(ctx context.Context, c *client.Client, opts InitSessionOptions)

InitSession initializes or attaches to a session. It starts background watchers for session metadata and stream events.

func IsCommandDelegatedSubagent

func IsCommandDelegatedSubagent(sub api.Session) bool

IsCommandDelegatedSubagent reports whether sub represents a user-invoked delegated slash command rather than an autonomous invoke_agent subagent.

func KillSubagent

func KillSubagent(subagentID string) error

KillSubagent sends a cancel request to terminate an active child subagent.

func KillTask

func KillTask(taskID string) error

KillTask sends a kill request for an active background task in the active session.

func LaunchProviderAuth

func LaunchProviderAuth(provider string)

LaunchProviderAuth triggers the registered provider sign-in screen, if any.

func LoadStatusLine

func LoadStatusLine()

func ModelThinkingDefault

func ModelThinkingDefault(model *api.Model) *api.ThinkingSetting

ModelThinkingDefault reports the thinking a model applies without any session or agent override. The daemon resolves this into ThinkingDefault; the scan of declared capabilities keeps the status line correct when it does not.

func NewDraftSession

func NewDraftSession(modelOverride string)

NewDraftSession resets the REPL to a new draft session, preserving mode.

func NextPermissionMode

func NextPermissionMode(current api.PermissionMode) api.PermissionMode

NextPermissionMode returns the next permission mode in the cycle sequence: default -> accept_edits -> plan -> ask -> auto -> default.

func OpenSubagent

func OpenSubagent(subagentID string)

OpenSubagent opens the subagent live view for the specified subagent ID.

func RefreshDraftModelPreview

func RefreshDraftModelPreview(ctx context.Context)

RefreshDraftModelPreview re-resolves the draft session's model preview against the daemon. Callers use it after workspace mutations (providers, aliases) so the composer badge tracks the patched manifests before the first turn creates a real session.

func RefreshWorkspaceTools

func RefreshWorkspaceTools(ctx context.Context, agent string) (int, error)

RefreshWorkspaceTools fetches the workspace tools classified for agent using the active client and caches them in AppState. It returns the number of cached tools, and is a no-op when the cache already holds tools for that agent.

func RefreshWorkspaceWarnings

func RefreshWorkspaceWarnings()

RefreshWorkspaceWarnings fetches the latest workspace warnings from the daemon on a background goroutine so runtime auth-health diagnostics appear in the statusline immediately.

func ReloadWorkspace

func ReloadWorkspace(ctx context.Context) error

ReloadWorkspace instructs the daemon to reload workspace resources from disk and refreshes AppState with updated skills and commands.

func RemoveSlot

func RemoveSlot(id string)

RemoveSlot removes the item with matching ID from the slot queue.

func RequestExit

func RequestExit()

RequestExit requests the REPL application to terminate.

func ResetApp

func ResetApp()

ResetApp resets AppState to its default values while preserving version, workspace, and warnings.

func ResetForSessionSwitch

func ResetForSessionSwitch()

ResetForSessionSwitch prepares the transcript for a loaded or resumed session. It snapshots the Header and enters Frozen mode. If previously frozen, it increments Epoch.

func ResetSession

func ResetSession()

ResetSession resets the session state to its initial default mode, cancels any active watchers or session-scoped background goroutines, and waits for them to exit.

func ResetStream

func ResetStream()

ResetStream resets StreamState to its initial empty state.

func ResetToDraft

func ResetToDraft()

ResetToDraft resets the transcript back to draft mode. If the transcript was frozen, Epoch is incremented to clear terminal scrollback. If it was not frozen (draft), Epoch is preserved and items are simply cleared.

func ResetTranscript

func ResetTranscript(initial ...TranscriptItem)

ResetTranscript increments Epoch by 1 and sets Items to a copy of initial, or nil if len(initial) == 0.

func RestartDaemon

func RestartDaemon(ctx context.Context) (*api.HealthResponse, error)

RestartDaemon stops any running daemon, spawns a new background process, waits for it to become healthy, and resyncs state.

func SaveStatusLine

func SaveStatusLine(cfg StatusLineConfig) ([]string, error)

func SeedQueue

func SeedQueue(items []api.QueueItem)

SeedQueue imports initial queue items (e.g. from session state) into the active conversation queue.

func SeedTodos

func SeedTodos(items []api.TodoItem)

SeedTodos imports initial todos (e.g. from session state) into the active conversation checklist.

func Send

func Send(text string, attachments ...api.Attachment)

Send sends a user prompt message to the active session. If no session exists yet, one is created lazily. Send sends a prompt to the active session, creating one lazily if needed.

func SendCommand

func SendCommand(cmd string)

SendCommand executes a direct user shell command (!) in the active session sandbox without triggering an LLM turn. If no session exists yet, one is created lazily.

func SendCompact

func SendCompact(focus string)

SendCompact triggers manual context compaction for the active session.

func SendWithUserText

func SendWithUserText(text, userText string, attachments ...api.Attachment)

SendWithUserText sends text to the active session while scanning only userText (rather than any server-rendered prompt or MCP resource body in text) for structured @-mention reconciliation and 3.4 fallback lookup.

func SetActiveModelID

func SetActiveModelID(id string)

SetActiveModelID records the identifier of the model the current label refers to, for updates that carry an identifier but no model description.

func SetAgent

func SetAgent(agentName string)

SetAgent updates the agent for the session, either via daemon API or in draft config.

func SetClient

func SetClient(c *client.Client)

SetClient sets the active daemon client in the session store.

func SetCtrlCPending

func SetCtrlCPending(pending bool)

SetCtrlCPending updates the Ctrl+C exit confirmation state.

func SetDaemonStatus

func SetDaemonStatus(status DaemonStatus)

SetDaemonStatus updates the daemon connection status in AppState.

func SetDefaultAgent

func SetDefaultAgent(agent string)

SetDefaultAgent records the workspace's default agent name in AppState. It is the agent used for tool status classification when the session has none.

func SetHeaderMeta

func SetHeaderMeta(version, workspace string)

SetHeaderMeta updates the version and workspace metadata in AppState.

func SetHint

func SetHint(hint string)

SetHint updates the status line hint.

func SetMode

func SetMode(mode api.PermissionMode)

SetMode updates the active permission mode immediately and debounces syncing to the daemon.

func SetModeAndSend

func SetModeAndSend(mode api.PermissionMode, text string, attachments ...api.Attachment)

SetModeAndSend switches the session permission mode synchronously (canceling any pending mode debounce) and immediately submits text as a turn in that mode.

func SetModel

func SetModel(modelID string)

SetModel updates the model for the session, either via daemon API or in draft config.

func SetModelInfo

func SetModelInfo(label, thinking string)

SetModelInfo sets the display model label and reasoning effort.

func SetOnboardingCredentials

func SetOnboardingCredentials(apiKey, endpoint, authType, authEnv string)

SetOnboardingCredentials updates the API key / endpoint for the draft.

func SetOnboardingMode

func SetOnboardingMode(mode api.PermissionMode)

SetOnboardingMode updates the default permission mode.

func SetOnboardingOAuth

func SetOnboardingOAuth(status, authURL, account, errMsg string)

SetOnboardingOAuth updates interactive OAuth progress in the store.

func SetOnboardingProvider

func SetOnboardingProvider(provider string)

SetOnboardingProvider selects a provider for the draft.

func SetOnboardingScope

func SetOnboardingScope(scope string)

SetOnboardingScope updates the draft provider scope ("user", "workspace", "project").

func SetProviderAuthLauncher

func SetProviderAuthLauncher(fn func(provider string))

SetProviderAuthLauncher registers the callback invoked when the inline re-authentication prompt starts a provider sign-in flow.

func SetQuota

func SetQuota(quota api.ModelQuota)

SetQuota records a quota reading for the active session's model. A reading for a different model is ignored, since showing another model's window would be a false fact.

func SetSession

func SetSession(sess *api.Session)

SetSession updates the session and its configuration. If sess is non-nil, Mode defaults to api.ModeDefault if empty.

func SetSessionAgent

func SetSessionAgent(agent string)

SetSessionAgent updates the active agent name in SessionState.

func SetSessionMode

func SetSessionMode(mode api.PermissionMode)

SetSessionMode updates the permission mode in SessionState without syncing to the daemon.

func SetSessionModelInfo

func SetSessionModelInfo(model *api.Model, setting *api.ThinkingSetting)

SetSessionModelInfo records a resolved model: its identifier, display label, and reasoning effort. The identifier is what lets `/model` highlight the active row even when no model was selected explicitly.

func SetSubagentOpener

func SetSubagentOpener(fn func(string))

SetSubagentOpener registers a callback that opens a subagent's live view.

func SetThinking

func SetThinking(setting api.ThinkingSetting, command, description string)

func SetUsage

func SetUsage(usage api.SessionUsage)

SetUsage stores usage as the active session's usage when it belongs to that session.

func SetWorkspaceAgents

func SetWorkspaceAgents(agents []api.Agent)

SetWorkspaceAgents updates the workspace agents in AppState.

func SetWorkspaceCommands

func SetWorkspaceCommands(commands []api.Command)

SetWorkspaceCommands updates the workspace commands in AppState.

func SetWorkspaceMCPServers

func SetWorkspaceMCPServers(servers []api.MCPServer)

SetWorkspaceMCPServers replaces the cached listing used by the warnings view and MCP tools.

func SetWorkspaceRules

func SetWorkspaceRules(rules []api.Rule)

SetWorkspaceRules updates the workspace rules in AppState.

func SetWorkspaceSkills

func SetWorkspaceSkills(skills []api.Skill)

SetWorkspaceSkills updates the workspace skills in AppState.

func SetWorkspaceTools

func SetWorkspaceTools(tools []api.Tool, agent string)

SetWorkspaceTools updates the workspace tools in AppState along with the name of the agent the tool statuses were classified for.

func SetWorkspaceWarnings

func SetWorkspaceWarnings(warnings []string, sandboxWarnings ...string)

SetWorkspaceWarnings updates the warning view and the sandbox-only header warnings.

func SocketPath

func SocketPath() string

SocketPath returns the Unix domain socket path of the active client, if any.

func StageClipboardMedia

func StageClipboardMedia(ref string, data []byte, mimeType, displayName string) api.Attachment

StageClipboardMedia buffers pasted media bytes in memory until the turn is submitted (avoiding orphaned session creation or disk writes on canceled drafts) and returns the corresponding Attachment descriptor.

func StartDaemon

func StartDaemon(ctx context.Context) (*api.HealthResponse, error)

StartDaemon ensures the background Brain Daemon is running.

func StartOnboarding

func StartOnboarding(wsPath string, status api.WorkspaceStatus, isSetupCmd bool)

StartOnboarding initializes the wizard with the workspace status.

func StopDaemon

func StopDaemon(ctx context.Context) error

StopDaemon gracefully stops the running Brain Daemon.

func StreamTaskOutput

func StreamTaskOutput(ctx context.Context, taskID string) iter.Seq2[string, error]

StreamTaskOutput streams live output chunks for a background task.

func SubmitPlanReview

func SubmitPlanReview(req api.PlanReviewRequest, decision api.PlanReviewDecision, done func(error))

SubmitPlanReview submits a user approval or keep-planning decision for a pending plan review.

func SubmitQuestion

func SubmitQuestion(req api.QuestionRequest, response api.QuestionResponse, done func(error))

func SubmitSubagentQuestion

func SubmitSubagentQuestion(subagentID string, req api.QuestionRequest, resp api.QuestionResponse, done func(error))

SubmitSubagentQuestion submits a user answer to a pending question for a child subagent.

func SwitchSession

func SwitchSession(sessionID string)

SwitchSession loads an existing session and switches to it asynchronously.

func ToggleOnboardingMCP

func ToggleOnboardingMCP(mcp string)

ToggleOnboardingMCP toggles a global MCP server between enabled and disabled.

func ToggleOnboardingTool

func ToggleOnboardingTool(tool string)

ToggleOnboardingTool toggles a tool between enabled and disabled.

func UpsertSubagent

func UpsertSubagent(sub api.Session)

UpsertSubagent updates an existing child subagent in SessionState by ID, or appends it.

func UpsertTask

func UpsertTask(task api.Task)

UpsertTask updates an existing task in SessionState by ID, or appends it.

func UseApp

func UseApp[U comparable](selector func(AppState) U) U

UseApp subscribes a component to a comparable slice of AppState.

func UseContext

func UseContext() api.ContextState

UseContext subscribes a component to the active session's ContextState.

func UseHasActiveSlot

func UseHasActiveSlot() bool

UseHasActiveSlot reports whether there is currently an active slot.

func UseHideComposer

func UseHideComposer() bool

UseHideComposer reports whether the currently active slot component hides the composer.

func UseHint

func UseHint(hint string)

UseHint sets the status line hint while the calling component is mounted and restores the previous hint when the component unmounts.

func UseIsStreaming

func UseIsStreaming() bool

UseIsStreaming reports whether an LLM turn is currently streaming.

func UseMode

func UseMode() api.PermissionMode

UseMode returns the active permission mode, defaulting to api.ModeDefault if unset.

func UseOnboarding

func UseOnboarding[U comparable](selector func(OnboardingState) U) U

UseOnboarding subscribes a component to a comparable slice of OnboardingState.

func UseRunningDelegatedSubagents

func UseRunningDelegatedSubagents() []api.Session

UseRunningDelegatedSubagents subscribes a component to running delegated slash-command subagents (excluding autonomous invoke_agent background workers).

func UseRunningSubagents

func UseRunningSubagents() []api.Session

UseRunningSubagents subscribes a component to the active session's running subagents.

func UseRunningTasks

func UseRunningTasks() []api.Task

UseRunningTasks subscribes a component to the active session's running and pending tasks.

func UseSession

func UseSession[U comparable](selector func(SessionState) U) U

UseSession subscribes a component to a comparable slice of SessionState.

func UseSlot

func UseSlot[U comparable](selector func(SlotState) U) U

UseSlot subscribes a component to a comparable slice of SlotState.

func UseStream

func UseStream[U comparable](selector func(StreamState) U) U

UseStream subscribes a component to a comparable slice of StreamState.

func UseSubagents

func UseSubagents() []api.Session

UseSubagents subscribes a component to the active session's child subagents.

func UseTasks

func UseTasks() []api.Task

UseTasks subscribes a component to the active session's tasks.

func UseTranscript

func UseTranscript[U comparable](selector func(TranscriptState) U) U

UseTranscript subscribes a component to a comparable slice of TranscriptState.

func UseWaitingSubagents

func UseWaitingSubagents() []api.Session

UseWaitingSubagents subscribes a component to the active session's subagents waiting for permission or a question.

Types

type AppState

type AppState struct {
	CtrlCPending  bool
	ExitRequested bool
	Hint          string
	Version       string
	Workspace     string
	Branch        string
	Warnings      *[]string
	Agents        *[]api.Agent
	Commands      *[]api.Command
	Skills        *[]api.Skill
	Rules         *[]api.Rule
	Tools         *[]api.Tool
	// MCPServers holds the last retrieved MCP server listing, including live
	// connection status and everything discovered on each server.
	MCPServers *[]api.MCPServer
	// ToolsAgent is the agent the cached Tools statuses were classified for.
	ToolsAgent string
	// ToolsFetched records that a tool listing has been retrieved at least once,
	// so an empty toolset is distinguishable from "never fetched" and does not
	// re-trigger a fetch on every render.
	ToolsFetched    bool
	DefaultAgent    string
	DaemonStatus    DaemonStatus
	SandboxWarnings *[]string
}

AppState holds global application UI state for the REPL.

func GetApp

func GetApp() AppState

GetApp returns the current AppState snapshot.

type CommandData

type CommandData struct {
	Command string
	Output  string
}

CommandData holds the output of a local slash command.

type ContextUsageData

type ContextUsageData struct {
	ModelName string
	Context   api.ContextState
}

ContextUsageData holds the data for the /context usage view.

type DaemonStatus

type DaemonStatus string

DaemonStatus represents the connection health state between the REPL and Brain Daemon.

const (
	DaemonConnected    DaemonStatus = "connected"
	DaemonDisconnected DaemonStatus = "disconnected"
	DaemonRestarting   DaemonStatus = "restarting"
)

func UseDaemonStatus

func UseDaemonStatus() DaemonStatus

UseDaemonStatus subscribes a component to AppState.DaemonStatus.

type ErrorData

type ErrorData struct {
	Title   string
	Message string
}

ErrorData holds a local or turn error message.

type HeaderData

type HeaderData struct {
	Version     string
	Model       string
	Thinking    string
	Workspace   string
	Branch      string
	SandboxMode api.SandboxMode
	Warnings    []string
}

HeaderData holds the data for the startup banner.

func CurrentHeaderData

func CurrentHeaderData() HeaderData

CurrentHeaderData returns a snapshot of HeaderData combining AppState metadata with the active session's ModelLabel and Thinking effort.

func UseHeaderData

func UseHeaderData() HeaderData

UseHeaderData returns reactive HeaderData subscribed to changes in AppState metadata, ModelLabel, Thinking effort, and the session's sandbox backend.

type InitSessionOptions

type InitSessionOptions struct {
	SessionID string
	Agent     string
	Model     string
	Title     string

	// Sandbox is the requested sandbox isolation backend ("native" or
	// "local") for sessions this REPL creates; empty lets the daemon
	// resolve the host default.
	Sandbox     api.SandboxMode
	StartDaemon func(ctx context.Context, socketPath string) error
}

InitSessionOptions specifies options for initializing or connecting to a session.

type MediaPart

type MediaPart struct {
	BlockType api.BlockType
	Media     api.Media
}

type Message

type Message struct {
	ID          string
	SourceID    string
	Role        api.Role
	Parts       []MessagePart
	CreatedAt   time.Time
	Streaming   bool
	Attachments []api.Attachment
}

Message preserves the order of its parts. ID is a stable view identity; SourceID is the persisted message ID.

type MessagePart

type MessagePart struct {
	ID      string
	Type    MessagePartType
	Thought *ThoughtPart
	Text    *TextPart
	Tool    *ToolPart
	Media   *MediaPart
}

MessagePart is a tagged union. Only the field identified by Type is set.

type MessagePartType

type MessagePartType string
const (
	PartThought MessagePartType = "thought"
	PartText    MessagePartType = "text"
	PartTool    MessagePartType = "tool"
	PartMedia   MessagePartType = "media"
)

type ModelLabels

type ModelLabels struct {
	Full, Compact string
}

type ModelSwitchRequest

type ModelSwitchRequest struct {
	Model             string
	MissingModalities []string
}

ModelSwitchRequest describes a pending confirmation prompt when switching models would drop active-session modalities.

type NoticeData

type NoticeData struct {
	Text     string
	Severity NoticeSeverity
}

NoticeData holds a local informational notice.

type NoticeSeverity

type NoticeSeverity string
const NoticeSeverityWarning NoticeSeverity = "warning"

type OnboardingState

type OnboardingState struct {
	Revision         int
	Active           bool
	IsSetupCmd       bool
	Step             OnboardingStep
	History          []OnboardingStep
	Workspace        string
	Status           api.WorkspaceStatus
	Scope            string // "user", "workspace", "project"
	SelectedProvider string
	APIKey           string
	Endpoint         string
	AuthType         string
	AuthEnv          string
	DefaultMode      api.PermissionMode
	DisabledTools    map[string]bool
	DisabledMCPs     map[string]bool
	Verifying        bool
	VerifyError      string
	OAuthAuthURL     string
	OAuthStatus      string // "idle", "authorizing", "authenticated", "error"
	OAuthAccount     string
	OAuthError       string
	OfferInit        bool
	Completed        bool
}

OnboardingState encapsulates the mutable draft state of the onboarding wizard.

func GetOnboarding

func GetOnboarding() OnboardingState

GetOnboarding returns a snapshot of the current OnboardingState.

func (OnboardingState) IsProviderConfigured

func (s OnboardingState) IsProviderConfigured(providerName string) bool

IsProviderConfigured reports whether p has a detected key or is local ollama.

func (OnboardingState) ProviderSummary

func (s OnboardingState) ProviderSummary(providerName string) *api.ProviderSummary

ProviderSummary returns the summary for a provider, if known.

type OnboardingStep

type OnboardingStep string

OnboardingStep identifies the active screen in the onboarding or /setup wizard.

const (
	StepNone         OnboardingStep = ""
	StepTrust        OnboardingStep = "trust"
	StepProviderSrc  OnboardingStep = "provider_src"
	StepProviderPick OnboardingStep = "provider_pick"
	StepCredentials  OnboardingStep = "credentials"
	StepMode         OnboardingStep = "mode"
	StepTools        OnboardingStep = "tools"
	StepReview       OnboardingStep = "review"
	StepDone         OnboardingStep = "done"
)

type ProviderReauthRequest

type ProviderReauthRequest struct {
	Provider string
	Message  string
}

ProviderReauthRequest describes a pending inline re-authentication prompt shown when a turn fails because an OAuth provider session expired.

type QuotaState

type QuotaState struct {
	Known    bool
	BucketID string
	// RemainingPct is whole percent of the window still available (0-100).
	RemainingPct int
	Unlimited    bool
	// ResetAt is when the window refills; zero when the provider did not say.
	ResetAt time.Time
	// Account is the authenticated identity behind the window, when known.
	Account string
}

QuotaState is the comparable snapshot of the active model's bottleneck quota bucket shown in the status line.

func UseQuota

func UseQuota() QuotaState

UseQuota subscribes a component to the active model's bottleneck quota reading.

type SessionState

type SessionState struct {
	Session    *api.Session
	Config     api.SessionConfig
	Context    api.ContextState
	Usage      api.SessionUsage
	ModelLabel string
	// ModelID is the identifier of the model ModelLabel was derived from. A
	// session with no explicit model selection still resolves to one (agent or
	// workspace default), so this is what identifies the active model when
	// Config.Model is empty or an alias.
	ModelID   string
	Model     *api.Model
	Thinking  string
	Tasks     *[]api.Task
	Subagents *[]api.Session
	Ready     bool

	// ModelQuotaBilled reports the active model is billed against a
	// subscription window rather than per token, so usage readouts show
	// remaining capacity instead of a dollar figure.
	ModelQuotaBilled bool
	// Quota is the most recent quota reading for the active model, pushed by
	// the daemon after each turn and on rate limits. nil until first known.
	Quota *api.ModelQuota

	// SandboxMode is the sandbox isolation backend the active or draft session
	// runs under ("native" or "local").
	SandboxMode api.SandboxMode
}

SessionState holds the active session and its configuration, permission mode, display model label, background tasks, and context window state.

func GetSession

func GetSession() SessionState

GetSession returns the current SessionState snapshot.

func (SessionState) ActiveModelID

func (s SessionState) ActiveModelID() string

ActiveModelID reports which model the session actually runs on. A draft session selects none explicitly — the daemon resolves it to the agent or workspace default — and an explicit selection may be an alias, so the resolved identifier takes precedence over the raw configuration values.

func (SessionState) ModelLabels

func (s SessionState) ModelLabels() ModelLabels

type SlotItem

type SlotItem struct {
	ID   string
	Kind SlotKind
	Data any
}

SlotItem is a pure data descriptor enqueued into the Slot.

func UseActiveSlot

func UseActiveSlot() *SlotItem

UseActiveSlot returns the currently active SlotItem, or nil if none.

type SlotKind

type SlotKind string

SlotKind identifies the kind of UI component rendered in the Slot.

const (
	SlotKindPermission     SlotKind = "permission"
	SlotKindQuestion       SlotKind = "question"
	SlotKindPlanReview     SlotKind = "plan_review"
	SlotKindPicker         SlotKind = "picker"
	SlotKindAutocomplete   SlotKind = "autocomplete"
	SlotKindModelSwitch    SlotKind = "model_switch"
	SlotKindProviderReauth SlotKind = "provider_reauth"
)

func (SlotKind) HidesComposer

func (k SlotKind) HidesComposer() bool

HidesComposer reports whether this slot kind should hide the Composer while active.

type SlotState

type SlotState struct {
	Active *SlotItem
	Queue  *[]SlotItem
}

SlotState holds the FIFO queue of SlotItems and the currently active front item.

func GetSlot

func GetSlot() SlotState

GetSlot returns the current SlotState snapshot.

type StatusLineConfig

type StatusLineConfig struct {
	Rows    [][]StatusLineSegmentID `json:"rows"`
	Compact bool                    `json:"compact"`
}

func GetStatusLine

func GetStatusLine() StatusLineConfig

func UseStatusLine

func UseStatusLine() StatusLineConfig

func ValidateStatusLineConfig

func ValidateStatusLineConfig(cfg StatusLineConfig) (StatusLineConfig, []string)

type StatusLineSegmentID

type StatusLineSegmentID string
const (
	StatusLineHint     StatusLineSegmentID = "hint"
	StatusLineMode     StatusLineSegmentID = "mode"
	StatusLineModel    StatusLineSegmentID = "model"
	StatusLineEffort   StatusLineSegmentID = "effort"
	StatusLineWarnings StatusLineSegmentID = "warnings"
	StatusLineContext  StatusLineSegmentID = "context"
	StatusLineCost     StatusLineSegmentID = "cost"
	StatusLineTokens   StatusLineSegmentID = "tokens"
)

type StreamState

type StreamState struct {
	Messages          *[]Message
	Streaming         bool
	WaitingPermission bool
	WaitingQuestion   bool
	WaitingPlanReview bool
	Status            api.SessionStatus
	PendingCommand    string
	Queue             *[]api.QueueItem
	Todos             *[]api.TodoItem

	// Delegated reports that this session is waiting on child subagents rather
	// than running a turn of its own, so the work shown as in flight belongs to
	// a subagent. It only applies while Streaming is true.
	Delegated bool

	// TurnFailed reports that the turn that just ended ended in failure. The
	// stream settles back to idle immediately, so without this flag a failed
	// turn and a finished one are indistinguishable after the fact, and the
	// terminal status indicators could not show the failure at all.
	TurnFailed bool

	// TurnStartedAt is when the current turn started streaming. BaseInput and
	// BaseOutput are the session's token totals at that moment, and CallInput
	// and CallOutput are the running totals of the LLM call in flight, so the
	// turn's tokens so far are (session totals - base) + call.
	TurnStartedAt time.Time
	BaseInput     int64
	BaseOutput    int64
	CallInput     int64
	CallOutput    int64
}

StreamState holds the active stream of in-flight messages and execution status.

func GetStream

func GetStream() StreamState

GetStream returns the current StreamState snapshot.

type StreamStatus

type StreamStatus string
const (
	StreamIdle              StreamStatus = "idle"
	StreamRunning           StreamStatus = "running"
	StreamWaitingPermission StreamStatus = "waiting_permission"
	StreamWaitingQuestion   StreamStatus = "waiting_question"
	StreamWaitingPlanReview StreamStatus = "waiting_plan_review"
	StreamCompleted         StreamStatus = "completed"
	StreamFailed            StreamStatus = "failed"
)

type SubagentConversation

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

SubagentConversation maintains an isolated conversation stream for a subagent session.

func NewSubagentConversation

func NewSubagentConversation(sessionID string) *SubagentConversation

NewSubagentConversation creates an isolated accumulator for tracking a subagent session's live timeline and events.

func (*SubagentConversation) ApplyEvent

func (s *SubagentConversation) ApplyEvent(event api.Event)

ApplyEvent processes a live SSE event for this subagent session.

func (*SubagentConversation) IsStreaming

func (s *SubagentConversation) IsStreaming() bool

IsStreaming reports whether an LLM turn is currently streaming.

func (*SubagentConversation) LoadTimeline

func (s *SubagentConversation) LoadTimeline(entries []api.TimelineEntry, pending ...[]api.QuestionRequest)

LoadTimeline initializes or updates the conversation history from timeline entries.

func (*SubagentConversation) LoadTimelineSnapshot

func (s *SubagentConversation) LoadTimelineSnapshot(sess *api.Session, entries []api.TimelineEntry, pendingQuestions []api.QuestionRequest)

LoadTimelineSnapshot hydrates the subagent conversation from its session snapshot and persisted timeline.

func (*SubagentConversation) Messages

func (s *SubagentConversation) Messages() []Message

Messages returns all projected messages (finalized history + live stream) in chronological order.

func (*SubagentConversation) PendingPermissions

func (s *SubagentConversation) PendingPermissions() []api.PermissionRequest

PendingPermissions returns the pending permission requests for this subagent.

func (*SubagentConversation) PendingQuestions

func (s *SubagentConversation) PendingQuestions() []api.QuestionRequest

PendingQuestions returns the pending questions for this subagent.

func (*SubagentConversation) ReconcileStreamStatus

func (s *SubagentConversation) ReconcileStreamStatus(sess *api.Session)

ReconcileStreamStatus aligns the subagent stream state with its session snapshot.

func (*SubagentConversation) RemovePermission

func (s *SubagentConversation) RemovePermission(reqID string)

RemovePermission removes a resolved permission request by ID from the subagent conversation.

func (*SubagentConversation) RemoveQuestion

func (s *SubagentConversation) RemoveQuestion(reqID string)

RemoveQuestion removes a resolved question request by ID from the subagent conversation.

func (*SubagentConversation) SeedPermissions

func (s *SubagentConversation) SeedPermissions(requests []api.PermissionRequest)

SeedPermissions imports pending permission requests into the subagent conversation.

func (*SubagentConversation) SessionStatus

func (s *SubagentConversation) SessionStatus() api.SessionStatus

SessionStatus returns the current execution status of the subagent.

func (*SubagentConversation) Todos

func (s *SubagentConversation) Todos() []api.TodoItem

Todos returns a snapshot of active checklist items for the subagent.

func (*SubagentConversation) TurnStats

func (s *SubagentConversation) TurnStats() (startedAt time.Time, input int64, output int64)

TurnStats returns the start time, input tokens, and output tokens for the current turn.

type TextPart

type TextPart struct {
	Text string
}

type ThoughtPart

type ThoughtPart struct {
	Text      string
	Signature string
	Streaming bool
}

type ToolPart

type ToolPart struct {
	ID               string
	Call             *api.ToolCall
	Response         *api.Message
	Status           ToolStatus
	Permissions      []api.PermissionRequest
	Question         *api.QuestionRecord
	PermissionReview *api.PermissionReview
}

ToolPart joins a tool call and its response by ID.

type ToolStatus

type ToolStatus string
const (
	ToolReceiving         ToolStatus = "receiving"
	ToolPending           ToolStatus = "pending"
	ToolRunning           ToolStatus = "running"
	ToolWaitingPermission ToolStatus = "waiting_permission"
	ToolSucceeded         ToolStatus = "succeeded"
	ToolFailed            ToolStatus = "failed"
	ToolInterrupted       ToolStatus = "interrupted"
)

type TranscriptItem

type TranscriptItem struct {
	ID   string
	Kind TranscriptKind
	Data any
}

TranscriptItem represents a single finalized item in the transcript scrollback.

type TranscriptKind

type TranscriptKind string

TranscriptKind identifies the kind of item in the transcript scrollback.

const (
	TranscriptKindHeader       TranscriptKind = "header"
	TranscriptKindTimeline     TranscriptKind = "timeline"
	TranscriptKindNotice       TranscriptKind = "notice"
	TranscriptKindError        TranscriptKind = "error"
	TranscriptKindCommand      TranscriptKind = "command"
	TranscriptKindMessage      TranscriptKind = "message"
	TranscriptKindContextUsage TranscriptKind = "context_usage"
)

type TranscriptState

type TranscriptState struct {
	Epoch  int
	Frozen bool
	Items  *[]TranscriptItem
}

TranscriptState holds the current transcript epoch, frozen status, and finalized items.

func GetTranscript

func GetTranscript() TranscriptState

GetTranscript returns the current TranscriptState snapshot.

type UsageTotals

type UsageTotals struct {
	Calls         int64
	UnpricedCalls int64
	QuotaCalls    int64
	CostNano      int64
	InputTokens   int64
	OutputTokens  int64
}

UsageTotals is the comparable subset of session usage shown in the status line.

func UseUsageTotals

func UseUsageTotals() UsageTotals

UseUsageTotals subscribes a component to the active session's usage totals.

type Warning

type Warning struct {
	Source  string
	Message string
}

func UseWarnings

func UseWarnings() []Warning

Jump to

Keyboard shortcuts

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