1// Package subagents discovers named agent profiles that can be selected by
2// zut's subagent supervisor. Profiles use the common markdown/frontmatter layout:
3// a YAML-like metadata block followed by the agent's system prompt.
4//
5// Discovery prefers explicitly configured directories, then the shared
6// ~/.agents/agents directory, and finally the optional ~/.pi/agent/agents
7// compatibility directory. Profiles are metadata plus instructions; the main
8// agent sees only the compact manifest, while a selected child loads the full
9// profile itself.
10package subagents
11
12import (
13 "fmt"
14 "os"
15 "path/filepath"
16 "sort"
17 "strconv"
18 "strings"
19)
20
21const maxProfileBytes = 1 << 20
22
23// Profile is one discovered named subagent definition.
24type Profile struct {
25 Name string
26 Description string
27 SystemPrompt string
28 Tools []string
29 Model string
30 Provider string
31 Thinking string
32
33 // Nil means the profile did not specify whether fast mode is enabled.
34 FastMode *bool
35
36 // SystemPromptMode is "append" (the default) or "replace".
37 SystemPromptMode string
38
39 // Nil means the profile did not specify the inheritance behavior.
40 InheritProjectContext *bool
41 InheritSkills *bool
42
43 Path string
44 Source string
45}
46
47// Discover returns profiles in precedence order, sorted by name. A profile
48// with the same name in a higher-priority directory shadows lower-priority
49// copies. Missing directories are normal and do not produce errors.
50func Discover(cwd, userHome string) ([]*Profile, []error) {
51 seen := make(map[string]*Profile)
52 var errs []error
53
54 for _, loc := range searchDirs(cwd, userHome) {
55 entries, err := os.ReadDir(loc.dir)
56 if err != nil {
57 if os.IsNotExist(err) {
58 if info, statErr := os.Stat(loc.dir); statErr == nil && !info.IsDir() {
59 errs = append(errs, fmt.Errorf("read subagent directory %s: not a directory", loc.dir))
60 }
61 } else {
62 errs = append(errs, fmt.Errorf("read subagent directory %s: %w", loc.dir, err))
63 }
64 continue
65 }
66 for _, entry := range entries {
67 if !entry.Type().IsRegular() || !strings.HasSuffix(strings.ToLower(entry.Name()), ".md") {
68 continue
69 }
70 path := filepath.Join(loc.dir, entry.Name())
71 profile, err := load(path, loc.label)
72 if err != nil {
73 if !os.IsNotExist(err) {
74 errs = append(errs, fmt.Errorf("read subagent profile %s: %w", path, err))
75 }
76 continue
77 }
78 if !validName(profile.Name) || profile.SystemPrompt == "" {
79 continue
80 }
81 if _, exists := seen[profile.Name]; exists {
82 continue
83 }
84 seen[profile.Name] = profile
85 }
86 }
87
88 out := make([]*Profile, 0, len(seen))
89 for _, profile := range seen {
90 out = append(out, profile)
91 }
92 sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
93 return out, errs
94}
95
96// Find returns a profile by its exact name, or nil when it is unavailable.
97func Find(profiles []*Profile, name string) *Profile {
98 name = strings.TrimSpace(name)
99 for _, profile := range profiles {
100 if profile != nil && profile.Name == name {
101 return profile
102 }
103 }
104 return nil
105}
106
107// ModelSelection splits a provider-qualified model value such as
108// "openai-codex/gpt-5.6-luna". Explicit provider metadata must be paired
109// with an unqualified model; model IDs may contain slashes when no provider
110// metadata is supplied.
111func (p *Profile) ModelSelection() (provider, model string) {
112 if p == nil {
113 return "", ""
114 }
115 provider = strings.TrimSpace(p.Provider)
116 model = strings.TrimSpace(p.Model)
117 if provider == "" {
118 if before, after, ok := strings.Cut(model, "/"); ok {
119 provider, model = strings.TrimSpace(before), strings.TrimSpace(after)
120 }
121 }
122 return provider, model
123}
124
125// SystemPromptAddendum renders the compact [subagents_list] manifest for the
126// parent model. Full profile bodies are intentionally omitted: the selected
127// child loads its own instructions, and keeping them out of every parent turn
128// avoids unnecessary context and accidental instruction mixing.
129func SystemPromptAddendum(profiles []*Profile) string {
130 if len(profiles) == 0 {
131 return ""
132 }
133 var sb strings.Builder
134 sb.WriteString("[subagents_list]\n")
135 sb.WriteString("Named subagents available to subagent_spawn. Choose the profile whose description best matches the independent task and pass its name as the tool's agent field. The selected profile's instructions, model, thinking level, tool limits, and fast-mode preference are applied to the child.\n")
136 for _, profile := range profiles {
137 if profile == nil {
138 continue
139 }
140 name := manifestValue(profile.Name)
141 description := manifestValue(profile.Description)
142 if description == "" {
143 description = "(no description)"
144 }
145 metadata := make([]string, 0, 5)
146 if model := manifestValue(profile.Model); model != "" {
147 metadata = append(metadata, "model="+model)
148 }
149 if provider := manifestValue(profile.Provider); provider != "" {
150 metadata = append(metadata, "provider="+provider)
151 }
152 if thinking := manifestValue(profile.Thinking); thinking != "" {
153 metadata = append(metadata, "thinking="+thinking)
154 }
155 if len(profile.Tools) > 0 {
156 metadata = append(metadata, "tools="+manifestValue(strings.Join(profile.Tools, ",")))
157 }
158 if profile.FastMode != nil {
159 metadata = append(metadata, "fastMode="+strconv.FormatBool(*profile.FastMode))
160 }
161 if len(metadata) > 0 {
162 fmt.Fprintf(&sb, "- %s [%s]: %s\n", name, strings.Join(metadata, " "), description)
163 } else {
164 fmt.Fprintf(&sb, "- %s: %s\n", name, description)
165 }
166 }
167 sb.WriteString("[/subagents_list]")
168 return sb.String()
169}
170
171type location struct {
172 dir string
173 label string
174}
175
176func searchDirs(cwd, userHome string) []location {
177 var out []location
178 add := func(dir, label string) {
179 if strings.TrimSpace(dir) != "" {
180 out = append(out, location{dir: dir, label: label})
181 }
182 }
183 if extra := os.Getenv("ZUT_AGENT_PROFILES"); extra != "" {
184 for _, dir := range filepath.SplitList(extra) {
185 dir = strings.TrimSpace(dir)
186 if dir != "" && !filepath.IsAbs(dir) && strings.TrimSpace(cwd) != "" {
187 dir = filepath.Join(cwd, dir)
188 }
189 add(dir, "configured")
190 }
191 }
192 if userHome != "" {
193 add(filepath.Join(userHome, ".agents", "agents"), "global (agents)")
194 // This is an additional compatibility location. The shared .agents
195 // path above remains zut's documented default.
196 add(filepath.Join(userHome, ".pi", "agent", "agents"), "global (pi)")
197 }
198 return out
199}
200
201func load(path, source string) (*Profile, error) {
202 info, err := os.Stat(path)
203 if err != nil {
204 return nil, err
205 }
206 if !info.Mode().IsRegular() {
207 return nil, fmt.Errorf("not a regular file")
208 }
209 if info.Size() > maxProfileBytes {
210 return nil, fmt.Errorf("profile is larger than %d bytes", maxProfileBytes)
211 }
212 raw, err := os.ReadFile(path)
213 if err != nil {
214 return nil, err
215 }
216 front, body, err := splitFrontmatter(string(raw))
217 if err != nil {
218 return nil, err
219 }
220 values, lists := parseFrontmatter(front)
221 name := unquote(values["name"])
222 if name == "" {
223 name = strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
224 }
225 thinking, err := parseThinkingValue(values["thinking"], "thinking")
226 if err != nil {
227 return nil, err
228 }
229 reasoning, err := parseThinkingValue(values["reasoning"], "reasoning")
230 if err != nil {
231 return nil, err
232 }
233 if thinking == "" {
234 thinking = reasoning
235 }
236 model := strings.TrimSpace(unquote(values["model"]))
237 provider := strings.TrimSpace(unquote(values["provider"]))
238 if provider != "" && strings.Contains(model, "/") {
239 return nil, fmt.Errorf("model must not include a provider when provider is set")
240 }
241 profile := &Profile{
242 Name: strings.TrimSpace(name),
243 Description: strings.TrimSpace(unquote(values["description"])),
244 SystemPrompt: strings.TrimSpace(body),
245 Tools: lists["tools"],
246 Model: model,
247 Provider: provider,
248 Thinking: thinking,
249 Path: path,
250 Source: source,
251 }
252 profile.SystemPromptMode = "append"
253 if mode, ok := values["systempromptmode"]; ok {
254 switch strings.ToLower(strings.TrimSpace(unquote(mode))) {
255 case "", "append":
256 case "replace":
257 profile.SystemPromptMode = "replace"
258 default:
259 return nil, fmt.Errorf("systemPromptMode must be append or replace")
260 }
261 }
262 if raw, ok := values["inheritprojectcontext"]; ok {
263 value, parsed := parseOptionalBool(raw)
264 if !parsed {
265 return nil, fmt.Errorf("inheritProjectContext must be true or false")
266 }
267 profile.InheritProjectContext = &value
268 }
269 if raw, ok := values["inheritskills"]; ok {
270 value, parsed := parseOptionalBool(raw)
271 if !parsed {
272 return nil, fmt.Errorf("inheritSkills must be true or false")
273 }
274 profile.InheritSkills = &value
275 }
276 if raw, ok := values["fastmode"]; ok {
277 value, parsed := parseOptionalBool(raw)
278 if !parsed {
279 return nil, fmt.Errorf("fastMode must be true or false")
280 }
281 profile.FastMode = &value
282 }
283 return profile, nil
284}
285
286func splitFrontmatter(raw string) (front, body string, err error) {
287 rest := strings.TrimLeft(raw, " \t\r\n")
288 firstEnd := strings.IndexByte(rest, '\n')
289 if firstEnd < 0 || strings.TrimSpace(rest[:firstEnd]) != "---" {
290 return "", raw, nil
291 }
292 rest = rest[firstEnd+1:]
293 for offset := 0; offset <= len(rest); {
294 rel := strings.Index(rest[offset:], "\n---")
295 if rel < 0 {
296 // A document that starts a frontmatter block but never closes
297 // it is malformed, not a body-only profile.
298 return "", "", fmt.Errorf("frontmatter: missing closing delimiter")
299 }
300 end := offset + rel
301 after := end + len("\n---")
302 if after == len(rest) || rest[after] == '\n' || rest[after] == '\r' {
303 return rest[:end], strings.TrimLeft(rest[after:], " \t\r\n"), nil
304 }
305 offset = after
306 }
307 return "", raw, nil
308}
309
310func parseFrontmatter(front string) (map[string]string, map[string][]string) {
311 values := make(map[string]string)
312 lists := make(map[string][]string)
313 lines := strings.Split(front, "\n")
314 for i := 0; i < len(lines); i++ {
315 line := lines[i]
316 trimmed := strings.TrimSpace(line)
317 if trimmed == "" || strings.HasPrefix(trimmed, "#") || strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") {
318 continue
319 }
320 colon := strings.IndexByte(trimmed, ':')
321 if colon < 0 {
322 continue
323 }
324 key := normalizeKey(trimmed[:colon])
325 value := strings.TrimSpace(trimmed[colon+1:])
326 if value == "" {
327 var items []string
328 for j := i + 1; j < len(lines); j++ {
329 next := strings.TrimSpace(lines[j])
330 if next == "" {
331 continue
332 }
333 if !strings.HasPrefix(next, "-") || (len(lines[j]) > 0 && !strings.HasPrefix(lines[j], " ") && !strings.HasPrefix(lines[j], "\t")) {
334 break
335 }
336 items = append(items, unquote(strings.TrimSpace(strings.TrimPrefix(next, "-"))))
337 i = j
338 }
339 if len(items) > 0 {
340 lists[key] = items
341 }
342 continue
343 }
344 if key == "tools" {
345 lists[key] = parseList(value)
346 continue
347 }
348 values[key] = unquote(value)
349 }
350 return values, lists
351}
352
353func normalizeKey(key string) string {
354 key = strings.ToLower(strings.TrimSpace(key))
355 key = strings.ReplaceAll(key, "-", "")
356 key = strings.ReplaceAll(key, "_", "")
357 return key
358}
359
360func parseList(value string) []string {
361 value = strings.TrimSpace(value)
362 value = strings.TrimPrefix(value, "[")
363 value = strings.TrimSuffix(value, "]")
364 if value == "" {
365 return nil
366 }
367 parts := strings.Split(value, ",")
368 out := make([]string, 0, len(parts))
369 for _, part := range parts {
370 if item := strings.TrimSpace(unquote(part)); item != "" {
371 out = append(out, item)
372 }
373 }
374 return out
375}
376
377func parseThinkingValue(value, field string) (string, error) {
378 switch strings.ToLower(strings.TrimSpace(unquote(value))) {
379 case "":
380 return "", nil
381 case "off":
382 return "off", nil
383 case "minimal", "minimum":
384 return "minimum", nil
385 case "low", "medium", "high", "xhigh", "max":
386 return strings.ToLower(strings.TrimSpace(unquote(value))), nil
387 case "maximum":
388 return "xhigh", nil
389 default:
390 return "", fmt.Errorf("%s must be off|minimum|low|medium|high|xhigh|max", field)
391 }
392}
393
394func parseOptionalBool(value string) (bool, bool) {
395 parsed, err := strconv.ParseBool(strings.TrimSpace(unquote(value)))
396 return parsed, err == nil
397}
398
399func validName(name string) bool {
400 name = strings.TrimSpace(name)
401 if name == "" || len(name) > 128 {
402 return false
403 }
404 for _, r := range name {
405 if r == '/' || r == '\\' || r == '\x00' || r < 0x20 {
406 return false
407 }
408 }
409 return true
410}
411
412func manifestValue(value string) string {
413 return strings.Join(strings.Fields(value), " ")
414}
415
416func unquote(value string) string {
417 value = strings.TrimSpace(value)
418 if len(value) >= 2 && ((value[0] == '"' && value[len(value)-1] == '"') || (value[0] == '\'' && value[len(value)-1] == '\'')) {
419 return value[1 : len(value)-1]
420 }
421 return value
422}