v0.0.29 e425dbb

build.go RawHistoryFolder

1package agent
2
3import (
4	"fmt"
5	"os"
6	"path/filepath"
7	"strings"
8
9	"github.com/patriceckhart/zot/internal/agent/tools"
10	"github.com/patriceckhart/zot/internal/core"
11	"github.com/patriceckhart/zot/internal/provider"
12	"github.com/patriceckhart/zot/internal/skills"
13)
14
15// Resolved is the effective configuration after merging CLI, config, defaults.
16type Resolved struct {
17	Provider   string
18	Model      string
19	Credential string // api key or oauth access token
20	AuthMethod string // "apikey" | "oauth" | "" (no credential yet)
21	AccountID  string // ChatGPT account id (for openai oauth), "" otherwise
22	BaseURL    string
23	CWD        string
24	Reasoning  string
25
26	ToolRegistry core.Registry
27	ToolSummary  []ToolSummary
28	SystemPrompt string
29	MaxSteps     int
30	Sandbox      *tools.Sandbox
31
32	// SkillTool is the on-demand skill loader registered with the
33	// agent's tool registry, or nil if no SKILL.md files were
34	// discovered. Exposed so the tui can list / preview skills.
35	SkillTool *skills.Tool
36
37	// Bookkeeping for MergeExtensionTools. Captured at Resolve time
38	// so the system prompt can be rebuilt later without re-running
39	// resolve.
40	systemAppend     []string
41	systemCustom     string
42	toolDescriptions map[string]string
43}
44
45// HasCredential reports whether a credential was resolved.
46func (r Resolved) HasCredential() bool { return r.Credential != "" }
47
48// MergeExtensionTools folds every tool registered by an extension
49// into r's ToolRegistry and re-renders the system prompt's tool
50// summary so the model sees both built-in and extension tools.
51//
52// Idempotent: calling twice with the same manager state has no
53// effect on the second pass (existing names are preserved). Built-in
54// tools always win on conflict.
55func (r *Resolved) MergeExtensionTools(mgr ExtensionToolSource) {
56	if mgr == nil {
57		return
58	}
59	infos := mgr.Tools()
60	if len(infos) == 0 {
61		return
62	}
63	changed := false
64	for _, info := range infos {
65		if _, exists := r.ToolRegistry[info.Name]; exists {
66			continue
67		}
68		r.ToolRegistry[info.Name] = mgr.NewExtensionTool(info)
69		changed = true
70	}
71	if !changed {
72		return
73	}
74	// Re-render the system prompt with the merged tool list. Skill
75	// addendum is preserved by walking the existing append slice.
76	append_ := r.systemAppend
77	r.SystemPrompt = BuildSystemPrompt(SystemPromptOpts{
78		CWD:    r.CWD,
79		Tools:  toolSummariesFromRegistry(r.ToolRegistry, r.toolDescriptions),
80		Custom: r.systemCustom,
81		Append: append_,
82	})
83}
84
85// ExtensionToolSource is the slice of the extension manager that
86// MergeExtensionTools needs. Lives here as an interface so the
87// build package doesn't import internal/agent/extensions (which
88// imports core, which imports... avoid the cycle).
89type ExtensionToolSource interface {
90	Tools() []ExtensionToolInfo
91	NewExtensionTool(info ExtensionToolInfo) core.Tool
92}
93
94// ExtensionToolInfo mirrors extensions.ToolInfo so we can declare
95// ExtensionToolSource here without importing the extensions
96// package. The cli wires a tiny adapter to bridge them.
97type ExtensionToolInfo struct {
98	Extension   string
99	Name        string
100	Description string
101	Schema      []byte
102}
103
104// toolSummariesFromRegistry rebuilds the system-prompt tool list
105// from a (possibly extended) registry, using cached descriptions for
106// the human-readable summary text.
107func toolSummariesFromRegistry(reg core.Registry, cached map[string]string) []ToolSummary {
108	out := make([]ToolSummary, 0, len(reg))
109	for name, t := range reg {
110		desc := t.Description()
111		if d, ok := cached[name]; ok && d != "" {
112			desc = d
113		}
114		out = append(out, ToolSummary{Name: name, Description: desc})
115	}
116	return out
117}
118
119// Resolve merges args, config, and env into a Resolved set.
120//
121// Unlike the earlier version, Resolve NEVER returns an error for
122// missing credentials: the TUI can start without them and launch a
123// login flow. requireCred controls whether missing credentials are a
124// hard error (used by print/json modes).
125func Resolve(args Args, requireCred bool) (Resolved, error) {
126	cfg, _ := LoadConfig()
127
128	// User-requested provider (explicit > config > default).
129	provName := firstNonEmpty(args.Provider, cfg.Provider, "anthropic")
130	if provName != "anthropic" && provName != "openai" {
131		return Resolved{}, fmt.Errorf("provider must be anthropic or openai (got %q)", provName)
132	}
133
134	// Try the requested provider first.
135	cred, method, accountID, credErr := ResolveCredentialFull(provName, args.APIKey)
136
137	// If the user did NOT explicitly pick a provider and the default one
138	// has no credentials, auto-fall-back to whichever provider is actually
139	// logged in. That way running plain `zot` after `/login` (any provider)
140	// never shows a "not logged in" banner.
141	userPickedProvider := args.Provider != ""
142	if credErr != nil && !userPickedProvider {
143		other := "openai"
144		if provName == "openai" {
145			other = "anthropic"
146		}
147		if c, m, a, err := ResolveCredentialFull(other, args.APIKey); err == nil {
148			provName = other
149			cred, method, accountID, credErr = c, m, a, err
150		}
151	}
152
153	model := firstNonEmpty(args.Model, cfg.Model)
154	if model == "" {
155		if provName == "openai" {
156			model = "gpt-5"
157		} else {
158			model = provider.DefaultModel.ID
159		}
160	}
161	// If the resolved model belongs to a different provider (e.g. config
162	// says gpt-5 but we fell back to anthropic), pick that provider's default.
163	if m, err := provider.FindModel("", model); err == nil && m.Provider != provName {
164		if provName == "openai" {
165			model = "gpt-5"
166		} else {
167			model = provider.DefaultModel.ID
168		}
169	}
170	if _, err := provider.FindModel(provName, model); err != nil {
171		return Resolved{}, err
172	}
173
174	if credErr != nil && requireCred {
175		return Resolved{}, fmt.Errorf("%w; set %s_API_KEY, pass --api-key, or run `zot` and /login",
176			credErr, envVarName(provName))
177	}
178
179	sandbox := tools.NewSandbox(args.CWD)
180	reg := buildToolRegistry(args, args.CWD, sandbox)
181
182	// Skill discovery: scan project + global locations and, if any
183	// SKILL.md files were found, register the on-demand `skill`
184	// loader tool plus a system-prompt manifest so the model knows
185	// what's available.
186	homeDir, _ := os.UserHomeDir()
187	discovered, _ := skills.Discover(ZotHome(), args.CWD, homeDir)
188	var skillTool *skills.Tool
189	var skillAddendum string
190	if len(discovered) > 0 {
191		skillTool = skills.NewTool(discovered)
192		reg[skillTool.Name()] = skillTool
193		skillAddendum = skills.SystemPromptAddendum(discovered)
194	}
195	_ = skillTool
196
197	summaries := toolSummaries(reg, args)
198
199	append_ := append([]string(nil), args.AppendSystemPrompt...)
200	if skillAddendum != "" {
201		append_ = append(append_, skillAddendum)
202	}
203
204	// Custom system prompt resolution order:
205	//   1. --system-prompt flag (highest priority; ad-hoc per run)
206	//   2. $ZOT_HOME/SYSTEM.md (persistent user override)
207	//   3. built-in default (defaultIdentity + defaultGuidelines)
208	custom := args.SystemPrompt
209	if custom == "" {
210		custom = readUserSystemPrompt(ZotHome())
211	}
212
213	sys := BuildSystemPrompt(SystemPromptOpts{
214		CWD:    args.CWD,
215		Tools:  summaries,
216		Custom: custom,
217		Append: append_,
218	})
219
220	reasoning := firstNonEmpty(args.Reasoning, cfg.Reasoning)
221
222	max := args.MaxSteps
223	if max <= 0 {
224		max = 50
225	}
226
227	return Resolved{
228		Provider:         provName,
229		Model:            model,
230		Credential:       cred,
231		AuthMethod:       method,
232		AccountID:        accountID,
233		BaseURL:          args.BaseURL,
234		CWD:              args.CWD,
235		Reasoning:        reasoning,
236		ToolRegistry:     reg,
237		ToolSummary:      summaries,
238		SystemPrompt:     sys,
239		MaxSteps:         max,
240		Sandbox:          sandbox,
241		SkillTool:        skillTool,
242		systemAppend:     append_,
243		systemCustom:     custom,
244		toolDescriptions: descMapFromSummaries(summaries),
245	}, nil
246}
247
248// readUserSystemPrompt looks for $ZOT_HOME/SYSTEM.md and returns its
249// trimmed contents, or "" when the file is missing / unreadable /
250// empty. Errors are intentionally swallowed: the file is optional,
251// and any failure to read it should fall back to the built-in
252// default system prompt rather than crash the run.
253func readUserSystemPrompt(zotHome string) string {
254	if zotHome == "" {
255		return ""
256	}
257	path := filepath.Join(zotHome, "SYSTEM.md")
258	raw, err := os.ReadFile(path)
259	if err != nil {
260		return ""
261	}
262	return strings.TrimSpace(string(raw))
263}
264
265// descMapFromSummaries indexes the human-readable descriptions for
266// the renderToolsSection rebuild path.
267func descMapFromSummaries(summaries []ToolSummary) map[string]string {
268	out := make(map[string]string, len(summaries))
269	for _, s := range summaries {
270		out[s.Name] = s.Description
271	}
272	return out
273}
274
275// NewClient returns a provider.Client for r, choosing the auth mode
276// based on r.AuthMethod. Panics if no credential is present; callers
277// must check HasCredential() first.
278func (r Resolved) NewClient() provider.Client {
279	if !r.HasCredential() {
280		panic("NewClient called without credential; check HasCredential first")
281	}
282	if r.Provider == "openai" {
283		if r.AuthMethod == "oauth" {
284			return provider.NewOpenAICodex(r.Credential, r.AccountID, r.BaseURL)
285		}
286		return provider.NewOpenAI(r.Credential, r.BaseURL)
287	}
288	if r.AuthMethod == "oauth" {
289		return provider.NewAnthropicOAuth(r.Credential, r.BaseURL)
290	}
291	return provider.NewAnthropic(r.Credential, r.BaseURL)
292}
293
294// UseSandbox replaces the sandbox pointer that every tool in r's
295// registry references. Used to keep the /lock state stable across
296// agent rebuilds (e.g. /login, /model switching providers).
297func (r *Resolved) UseSandbox(s *tools.Sandbox) {
298	if s == nil || r == nil {
299		return
300	}
301	r.Sandbox = s
302	for name, t := range r.ToolRegistry {
303		switch v := t.(type) {
304		case *tools.ReadTool:
305			v.Sandbox = s
306		case *tools.WriteTool:
307			v.Sandbox = s
308		case *tools.EditTool:
309			v.Sandbox = s
310		case *tools.BashTool:
311			v.Sandbox = s
312		}
313		_ = name
314	}
315}
316
317// NewAgent constructs a core.Agent from r. Requires a credential.
318func (r Resolved) NewAgent() *core.Agent {
319	a := core.NewAgent(r.NewClient(), r.Model, r.SystemPrompt, r.ToolRegistry)
320	a.MaxSteps = r.MaxSteps
321	a.Reasoning = r.Reasoning
322	return a
323}
324
325func buildToolRegistry(args Args, cwd string, sandbox *tools.Sandbox) core.Registry {
326	if args.NoTools {
327		return core.Registry{}
328	}
329	all := map[string]core.Tool{
330		"read":  &tools.ReadTool{CWD: cwd, Sandbox: sandbox},
331		"write": &tools.WriteTool{CWD: cwd, Sandbox: sandbox},
332		"edit":  &tools.EditTool{CWD: cwd, Sandbox: sandbox},
333		"bash":  &tools.BashTool{CWD: cwd, Sandbox: sandbox},
334	}
335	reg := core.Registry{}
336	if len(args.Tools) == 0 {
337		for _, t := range all {
338			reg[t.Name()] = t
339		}
340		return reg
341	}
342	for _, name := range args.Tools {
343		if t, ok := all[name]; ok {
344			reg[name] = t
345		}
346	}
347	return reg
348}
349
350func toolSummaries(reg core.Registry, args Args) []ToolSummary {
351	order := []string{"read", "write", "edit", "bash"}
352	var out []ToolSummary
353	for _, name := range order {
354		if t, ok := reg[name]; ok {
355			out = append(out, ToolSummary{Name: t.Name(), Description: t.Description()})
356		}
357	}
358	return out
359}
360
361func firstNonEmpty(vals ...string) string {
362	for _, v := range vals {
363		if v != "" {
364			return v
365		}
366	}
367	return ""
368}
369
370func envVarName(provider string) string {
371	switch provider {
372	case "openai":
373		return "OPENAI"
374	default:
375		return "ANTHROPIC"
376	}
377}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close