1package tools
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "strings"
8 "time"
9
10 "github.com/bnema/zut/packages/agent/subagents"
11 "github.com/bnema/zut/packages/core"
12 "github.com/bnema/zut/packages/provider"
13)
14
15// SubagentSpawnTool lets the main agent fork a background sub-agent
16// against the host's cwd via subagents.Supervisor.SpawnReq. The sub-agent runs
17// in parallel: the tool returns the agent id immediately and the main
18// turn continues uninterrupted. The user can monitor / chat with the
19// spawned agent via /subagents.
20//
21// Available when the host's launch-time tool policy permits delegation. The
22// primary-agent prompt decides whether delegation is proactive or only on an
23// explicit user request.
24type SubagentSpawnTool struct {
25 // Supervisor is the supervisor used to spawn agents. Nil means subagents
26 // are unavailable in this mode and the tool always errors.
27 Supervisor *subagents.Supervisor
28
29 // Enabled reports whether the host currently exposes this tool. When nil,
30 // the tool is treated as disabled.
31 Enabled func() bool
32
33 // DefaultModel and DefaultProvider return the host agent's resolved
34 // model and provider. They are used when the tool call omits both
35 // fields and does not select a named profile, so auto-subagents follows
36 // the same auth route as the user sees in the parent session.
37 DefaultModel func() string
38 DefaultProvider func() string
39 DefaultReasoning func() string
40
41 // ResolveSubagent validates and resolves a named markdown profile.
42 // The child receives only the name and loads the profile itself.
43 ResolveSubagent func(name string) (*subagents.Profile, error)
44
45 // OnSpawned, if set, is called after every successful spawn with
46 // the new agent + the task it was started with. Used by the
47 // interactive host to track agents and surface a summary back
48 // in chat when all sub-agents finish.
49 OnSpawned func(agent *subagents.Agent, task string)
50}
51
52type subagentSpawnArgs struct {
53 Task string `json:"task"`
54 Agent string `json:"agent,omitempty"`
55 Model string `json:"model,omitempty"`
56 Provider string `json:"provider,omitempty"`
57 Reasoning string `json:"reasoning,omitempty"`
58 Thinking string `json:"thinking,omitempty"`
59 Isolation string `json:"isolation,omitempty"`
60 Timeout string `json:"timeout,omitempty"`
61 MaxTurns *int `json:"max_turns,omitempty"`
62}
63
64const subagentSpawnSchemaTemplate = `{
65 "type": "object",
66 "properties": {
67 "task": {
68 "type": "string",
69 "description": "The full task description for the sub-agent. Be specific: the child normally has the main agent's built-in tools, including lsp when enabled, but a selected profile can restrict its tools; it shares this working directory and starts with NO context from this conversation."
70 },
71 "agent": {
72 "type": "string",
73 "description": "Optional named markdown profile from [subagents_list]. The child applies that profile's system prompt, model, thinking level, tool limits, and fast-mode preference. Omit for a generic child."
74 },
75 "model": {
76 "type": "string",
77 "description": "Optional model id to pin the sub-agent to. Normally omit both model and provider so the sub-agent inherits the host session's resolved provider/model/auth route, or omit them when using an agent profile. Do not infer provider from model name. If you override this, also provide provider."
78 },
79 "provider": {
80 "type": "string",
81 "description": "Optional provider id. Normally omit both model and provider so the sub-agent inherits the host session. If you override this, also provide model. Note: openai means public OpenAI API-key auth; openai-codex means ChatGPT/Codex subscription auth."
82 },
83 "reasoning": {
84 "type": "string",
85 "enum": ["off", "minimum", "low", "medium", "high", "xhigh", "max"],
86 "description": "Optional reasoning/thinking level for the child. Overrides the selected profile's thinking level when provided."
87 },
88 "thinking": {
89 "type": "string",
90 "enum": ["off", "minimum", "low", "medium", "high", "xhigh", "max"],
91 "description": "Alias for reasoning, accepted for compatibility with common agent profile terminology. Prefer reasoning when both are available."
92 },
93 "isolation": {
94 "type": "string",
95 "enum": ["shared", "worktree"],
96 "description": "Workspace mode. Shared preserves existing behavior; worktree captures a patch without merging it."
97 },
98 "timeout": {
99 "type": "string",
100 "description": "Optional Go duration such as 20m."
101 },
102 "max_turns": {
103 "type": "integer",
104 "minimum": 1,
105 "maximum": %d,
106 "description": "Optional maximum prompt-level turns for this worker. Omit to use the supervisor default; the effective policy allows 1 through %d."
107 }
108 },
109 "required": ["task"]
110}`
111
112func (t *SubagentSpawnTool) Name() string { return "subagent_spawn" }
113func (t *SubagentSpawnTool) Description() string {
114 return "Spawn a background sub-agent to work on a parallel sub-task. Optionally select a named markdown profile, model/provider/reasoning, timeout, turn limit, and shared/worktree isolation, and fast-mode preference. Returns the sub-agent id immediately. Completion is host-event-driven: wait only for the injected [auto-subagents update]; never use bash sleep, watch, tail -f, polling loops, repeated subagent_status, or dashboard/metadata/event-log/file checks solely to wait. Work on unrelated independent tasks or end/yield your turn. Legitimate waits inside user-requested commands, provider flows, extensions, or tests are allowed."
115}
116func (t *SubagentSpawnTool) Schema() json.RawMessage {
117 maxTurns := 3
118 if t.Supervisor != nil {
119 if limit := t.Supervisor.MaxTurns(); limit > 0 {
120 maxTurns = limit
121 }
122 }
123 return json.RawMessage(fmt.Sprintf(subagentSpawnSchemaTemplate, maxTurns, maxTurns))
124}
125
126func (t *SubagentSpawnTool) Execute(ctx context.Context, raw json.RawMessage, progress func(string)) (core.ToolResult, error) {
127 prefix := t.Name()
128 if t.Supervisor == nil {
129 return protocolToolError(prefix + ": subagent supervisor not available in this mode")
130 }
131 if t.Enabled == nil || !t.Enabled() {
132 return protocolToolError(prefix + ": subagent delegation is unavailable in this mode")
133 }
134 var a subagentSpawnArgs
135 if err := json.Unmarshal(raw, &a); err != nil {
136 return core.ToolResult{}, fmt.Errorf("invalid args: %w", err)
137 }
138 task := strings.TrimSpace(a.Task)
139 if task == "" {
140 return protocolToolError(prefix + ": task is required")
141 }
142
143 workspaceMode := subagents.WorkspaceShared
144 if value := strings.TrimSpace(a.Isolation); value != "" {
145 workspaceMode = subagents.WorkspaceMode(value)
146 if workspaceMode != subagents.WorkspaceShared && workspaceMode != subagents.WorkspaceWorktree {
147 return protocolToolError(prefix + ": isolation must be shared or worktree")
148 }
149 }
150 var timeout time.Duration
151 if value := strings.TrimSpace(a.Timeout); value != "" {
152 parsed, parseErr := time.ParseDuration(value)
153 if parseErr != nil || parsed <= 0 {
154 return protocolToolError(prefix + ": timeout must be a positive duration")
155 }
156 timeout = parsed
157 }
158 if a.MaxTurns != nil {
159 if *a.MaxTurns < 1 {
160 return protocolToolError(prefix + ": max_turns must be positive")
161 }
162 if limit := t.Supervisor.MaxTurns(); limit > 0 && *a.MaxTurns > limit {
163 return protocolToolError(fmt.Sprintf("%s: max_turns must be 1 through %d; omit it to use the supervisor default", prefix, limit))
164 }
165 }
166
167 agentName := strings.TrimSpace(a.Agent)
168 var profile *subagents.Profile
169 var fastModeOverride *bool
170 if agentName != "" {
171 if t.ResolveSubagent == nil {
172 return protocolToolError(prefix + ": named subagent profiles are unavailable")
173 }
174 var err error
175 profile, err = t.ResolveSubagent(agentName)
176 if err != nil {
177 return protocolToolError(prefix + ": " + err.Error())
178 }
179 if profile == nil {
180 return protocolToolError(prefix + ": unknown subagent profile " + agentName)
181 }
182 agentName = profile.Name
183 fastModeOverride = profile.FastMode
184 }
185
186 model := strings.TrimSpace(a.Model)
187 providerID := strings.TrimSpace(a.Provider)
188 var profileTools []string
189 if profile != nil {
190 profileTools = append([]string(nil), profile.Tools...)
191 }
192 if (model == "") != (providerID == "") {
193 return protocolToolError(prefix + ": omit both model/provider to inherit the host or profile, or provide both explicitly")
194 }
195 if profile != nil {
196 // A profile may specify a qualified model, a bare model, a provider,
197 // or neither. Fill only missing pieces so explicit spawn options win;
198 // the parent session supplies whatever the profile leaves unspecified.
199 profileProvider, profileModel := profile.ModelSelection()
200 if model == "" {
201 model = profileModel
202 }
203 if providerID == "" {
204 providerID = profileProvider
205 }
206 }
207 if model == "" && t.DefaultModel != nil {
208 model = strings.TrimSpace(t.DefaultModel())
209 }
210 if providerID == "" && t.DefaultProvider != nil {
211 providerID = strings.TrimSpace(t.DefaultProvider())
212 }
213
214 reasoning, err := reasoningOverride(a.Reasoning, a.Thinking)
215 if err != nil {
216 return protocolToolError(prefix + ": " + err.Error())
217 }
218 if reasoning == "" && profile != nil && strings.TrimSpace(profile.Thinking) != "" {
219 reasoning, err = reasoningOverride(profile.Thinking, "")
220 if err != nil {
221 return protocolToolError(prefix + ": profile " + profile.Name + ": " + err.Error())
222 }
223 }
224 if reasoning == "" && t.DefaultReasoning != nil {
225 reasoning, err = reasoningOverride(t.DefaultReasoning(), "")
226 if err != nil {
227 return protocolToolError(prefix + ": host " + err.Error())
228 }
229 }
230
231 maxTurns := 0
232 if a.MaxTurns != nil {
233 maxTurns = *a.MaxTurns
234 }
235 agent, err := t.Supervisor.SpawnReq(ctx, subagents.SpawnRequest{
236 Task: task,
237 Model: model,
238 Provider: providerID,
239 Reasoning: reasoning,
240 FastMode: fastModeOverride,
241 Subagent: agentName,
242 Timeout: timeout,
243 MaxTurns: maxTurns,
244 WorkspaceMode: workspaceMode,
245 Tools: profileTools,
246 })
247 if err != nil {
248 return core.ToolResult{}, fmt.Errorf("%s: %w", prefix, err)
249 }
250 if t.OnSpawned != nil {
251 t.OnSpawned(agent, task)
252 }
253
254 var sb strings.Builder
255 fmt.Fprintf(&sb, "spawned sub-agent %s\n", agent.ID)
256 fmt.Fprintf(&sb, "state: %s/%s\n", agent.ProcessState(), agent.TurnState())
257 fmt.Fprintf(&sb, "workspace: %s\n", agent.WorkspaceMode)
258 fmt.Fprintf(&sb, "task: %s\n", truncateTask(task, 200))
259 if agentName != "" {
260 fmt.Fprintf(&sb, "agent: %s\n", agentName)
261 }
262 if model != "" {
263 fmt.Fprintf(&sb, "model: %s\n", model)
264 }
265 if providerID != "" {
266 fmt.Fprintf(&sb, "provider: %s\n", providerID)
267 }
268 if reasoning != "" {
269 fmt.Fprintf(&sb, "reasoning: %s\n", reasoning)
270 }
271 if agent.FastMode {
272 sb.WriteString("fast mode: enabled\n")
273 }
274 if fastModeOverride != nil && *fastModeOverride && agent.FastModeOverridesHost() {
275 sb.WriteString("warning: subagent profile has fast mode enabled, overriding global fast mode off\n")
276 }
277 sb.WriteString("\nThe sub-agent is running in the background. Completion is host-event-driven: wait for the injected [auto-subagents update], the only completion signal. ")
278 sb.WriteString("Never use bash sleep, watch, tail -f, polling loops, repeated subagent_status, or dashboard/metadata/event-log/file checks solely to wait. ")
279 sb.WriteString("Work on unrelated independent tasks; otherwise end or yield your turn. Legitimate waits inside user-requested commands, provider flows, extensions, or tests are allowed.")
280 return core.ToolResult{
281 Content: []provider.Content{provider.TextBlock{Text: sb.String()}},
282 Details: map[string]any{
283 "agent_id": agent.ID,
284 "task": task,
285 "agent": agentName,
286 "model": model,
287 "provider": providerID,
288 "reasoning": reasoning,
289 "fast_mode": agent.FastMode,
290 "isolation": string(workspaceMode),
291 "timeout": agent.Timeout.String(),
292 "max_turns": agent.MaxTurns,
293 "state": agent.Status(),
294 "process_state": string(agent.ProcessState()),
295 "turn_state": string(agent.TurnState()),
296 "result_ref": subagents.ResultRef(agent.ID),
297 },
298 }, nil
299}
300
301func reasoningOverride(reasoning, thinking string) (string, error) {
302 reasoning = strings.TrimSpace(reasoning)
303 thinking = strings.TrimSpace(thinking)
304 if reasoning != "" && thinking != "" && provider.NormalizeReasoning(reasoning) != provider.NormalizeReasoning(thinking) {
305 return "", fmt.Errorf("reasoning and thinking disagree; provide only one")
306 }
307 value := reasoning
308 if value == "" {
309 value = thinking
310 }
311 if value == "" {
312 return "", nil
313 }
314 normalized := provider.NormalizeReasoning(value)
315 switch normalized {
316 case "":
317 return "off", nil
318 case "minimum", "low", "medium", "high", "xhigh", "max":
319 return normalized, nil
320 default:
321 return "", fmt.Errorf("reasoning must be off|minimum|low|medium|high|xhigh|max")
322 }
323}
324
325// protocolToolError keeps model-visible validation failures in the
326// ToolResult channel rather than treating them as host execution errors.
327func protocolToolError(msg string) (core.ToolResult, error) {
328 //nolint:nilerr // ToolResult.IsError is the established tool protocol.
329 return toolErr(msg), nil
330}
331
332func toolErr(msg string) core.ToolResult {
333 return core.ToolResult{
334 Content: []provider.Content{provider.TextBlock{Text: msg}},
335 IsError: true,
336 }
337}
338
339func truncateTask(s string, n int) string {
340 if len(s) <= n {
341 return s
342 }
343 return s[:n-3] + "..."
344}