coding

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package coding wires the runtime pieces into a working coding agent: provider + agent loop + tools + session persistence. It is the seam the CLI modes sit on, and the precursor to P3's full orchestrator.

Index

Constants

View Source
const DefaultModel = "anthropic/claude-sonnet-5"

DefaultModel is the model tau picks when neither the caller nor settings name one.

It is provider-qualified deliberately. A bare id is ambiguous once the compiled catalog spans every provider — a dozen of them resell claude-sonnet-5 — and the resolver's tie-break is a sort over ids, which would silently start the session on whichever reseller happened to sort highest. A user typing a bare id still gets that behaviour, which is Pi's; tau's own default must not depend on it.

Variables

View Source
var ErrRunning = errors.New("the agent is still working — press Esc to stop it first")

ErrRunning is returned by operations that cannot run while the agent is mid-turn.

Functions

func BuildRegistry added in v0.2.1

func BuildRegistry(store auth.CredentialStore) (*models.Registry, []string, error)

BuildRegistry composes the compiled provider catalog with ~/.tau/models.json.

A missing or malformed models.json is not fatal: the built-ins still work, which matters because the file is hand-edited and losing every provider over one stray comma would be the worse outcome. The problem is returned as a warning rather than printed, so the caller decides where it surfaces.

func FormatUsage added in v0.2.1

func FormatUsage(u ai.Usage) string

FormatUsage renders a usage summary for a human.

The cache figures appear only when there are any, but when there are they matter more than the input count: on a cached turn the input number is the small remainder, and printing it alone makes a working cache look like a broken token counter.

Types

type JSONEvent

type JSONEvent struct {
	Type string `json:"type"`

	// Message carries the subject message for message_* and turn_end.
	Message json.RawMessage `json:"message,omitempty"`
	// Delta is the incremental text or thinking for message_update, so
	// consumers can render progressively without reassembling the message.
	Delta string `json:"delta,omitempty"`
	// DeltaKind is "text" or "thinking" when Delta is set.
	DeltaKind string `json:"deltaKind,omitempty"`

	ToolCallID string          `json:"toolCallId,omitempty"`
	ToolName   string          `json:"toolName,omitempty"`
	Args       map[string]any  `json:"args,omitempty"`
	Result     json.RawMessage `json:"result,omitempty"`
	IsError    bool            `json:"isError,omitempty"`

	// Usage and Cost accompany the terminal event.
	Usage *ai.Usage `json:"usage,omitempty"`
	// Error is set on the terminal event when the run failed.
	Error string `json:"error,omitempty"`
	// SessionPath is emitted once at start so a caller can resume later.
	SessionPath string `json:"sessionPath,omitempty"`
	Model       string `json:"model,omitempty"`
}

JSONEvent is one line of `tau --mode json` output. The stream is JSONL: exactly one event per line, LF-terminated, so consumers can parse incrementally without buffering the whole run.

type JSONWriter

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

JSONWriter serializes agent events as JSONL.

func NewJSONWriter

func NewJSONWriter(w io.Writer) *JSONWriter

NewJSONWriter builds a JSONL event writer.

func (*JSONWriter) Emit

func (j *JSONWriter) Emit(ev JSONEvent)

Emit writes one event.

func (*JSONWriter) Err

func (j *JSONWriter) Err() error

Err returns the first write failure, if any.

func (*JSONWriter) Sink

func (j *JSONWriter) Sink() agent.Sink

Sink returns an agent.Sink that renders the run as JSONL.

type Options

type Options struct {
	Cwd           string
	ModelID       string
	ThinkingLevel ai.ModelThinkingLevel
	SystemPrompt  string
	// NoTools disables tool use entirely.
	NoTools bool
	// NoSession skips persistence (useful for one-shot runs).
	NoSession bool
	// AppendSystemPrompt is appended after the built system prompt.
	AppendSystemPrompt string
	// NoSkills disables skill discovery.
	NoSkills bool
	// TrustOverride forces the project-trust decision (--approve/--no-approve).
	TrustOverride *bool
	// Extensions are loaded before the session starts, in order.
	Extensions []extension.Extension
	// Mode is reported to extensions so they can degrade gracefully.
	Mode extension.Mode
	// Resume opens the most recent session for Cwd instead of creating one.
	Resume bool
	// SessionPath opens a specific session file.
	SessionPath string
	// UI is the host's interactive surface, handed to extensions and to the
	// built-in commands that need to ask the user something. Nil is headless.
	UI extension.UI
	// Interactive supplies the built-in commands that need dialogs. The host
	// may pass a value whose session pointer is filled in after New returns —
	// nothing calls it during construction.
	Interactive slashcmd.Interactive
}

Options configures a coding session.

type Session

