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 + built-in
183 // skills shipped with the binary. If any are found, register
184 // the on-demand `skill` loader tool plus a system-prompt
185 // manifest so the model knows what's available.
186 //
187 // --no-skill bypasses the entire mechanism: no manifest in the
188 // system prompt, no `skill` tool in the registry. Useful for a
189 // clean-room run with zero extra context biasing the model.
190 var (
191 discovered []*skills.Skill
192 skillTool *skills.Tool
193 skillAddendum string
194 )
195 if !args.NoSkill {
196 homeDir, _ := os.UserHomeDir()
197 discovered, _ = skills.Discover(ZotHome(), args.CWD, homeDir, args.WithSkills)
198 if len(discovered) > 0 {
199 skillTool = skills.NewTool(discovered)
200 reg[skillTool.Name()] = skillTool
201 skillAddendum = skills.SystemPromptAddendum(discovered)
202 }
203 }
204 _ = skillTool
205
206 summaries := toolSummaries(reg, args)
207
208 append_ := append([]string(nil), args.AppendSystemPrompt...)
209 if skillAddendum != "" {
210 append_ = append(append_, skillAddendum)
211 }
212
213 // Custom system prompt resolution order:
214 // 1. --system-prompt flag (highest priority; ad-hoc per run)
215 // 2. $ZOT_HOME/SYSTEM.md (persistent user override)
216 // 3. built-in default (defaultIdentity + defaultGuidelines)
217 custom := args.SystemPrompt
218 if custom == "" {
219 custom = readUserSystemPrompt(ZotHome())
220 }
221
222 sys := BuildSystemPrompt(SystemPromptOpts{
223 CWD: args.CWD,
224 Tools: summaries,
225 Custom: custom,
226 Append: append_,
227 })
228
229 reasoning := firstNonEmpty(args.Reasoning, cfg.Reasoning)
230
231 max := args.MaxSteps
232 if max <= 0 {
233 max = 50
234 }
235
236 return Resolved{
237 Provider: provName,
238 Model: model,
239 Credential: cred,
240 AuthMethod: method,
241 AccountID: accountID,
242 BaseURL: args.BaseURL,
243 CWD: args.CWD,
244 Reasoning: reasoning,
245 ToolRegistry: reg,
246 ToolSummary: summaries,
247 SystemPrompt: sys,
248 MaxSteps: max,
249 Sandbox: sandbox,
250 SkillTool: skillTool,
251 systemAppend: append_,
252 systemCustom: custom,
253 toolDescriptions: descMapFromSummaries(summaries),
254 }, nil
255}
256
257// readUserSystemPrompt looks for $ZOT_HOME/SYSTEM.md and returns its
258// trimmed contents, or "" when the file is missing / unreadable /
259// empty. Errors are intentionally swallowed: the file is optional,
260// and any failure to read it should fall back to the built-in
261// default system prompt rather than crash the run.
262func readUserSystemPrompt(zotHome string) string {
263 if zotHome == "" {
264 return ""
265 }
266 path := filepath.Join(zotHome, "SYSTEM.md")
267 raw, err := os.ReadFile(path)
268 if err != nil {
269 return ""
270 }
271 return strings.TrimSpace(string(raw))
272}
273
274// descMapFromSummaries indexes the human-readable descriptions for
275// the renderToolsSection rebuild path.
276func descMapFromSummaries(summaries []ToolSummary) map[string]string {
277 out := make(map[string]string, len(summaries))
278 for _, s := range summaries {
279 out[s.Name] = s.Description
280 }
281 return out
282}
283
284// NewClient returns a provider.Client for r, choosing the auth mode
285// based on r.AuthMethod. Panics if no credential is present; callers
286// must check HasCredential() first.
287func (r Resolved) NewClient() provider.Client {
288 if !r.HasCredential() {
289 panic("NewClient called without credential; check HasCredential first")
290 }
291 if r.Provider == "openai" {
292 if r.AuthMethod == "oauth" {
293 return provider.NewOpenAICodex(r.Credential, r.AccountID, r.BaseURL)
294 }
295 return provider.NewOpenAI(r.Credential, r.BaseURL)
296 }
297 if r.AuthMethod == "oauth" {
298 return provider.NewAnthropicOAuth(r.Credential, r.BaseURL)
299 }
300 return provider.NewAnthropic(r.Credential, r.BaseURL)
301}
302
303// UseSandbox replaces the sandbox pointer that every tool in r's
304// registry references. Used to keep the /lock state stable across
305// agent rebuilds (e.g. /login, /model switching providers).
306func (r *Resolved) UseSandbox(s *tools.Sandbox) {
307 if s == nil || r == nil {
308 return
309 }
310 r.Sandbox = s
311 for name, t := range r.ToolRegistry {
312 switch v := t.(type) {
313 case *tools.ReadTool:
314 v.Sandbox = s
315 case *tools.WriteTool:
316 v.Sandbox = s
317 case *tools.EditTool:
318 v.Sandbox = s
319 case *tools.BashTool:
320 v.Sandbox = s
321 }
322 _ = name
323 }
324}
325
326// NewAgent constructs a core.Agent from r. Requires a credential.
327func (r Resolved) NewAgent() *core.Agent {
328 a := core.NewAgent(r.NewClient(), r.Model, r.SystemPrompt, r.ToolRegistry)
329 a.MaxSteps = r.MaxSteps
330 a.Reasoning = r.Reasoning
331 return a
332}
333
334func buildToolRegistry(args Args, cwd string, sandbox *tools.Sandbox) core.Registry {
335 if args.NoTools {
336 return core.Registry{}
337 }
338 all := map[string]core.Tool{
339 "read": &tools.ReadTool{CWD: cwd, Sandbox: sandbox},
340 "write": &tools.WriteTool{CWD: cwd, Sandbox: sandbox},
341 "edit": &tools.EditTool{CWD: cwd, Sandbox: sandbox},
342 "bash": &tools.BashTool{CWD: cwd, Sandbox: sandbox},
343 }
344 reg := core.Registry{}
345 if len(args.Tools) == 0 {
346 for _, t := range all {
347 reg[t.Name()] = t
348 }
349 return reg
350 }
351 for _, name := range args.Tools {
352 if t, ok := all[name]; ok {
353 reg[name] = t
354 }
355 }
356 return reg
357}
358
359func toolSummaries(reg core.Registry, args Args) []ToolSummary {
360 order := []string{"read", "write", "edit", "bash"}
361 var out []ToolSummary
362 for _, name := range order {
363 if t, ok := reg[name]; ok {
364 out = append(out, ToolSummary{Name: t.Name(), Description: t.Description()})
365 }
366 }
367 return out
368}
369
370func firstNonEmpty(vals ...string) string {
371 for _, v := range vals {
372 if v != "" {
373 return v
374 }
375 }
376 return ""
377}
378
379func envVarName(provider string) string {
380 switch provider {
381 case "openai":
382 return "OPENAI"
383 default:
384 return "ANTHROPIC"
385 }
386}