1package agent
2
3import (
4 "context"
5 "fmt"
6 "strings"
7 "sync"
8
9 "github.com/bnema/zut/packages/agent/subagents"
10 "github.com/bnema/zut/packages/agent/tools"
11 "github.com/bnema/zut/packages/core"
12)
13
14// newResidentChildRunner is the host-owned construction boundary for one
15// resident child. It resolves a fresh provider client and a fresh core.Agent
16// exactly once for the child's durable session; no subprocess configuration or
17// credential transfer is involved.
18func newResidentChildRunner(args Args, spec subagents.ResidentChildSpec, journal *subagents.ResidentJournal) (subagents.ResidentTurnRunner, error) {
19 if strings.TrimSpace(spec.SessionID) == "" {
20 return nil, fmt.Errorf("resident child %q has no session identity", spec.ID)
21 }
22 resolved, err := Resolve(args, true)
23 if err != nil {
24 return nil, fmt.Errorf("resolve resident child %q: %w", spec.ID, err)
25 }
26
27 registry, err := residentChildRegistry(resolved.ToolRegistry, spec.Tools)
28 if err != nil {
29 return nil, err
30 }
31 system := resolved.SystemPrompt
32 if extra := strings.TrimSpace(spec.SystemPrompt); extra != "" {
33 if spec.SystemPromptMode == "replace" {
34 system = extra
35 } else {
36 system = strings.TrimSpace(system) + "\n\n" + extra
37 }
38 }
39 agent := core.NewAgent(resolved.NewClient(), resolved.Model, system, registry)
40 agent.MaxSteps = resolved.MaxSteps
41 agent.ContextWindow = resolved.ContextWindow
42 agent.MaxTokens = resolved.MaxOutput
43 agent.Reasoning = resolved.Reasoning
44 agent.Temperature = resolved.Temperature
45 agent.FastMode = resolved.FastMode
46 if journal != nil {
47 baseline := journal.ConfigureUsage(resolved.ContextWindow, resolved.AuthMethod == "oauth")
48 agent.SeedCost(baseline.Usage)
49 }
50 if err := agent.BindSessionID(spec.SessionID); err != nil {
51 return nil, fmt.Errorf("bind resident child %q session: %w", spec.ID, err)
52 }
53 if journal != nil {
54 messages, err := subagents.ReadResidentTranscriptMessages(journal.Dir())
55 if err != nil {
56 return nil, fmt.Errorf("restore resident child %q transcript: %w", spec.ID, err)
57 }
58 if len(messages) > 0 {
59 agent.SetMessages(messages)
60 }
61 }
62 return func(ctx context.Context, prompt string) error {
63 if ctx == nil {
64 ctx = context.Background()
65 }
66 turnCtx, cancel := context.WithCancel(ctx)
67 defer cancel()
68 var journalErr error
69 var journalMu sync.Mutex
70 err := agent.Prompt(turnCtx, prompt, nil, func(event core.AgentEvent) {
71 if err := journal.RecordAgentEvent(event); err != nil {
72 journalMu.Lock()
73 if journalErr == nil {
74 journalErr = err
75 cancel()
76 }
77 journalMu.Unlock()
78 }
79 })
80 journalMu.Lock()
81 defer journalMu.Unlock()
82 if journalErr != nil {
83 return fmt.Errorf("persist resident child transcript: %w", journalErr)
84 }
85 return err
86 }, nil
87}
88
89// residentChildArgs applies the complete durable child specification without
90// rediscovering a mutable profile file. That preserves the profile inheritance
91// decision accepted at spawn time across explicit resume and restart.
92func residentChildArgs(args Args, parentProvider string, spec subagents.ResidentChildSpec) Args {
93 next := args
94 // An explicit CLI key belongs to the provider that resolved the parent.
95 // A child can select another provider, but it must resolve that provider's
96 // own credential rather than forwarding or persisting the parent's key.
97 if canonicalProvider(parentProvider) != canonicalProvider(spec.Provider) {
98 next.APIKey = ""
99 }
100 next.Provider = spec.Provider
101 next.BaseURL = spec.BaseURL
102 next.InsecureTLS = spec.InsecureTLS
103 next.Model = spec.Model
104 next.Reasoning = spec.Reasoning
105 next.FastMode = spec.FastMode
106 next.FastModeSet = true
107 if strings.TrimSpace(spec.Workspace) != "" {
108 next.CWD = spec.Workspace
109 }
110 if spec.InheritSkills != nil && !*spec.InheritSkills {
111 next.NoSkill = true
112 }
113 if spec.InheritProjectContext != nil && !*spec.InheritProjectContext {
114 next.NoContextFiles = true
115 }
116 return next
117}
118
119// residentChildRegistry applies an already validated, exact child tool list.
120// It always strips delegation and host-goal mutation tools: child agents are
121// independent workers, not nested orchestrators or goal owners.
122func residentChildRegistry(catalogue core.Registry, names []string) (core.Registry, error) {
123 registry := make(core.Registry, len(names))
124 for _, name := range names {
125 name = strings.TrimSpace(name)
126 if name == "" {
127 return nil, fmt.Errorf("resident child has an empty tool name")
128 }
129 if name == tools.SubagentSpawnToolName || name == tools.SubagentStatusToolName || name == tools.SubagentStopToolName || name == tools.SubagentResumeToolName || name == "update_goal" {
130 return nil, fmt.Errorf("resident child tool %q is not allowed", name)
131 }
132 tool, ok := catalogue[name]
133 if !ok {
134 return nil, fmt.Errorf("resident child declares unavailable tool %q", name)
135 }
136 registry[name] = tool
137 }
138 return registry, nil
139}