type Session struct {
	Agent   *agent.Agent
	Env     *osenv.OSEnv
	Model   *ai.Model
	Session *session.Session
	Path    string
	// Cwd is the directory the session is bound to.
	Cwd string
	// Extensions dispatches hooks; nil when no extensions are loaded.
	Extensions *extension.Runner
	// Trust records whether project-scoped resources were allowed to load.
	Trust trust.Outcome
	// Models is the composed provider catalog: built-ins plus models.json.
	Models *models.Registry
	// Settings is the merged global+project configuration.
	Settings *settings.Resolved
	// Commands is the slash-command registry for this session.
	Commands *slashcmd.Registry
	// UI is the host's interactive surface; never nil.
	UI extension.UI
	// Warnings are non-fatal startup problems — a malformed models.json, say.
	// The session runs regardless; the host decides whether to show them.
	Warnings []string
	// contains filtered or unexported fields
}

Session is a running coding agent bound to a persisted session file.

func New

func New(ctx context.Context, opts Options) (*Session, error)

New builds a coding session.

func (*Session) AvailableModels

func (s *Session) AvailableModels() []ai.Model

AvailableModels lists every model the registry knows, provider-qualified.

func (*Session) Close

func (s *Session) Close(ctx context.Context, reason string)

Close emits session shutdown to extensions.

func (*Session) CycleModel

func (s *Session) CycleModel(ctx context.Context, delta int) *ai.Model

CycleModel steps through the cycle set by delta, wrapping at both ends.

func (*Session) CycleModels

func (s *Session) CycleModels() []ai.Model

CycleModels is the ordered set Ctrl+P cycles through: the models named by the enabledModels setting, or everything when the setting is empty.

Pi treats an unmatched pattern as a warning rather than an error, so a setting that names a model from an unconfigured provider still leaves a usable cycle set.

func (*Session) CycleThinkingLevel

func (s *Session) CycleThinkingLevel(ctx context.Context, delta int) ai.ModelThinkingLevel

CycleThinkingLevel steps to the next level this model supports.

func (*Session) Describe

func (s *Session) Describe() string

Describe renders a one-line summary for status output.

func (*Session) LastAssistantText

func (s *Session) LastAssistantText() string

LastAssistantText returns the text of the most recent assistant message.

func (*Session) ListSessions

func (s *Session) ListSessions(ctx context.Context) ([]session.Metadata, error)

ListSessions returns this directory's sessions, most recent first.

func (*Session) Prompt

func (s *Session) Prompt(ctx context.Context, text string) ([]ai.Message, error)

Prompt runs one agent loop.

func (*Session) ResolveModelSpec

func (s *Session) ResolveModelSpec(spec string) (models.Match, error)

ResolveModelSpec is a lookup that does not switch models, for previewing a selection.

func (*Session) RestoredMessages

func (s *Session) RestoredMessages() []ai.Message

RestoredMessages returns the transcript the session was opened with, so a host can replay it into its display.

func (*Session) RunCommand

func (s *Session) RunCommand(ctx context.Context, line string) (slashcmd.Result, error)

RunCommand parses and executes a slash-command line.

It must not be called from a host's render goroutine: a command may open a dialog and block until the user answers.

func (*Session) SaveTrust

func (s *Session) SaveTrust(ctx context.Context, decision string) (string, error)

SaveTrust records a project-trust decision for future sessions.

func (*Session) SessionSummary

func (s *Session) SessionSummary() string

SessionSummary renders the /session report.

func (*Session) SetModel

func (s *Session) SetModel(ctx context.Context, spec string) (*ai.Model, error)

SetModel switches the model for subsequent turns, records the change in the session, and notifies extensions.

func (*Session) SetThinkingLevel

func (s *Session) SetThinkingLevel(ctx context.Context, level ai.ModelThinkingLevel) ai.ModelThinkingLevel

SetThinkingLevel changes the reasoning level, clamped to what the model supports, and records it in the session.

func (*Session) StartSession

func (s *Session) StartSession(ctx context.Context) error

StartSession replaces the current session with a new empty one.

func (*Session) SwitchSession

func (s *Session) SwitchSession(ctx context.Context, meta session.Metadata) error

SwitchSession opens an existing session file and adopts its transcript.

func (*Session) ThinkingLevel

func (s *Session) ThinkingLevel() ai.ModelThinkingLevel

ThinkingLevel reports the reasoning level in force.

func (*Session) ToolNames

func (s *Session) ToolNames() []string

ToolNames lists the active tools.

func (*Session) ToolsByName

func (s *Session) ToolsByName() map[string]agent.Tool

ToolsByName exposes the full registered tool set for activation UIs.

func (*Session) Usage

func (s *Session) Usage() ai.Usage

Usage sums token usage across the transcript.

Jump to

Keyboard shortcuts

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