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.
This file implements the `!command` shell passthrough shared by the TUI and the REPL. A passthrough command runs locally — no model call, no approval, no sandbox; it is the user's explicit full-access escape hatch, mirroring codex's user shell command. Its output streams back to the caller, and once it settles the command plus its exit result is recorded in the conversation as a user-role <user_shell_command> message, so the model sees exactly what the user ran and what came back.
Index ¶
- Constants
- Variables
- func AddWritablePath(raw string) (path string, alreadySeeded bool, err error)
- func DisplayHomePath(p string) string
- func PersistTurn(out io.Writer, h Host)
- func PrintProviderHelp(w io.Writer)
- func RecentSessions(store *session.Store, n int) ([]session.SessionHeader, error)
- func ResolveContextWindow(providerName, model string) int
- func ResolveResumeID(store *session.Store, arg string) (string, error)
- func SessionPreview(store *session.Store, id string) string
- func UserShellDisplayOutput(output string) string
- func UserShellMessage(command string, exitCode int, d time.Duration, output string) agentcore.UserMessage
- func UserShellRecord(command string, exitCode int, d time.Duration, output string) string
- type Editor
- type Host
- type LiveConfig
- type ResumeItem
- type TelemetryHolder
- func (h *TelemetryHolder) CumulativeCompactionCount() int
- func (h *TelemetryHolder) CumulativeContextUtilization() float64
- func (h *TelemetryHolder) CumulativeToolDurations() map[string]agentcore.ToolTiming
- func (h *TelemetryHolder) CumulativeTruncationCount() int
- func (h *TelemetryHolder) CumulativeTurns() int
- func (h *TelemetryHolder) Fold(ev agentcore.TelemetryEvent)
- func (h *TelemetryHolder) HasTelemetry() bool
- func (h *TelemetryHolder) Last() *agentcore.TelemetryEvent
- func (h *TelemetryHolder) LatestContextTokens() int
- func (h *TelemetryHolder) LatestContextWindow() int
- func (h *TelemetryHolder) Reset()
- type UserShellOutcome
- type UserShellRecordData
- type UserShellRun
- type WritablePathEntry
- type WritableRemoval
Constants ¶
const ( WritableSourceConfig = "config.toml" // the [permissions] seed WritableSourceSaved = "permissions.toml" // the managed store WritableSourceSession = "session" // granted from an approval dialog )
Where a writable path comes from; displayed next to the path.
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 ¶
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 AddWritablePath ¶ added in v1.2.3
AddWritablePath grants a path for this session and persists it to the managed store, so it survives restarts. A path config.toml already seeds is only (re)granted for the session — persisting a duplicate would just make the removal message confusing. The path is validated first; on a store write error nothing is granted (the caller reports and fails closed).
func DisplayHomePath ¶ added in v1.2.3
DisplayHomePath shortens a path under $HOME to "~/…" for display; the grant itself always uses the full path.
func PersistTurn ¶
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 ¶
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 ¶
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 ResolveContextWindow ¶ added in v1.2.13
ResolveContextWindow resolves the context-token budget for a (provider, model) pair: the value models.dev publishes when its catalog knows the model, DefaultContextWindow otherwise. The catalog is read from the same 24h disk cache the reasoning ladder uses, so this never blocks on the network; a model the catalog does not cover (custom base URL, brand-new release) keeps the historical 1M fallback.
func ResolveResumeID ¶
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 ¶
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.
func UserShellDisplayOutput ¶ added in v1.2.12
UserShellDisplayOutput caps the output a UI card renders. Callers pass the raw buffered output; the returned text is safe to split into display rows.
func UserShellMessage ¶ added in v1.2.12
func UserShellMessage(command string, exitCode int, d time.Duration, output string) agentcore.UserMessage
UserShellMessage wraps UserShellRecord as the user-role message appended to the conversation. The output is capped first, so a chatty command can never flow into the model window whole.
func UserShellRecord ¶ added in v1.2.12
UserShellRecord renders the conversation record for a settled passthrough command: codex's user-role <user_shell_command> fragment verbatim, so the model sees the command, its exit code, duration, and output in the shape it already knows from codex sessions.
Types ¶
type Editor ¶
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.
func (*LiveConfig) RefreshContextWindow ¶ added in v1.2.13
func (l *LiveConfig) RefreshContextWindow()
RefreshContextWindow re-resolves ContextWindow from the current provider and model. Call it after a /model or /provider switch, and after /resume applies a session header, so the status-bar percentage and the auto-compaction threshold track the model actually in use instead of the launch model.
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 ¶
func (h *TelemetryHolder) Fold(ev agentcore.TelemetryEvent)
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 ¶
func (h *TelemetryHolder) Last() *agentcore.TelemetryEvent
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).
type UserShellOutcome ¶ added in v1.2.12
type UserShellOutcome struct {
// Command is the command line the user typed, without the leading "!".
Command string
// ExitCode is the process exit code (-1 when the command was aborted).
ExitCode int
// Duration is the wall-clock run time (zero when aborted, mirroring codex).
Duration time.Duration
// Output is the command's combined output, bounded by the in-memory window.
Output string
// TimedOut reports the one-hour backstop fired and the process was killed.
TimedOut bool
// Aborted reports the user interrupted the command (Ctrl+C / Esc).
Aborted bool
}
UserShellOutcome is a settled passthrough command.
type UserShellRecordData ¶ added in v1.2.12
UserShellRecordData is the parsed form of a <user_shell_command> message.
func ParseUserShellRecord ¶ added in v1.2.12
func ParseUserShellRecord(text string) (UserShellRecordData, bool)
ParseUserShellRecord recognizes a conversation message written by UserShellRecord and extracts its command, exit code, and output. ok is false for every other message, so replay paths render a record as the shell card it was instead of dumping raw XML into the transcript.
type UserShellRun ¶ added in v1.2.12
type UserShellRun struct {
// Command is the command line being run (without the leading "!").
Command string
// contains filtered or unexported fields
}
UserShellRun is one in-flight passthrough command. The process lives on the shared execsess manager, so it is covered by the same LRU bookkeeping and kill-on-exit as the agent's own shells.
func StartUserShell ¶ added in v1.2.12
func StartUserShell(mgr *execsess.Manager, cwd, command string) (*UserShellRun, error)
StartUserShell spawns command under the login shell in cwd. It is the `!` escape hatch: no sandbox, no approval, no model call.
func (*UserShellRun) Done ¶ added in v1.2.12
func (u *UserShellRun) Done() bool
Done reports whether the process has exited.
func (*UserShellRun) Output ¶ added in v1.2.12
func (u *UserShellRun) Output() string
Output returns everything buffered so far: the running UI polls this while the command streams.
func (*UserShellRun) Wait ¶ added in v1.2.12
func (u *UserShellRun) Wait(ctx context.Context) UserShellOutcome
Wait blocks until the process exits, the timeout fires, or ctx is cancelled. A cancelled ctx is the user's Ctrl+C: the command is killed and the outcome reports codex's aborted shape (exit code -1, "command aborted by user", zero duration).
type WritablePathEntry ¶ added in v1.2.3
WritablePathEntry is one writable root with its provenance. Sources merge in the order config.toml → permissions.toml → session, first label winning, so the list reads the same as the startup merge in cmd/golder.
func ListWritablePaths ¶ added in v1.2.3
func ListWritablePaths() ([]WritablePathEntry, []string)
ListWritablePaths merges the two files with the live session registry. Unreadable entries and malformed files become warnings (returned, not printed) rather than errors: the list is a debugging aid and works even when half of it is broken.
type WritableRemoval ¶ added in v1.2.3
WritableRemoval reports what a removal touched, so the caller can warn when the unedited config.toml seed still re-grants the path at the next launch.
func RemoveWritablePath ¶ added in v1.2.3
func RemoveWritablePath(raw string) (WritableRemoval, error)
RemoveWritablePath revokes a path for this session and deletes it from the managed store. config.toml is never rewritten (that would drop the user's comments); a seed it still holds is reported via WasConfig.
func (WritableRemoval) Found ¶ added in v1.2.3
func (r WritableRemoval) Found() bool
Found reports whether the path was granted by any source.
Source Files
¶
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). |