chat

package
v0.158.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 17 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 chat implements the gk chat engine: a multi-turn, tool-calling conversation over the repository, built on provider.ToolCaller and the sandboxed read-only tool registry in internal/chat/tools.

Index

Constants

View Source
const CompactSummaryIntro = "[/compact] Summarize our conversation so far so we can continue with less context."

compactSummaryIntro is the synthetic USER-role message that opens the two-message pair compactSummaryMessages builds. Anthropic's Messages API rejects any request whose FIRST message isn't role "user", and separately rejects two consecutive messages of the same role — a fold that began history with a bare assistant-role summary (or that glued a synthetic user message directly in front of the next kept turn's own user message) fails one constraint or the other. Framing it as "user asks for a recap, assistant recaps" satisfies both with the fewest synthetic bytes and reads coherently if a human ever inspects the transcript. Kept in English for the same reason as compactSummaryPrefix. CompactSummaryIntro is exported so callers that inspect replayed history (e.g. the REPL's arrow-key seed) can recognize this synthetic user-role message. See IsSyntheticUserMessage.

Variables

View Source
var ErrFirstRoundFailed = errors.New("chat: round 0 failed before any assistant/tool history existed")

ErrFirstRoundFailed marks a failure at round 0 of a virgin session — no assistant/tool message exists anywhere in history yet (turnStart == 0 AND round == 0). This is the ONE failure gk chat's session-start fallback (chat.go's resolveChatProviderChain + runFirstChatTurn) may safely retry against the next ToolCaller in its provider chain: since nothing vendor-specific (tool_use IDs) has been generated yet, restarting fresh with a different provider can't corrupt anything. Any LATER round's failure is returned bare instead — the session has already committed to this provider's tool_use IDs, so mid-conversation failover is never attempted.

View Source
var ErrMaxRounds = errors.New("chat: tool-call round limit reached without a final answer")

ErrMaxRounds reports a turn that spent its round budget without the model producing a final answer.

Functions

func IsCodeAnswerable

func IsCodeAnswerable(question string) bool

IsCodeAnswerable reports whether a chat question should be grounded in the current repository's code before it is answered — i.e. whether the code here can plausibly answer it. It is a pure, deterministic, allocation- light heuristic over the question text alone (no model call): true when the question carries a code/repo signal, false otherwise.

Ambiguity fails open toward false (do NOT force investigation), so a repo-independent question is never gated. The engine uses this only to decide whether to spend a single "use your tools first" reprompt — a nudge, not a wall — so a false negative merely leaves today's behavior unchanged, while a false positive costs at most one extra, harmless investigation round (which the engine caps).

func IsSyntheticUserMessage

func IsSyntheticUserMessage(text string) bool

IsSyntheticUserMessage reports whether text is a user-role message the engine SYNTHESIZED rather than one the human typed — currently just the /compact intro. A --continue replay must not seed such a message into the REPL's ↑/↓ history, or the arrow keys would replay a prompt the user never entered.

func LastSessionID

func LastSessionID(ctx context.Context, runner git.Runner) string

LastSessionID returns the id recorded by the most recent session, or "" when none exists.

func SystemPrompt

func SystemPrompt(repoContext, repoMap, lang string, easy bool) string

SystemPrompt composes the gk chat role, its non-negotiable rules, and the (untrusted, tag-escaped) repository context. The rules live in the system slot so repository content — which flows in as tool results and user-pasted text — can never masquerade as instructions. The rules are still advisory for the model; the ENFORCED boundary is the sandbox and argument validation in internal/chat/tools.

repoMap is the opt-in (ai.chat.auto_context) REPO_MAP block: a depth/ file-capped directory tree the caller built from `git ls-files`. Empty when the config is off/unset — in that case no REPO_MAP fence is emitted at all, so a disabled/default config produces byte-identical output to before this parameter existed.

Types

type CompactResult

type CompactResult struct {
	// Compacted is false when there was nothing worth folding (the
	// conversation has compactKeepTurns turns or fewer) — no provider call
	// was made and history is untouched.
	Compacted bool
	// TurnsFolded/TurnsKept count turns, not messages.
	TurnsFolded int
	TurnsKept   int
	// TokensBefore/TokensAfter are estimateTokens(history) immediately
	// before and after the fold (post hard-trim fallback, if that fired).
	TokensBefore int
	TokensAfter  int
	// SummaryTokens is the summarize call's own reported usage (0 if the
	// provider returned none).
	SummaryTokens int
}

CompactResult reports what one Engine.Compact call actually did.

type Engine

