subagent_stop.go RawHistoryFolder
1package tools
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "strings"
8
9 "github.com/bnema/zut/packages/agent/subagents"
10 "github.com/bnema/zut/packages/core"
11 "github.com/bnema/zut/packages/provider"
12)
13
14// SubagentStopTool lets the manager request termination of a stuck background
15// sub-agent through the resident manager's cancellation lifecycle.
16type SubagentStopTool struct {
17 ResidentManager *subagents.ResidentManager
18 Enabled func() bool
19}
20
21type subagentStopArgs struct {
22 AgentID string `json:"agent_id"`
23}
24
25type subagentActionResponse struct {
26 Action string `json:"action"`
27 Agent subagentStatusEntry `json:"agent"`
28}
29
30const subagentStopSchema = `{
31 "type": "object",
32 "properties": {
33 "agent_id": {
34 "type": "string",
35 "description": "Child id or unique id prefix for the stuck resident sub-agent to terminate."
36 }
37 },
38 "required": ["agent_id"]
39}`
40
41func (t *SubagentStopTool) Name() string { return SubagentStopToolName }
42
43func (t *SubagentStopTool) Description() string {
44 return "Request termination of a stuck resident sub-agent."
45}
46
47func (t *SubagentStopTool) Schema() json.RawMessage {
48 return json.RawMessage(subagentStopSchema)
49}
50
51func (t *SubagentStopTool) Execute(ctx context.Context, raw json.RawMessage, _ func(string)) (core.ToolResult, error) {
52 if ctx != nil {
53 select {
54 case <-ctx.Done():
55 return core.ToolResult{}, ctx.Err()
56 default:
57 }
58 }
59 prefix := t.Name()
60 if t.ResidentManager == nil {
61 return protocolToolError(prefix + ": subagent runtime not available in this mode")
62 }
63 if t.Enabled == nil || !t.Enabled() {
64 return protocolToolError(prefix + ": subagent management is unavailable in this mode")
65 }
66
67 var args subagentStopArgs
68 if err := decodeSubagentArgs(raw, &args); err != nil {
69 return core.ToolResult{}, err
70 }
71 id := strings.TrimSpace(args.AgentID)
72 if id == "" {
73 return protocolToolError(prefix + ": agent_id is required")
74 }
75 snapshot, ok := findResidentStatusSnapshot(t.ResidentManager.Snapshot(), id)
76 if !ok {
77 return protocolToolError(fmt.Sprintf("%s: no such agent %q", prefix, id))
78 }
79 if err := t.ResidentManager.Stop(ctx, snapshot.ID); err != nil {
80 return core.ToolResult{}, fmt.Errorf("%s: %w", prefix, err)
81 }
82 if updated, ok := t.ResidentManager.SnapshotFor(snapshot.ID); ok {
83 snapshot = updated
84 }
85 return renderResidentAction("stop_requested", publicResidentStatus(snapshot))
86}
87
88func renderResidentAction(action string, entry subagentStatusEntry) (core.ToolResult, error) {
89 response := subagentActionResponse{Action: action, Agent: entry}
90 data, err := json.Marshal(response)
91 if err != nil {
92 return core.ToolResult{}, fmt.Errorf("subagent action: encode response: %w", err)
93 }
94 return core.ToolResult{Content: []provider.Content{provider.TextBlock{Text: string(data)}}, Details: response}, nil
95}