1package modes
2
3import (
4 "context"
5 "fmt"
6 "strings"
7
8 agenttools "github.com/bnema/zut/packages/agent/tools"
9 "github.com/bnema/zut/packages/core"
10 "github.com/bnema/zut/packages/provider"
11)
12
13const goalContinueMetaKey = "zut_goal_continue"
14
15func (i *Interactive) goalUpdatesAvailable() bool {
16 ag := i.Agent()
17 if ag == nil {
18 return false
19 }
20 _, ok := ag.ToolsSnapshot()[agenttools.UpdateGoalToolName]
21 return ok
22}
23
24func (i *Interactive) goalContinuationMessage() (provider.Message, bool) {
25 if i.cfg.CurrentGoal == nil || !i.goalUpdatesAvailable() {
26 return provider.Message{}, false
27 }
28 goal := i.cfg.CurrentGoal()
29 if goal == nil || goal.Status != core.GoalActive || strings.TrimSpace(goal.Objective) == "" {
30 return provider.Message{}, false
31 }
32 text := goal.Objective +
33 "\n\nContinue working autonomously toward this active goal. Do not stop at a progress update. Continue until the goal is complete or blocked, then call update_goal."
34 return provider.Message{
35 Role: provider.RoleUser,
36 Content: []provider.Content{provider.TextBlock{Text: text}},
37 Meta: map[string]string{goalContinueMetaKey: "true"},
38 }, true
39}
40
41func (i *Interactive) goalIdleLocked() bool {
42 return !i.busy && i.agent != nil && len(i.queued) == 0 && i.agent.QueuedMessageCount() == 0
43}
44
45func (i *Interactive) goalContinuationIfIdle() (provider.Message, bool) {
46 message, ok := i.goalContinuationMessage()
47 if !ok {
48 return provider.Message{}, false
49 }
50 i.mu.Lock()
51 defer i.mu.Unlock()
52 if !i.goalIdleLocked() {
53 return provider.Message{}, false
54 }
55 return message, true
56}
57
58func (i *Interactive) requestGoalContinuationIfIdle(parent context.Context) bool {
59 message, ok := i.goalContinuationMessage()
60 if !ok {
61 return false
62 }
63 i.mu.Lock()
64 if !i.goalIdleLocked() {
65 i.mu.Unlock()
66 return false
67 }
68 i.busy = true
69 i.mu.Unlock()
70 i.startGoalContinuation(parent, message)
71 return true
72}
73
74func (i *Interactive) startGoalContinuation(parent context.Context, message provider.Message) {
75 goalMessage, goalActive := i.goalContinuationMessage()
76 i.mu.Lock()
77 ag := i.agent
78 if ag == nil {
79 i.busy = false
80 pendingIdleWork := i.takePendingIdleWorkLocked()
81 i.mu.Unlock()
82 runPendingIdleWork(pendingIdleWork)
83 i.invalidate()
84 return
85 }
86 if len(i.queued) > 0 {
87 next := i.queued[0]
88 i.queued = i.queued[1:]
89 i.mu.Unlock()
90 i.startTurn(parent, next)
91 return
92 }
93 if ag.QueuedMessageCount() > 0 {
94 i.mu.Unlock()
95 i.startTurnRequest(parent, "", nil, true, false)
96 return
97 }
98 if !goalActive || userMessageText(goalMessage) != userMessageText(message) {
99 i.busy = false
100 pendingIdleWork := i.takePendingIdleWorkLocked()
101 i.mu.Unlock()
102 runPendingIdleWork(pendingIdleWork)
103 // The objective may have been replaced while the prior turn was
104 // finishing. Re-evaluate it now instead of waiting for another event;
105 // the idle gate still gives queued user work priority.
106 i.requestGoalContinuationIfIdle(parent)
107 i.invalidate()
108 return
109 }
110 i.mu.Unlock()
111 ag.AppendUserContext(userMessageText(message), message.Meta)
112
113 // Persistence callbacks run synchronously from AppendUserContext, so never
114 // hold the TUI mutex across it. Re-check user work that may have arrived
115 // while the hidden continuation was being persisted.
116 i.mu.Lock()
117 if len(i.queued) > 0 {
118 next := i.queued[0]
119 i.queued = i.queued[1:]
120 i.mu.Unlock()
121 i.startTurn(parent, next)
122 return
123 }
124 i.mu.Unlock()
125 i.startTurnRequest(parent, "", nil, true, false)
126}
127
128func copySessionGoal(goal *core.SessionGoal) *core.SessionGoal {
129 if goal == nil {
130 return nil
131 }
132 copyGoal := *goal
133 return ©Goal
134}
135
136func (i *Interactive) updateActiveGoal(status core.GoalStatus, reason string) {
137 if i.cfg.CurrentGoal == nil || i.cfg.PersistGoal == nil {
138 return
139 }
140 goal := copySessionGoal(i.cfg.CurrentGoal())
141 if goal == nil || goal.Status != core.GoalActive {
142 return
143 }
144 goal.Status = status
145 goal.Reason = reason
146 if err := i.cfg.PersistGoal(goal); err != nil {
147 i.ReportError(fmt.Errorf("persist goal: %w", err))
148 return
149 }
150 i.setGoalStatus(goal)
151}
152
153func (i *Interactive) runGoalCommand(ctx context.Context, cmd string, parts []string) {
154 if i.cfg.CurrentGoal == nil || i.cfg.PersistGoal == nil {
155 i.setGoalCommandError("goal: session persistence is unavailable")
156 return
157 }
158
159 current := copySessionGoal(i.cfg.CurrentGoal())
160 if len(parts) == 1 {
161 if current == nil {
162 i.setGoalCommandStatus("no autonomous goal")
163 return
164 }
165 status := fmt.Sprintf("goal %s: %s", current.Status, current.Objective)
166 if current.Reason != "" {
167 status += " (" + current.Reason + ")"
168 }
169 i.setGoalCommandStatus(status)
170 return
171 }
172
173 startIfIdle := false
174 startTitle := false
175 arg := ""
176 if len(parts) == 2 {
177 arg = strings.ToLower(parts[1])
178 }
179 switch arg {
180 case "pause":
181 if current == nil {
182 i.setGoalCommandError("goal: no goal to pause")
183 return
184 }
185 current.Status = core.GoalPaused
186 current.Reason = ""
187 case "resume":
188 if current == nil {
189 i.setGoalCommandError("goal: no goal to resume")
190 return
191 }
192 current.Status = core.GoalActive
193 current.Reason = ""
194 startIfIdle = true
195 case "clear":
196 if err := i.cfg.PersistGoal(nil); err != nil {
197 i.setGoalCommandError("goal: " + err.Error())
198 return
199 }
200 i.setGoalStatus(nil)
201 i.setGoalCommandStatus("autonomous goal cleared")
202 return
203 default:
204 objective := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(cmd), parts[0]))
205 if objective == "" {
206 i.setGoalCommandError("usage: /goal <objective>|pause|resume|clear")
207 return
208 }
209 current = &core.SessionGoal{Objective: objective, Status: core.GoalActive}
210 startIfIdle = true
211 startTitle = true
212 }
213
214 if startIfIdle && !i.goalUpdatesAvailable() {
215 i.setGoalCommandError("goal: update_goal is unavailable; enable the default tools")
216 return
217 }
218 if err := i.cfg.PersistGoal(current); err != nil {
219 i.setGoalCommandError("goal: " + err.Error())
220 return
221 }
222 i.setGoalStatus(current)
223 i.setGoalCommandStatus(fmt.Sprintf("autonomous goal %s: %s", current.Status, current.Objective))
224 if startTitle {
225 i.maybeStartSessionTitle(ctx, current.Objective)
226 }
227 if startIfIdle {
228 i.requestGoalContinuationIfIdle(ctx)
229 }
230}
231
232// RefreshGoal reloads the status badge after the CLI commits a session switch.
233func (i *Interactive) RefreshGoal() {
234 if i.cfg.CurrentGoal == nil {
235 i.setGoalStatus(nil)
236 return
237 }
238 i.setGoalStatus(i.cfg.CurrentGoal())
239}
240
241func (i *Interactive) setGoalStatus(goal *core.SessionGoal) {
242 status := core.GoalStatus("")
243 if goal != nil {
244 status = goal.Status
245 }
246 i.mu.Lock()
247 i.goalStatus = status
248 i.mu.Unlock()
249 i.invalidate()
250}
251
252func (i *Interactive) setGoalCommandStatus(message string) {
253 i.mu.Lock()
254 i.statusOK = message
255 i.statusErr = ""
256 i.mu.Unlock()
257 i.invalidate()
258}
259
260func (i *Interactive) setGoalCommandError(message string) {
261 i.mu.Lock()
262 i.statusOK = ""
263 i.statusErr = message
264 i.mu.Unlock()
265 i.invalidate()
266}