type Engine struct {
	Caller       provider.ToolCaller
	Registry     *tools.Registry
	SystemPrompt string
	// MaxTokens caps each provider response (0 → provider default).
	MaxTokens int
	// MaxToolRounds bounds provider round-trips per turn (0 → 15).
	MaxToolRounds int
	// RoundTimeout bounds ONE provider call, not the whole turn — a
	// 15-round turn is legitimate; a single hung HTTP call is not.
	RoundTimeout time.Duration
	// TurnByteCap bounds cumulative tool-result bytes per turn.
	TurnByteCap int
	// HistoryBudget approximates the token budget for replayed history
	// (0 → no trimming).
	HistoryBudget int
	// Session, when set, persists every message as it happens (post-
	// redaction — Registry redacts before results reach the engine).
	Session *Session
	// OnToolCall/OnToolResult are UI hooks for the one-line transparency
	// display; nil-safe. OnRound fires after every provider reply with the
	// turn's cumulative token count so a live spinner can show spend as it
	// grows.
	OnToolCall   func(call provider.ToolCall)
	OnToolResult func(call provider.ToolCall, res provider.ToolResult)
	OnRound      func(round, tokensSoFar int, approx bool)
	// OnTextDelta, when set, opts every round of every turn into
	// text-only SSE streaming: it is forwarded verbatim as
	// ChatInput.OnTextDelta on each ChatWithTools call. nil (the
	// default) leaves every round on the existing non-stream path — see
	// ChatInput.OnTextDelta's docstring for the streaming/fallback
	// contract. GK_AGENT/--json callers must leave this nil to keep the
	// envelope contract (chat.go gates it on JSONOut()).
	OnTextDelta func(string)
	// OnStreamReset is forwarded as ChatInput.OnStreamReset: an adapter
	// fires it when a streaming round is abandoned for the non-stream
	// fallback after already delivering text, so the terminal UI can void
	// the stale partial. nil when OnTextDelta is nil (no streaming).
	OnStreamReset func()
	Dbg           func(string, ...any)
	// contains filtered or unexported fields
}

Engine drives the agentic loop: one RunTurn per user input, each turn alternating provider round-trips with sandboxed tool dispatch until the model answers in text. The engine owns every limit (rounds, bytes, repeats, timeouts) — providers and tools stay policy-free.

func (*Engine) ClearHistory

func (e *Engine) ClearHistory() error

ClearHistory drops the in-memory conversation and records a clear marker so a later --continue replay starts from the same empty context instead of resurrecting what the user explicitly cleared (the file keeps the full record for audit; only replay semantics change). The returned error means the marker did NOT land — live memory is cleared but a future --continue would restore the pre-clear context, which the caller should tell the user instead of hiding.

func (*Engine) Compact

func (e *Engine) Compact(ctx context.Context, sum provider.Summarizer, lang string) (CompactResult, error)

Compact folds every turn before the last compactKeepTurns turns into a single synthetic summary message, via exactly ONE call to sum. The caller is responsible for handing in the session's OWN provider (e.g. by type-asserting Engine.Caller, which chat.go's remoteGuardedCaller already wraps with the same remote-policy re-check ChatWithTools gets) — never a different vendor: a --continue replay must stay on one provider's tool_use ID space and voice (see provider.ToolCaller's docstring), and reusing the exact wrapped caller already driving the session is the simplest way to guarantee that.

On any error from sum.Summarize, e.history is left COMPLETELY untouched — nothing is computed or assigned until after Summarize has already succeeded — so a failed /compact costs nothing but the attempt; the caller can retry or just keep talking.

Once Summarize succeeds, Compact re-applies the SAME hard-trim fallback every RunTurn round already uses (trimHistory, gated on HistoryBudget): a pathologically small budget, or a summary that still didn't shrink enough, degrades to the exact mechanism RunTurn's histCache already falls back to — never a new, second trimming code path. Because trimHistory's own budget check is a cheap no-op when already under budget, calling it here unconditionally (whenever HistoryBudget > 0) costs nothing in the common case and gives /compact's own reported TokensAfter a guarantee, rather than depending on incidentally hitting budget enforcement lazily on the NEXT turn.

trimmedTurnHistory's cache (see history.go) needs no explicit invalidation here: it lives entirely as a local variable inside one RunTurn call and is rebuilt from e.history at the start of every turn — /compact only ever runs BETWEEN turns (a REPL meta command, never invoked mid-round), so by the time the next RunTurn seeds a fresh cache, e.history already reflects the fold.

