cli

package
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: MIT Imports: 18 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 cli is the contract and shared-type layer for golder's command-line surface. It holds the interfaces and value types that the cmd/golder entry point and the internal/cli/* subpackages share, without depending on any of them, so those subpackages can be assembled and tested in isolation.

Subpackage layout (assembled incrementally by the CLI restructure):

internal/cli            — Host/Editor contracts, LiveConfig, TelemetryHolder
internal/cli/ui         — color, markdown, imageref helpers
internal/cli/config     — config-file loading and overrides
internal/cli/run        — run assembly and tool wiring
internal/cli/headless   — headless session and subagent RPC drivers
internal/cli/goal       — /goal state machine
internal/cli/btw        — /btw side thread
internal/cli/status     — /status command
internal/cli/repl       — interactive REPL and line editor
internal/cli/testutil   — cross-subpackage test helpers

The Host interface (see host.go) is the seam that lets the /goal, /btw, /status and REPL subpackages read and mutate the session's live state without importing the concrete replDeps aggregate that assembles it.

This file defines the Host and Editor contracts that let the /goal, /btw, /status and REPL subpackages read and mutate a session's live state without importing the concrete replDeps aggregate that assembles it (see doc.go). The aggregate implements Host by exposing accessor and mutator methods over its fields; the line editor implements Editor.

This file defines LiveConfig, the mutable run configuration a control command may change mid-session. It was moved verbatim from cmd/golder (the former liveRunConfig) and exported so the run, repl, btw, status and goal subpackages can read and mutate it through the Host contract. The run closure reads it on every prompt, so a /model switch takes effect on the next turn. It carries no lock: it is read and written only on the REPL's single main goroutine (slash actions and the run are both invoked synchronously from the REPL loop, never concurrently).

This file holds PersistTurn, the session-tree persistence step shared by the REPL loop and the /goal autonomous loop. It reads and advances a session's mutable cursor state through the Host contract, so a command need not import the concrete replDeps aggregate to persist the tail of a turn.

