1package agent
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "path/filepath"
8 "runtime"
9 "strings"
10
11 zotdocs "github.com/patriceckhart/zot"
12 "github.com/patriceckhart/zot/packages/agent/skills"
13 "github.com/patriceckhart/zot/packages/agent/tools"
14 "github.com/patriceckhart/zot/packages/core"
15 "github.com/patriceckhart/zot/packages/provider"
16)
17
18// Resolved is the effective configuration after merging CLI, config, defaults.
19type Resolved struct {
20 Provider string
21 Model string
22 Credential string // api key or oauth access token
23 AuthMethod string // "apikey" | "oauth" | "" (no credential yet)
24 AccountID string // ChatGPT account id (for openai oauth), "" otherwise
25 BaseURL string
26 InsecureTLS bool
27 CWD string
28 Reasoning string
29 Temperature *float32
30
31 ToolRegistry core.Registry
32 ToolSummary []ToolSummary
33 SystemPrompt string
34 MaxSteps int
35 Sandbox *tools.Sandbox
36
37 // MaxOutput is the resolved model's maximum output-token budget
38 // (from the catalog). Passed to the agent so each turn requests
39 // the model's full output capacity instead of the provider's
40 // conservative default (e.g. Bedrock's 4096, which truncates
41 // long writes/edits with stopReason=length).
42 MaxOutput int
43
44 // SkillTool is the on-demand skill loader registered with the
45 // agent's tool registry, or nil if no SKILL.md files were
46 // discovered. Exposed so the tui can list / preview skills.
47 SkillTool *skills.Tool
48
49 // Bookkeeping for MergeExtensionTools. Captured at Resolve time
50 // so the system prompt can be rebuilt later without re-running
51 // resolve.
52 systemAppend []string
53 systemCustom string
54 toolDescriptions map[string]string
55}
56
57// HasCredential reports whether a credential was resolved.
58func (r Resolved) HasCredential() bool { return r.Credential != "" }
59
60// MergeExtensionTools folds every tool registered by an extension
61// into r's ToolRegistry and re-renders the system prompt's tool
62// summary so the model sees both built-in and extension tools.
63//
64// Idempotent: calling twice with the same manager state has no
65// effect on the second pass (existing names are preserved). Built-in
66// tools always win on conflict.
67func (r *Resolved) MergeExtensionTools(mgr ExtensionToolSource) {
68 if mgr == nil {
69 return
70 }
71 infos := mgr.Tools()
72 if len(infos) == 0 {
73 return
74 }
75 changed := false
76 for _, info := range infos {
77 if _, exists := r.ToolRegistry[info.Name]; exists {
78 continue
79 }
80 r.ToolRegistry[info.Name] = mgr.NewExtensionTool(info)
81 changed = true
82 }
83 if !changed {
84 return
85 }
86 // Re-render the system prompt with the merged tool list. Skill
87 // addendum is preserved by walking the existing append slice.
88 append_ := r.systemAppend
89 r.SystemPrompt = BuildSystemPrompt(SystemPromptOpts{
90 CWD: r.CWD,
91 Tools: toolSummariesFromRegistry(r.ToolRegistry, r.toolDescriptions),
92 Custom: r.systemCustom,
93 Append: append_,
94 ZotDocsDir: filepath.Join(ZotHome(), "docs"),
95 })
96}
97
98// ExtensionToolSource is the slice of the extension manager that
99// MergeExtensionTools needs. Lives here as an interface so the
100// build package doesn't import packages/agent/extensions (which
101// imports core, which imports... avoid the cycle).
102type ExtensionToolSource interface {
103 Tools() []ExtensionToolInfo
104 NewExtensionTool(info ExtensionToolInfo) core.Tool
105}
106
107// ExtensionToolInfo mirrors extensions.ToolInfo so we can declare
108// ExtensionToolSource here without importing the extensions
109// package. The cli wires a tiny adapter to bridge them.
110type ExtensionToolInfo struct {
111 Extension string
112 Name string
113 Description string
114 Schema []byte
115}
116
117// toolSummariesFromRegistry rebuilds the system-prompt tool list
118// from a (possibly extended) registry, using cached descriptions for
119// the human-readable summary text.
120func toolSummariesFromRegistry(reg core.Registry, cached map[string]string) []ToolSummary {
121 out := make([]ToolSummary, 0, len(reg))
122 for name, t := range reg {
123 desc := t.Description()
124 if d, ok := cached[name]; ok && d != "" {
125 desc = d
126 }
127 out = append(out, ToolSummary{Name: name, Description: desc})
128 }
129 return out
130}
131
132// defaultModelForProvider returns the model id zot prefers when the
133// caller didn't pick one. Mirrors the per-provider switch used at
134// multiple points in Resolve; centralised so the unknown-model
135// recovery path and the no-model-configured path can't drift.
136//
137// Returns the empty string for "ollama", which has no built-in
138// default — the caller is expected to special-case ollama and
139// error or use whatever the user passed.
140func defaultModelForProvider(prov string) string {
141 switch prov {
142 case "openai":
143 return "gpt-5"
144 case "openai-codex":
145 return "gpt-5.5"
146 case "openai-responses":
147 return "gpt-5"
148 case "kimi":
149 return "kimi-for-coding"
150 case "deepseek":
151 return "deepseek-v4-pro"
152 case "google":
153 return "gemini-2.5-pro"
154 case "ollama":
155 return ""
156 case "moonshotai", "moonshotai-cn":
157 return "kimi-k2.6"
158 case "cerebras":
159 return "qwen-3-235b-a22b-instruct-2507"
160 case "groq":
161 return "llama-3.3-70b-versatile"
162 case "xai":
163 return "grok-code-fast-1"
164 case "together":
165 return "Qwen/Qwen3-Coder-480B-A35B-Instruct"
166 case "huggingface":
167 return "moonshotai/Kimi-K2-Instruct"
168 case "openrouter":
169 return "anthropic/claude-sonnet-4.5"
170 case "mistral":
171 return "mistral-large-latest"
172 case "zai":
173 return "glm-4.7"
174 case "xiaomi", "xiaomi-token-plan-ams", "xiaomi-token-plan-cn", "xiaomi-token-plan-sgp":
175 return "mimo-v2.5"
176 case "minimax", "minimax-cn":
177 return "MiniMax-M2.7"
178 case "fireworks":
179 return "accounts/fireworks/models/kimi-k2p6"
180 case "vercel-ai-gateway":
181 return "anthropic/claude-sonnet-4.5"
182 case "opencode":
183 return "claude-sonnet-4-5"
184 case "opencode-go":
185 return "kimi-k2.6"
186 case "amazon-bedrock":
187 return "anthropic.claude-sonnet-4-5-20250929-v1:0"
188 case "google-vertex":
189 return "gemini-2.5-pro"
190 case "azure-openai-responses":
191 return "gpt-5"
192 case "github-copilot":
193 return "claude-sonnet-4.5"
194 default:
195 // Custom providers: pick the first model from the catalog for
196 // that provider, or fall back to the global default.
197 if models := provider.ModelsForProvider(prov); len(models) > 0 {
198 return models[0].ID
199 }
200 return provider.DefaultModel.ID
201 }
202}
203
204// knownProviders is the set of provider ids zot recognises. Used by
205// Resolve to validate args.Provider, by extension-callers, and by the
206// auto-fallback logic that picks any logged-in provider when the user's
207// preferred one has no credentials.
208var knownProviders = []string{
209 "anthropic", "openai", "openai-codex", "openai-responses", "kimi", "deepseek", "google", "ollama",
210 "moonshotai", "moonshotai-cn",
211 "cerebras", "groq", "xai", "together", "huggingface", "openrouter",
212 "mistral", "zai",
213 "xiaomi", "xiaomi-token-plan-ams", "xiaomi-token-plan-cn", "xiaomi-token-plan-sgp",
214 "minimax", "minimax-cn",
215 "fireworks", "vercel-ai-gateway",
216 "opencode", "opencode-go",
217 "amazon-bedrock", "google-vertex", "azure-openai-responses",
218 "github-copilot", "cloudflare-workers-ai", "cloudflare-ai-gateway",
219}
220
221func isKnownProvider(name string) bool {
222 for _, p := range knownProviders {
223 if p == name {
224 return true
225 }
226 }
227 _, ok := provider.CustomProviders()[name]
228 return ok
229}
230
231// isBuiltinProvider reports whether name is in the hardcoded
232// knownProviders list (not a user-defined custom provider).
233func isBuiltinProvider(name string) bool {
234 for _, p := range knownProviders {
235 if p == name {
236 return true
237 }
238 }
239 return false
240}
241
242// providerAliases maps common short / alternate provider names to the
243// canonical id in knownProviders. Users (and other agents) reach for
244// "bedrock" or "vertex" far more naturally than the fully-qualified
245// "amazon-bedrock" / "google-vertex"; without this mapping an alias is
246// treated as an unknown provider and Resolve silently falls back to
247// anthropic, producing a misleading "no credential for anthropic" error
248// after the user explicitly picked, say, bedrock.
249var providerAliases = map[string]string{
250 "bedrock": "amazon-bedrock",
251 "aws-bedrock": "amazon-bedrock",
252 "amazon": "amazon-bedrock",
253 "vertex": "google-vertex",
254 "gcp-vertex": "google-vertex",
255 "gemini": "google",
256 "googleai": "google",
257 "google-ai": "google",
258 "azure": "azure-openai-responses",
259 "azure-openai": "azure-openai-responses",
260 "copilot": "github-copilot",
261 "github": "github-copilot",
262 "codex": "openai-codex",
263 "moonshot": "moonshotai",
264 "kimi-code": "kimi",
265 "ai-gateway": "vercel-ai-gateway",
266 "vercel": "vercel-ai-gateway",
267 "cloudflare": "cloudflare-workers-ai",
268 "workers-ai": "cloudflare-workers-ai",
269 "hf": "huggingface",
270}
271
272// canonicalProvider normalises a user-supplied provider name: trims
273// surrounding whitespace, lower-cases it, and resolves any known alias
274// to its canonical id. Unknown names are returned trimmed/lower-cased
275// and unchanged so the existing unknown-provider handling still runs.
276func canonicalProvider(name string) string {
277 n := strings.ToLower(strings.TrimSpace(name))
278 if n == "" {
279 return n
280 }
281 if canon, ok := providerAliases[n]; ok {
282 return canon
283 }
284 return n
285}
286
287// Resolve merges args, config, and env into a Resolved set.
288//
289// Unlike the earlier version, Resolve NEVER returns an error for
290// missing credentials: the TUI can start without them and launch a
291// login flow. requireCred controls whether missing credentials are a
292// hard error (used by print/json modes).
293func Resolve(args Args, requireCred bool) (Resolved, error) {
294 cfg, _ := LoadConfig()
295
296 // User-requested provider (explicit > config > default).
297 // Normalise common aliases (e.g. "bedrock" -> "amazon-bedrock")
298 // before validation so an alias is never mistaken for an unknown
299 // provider and silently downgraded to anthropic.
300 argProvider := canonicalProvider(args.Provider)
301 provName := firstNonEmpty(argProvider, canonicalProvider(cfg.Provider), "anthropic")
302 if !isKnownProvider(provName) {
303 // Unknown provider (maybe removed or renamed). Fall back to
304 // the first provider that has credentials, or anthropic.
305 // Custom providers (from models.json) are already accepted
306 // by isKnownProvider, so we only reach here for truly unknown
307 // names.
308 provName = "anthropic"
309 if _, _, _, err := ResolveCredentialFull("openai", ""); err == nil {
310 provName = "openai"
311 }
312 if _, _, _, err := ResolveCredentialFull("openai-codex", ""); err == nil {
313 provName = "openai-codex"
314 }
315 if _, _, _, err := ResolveCredentialFull("kimi", ""); err == nil {
316 provName = "kimi"
317 }
318 if _, _, _, err := ResolveCredentialFull("deepseek", ""); err == nil {
319 provName = "deepseek"
320 }
321 if _, _, _, err := ResolveCredentialFull("anthropic", ""); err == nil {
322 provName = "anthropic"
323 }
324 // Reset the saved config so this doesn't keep happening.
325 cfg.Provider = provName
326 cfg.Model = ""
327 _ = SaveConfig(cfg)
328 }
329
330 var (
331 cred string
332 method string
333 accountID string
334 credErr error
335 )
336 if provName == "ollama" {
337 cred = firstNonEmpty(args.APIKey, "ollama")
338 method = "apikey"
339 } else {
340 cred, method, accountID, credErr = ResolveCredentialFull(provName, args.APIKey)
341 }
342
343 // Persist --api-key for custom providers so subsequent runs don't
344 // need to pass it again.
345 if !isBuiltinProvider(provName) && args.APIKey != "" {
346 if store := AuthStoreFor(); store != nil {
347 _ = store.SetAPIKey(provName, args.APIKey)
348 }
349 }
350
351 // If the user did NOT explicitly pick a provider (neither via --provider
352 // nor by saving one in config.json) and the default one has no
353 // credentials, auto-fall-back to whichever provider is actually logged
354 // in. That way running plain `zot` after `/login` (any provider) never
355 // shows a "not logged in" banner.
356 //
357 // Critical: when the user HAS saved a provider in config.json (e.g.
358 // "deepseek" with "deepseek-v4-flash"), that choice is respected even
359 // if no credential is found — the tui will show the login dialog or
360 // surface a clear credential error rather than silently switching to
361 // a completely different provider and model.
362 // autoFellBack tracks whether the provider was changed by the
363 // auto-fallback loop (no explicit provider from CLI or config,
364 // and the default had no credentials). When false, the provider
365 // came from the user's explicit choice (--provider or config.json)
366 // and must be respected, including any model id that may belong
367 // to a different provider in the catalog — for example when using
368 // a gateway/router like OpenRouter with "deepseek/deepseek-v4-flash".
369 var autoFellBack bool
370 userPickedProvider := args.Provider != "" || cfg.Provider != ""
371 if credErr != nil && !userPickedProvider && provName != "ollama" {
372 autoFellBack = true
373 // Scan every known provider (not a hardcoded subset) so any
374 // env-based credential is discovered, e.g. an env-only
375 // amazon-bedrock setup (AWS_BEARER_TOKEN_BEDROCK / AWS_PROFILE /
376 // IAM keys) when no config.json pins the provider, such as after
377 // pointing ZOT_HOME at a fresh home dir. Iteration order of
378 // knownProviders defines fallback priority. ollama is skipped:
379 // it has no credential and would always "match".
380 for _, other := range knownProviders {
381 if other == provName || other == "ollama" {
382 continue
383 }
384 if c, m, a, err := ResolveCredentialFull(other, args.APIKey); err == nil {
385 provName = other
386 cred, method, accountID, credErr = c, m, a, err
387 break
388 }
389 }
390 }
391
392 model := firstNonEmpty(args.Model, cfg.Model)
393 if model == "" {
394 if provName == "ollama" {
395 return Resolved{}, fmt.Errorf("ollama requires --model (e.g. --model llama3)")
396 }
397 model = defaultModelForProvider(provName)
398 }
399 // If the resolved model belongs to a different provider (e.g. config
400 // says gpt-5 but we auto-fell back to anthropic), pick that provider's
401 // default. This override only fires when the provider was auto-fallback-
402 // changed, NOT when the user explicitly configured the pair — gateway/
403 // router providers (openrouter, vercel-ai-gateway, etc.) can serve
404 // models from any provider in the catalog.
405 if autoFellBack && provName != "ollama" {
406 if m, err := provider.FindModel("", model); err == nil && m.Provider != provName {
407 model = defaultModelForProvider(provName)
408 }
409 }
410 resolvedModel, err := provider.FindModel(provName, model)
411 if err != nil && provName == "ollama" {
412 // ollama is intentionally open-catalogue: any model id the
413 // local server understands is valid, even if not in the
414 // baked-in catalog.
415 resolvedModel = provider.Model{
416 Provider: "ollama",
417 ID: model,
418 DisplayName: model,
419 ContextWindow: 32768,
420 MaxOutput: 8192,
421 BaseURL: args.BaseURL,
422 Source: "ollama",
423 }
424 err = nil
425 }
426 // Custom providers are open-catalogue like ollama: any model id the
427 // endpoint understands is valid. Use the provider-level base URL.
428 if err != nil {
429 if cfg, ok := provider.CustomProviders()[provName]; ok {
430 resolvedModel = provider.Model{
431 Provider: provName,
432 ID: model,
433 DisplayName: model,
434 BaseURL: cfg.BaseURL,
435 Source: "user",
436 }
437 err = nil
438 }
439 }
440 if cfg, ok := provider.CustomProviders()[provName]; ok && err == nil && resolvedModel.BaseURL == "" && cfg.BaseURL != "" {
441 // Fall back to the provider-level base URL when the model does
442 // not define its own endpoint.
443 resolvedModel.BaseURL = cfg.BaseURL
444 }
445 if err != nil {
446 // The model the user (or persisted config) asked for is no
447 // longer in the active catalogue — they probably removed it
448 // from their models.json or upgraded zot and the id changed.
449 // Refusing to launch is the wrong move: it strands the user
450 // with no way to even open the TUI and pick a new model.
451 // Fall back to the provider's default, warn on stderr, and,
452 // when the stale id came from the persisted config (not an
453 // explicit --model flag), repair the config so the warning
454 // doesn't repeat on every launch.
455
456 // Gateway providers can accept route-qualified ids that are not in
457 // zot's local catalog yet, for example OpenRouter's
458 // "deepseek/deepseek-v4-flash". Preserve only route-qualified ids;
459 // plain unknown values are likely typos and should still fall back.
460 if isGatewayProvider(provName) && isGatewayRoutedModelID(model) {
461 resolvedModel = provider.Model{
462 Provider: provName,
463 ID: model,
464 DisplayName: model,
465 ContextWindow: 1000000,
466 MaxOutput: 64000,
467 BaseURL: "",
468 Source: "gateway",
469 }
470 err = nil
471 // Don't repair config — the routed model id may be valid upstream.
472 } else {
473 fallback := defaultModelForProvider(provName)
474 fm, ferr := provider.FindModel(provName, fallback)
475 if ferr != nil {
476 // Even the provider default is gone (catastrophic
477 // catalogue trim). Last resort: any model on this
478 // provider, then the global DefaultModel.
479 if candidates := provider.ModelsForProvider(provName); len(candidates) > 0 {
480 fm = candidates[0]
481 ferr = nil
482 } else {
483 fm = provider.DefaultModel
484 ferr = nil
485 }
486 }
487 fmt.Fprintf(os.Stderr,
488 "zot: model %q is not in the active catalogue; using %q instead. Pick a different model with --model or /model.\n",
489 model, fm.ID)
490 if args.Model == "" && cfg.Model == model {
491 cfg.Model = fm.ID
492 _ = SaveConfig(cfg)
493 }
494 resolvedModel = fm
495 model = fm.ID
496 }
497 }
498
499 explicitBaseURL := args.BaseURL != "" || (resolvedModel.Source == "user" && resolvedModel.BaseURL != "")
500
501 // If the model defines a base URL (e.g. local ollama) and the
502 // user didn't pass --base-url, use the model's URL. For ollama,
503 // keep http://localhost:11434 as a fallback only after the model
504 // metadata has had a chance to provide a custom baseUrl.
505 if args.BaseURL == "" && resolvedModel.BaseURL != "" {
506 args.BaseURL = resolvedModel.BaseURL
507 }
508 if args.BaseURL == "" && provName == "ollama" {
509 args.BaseURL = "http://localhost:11434"
510 }
511
512 // Insecure TLS is intentionally scoped to explicit custom endpoints.
513 // Built-in provider base URLs, auth calls, and model discovery keep normal
514 // certificate verification even when --insecure is present.
515 insecureTLS := (args.InsecureTLS || cfg.Insecure) && explicitBaseURL
516
517 // If the model has a base URL, credentials are optional (local
518 // models like ollama don't need real API keys).
519 if resolvedModel.BaseURL != "" && credErr != nil {
520 cred = "ollama"
521 credErr = nil
522 requireCred = false
523 }
524
525 if credErr != nil && requireCred {
526 return Resolved{}, fmt.Errorf("%w; set %s_API_KEY, pass --api-key, or run `zot` and /login",
527 credErr, envVarName(provName))
528 }
529
530 sandbox := tools.NewSandbox(args.CWD)
531 reg := buildToolRegistry(args, args.CWD, sandbox)
532
533 docsDir, _ := zotdocs.EnsureInstalled(ZotHome())
534
535 // Skill discovery: scan project + global locations + built-in
536 // skills shipped with the binary. If any are found, register
537 // the on-demand `skill` loader tool plus a system-prompt
538 // manifest so the model knows what's available.
539 //
540 // --no-skill bypasses the entire mechanism: no manifest in the
541 // system prompt, no `skill` tool in the registry. Useful for a
542 // clean-room run with zero extra context biasing the model.
543 var (
544 discovered []*skills.Skill
545 skillTool *skills.Tool
546 skillAddendum string
547 )
548 if !args.NoSkill {
549 homeDir, _ := os.UserHomeDir()
550 discovered, _ = skills.Discover(ZotHome(), args.CWD, homeDir, args.WithSkills)
551 if len(discovered) > 0 {
552 skillTool = skills.NewTool(discovered)
553 reg[skillTool.Name()] = skillTool
554 skillAddendum = skills.SystemPromptAddendum(discovered)
555 }
556 }
557 _ = skillTool
558
559 summaries := toolSummaries(reg, args)
560
561 append_ := append([]string(nil), args.AppendSystemPrompt...)
562 if agentsAddendum := readAgentsContext(args.CWD, ZotHome()); agentsAddendum != "" {
563 append_ = append(append_, agentsAddendum)
564 }
565 if skillAddendum != "" {
566 append_ = append(append_, skillAddendum)
567 }
568 if AutoSwarmEnabled() {
569 append_ = append(append_, AutoSwarmSystemAddendum)
570 }
571
572 // Custom system prompt resolution order:
573 // 1. --system-prompt flag (highest priority; ad-hoc per run)
574 // 2. $ZOT_HOME/SYSTEM.md (persistent user override)
575 // 3. built-in default (defaultIdentity + defaultGuidelines)
576 custom := args.SystemPrompt
577 if custom == "" {
578 custom = readUserSystemPrompt(ZotHome())
579 }
580
581 sys := BuildSystemPrompt(SystemPromptOpts{
582 CWD: args.CWD,
583 Tools: summaries,
584 Custom: custom,
585 Append: append_,
586 ZotDocsDir: docsDir,
587 })
588
589 reasoning := provider.NormalizeReasoning(firstNonEmpty(args.Reasoning, cfg.Reasoning))
590 temperature := args.Temperature
591 if temperature == nil {
592 temperature = cfg.Temperature
593 }
594
595 max := args.MaxSteps // 0 = unlimited
596
597 return Resolved{
598 Provider: provName,
599 Model: model,
600 Credential: cred,
601 AuthMethod: method,
602 AccountID: accountID,
603 BaseURL: args.BaseURL,
604 InsecureTLS: insecureTLS,
605 CWD: args.CWD,
606 Reasoning: reasoning,
607 Temperature: temperature,
608 ToolRegistry: reg,
609 ToolSummary: summaries,
610 SystemPrompt: sys,
611 MaxSteps: max,
612 MaxOutput: resolvedModel.MaxOutput,
613 Sandbox: sandbox,
614 SkillTool: skillTool,
615 systemAppend: append_,
616 systemCustom: custom,
617 toolDescriptions: descMapFromSummaries(summaries),
618 }, nil
619}
620
621// readUserSystemPrompt looks for $ZOT_HOME/SYSTEM.md and returns its
622// trimmed contents, or "" when the file is missing / unreadable /
623// empty. Errors are intentionally swallowed: the file is optional,
624// and any failure to read it should fall back to the built-in
625// default system prompt rather than crash the run.
626func readUserSystemPrompt(zotHome string) string {
627 if zotHome == "" {
628 return ""
629 }
630 path := filepath.Join(zotHome, "SYSTEM.md")
631 raw, err := os.ReadFile(path)
632 if err != nil {
633 return ""
634 }
635 return strings.TrimSpace(string(raw))
636}
637
638// readAgentsContext loads optional AGENTS.md instruction files. No
639// default file is created or required: zot only includes files that
640// already exist. Global instructions ($ZOT_HOME/AGENTS.md) come first,
641// followed by project instructions from the top-most parent down to cwd.
642func readAgentsContext(cwd, zotHome string) string {
643 type contextFile struct {
644 path string
645 content string
646 }
647 var files []contextFile
648 seen := map[string]bool{}
649 add := func(path string) {
650 if path == "" {
651 return
652 }
653 abs, err := filepath.Abs(path)
654 if err == nil {
655 path = abs
656 }
657 if seen[path] {
658 return
659 }
660 raw, err := os.ReadFile(path)
661 if err != nil {
662 return
663 }
664 content := strings.TrimSpace(string(raw))
665 if content == "" {
666 return
667 }
668 seen[path] = true
669 files = append(files, contextFile{path: path, content: content})
670 }
671 addFirstFromDir := func(dir string) {
672 if dir == "" {
673 return
674 }
675 for _, name := range []string{"AGENTS.md", "AGENTS.MD"} {
676 path := filepath.Join(dir, name)
677 if _, err := os.Stat(path); err == nil {
678 add(path)
679 return
680 }
681 }
682 }
683
684 addFirstFromDir(zotHome)
685
686 if cwd != "" {
687 abs, err := filepath.Abs(cwd)
688 if err == nil {
689 cwd = abs
690 }
691 var dirs []string
692 for dir := filepath.Clean(cwd); ; dir = filepath.Dir(dir) {
693 dirs = append(dirs, dir)
694 parent := filepath.Dir(dir)
695 if parent == dir {
696 break
697 }
698 }
699 for i := len(dirs) - 1; i >= 0; i-- {
700 addFirstFromDir(dirs[i])
701 }
702 }
703
704 if len(files) == 0 {
705 return ""
706 }
707 var sb strings.Builder
708 sb.WriteString("Project context instructions loaded from AGENTS.md files. Follow them when working in this repository. Later files are more specific and may override earlier ones.\n")
709 for _, f := range files {
710 fmt.Fprintf(&sb, "\n## %s\n\n%s\n", f.path, f.content)
711 }
712 return strings.TrimSpace(sb.String())
713}
714
715// descMapFromSummaries indexes the human-readable descriptions for
716// the renderToolsSection rebuild path.
717func descMapFromSummaries(summaries []ToolSummary) map[string]string {
718 out := make(map[string]string, len(summaries))
719 for _, s := range summaries {
720 out[s.Name] = s.Description
721 }
722 return out
723}
724
725// NewClient returns a provider.Client for r, choosing the auth mode
726// based on r.AuthMethod. Panics if no credential is present; callers
727// must check HasCredential() first.
728func (r Resolved) NewClient() provider.Client {
729 if !r.HasCredential() {
730 panic("NewClient called without credential; check HasCredential first")
731 }
732 wrap := r.withHTTPClient
733 switch r.Provider {
734 case "ollama":
735 return wrap(provider.NewOpenAI(r.Credential, r.BaseURL))
736 case "kimi":
737 // kimi-coding speaks anthropic-messages on api.kimi.com/coding.
738 // Subscription OAuth (refreshed) wraps the same Anthropic-shaped client.
739 inner := wrap(provider.NewKimiCodingWithHeaders(r.Credential, r.BaseURL, kimiCodeHeaders()))
740 if r.AuthMethod == "oauth" {
741 return r.wrapWithRefresh(inner)
742 }
743 return inner
744 case "moonshotai":
745 return wrap(provider.NewMoonshot(r.Credential, r.BaseURL))
746 case "moonshotai-cn":
747 return wrap(provider.NewMoonshotCN(r.Credential, r.BaseURL))
748 case "deepseek":
749 return wrap(provider.NewDeepSeek(r.Credential, r.BaseURL))
750 case "openai":
751 return wrap(provider.NewOpenAI(r.Credential, r.BaseURL))
752 case "openai-codex":
753 inner := wrap(provider.NewOpenAICodex(r.Credential, r.AccountID, r.BaseURL))
754 return r.wrapWithRefresh(inner)
755 case "openai-responses":
756 // Public OpenAI Responses API (api.openai.com/v1/responses) via
757 // API key. Separate provider from `openai` (Chat Completions) and
758 // from `openai-codex` (ChatGPT subscription OAuth).
759 return wrap(provider.NewOpenAIResponses(r.Credential, r.BaseURL))
760 case "google":
761 return wrap(provider.NewGemini(r.Credential, r.BaseURL))
762 case "cerebras":
763 return wrap(provider.NewCerebras(r.Credential, r.BaseURL))
764 case "groq":
765 return wrap(provider.NewGroq(r.Credential, r.BaseURL))
766 case "xai":
767 return wrap(provider.NewXAI(r.Credential, r.BaseURL))
768 case "together":
769 return wrap(provider.NewTogether(r.Credential, r.BaseURL))
770 case "huggingface":
771 return wrap(provider.NewHuggingFace(r.Credential, r.BaseURL))
772 case "openrouter":
773 return wrap(provider.NewOpenRouter(r.Credential, r.BaseURL))
774 case "zai":
775 return wrap(provider.NewZAI(r.Credential, r.BaseURL))
776 case "xiaomi":
777 return wrap(provider.NewXiaomi(r.Credential, r.BaseURL))
778 case "xiaomi-token-plan-ams":
779 return wrap(provider.NewXiaomiTokenPlan("ams", r.Credential, r.BaseURL))
780 case "xiaomi-token-plan-cn":
781 return wrap(provider.NewXiaomiTokenPlan("cn", r.Credential, r.BaseURL))
782 case "xiaomi-token-plan-sgp":
783 return wrap(provider.NewXiaomiTokenPlan("sgp", r.Credential, r.BaseURL))
784 case "opencode":
785 return wrap(provider.NewOpenCode(r.Credential, r.BaseURL))
786 case "opencode-go":
787 return wrap(provider.NewOpenCodeGo(r.Credential, r.BaseURL))
788 case "minimax":
789 return wrap(provider.NewMinimaxAnthropic(r.Credential, r.BaseURL))
790 case "minimax-cn":
791 return wrap(provider.NewMinimaxCNAnthropic(r.Credential, r.BaseURL))
792 case "fireworks":
793 return wrap(provider.NewFireworksAnthropic(r.Credential, r.BaseURL))
794 case "vercel-ai-gateway":
795 return wrap(provider.NewVercelGatewayAnthropic(r.Credential, r.BaseURL))
796 case "mistral":
797 return wrap(provider.NewMistral(r.Credential, r.BaseURL))
798 case "amazon-bedrock":
799 return wrap(provider.NewBedrock(r.Credential, r.BaseURL))
800 case "google-vertex":
801 return wrap(provider.NewGoogleVertex(r.Credential, r.BaseURL))
802 case "azure-openai-responses":
803 return wrap(provider.NewAzureOpenAIResponses(r.Credential, r.BaseURL))
804 case "github-copilot":
805 return wrap(provider.NewGithubCopilot(r.Credential, r.BaseURL))
806 case "cloudflare-workers-ai":
807 return wrap(provider.NewCloudflareWorkersAI(r.Credential, r.BaseURL))
808 case "cloudflare-ai-gateway":
809 return wrap(provider.NewCloudflareAIGateway(r.Credential, r.BaseURL))
810 default:
811 // Custom providers: choose wire format from the models.json api field.
812 if cfg, ok := provider.CustomProviders()[r.Provider]; ok {
813 switch cfg.API {
814 case "anthropic":
815 return wrap(provider.NewAnthropicCompat(r.Provider, r.Credential, r.BaseURL))
816 default: // "openai"
817 return wrap(provider.NewOpenAICompat(r.Provider, r.Credential, r.BaseURL, ""))
818 }
819 }
820 if r.AuthMethod == "oauth" {
821 inner := wrap(provider.NewAnthropicOAuth(r.Credential, r.BaseURL))
822 return r.wrapWithRefresh(inner)
823 }
824 return wrap(provider.NewAnthropic(r.Credential, r.BaseURL))
825 }
826}
827
828func (r Resolved) withHTTPClient(c provider.Client) provider.Client {
829 if !r.InsecureTLS {
830 return c
831 }
832 return provider.WithHTTPClient(c, provider.NewHTTPClient(true))
833}
834
835// wrapWithRefresh wraps an OAuth client so the access token is
836// refreshed automatically before each API call. Without this, long
837// sessions (hours) silently fail when the 1-hour token expires.
838func (r Resolved) wrapWithRefresh(inner provider.Client) provider.Client {
839 provName := r.Provider
840 tokenProvider := provName
841 if provName == "openai-codex" {
842 tokenProvider = "openai"
843 }
844 baseURL := r.BaseURL
845 accountID := r.AccountID
846
847 refreshFn := func(ctx context.Context) (string, error) {
848 tok, err := refreshIfExpired(tokenProvider, loadOAuthToken(tokenProvider))
849 if err != nil {
850 return "", err
851 }
852 return tok.AccessToken, nil
853 }
854
855 factory := func(token string) provider.Client {
856 switch provName {
857 case "openai-codex":
858 return r.withHTTPClient(provider.NewOpenAICodex(token, accountID, baseURL))
859 case "kimi":
860 // anthropic-messages on api.kimi.com/coding.
861 return r.withHTTPClient(provider.NewKimiCodingWithHeaders(token, baseURL, kimiCodeHeaders()))
862 default:
863 return r.withHTTPClient(provider.NewAnthropicOAuth(token, baseURL))
864 }
865 }
866
867 return provider.NewRefreshingClient(inner, refreshFn, factory)
868}
869
870// UseSandbox replaces the sandbox pointer that every tool in r's
871// registry references. Used to keep the /jail state stable across
872// agent rebuilds (e.g. /login, /model switching providers).
873func (r *Resolved) UseSandbox(s *tools.Sandbox) {
874 if s == nil || r == nil {
875 return
876 }
877 r.Sandbox = s
878 for name, t := range r.ToolRegistry {
879 switch v := t.(type) {
880 case *tools.ReadTool:
881 v.Sandbox = s
882 case *tools.WriteTool:
883 v.Sandbox = s
884 case *tools.EditTool:
885 v.Sandbox = s
886 case *tools.BashTool:
887 v.Sandbox = s
888 }
889 _ = name
890 }
891}
892
893// NewAgent constructs a core.Agent from r. Requires a credential.
894func (r Resolved) NewAgent() *core.Agent {
895 a := core.NewAgent(r.NewClient(), r.Model, r.SystemPrompt, r.ToolRegistry)
896 a.MaxSteps = r.MaxSteps
897 a.MaxTokens = r.MaxOutput
898 a.Reasoning = r.Reasoning
899 a.Temperature = r.Temperature
900 return a
901}
902
903func buildToolRegistry(args Args, cwd string, sandbox *tools.Sandbox) core.Registry {
904 if args.NoTools {
905 return core.Registry{}
906 }
907 all := map[string]core.Tool{
908 "read": &tools.ReadTool{CWD: cwd, Sandbox: sandbox},
909 "write": &tools.WriteTool{CWD: cwd, Sandbox: sandbox},
910 "edit": &tools.EditTool{CWD: cwd, Sandbox: sandbox},
911 "bash": &tools.BashTool{CWD: cwd, Sandbox: sandbox},
912 }
913 reg := core.Registry{}
914 if len(args.Tools) == 0 {
915 for _, t := range all {
916 reg[t.Name()] = t
917 }
918 return reg
919 }
920 for _, name := range args.Tools {
921 if t, ok := all[name]; ok {
922 reg[name] = t
923 }
924 }
925 return reg
926}
927
928func toolSummaries(reg core.Registry, args Args) []ToolSummary {
929 order := []string{"read", "write", "edit", "bash"}
930 var out []ToolSummary
931 for _, name := range order {
932 if t, ok := reg[name]; ok {
933 out = append(out, ToolSummary{Name: t.Name(), Description: t.Description()})
934 }
935 }
936 return out
937}
938
939func firstNonEmpty(vals ...string) string {
940 for _, v := range vals {
941 if v != "" {
942 return v
943 }
944 }
945 return ""
946}
947
948func kimiCodeHeaders() map[string]string {
949 host, _ := os.Hostname()
950 if host == "" {
951 host = "unknown"
952 }
953 deviceID := ""
954 if home, err := os.UserHomeDir(); err == nil {
955 if b, err := os.ReadFile(filepath.Join(home, ".kimi", "device_id")); err == nil {
956 deviceID = strings.TrimSpace(string(b))
957 }
958 }
959 if deviceID == "" {
960 deviceID = "zot"
961 }
962 return map[string]string{
963 "User-Agent": "KimiCLI/1.41.0",
964 "X-Msh-Platform": "kimi_cli",
965 "X-Msh-Version": "1.41.0",
966 "X-Msh-Device-Name": host,
967 "X-Msh-Device-Model": runtime.GOOS + "-" + runtime.GOARCH,
968 "X-Msh-Os-Version": runtime.GOOS,
969 "X-Msh-Device-Id": deviceID,
970 }
971}
972
973func envVarName(provider string) string {
974 switch provider {
975 case "openai", "openai-codex", "openai-responses":
976 return "OPENAI"
977 case "kimi":
978 return "KIMI"
979 case "deepseek":
980 return "DEEPSEEK"
981 case "google":
982 return "GEMINI"
983 case "ollama":
984 return "OLLAMA"
985 case "moonshotai", "moonshotai-cn":
986 return "MOONSHOT"
987 case "groq":
988 return "GROQ"
989 case "xai":
990 return "XAI"
991 case "cerebras":
992 return "CEREBRAS"
993 case "together":
994 return "TOGETHER"
995 case "huggingface":
996 return "HF"
997 case "openrouter":
998 return "OPENROUTER"
999 case "mistral":
1000 return "MISTRAL"
1001 case "zai":
1002 return "ZAI"
1003 case "xiaomi":
1004 return "XIAOMI"
1005 case "xiaomi-token-plan-ams":
1006 return "XIAOMI_TOKEN_PLAN_AMS"
1007 case "xiaomi-token-plan-cn":
1008 return "XIAOMI_TOKEN_PLAN_CN"
1009 case "xiaomi-token-plan-sgp":
1010 return "XIAOMI_TOKEN_PLAN_SGP"
1011 case "minimax":
1012 return "MINIMAX"
1013 case "minimax-cn":
1014 return "MINIMAX_CN"
1015 case "fireworks":
1016 return "FIREWORKS"
1017 case "vercel-ai-gateway":
1018 return "AI_GATEWAY"
1019 case "opencode", "opencode-go":
1020 return "OPENCODE"
1021 case "github-copilot":
1022 return "COPILOT_GITHUB_TOKEN"
1023 case "cloudflare-workers-ai", "cloudflare-ai-gateway":
1024 return "CLOUDFLARE"
1025 case "amazon-bedrock":
1026 return "AWS"
1027 case "google-vertex":
1028 return "GOOGLE_CLOUD"
1029 case "azure-openai-responses":
1030 return "AZURE_OPENAI"
1031 default:
1032 return "ANTHROPIC"
1033 }
1034}