e.HistoryBudget itself travels into the persisted "compact" record (see Session.RecordCompact) so a later --continue replay can re-apply the IDENTICAL trimHistory pass compactReplayFold now does — without this, live memory and a replayed session would silently diverge whenever the hard-trim fallback above actually fired (it is a no-op, and so invisible, in the common case where the fold alone already fits budget).

The returned error, when non-nil AFTER a successful fold, means only the SESSION RECORD failed to persist (disk full, permissions, …): e.history is already folded for the rest of THIS process, but a later --continue replay of the file would not see the compaction and would replay the full original history instead of the folded summary — safe, just uncompacted. Compare Engine.ClearHistory's identical contract.

func (*Engine) History

func (e *Engine) History() []provider.ChatMessage

History returns the live conversation (for tests and the /clear command).

func (*Engine) LoadHistory

func (e *Engine) LoadHistory(msgs []provider.ChatMessage)

LoadHistory seeds the conversation (from Session.Replay for --continue).

func (*Engine) RunTurn

func (e *Engine) RunTurn(ctx context.Context, userInput string) (_ *TurnResult, err error)

RunTurn processes one user input to a final text answer. On ANY error the whole turn is rolled back — in memory by truncation, in the session file by an "aborted" marker that Replay honors — because a partial turn is not just untidy, it is POISON: Anthropic rejects two consecutive user messages and every tool_use must be answered by a tool_result, so a dangling user message or an unanswered tool call would wedge every subsequent round of the session (three review vendors converged on this). Roll back, report, and the next turn starts clean.

func (*Engine) TokenUsage

func (e *Engine) TokenUsage() TokenUsageReport

TokenUsage computes the current context composition — cheap, pure arithmetic over e.history/e.SystemPrompt, safe to call as often as `/tokens` or the end-of-turn 80%-budget warning need.

type Session

type Session struct {
	ID string
	// contains filtered or unexported fields
}

Session persists one conversation as an append-only JSONL file under .git/gk-chat/sessions/<id>.jsonl and tracks the latest id in .git/gk-chat/last-session for --continue.

func NewSession

func NewSession(ctx context.Context, runner git.Runner, id string) (*Session, error)

NewSession creates a fresh session file. The id folds in a timestamp passed by the caller so tests stay deterministic.

func OpenSession

func OpenSession(ctx context.Context, runner git.Runner, id string) (*Session, error)

OpenSession opens an existing session for appending and replay.

func (*Session) Append

func (s *Session) Append(rec SessionRecord) error

Append writes one record. Each line is a self-contained JSON object written with O_APPEND, so a crash mid-write corrupts at most the final line — which Replay tolerates by design.

func (*Session) RecordCompact

func (s *Session) RecordCompact(summary, model string, tokensUsed, historyBudget int) error

RecordCompact appends a /compact control record: summary is the summarizer's own output (the exact text compactSummaryMessages will wrap into the synthetic intro+summary pair on replay), model/tokensUsed are the summarize call's own usage, carried along for audit the same way a normal assistant record does. historyBudget is the Engine.HistoryBudget in effect at fold time — 0 when trimming is disabled — persisted so a later --continue replay can re-apply the identical hard-trim fallback Engine.Compact already applied in memory (see compactReplayFold); without it, replay would only ever see the untrimmed summary+kept shape, which silently diverges from live history whenever that fallback actually fired. Called by Engine.Compact ONLY after a summarize call has already succeeded and the in-memory history has already been folded — see that method's docstring for what a failure here does and does not undo.

func (*Session) Replay

func (s *Session) Replay() ([]provider.ChatMessage, int, error)

Replay reads the session back as provider messages. Corruption is contained, never fatal: an unparseable line (torn tail from a crash) is skipped and reported via the second return so the caller can warn — losing one line of history must not lose the session.

func (*Session) SetTitle

func (s *Session) SetTitle(title string) error

SetTitle appends a /rename title record. It is a control record exactly like the /clear marker — never replayed as a conversation message — so renaming mid-session costs one JSONL line and never touches prior history. Safe to call repeatedly; the latest record wins for display.

type SessionMeta

type SessionMeta struct {
	ID   string
	Path string
	// StartedAt is the first record's timestamp; the zero value means the
	// file had no parseable line at all (empty or fully corrupt).
	StartedAt time.Time
	// Title is the latest /rename record's text, or — when none exists —
	// the first non-empty user message, truncated to sessionTitleMaxLen
	// runes. Empty only when the session has no title and no user turn
	// yet (freshly created, untouched file).
	Title string
	// TurnCount counts every "user" record written to the file, including
	// one from a turn later rolled back by a turn_aborted marker — an
	// approximation cheap enough for a list view, not the exact
	// replay-surviving turn count Replay would report.
	TurnCount int
}