This file holds ProviderHelp, the "--help" provider block moved from cmd/golder (US-004, #361). It enumerates the built-in provider registry so the values accepted by --provider (and their env vars / default base URLs / protocols) stay in sync with the code rather than being hand-maintained.

This file implements the telemetry holder that retains per-run telemetry events (US-001, #291) and folds them into a cumulative accumulator for the /status command to display. It was moved verbatim from cmd/golder (telemetry_state.go, US-013) into the shared cli layer so the status and repl subpackages share one holder type.

Index

Constants

View Source
const DefaultContextWindow = 1000000

DefaultContextWindow is the fallback context-token budget used when a model's true window is unknown. It is deliberately large so auto-compaction only fires on genuinely long sessions (threshold = window - ReserveTokens), never on ordinary short exchanges.

Variables

View Source
var ErrLineInterrupted = errors.New("line input interrupted")

ErrLineInterrupted is returned by an Editor.ReadLine when the user hits an idle Ctrl+C at the prompt (rather than during a run). Control commands that run their own follow-up loop (e.g. /btw) check for it with errors.Is to leave the loop cleanly. It lives here, beside the Editor contract, so a subpackage can recognize the interrupt without importing the concrete line editor.

Functions

func PersistTurn

func PersistTurn(out io.Writer, h Host)

PersistTurn appends the messages produced since the last persist as a new branch descending from the host's current leaf, advancing the leaf and the persisted-message cursor. Growing the tree with AppendBranch (rather than a full linear Save) is what lets a later /tree leaf-switch fork the on-disk history instead of clobbering it. If nothing new was produced it is a no-op: rewriting the file would regenerate entry ids and flatten the tree.

func PrintProviderHelp

func PrintProviderHelp(w io.Writer)

PrintProviderHelp writes the "Supported providers" block appended to `--help` output. It enumerates the built-in provider registry so the list of values accepted by --provider (and their env vars / default base URLs / protocols) stays in sync with the code rather than being hand-maintained.

func RecentSessions

func RecentSessions(store *session.Store, n int) ([]session.SessionHeader, error)

RecentSessions returns up to n most-recently-updated session headers (the store already sorts newest-first). It backs the bare-/resume picker in every frontend so the list is identical everywhere.

func ResolveResumeID

func ResolveResumeID(store *session.Store, arg string) (string, error)

ResolveResumeID maps a /resume argument to a session id: a 1-based number selects the nth recent session, anything else is treated as a literal id (existence is validated by the loader). An empty argument is a usage error; callers show the recent list instead.

func SessionPreview

func SessionPreview(store *session.Store, id string) string

SessionPreview returns the first user message's excerpt for a session, falling back to the first assistant text. It is single-line and capped at previewRunes runes so CJK titles survive; "" when the session has no text.

Types

type Editor

type Editor interface {
	ReadLine(prompt string) (string, error)
}

Editor is the line-input contract a control command uses to read a follow-up line from the user (e.g. the /btw follow-up loop). It is satisfied by the REPL's line editor.

type Host

type Host interface {
	// Session collaborators.
	Store() *session.Store
	Header() session.SessionHeader
	AgentCtx() *agentcore.AgentContext
	Live() *LiveConfig
	Registry() *agenttool.ToolRegistry
	Reminders() *runtime.ReminderRegistry
	Slash() *runtime.SlashRegistry
	Creds() *provider.CredentialStore
	Notifier() *plugin.EventNotifier
	// NotifierHandle returns the plugin event-delivery callback for this
	// session's runs, or nil when no plugin subscribed.
	NotifierHandle() func(agentcore.AgentEvent)
	Trust() *trust.Manager
	// Permissions returns the live approval mode shared by the session's gates
	// and tools. /goal and /btw build their own runs and need it to enforce the
	// same mode as the main conversation.
	Permissions() *permissions.State
	// ReviewNotes returns the announcement sink for permission decisions, so a
	// side run's gate publishes decisions to the same transcript surface as the
	// main run.
	ReviewNotes() *run.ReviewNotes
	Goal() *agenttool.GoalState
	Telemetry() *TelemetryHolder

	// Dispatcher returns the session's hook dispatcher, or nil when no hooks are
	// configured (FR-18). Side-runs (/goal, /btw) install the per-turn seams onto
	// their own cfg via run.InstallSeams(cfg, host.Dispatcher(), host.HookDeps()).
	Dispatcher() *hooks.Dispatcher
	// HookDeps carries the session id / project dir stamped onto every HookInput.
	HookDeps() run.HookDeps

	// Cwd is the directory golder was launched in; it does not change during a
	// session and gates side-effect tools.
	Cwd() string
	// Input is the shared buffered stdin reader used by both the main loop and
	// the tool-call confirmation prompt.
	Input() *bufio.Reader
	// ConfirmMu serializes tool-call confirmation prompts across concurrent
	// side-effect tool calls.
	ConfirmMu() *sync.Mutex

	// Session-tree cursor and persistence bookkeeping.
	CurLeaf() string
	SetCurLeaf(id string)
	Persisted() int
	SetPersisted(n int)

	// Last /btw side thread from this process and its background base index.
	LastBtw() *agentcore.AgentContext
	SetLastBtw(ctx *agentcore.AgentContext)
	LastBtwBase() int
	SetLastBtwBase(n int)
}

Host is the seam through which a control command (/goal, /btw, /status) and the REPL loop access the collaborators and mutable state of a session. It is satisfied by the replDeps aggregate assembled once per session.

Getters return the shared collaborators (never copies, except where noted). The setters cover the fields a command may advance mid-session: the active session leaf, the persisted-message count, and the last /btw side thread.

type LiveConfig

type LiveConfig struct {
	Model        string
	ProviderName string
	Provider     provider.Provider
	BaseURL      string
	Protocol     string
	// ThinkingLevel is the reasoning-effort level applied to each turn. It is
	// seeded from the resolved config chain and read on every prompt.
	ThinkingLevel agentcore.ThinkingLevel
	// ContextWindow is the model's total context-token budget, used to gate
	// automatic compaction. When 0 the window is unknown and auto-compaction is
	// disabled; the REPL seeds it with a conservative default so long sessions
	// still compact rather than overflow.
	ContextWindow int

	// FetchedModels is the online model catalog pulled from the live provider's
	// endpoint by the bare-/model list (issue #566), sorted and
	// deduplicated. /model prefers it over the heuristic chain for ids it
	// contains (so a fetched id stays on the gateway that serves it) and reuses
	// it for numeric picks. The list is also persisted to a shared 24h disk
	// cache, so the network is consulted about once a day per provider rather
	// than once per session; this field is the session-lifetime copy, seeded
	// either from that cache or from a fresh fetch.
	FetchedModels []string
	FetchedAt     time.Time
	FetchedKey    string
}

LiveConfig is the mutable run configuration a control command may change mid-session.

type ResumeItem

type ResumeItem struct {
	Header  session.SessionHeader
	Preview string
}

ResumeItem pairs a session header with a human-readable preview.

func RecentSessionsWithPreview

func RecentSessionsWithPreview(store *session.Store, n int) ([]ResumeItem, error)

RecentSessionsWithPreview returns up to n recent sessions with previews, newest first. A session with no text yields an empty Preview.

type TelemetryHolder

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

TelemetryHolder holds the most recent run's telemetry event and a cumulative accumulator that sums metrics across all runs in the session.

func NewTelemetryHolder

func NewTelemetryHolder() *TelemetryHolder

NewTelemetryHolder creates a new, empty TelemetryHolder with no telemetry yet.

func (*TelemetryHolder) CumulativeCompactionCount

func (h *TelemetryHolder) CumulativeCompactionCount() int

CumulativeCompactionCount returns the total number of compactions across all runs.

func (*TelemetryHolder) CumulativeContextUtilization

func (h *TelemetryHolder) CumulativeContextUtilization() float64

CumulativeContextUtilization returns the latest utilization ratio, or 0 if no window is known.

func (*TelemetryHolder) CumulativeToolDurations

func (h *TelemetryHolder) CumulativeToolDurations() map[string]agentcore.ToolTiming

CumulativeToolDurations returns the aggregated tool timings across all runs.

func (*TelemetryHolder) CumulativeTruncationCount

func (h *TelemetryHolder) CumulativeTruncationCount() int

CumulativeTruncationCount returns the total number of truncations across all runs.

func (*TelemetryHolder) CumulativeTurns

func (h *TelemetryHolder) CumulativeTurns() int

CumulativeTurns returns the total number of turns across all runs.

func (*TelemetryHolder) Fold

Fold incorporates a new TelemetryEvent into the holder: it becomes the new "last run" event, and its metrics are added to the cumulative accumulator.

func (*TelemetryHolder) HasTelemetry

func (h *TelemetryHolder) HasTelemetry() bool

HasTelemetry returns true if at least one run has completed and telemetry is available.

func (*TelemetryHolder) Last

Last returns the most recent TelemetryEvent, or nil if no run has completed.

func (*TelemetryHolder) LatestContextTokens

func (h *TelemetryHolder) LatestContextTokens() int

LatestContextTokens returns the most recent observed context token count.

func (*TelemetryHolder) LatestContextWindow

func (h *TelemetryHolder) LatestContextWindow() int

LatestContextWindow returns the most recent observed context window size.

func (*TelemetryHolder) Reset

func (h *TelemetryHolder) Reset()

Reset clears the holder to "no telemetry yet", as if the session had just started. It is called when switching sessions (/fork, /clone, /import).

Directories

Path Synopsis
This file implements the /btw command (mirrors Claude Code's /btw and the pi agent extension @narumitw/pi-btw): a throwaway "side thread" for asking the model a quick side question that must NOT pollute the main conversation.
This file implements the /btw command (mirrors Claude Code's /btw and the pi agent extension @narumitw/pi-btw): a throwaway "side thread" for asking the model a quick side question that must NOT pollute the main conversation.
Package config implements golder's optional user config file at ~/.config/golder/config.toml (honoring $XDG_CONFIG_HOME when set) plus the provider-agnostic base-url env-var name derivation.
Package config implements golder's optional user config file at ~/.config/golder/config.toml (honoring $XDG_CONFIG_HOME when set) plus the provider-agnostic base-url env-var name derivation.
Package dreamcmd holds the CLI-side plumbing shared by the REPL and the TUI for the /dream memory-consolidation command: spawning the process-isolated `golder --dream` child, detecting a live consolidation lock, parsing the dry-run flag, and rendering the returned Report.
Package dreamcmd holds the CLI-side plumbing shared by the REPL and the TUI for the /dream memory-consolidation command: spawning the process-isolated `golder --dream` child, detecting a live consolidation lock, parsing the dry-run flag, and rendering the returned Report.
This file implements the /goal command (mirrors pi-goal / Claude Code's goal mode): given a high-level objective, golder runs the agent autonomously — re-prompting it turn after turn from the loop's follow-up seam — until the model declares the goal done (goal_complete), reports a true impasse (goal_blocked), or a safety guard (max turns / no-progress) or the token budget stops it.
This file implements the /goal command (mirrors pi-goal / Claude Code's goal mode): given a high-level objective, golder runs the agent autonomously — re-prompting it turn after turn from the loop's follow-up seam — until the model declares the goal done (goal_complete), reports a true impasse (goal_blocked), or a safety guard (max turns / no-progress) or the token budget stops it.
This file is the headless run driver: the print / stream-json run path (US-020) extracted from the CLI dispatch seam (#363).
This file is the headless run driver: the print / stream-json run path (US-020) extracted from the CLI dispatch seam (#363).
This file implements the /memory slash command (US-011, FR-20, #484) that prints a colored report describing the persistent memory store and the infinite-context state: entry counts by scope, the current context window and auto-compaction trigger point, current context usage, and checkpoint status.
This file implements the /memory slash command (US-011, FR-20, #484) that prints a colored report describing the persistent memory store and the infinite-context state: entry counts by scope, the current context window and auto-compaction trigger point, current context usage, and checkpoint status.
Package prompts holds the slash-command registry assembly shared by the REPL (internal/cli/repl) and the forthcoming TUI (internal/cli/tui).
Package prompts holds the slash-command registry assembly shared by the REPL (internal/cli/repl) and the forthcoming TUI (internal/cli/tui).
This file implements the manual `/dream` REPL command (SPEC §4.1, US-007): it spawns the process-isolated memory-consolidation subprocess (`golder --dream [--dream-dry-run] -C <projectDir>`) and renders the returned Report as a full-table change report.
This file implements the manual `/dream` REPL command (SPEC §4.1, US-007): it spawns the process-isolated memory-consolidation subprocess (`golder --dream [--dream-dry-run] -C <projectDir>`) and renders the returned Report as a full-table change report.
This file provides the single convergence entry point every driver calls to wire hooks into its run (#425, FR-16).
This file provides the single convergence entry point every driver calls to wire hooks into its run (#425, FR-16).
Package sessioncmd implements the `golder session` subcommand family (issue #570): sharing persisted sessions from the command line, without entering the REPL.
Package sessioncmd implements the `golder session` subcommand family (issue #570): sharing persisted sessions from the command line, without entering the REPL.
This file implements the /status slash command (US-002, #292) that prints a colored multi-section status report with runtime config, context usage, and more.
This file implements the /status slash command (US-002, #292) that prints a colored multi-section status report with runtime config, context usage, and more.
Package testutil holds test helpers shared across the internal/cli subpackages.
Package testutil holds test helpers shared across the internal/cli subpackages.
Package tui hosts the full-screen terminal UI for golder's interactive mode (US-001).
Package tui hosts the full-screen terminal UI for golder's interactive mode (US-001).
Package ui holds the leaf terminal-UI helpers shared across the cmd/golder and internal/cli subpackages: ANSI color gating (color.go), turn-end Markdown rendering (markdown.go), and prompt image-reference parsing (imageref.go).
Package ui holds the leaf terminal-UI helpers shared across the cmd/golder and internal/cli subpackages: ANSI color gating (color.go), turn-end Markdown rendering (markdown.go), and prompt image-reference parsing (imageref.go).

Jump to

Keyboard shortcuts

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