SessionMeta summarizes one session file for `gk chat sessions` — cheap enough to compute for every file in the directory without a full Replay reconstruction (no ToolCall/ToolResult shapes are rebuilt).

func ListSessions

func ListSessions(ctx context.Context, runner git.Runner) ([]SessionMeta, error)

ListSessions scans .git/gk-chat/sessions/*.jsonl and returns one SessionMeta per file, newest first (by StartedAt, tie-broken by ID descending — both monotonic for the timestamp-prefixed ids `gk chat` generates). No separate index file: this is a directory scan plus one lightweight pass per file. A missing sessions/ directory (no session created yet) returns (nil, nil), not an error. A single unreadable file is skipped rather than failing the whole listing — the same corruption-tolerant spirit as Replay.

type SessionRecord

type SessionRecord struct {
	TS         time.Time            `json:"ts"`
	Role       string               `json:"role"`
	Text       string               `json:"text,omitempty"`
	ToolCalls  []provider.ToolCall  `json:"tool_calls,omitempty"`
	ToolResult *provider.ToolResult `json:"tool_result,omitempty"`
	Model      string               `json:"model,omitempty"`
	TokensUsed int                  `json:"tokens_used,omitempty"`
	// HistoryBudget is Engine.HistoryBudget as it stood when a
	// recordRoleCompact record was written (0 for every other role, and
	// for any compact record written before this field existed) — see
	// RecordCompact and compactReplayFold. omitempty keeps every
	// non-compact record byte-identical to before this field was added.
	HistoryBudget int `json:"history_budget,omitempty"`
}

SessionRecord is one persisted conversation event — one JSON object per line (the aicommit audit-log shape). Tool results are stored POST-redaction: what's on disk is exactly what the provider saw, so a --continue replay never re-handles raw secrets.

type TokenUsageReport

type TokenUsageReport struct {
	SystemChars, SystemTokens   int
	HistoryChars, HistoryTokens int
	ToolChars, ToolTokens       int
	// UsedTokens is estimateTokens(history) — the exact figure trimHistory
	// compares against BudgetTokens (HistoryTokens+ToolTokens approximates
	// it for display, but per-bucket division can round differently than
	// dividing the combined char sum once; UsedTokens is the authoritative
	// number, the per-bucket split is composition detail).
	UsedTokens int
	// BudgetTokens is Engine.HistoryBudget as configured; 0 means no
	// budget (trimming disabled), matching trimHistory's own contract.
	BudgetTokens int
}

TokenUsageReport breaks down `/tokens`' context-composition display: chars and chars/4 estimates for the system prompt, the "history" bucket (user/assistant text plus tool-call requests), and the "tool results" bucket, plus the history-budget headroom trimHistory enforces.

The system prompt is deliberately kept OUT of UsedTokens/BudgetTokens: HistoryBudget/trimHistory only ever operate on the replayed message slice (see estimateTokens's own docstring — it never takes SystemPrompt as an argument), so folding the system prompt into the budget number would let a user read "80% of budget used" as covering something it structurally never has.

func (TokenUsageReport) Percent

func (r TokenUsageReport) Percent() float64

Percent returns UsedTokens/BudgetTokens in [0,1]. No budget configured (BudgetTokens <= 0) reports 0 — "no budget" must never read as "100% available" nor "0% used" being mistaken for "budget exhausted"; callers gate on BudgetTokens > 0 before treating this as a real percentage.

type TurnResult

type TurnResult struct {
	Text      string
	Model     string
	Rounds    int
	ToolCalls int
	// TokensUsed accumulates provider-reported usage across the turn's
	// rounds. Rounds whose provider returned no usage (some proxies drop
	// the field) are filled with the chars/4 estimate and flip
	// TokensApprox — the number is then a floor-ish approximation, not
	// billing truth.
	TokensUsed   int
	TokensApprox bool
}

TurnResult summarizes one completed turn.

Directories

Path Synopsis
Package tools implements the read-only tool surface `gk chat` exposes to the model: five whitelisted git subcommands and two file tools, every invocation passing through the Sandbox and the shared redaction pipeline before its result reaches a (remote) provider.
Package tools implements the read-only tool surface `gk chat` exposes to the model: five whitelisted git subcommands and two file tools, every invocation passing through the Sandbox and the shared redaction pipeline before its result reaches a (remote) provider.

Jump to

Keyboard shortcuts

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